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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21e8d0699df488e7ff186709b7864b885a3957d1 | 3,400 | cpp | C++ | src/applications/replicoscillator/edgedBasedDetection.cpp | TASBE/ImageAnalytics | 5d6fc1a64b4c17e263451fa4252c94dc86193d14 | [
"CC-BY-3.0"
] | 1 | 2019-08-29T20:48:32.000Z | 2019-08-29T20:48:32.000Z | src/applications/replicoscillator/edgedBasedDetection.cpp | TASBE/ImageAnalytics | 5d6fc1a64b4c17e263451fa4252c94dc86193d14 | [
"CC-BY-3.0"
] | 1 | 2021-11-02T18:14:21.000Z | 2021-11-02T18:19:50.000Z | src/applications/replicoscillator/edgedBasedDetection.cpp | TASBE/ImageAnalytics | 5d6fc1a64b4c17e263451fa4252c94dc86193d14 | [
"CC-BY-3.0"
] | null | null | null | /*
Copyright (C) 2011 - 2019, Raytheon BBN Technologies and contributors listed
in the AUTHORS file in TASBE Flow Analytics distribution's top directory.
This file is part of the TASBE Flow Analytics package, and is distributed
under the terms of the GNU General Public License, with a linking
exception, as described in the file LICENSE in the TASBE Image Analysis
package distribution's top directory.
*/
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/ximgproc/edge_filter.hpp"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace cv;
using namespace std;
Mat src;
Mat blurred;
int thresh = 100;
int max_thresh = 255;
int origBlurr;
RNG rng(12345);
/// Function header
void thresh_callback(int, void*);
void src_callback(int, void*);
/** @function main */
int main(int argc, char** argv) {
/// Load source image and convert it to gray
src = imread(argv[1], IMREAD_ANYDEPTH);
cout << "Bit depth: " << src.depth() * 8 << endl;
if (src.depth() > 1) {
/*
double minVal, maxVal;
minMaxLoc(src, &minVal, &maxVal);
cout << "Min Val: " << minVal << ", Max Val: " << maxVal << endl;
Mat full, partial;
double gain = 255/(maxVal - minVal);
src.convertTo(full, CV_8UC1, 255/(pow(2,16) - 1), 0);
src.convertTo(partial, CV_8UC1, gain, - minVal * gain);
minMaxLoc(full, &minVal, &maxVal);
cout << "full Min Val: " << minVal << ", full Max Val: " << maxVal << endl;
minMaxLoc(partial, &minVal, &maxVal);
cout << "partial Min Val: " << minVal << ", partial Max Val: " << maxVal << endl;
namedWindow("Full", CV_WINDOW_AUTOSIZE);
imshow("Full", full);
namedWindow("Partial", CV_WINDOW_AUTOSIZE);
imshow("Partial", partial);
waitKey(0);
*/
double minVal, maxVal;
minMaxLoc(src, &minVal, &maxVal);
Mat eightBit;
double gain = 255/(maxVal - minVal);
src.convertTo(eightBit, CV_8UC1, gain, - minVal * gain);
src = eightBit;
}
/// Convert image to gray and blur it
if (src.channels() > 1) {
Mat src_gray;
cvtColor(src, src_gray, CV_BGR2GRAY);
src = src_gray;
}
ximgproc::bilateralTextureFilter(src, blurred);
/// Create Window
namedWindow("Source", CV_WINDOW_AUTOSIZE);
imshow("Source", src);
createTrackbar(" Canny thresh:", "Source", &thresh, max_thresh,
thresh_callback);
createTrackbar(" Orig/Blurred", "Source", &origBlurr, 1, src_callback);
thresh_callback(0, 0);
waitKey(0);
return (0);
}
/** @function thresh_callback */
void thresh_callback(int, void*) {
Mat canny_output;
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
/// Detect edges using canny
Canny(blurred, canny_output, thresh, thresh * 2, 3);
/// Find contours
findContours(canny_output, contours, hierarchy, CV_RETR_EXTERNAL,
CV_CHAIN_APPROX_SIMPLE, Point(0, 0));
/// Draw contours
Mat drawing = Mat::zeros(canny_output.size(), CV_8UC3);
for (int i = 0; i < contours.size(); i++) {
Scalar color = Scalar(rng.uniform(0, 255), rng.uniform(0, 255),
rng.uniform(0, 255));
drawContours(drawing, contours, i, color, 2, 8, hierarchy, 0, Point());
}
/// Show in a window
namedWindow("Contours", CV_WINDOW_AUTOSIZE);
imshow("Contours", drawing);
namedWindow("Edges", CV_WINDOW_AUTOSIZE);
imshow("Edges", canny_output);
}
void src_callback(int, void*) {
if (origBlurr) {
imshow("Source", blurred);
} else {
imshow("Source", src);
}
}
| 26.153846 | 83 | 0.682647 | TASBE |
21f64e60d69cac1e09217f89d5dacb1865cf26c9 | 15,688 | cpp | C++ | mp/src/game/server/da/da_datamanager.cpp | Black-Stormy/DoubleAction | cef6ff5ec41f2fed938d8ee3d6ffd3c770f523c7 | [
"Unlicense"
] | null | null | null | mp/src/game/server/da/da_datamanager.cpp | Black-Stormy/DoubleAction | cef6ff5ec41f2fed938d8ee3d6ffd3c770f523c7 | [
"Unlicense"
] | null | null | null | mp/src/game/server/da/da_datamanager.cpp | Black-Stormy/DoubleAction | cef6ff5ec41f2fed938d8ee3d6ffd3c770f523c7 | [
"Unlicense"
] | null | null | null | #include "cbase.h"
using namespace std;
#ifdef WITH_DATA_COLLECTION
#undef min
#undef max
#include <time.h>
#include "da_datamanager.h"
#include "da_player.h"
#include "weapon_grenade.h"
#include "da_gamerules.h"
#include "da_briefcase.h"
#include "../datanetworking/math.pb.h"
#include "../datanetworking/data.pb.h"
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
#ifdef WITH_DATA_COLLECTION
void FillProtoBufVector(da::protobuf::Vector* pVector, const Vector& vecFill)
{
pVector->set_x(vecFill.x);
pVector->set_y(vecFill.y);
pVector->set_z(vecFill.z);
}
CDataManager g_DataManager( "CDataManager" );
CDataManager& DataManager()
{
return g_DataManager;
}
extern bool DASendData(const da::protobuf::GameData& pbGameData, std::string& sError);
static void SendData( CFunctor **pData, unsigned int nCount )
{
da::protobuf::GameData pbGameData;
g_DataManager.FillProtoBuffer(&pbGameData);
std::string sError;
if (!DASendData(pbGameData, sError))
Msg("Error sending game data: %s", sError.c_str());
}
static bool Account_LessFunc( AccountID_t const &a, AccountID_t const &b )
{
return a < b;
}
CDataManager::CDataManager( char const* name )
: CAutoGameSystemPerFrame(name)
{
m_aiConnectedClients.SetLessFunc(Account_LessFunc);
m_pSendData = NULL;
d = NULL;
m_bLevelStarted = false;
ClearData();
}
CDataManager::~CDataManager()
{
delete d;
}
void CDataManager::LevelInitPostEntity( void )
{
// If the thread is executing, then wait for it to finish
if ( m_pSendData )
{
m_pSendData->WaitForFinishAndRelease();
m_pSendData = NULL;
}
m_bLevelStarted = true;
d->z.m_flStartTime = gpGlobals->curtime;
d->z.m_flNextPositionsUpdate = gpGlobals->curtime;
CUtlMap<AccountID_t, char>::IndexType_t it = m_aiConnectedClients.FirstInorder();
while (it != m_aiConnectedClients.InvalidIndex())
{
// This player is gone for good. Remove him from the list and we'll
// count him as unique next time he shows up.
if (m_aiConnectedClients[it] == 0)
{
CUtlMap<AccountID_t, char>::IndexType_t iRemove = it;
m_aiConnectedClients.RemoveAt(iRemove);
it = m_aiConnectedClients.NextInorder(it);
continue;
}
// This player will be a unique player for the next map.
d->z.m_iUniquePlayers++;
it = m_aiConnectedClients.NextInorder(it);
}
}
void CDataManager::FrameUpdatePostEntityThink( void )
{
if (gpGlobals->curtime > d->z.m_flNextPositionsUpdate)
SavePositions();
}
ConVar da_data_positions_interval("da_data_positions_interval", "10", FCVAR_DEVELOPMENTONLY, "How often to query player positions");
void CDataManager::SavePositions()
{
if (IsSendingData())
return;
d->z.m_flNextPositionsUpdate = gpGlobals->curtime + da_data_positions_interval.GetFloat();
for (int i = 1; i <= gpGlobals->maxClients; i++)
{
CDAPlayer *pPlayer = ToDAPlayer(UTIL_PlayerByIndex( i ));
if (!pPlayer)
continue;
if (pPlayer->IsBot())
continue;
if (!pPlayer->IsAlive())
continue;
d->m_avecPlayerPositions.AddToTail(pPlayer->GetAbsOrigin());
if (pPlayer->IsInThirdPerson())
d->z.m_iThirdPersonActive += da_data_positions_interval.GetFloat();
else
d->z.m_iThirdPersonInactive += da_data_positions_interval.GetFloat();
if (pPlayer->m_bUsingVR)
d->z.m_iVRActive += da_data_positions_interval.GetFloat();
else
d->z.m_iVRInactive += da_data_positions_interval.GetFloat();
if (pPlayer->m_iPlatform == 1)
d->z.m_iWindows += da_data_positions_interval.GetFloat();
else if (pPlayer->m_iPlatform == 2)
d->z.m_iLinux += da_data_positions_interval.GetFloat();
else if (pPlayer->m_iPlatform == 3)
d->z.m_iMac += da_data_positions_interval.GetFloat();
}
ConVarRef sv_cheats("sv_cheats");
d->z.m_bCheated |= sv_cheats.GetBool();
}
int GetFlags(CDAPlayer* pPlayer)
{
unsigned long long flags = 0;
if (pPlayer->IsInThirdPerson())
flags |= 1<<da::protobuf::KILL_THIRDPERSON;
if (pPlayer->m_Shared.IsAimedIn())
flags |= 1<<da::protobuf::KILL_AIMIN;
if (pPlayer->m_Shared.IsDiving())
flags |= 1<<da::protobuf::KILL_DIVING;
if (pPlayer->m_Shared.IsRolling())
flags |= 1<<da::protobuf::KILL_ROLLING;
if (pPlayer->m_Shared.IsSliding())
flags |= 1<<da::protobuf::KILL_SLIDING;
if (pPlayer->m_Shared.IsWallFlipping(true))
flags |= 1<<da::protobuf::KILL_FLIPPING;
if (pPlayer->m_Shared.IsSuperFalling())
flags |= 1<<da::protobuf::KILL_SUPERFALLING;
if (pPlayer->IsStyleSkillActive())
flags |= 1<<da::protobuf::KILL_SKILL_ACTIVE;
if (pPlayer->m_Shared.m_bSuperSkill)
flags |= 1<<da::protobuf::KILL_SUPER_SKILL_ACTIVE;
if (DAGameRules()->GetBountyPlayer() == pPlayer)
flags |= 1<<da::protobuf::KILL_IS_TARGET;
if (pPlayer->HasBriefcase())
flags |= 1<<da::protobuf::KILL_HAS_BRIEFCASE;
if (pPlayer->IsBot())
flags |= 1<<da::protobuf::KILL_IS_BOT;
return flags;
}
void FillPlayerInfo(da::protobuf::PlayerInfo* pbPlayerInfo, CDAPlayer* pPlayer)
{
FillProtoBufVector(pbPlayerInfo->mutable_position(), pPlayer->GetAbsOrigin());
pbPlayerInfo->set_health(pPlayer->GetHealth());
pbPlayerInfo->set_flags(GetFlags(pPlayer));
pbPlayerInfo->set_skill(SkillIDToAlias((SkillID)pPlayer->m_Shared.m_iStyleSkill.Get()));
pbPlayerInfo->set_style(pPlayer->GetStylePoints());
pbPlayerInfo->set_total_style(pPlayer->GetTotalStyle());
pbPlayerInfo->set_kills(pPlayer->m_iKills);
pbPlayerInfo->set_deaths(pPlayer->m_iDeaths);
if (pPlayer->GetActiveDAWeapon())
pbPlayerInfo->set_weapon(WeaponIDToAlias(pPlayer->GetActiveDAWeapon()->GetWeaponID()));
if (!pPlayer->IsBot())
{
CSteamID ID;
pPlayer->GetSteamID(&ID);
pbPlayerInfo->set_accountid(ID.GetAccountID());
}
if (DAGameRules()->GetWaypoint(0))
{
pbPlayerInfo->set_waypoint(pPlayer->m_iRaceWaypoint);
FillProtoBufVector(pbPlayerInfo->mutable_objective_position(), DAGameRules()->GetWaypoint(pPlayer->m_iRaceWaypoint)->GetAbsOrigin());
}
if (pPlayer->HasBriefcase())
FillProtoBufVector(pbPlayerInfo->mutable_objective_position(), DAGameRules()->GetCaptureZone()->GetAbsOrigin());
if (pPlayer->m_iSlowMoType == SLOWMO_STYLESKILL)
pbPlayerInfo->set_slowmo_type("super");
else if (pPlayer->m_iSlowMoType == SLOWMO_ACTIVATED)
pbPlayerInfo->set_slowmo_type("active");
else if (pPlayer->m_iSlowMoType == SLOWMO_SUPERFALL)
pbPlayerInfo->set_slowmo_type("superfall");
else if (pPlayer->m_iSlowMoType == SLOWMO_PASSIVE)
pbPlayerInfo->set_slowmo_type("passive");
else if (pPlayer->m_iSlowMoType == SLOWMO_PASSIVE_SUPER)
pbPlayerInfo->set_slowmo_type("passivesuper");
else if (pPlayer->m_iSlowMoType == SLOWMO_NONE)
pbPlayerInfo->set_slowmo_type("none");
else
pbPlayerInfo->set_slowmo_type("unknown");
if (pPlayer->m_flSlowMoTime)
pbPlayerInfo->set_slowmo_seconds(pPlayer->m_flSlowMoTime - gpGlobals->curtime);
else
pbPlayerInfo->set_slowmo_seconds(pPlayer->m_flSlowMoSeconds);
}
void CDataManager::AddKillInfo(const CTakeDamageInfo& info, CDAPlayer* pVictim)
{
d->m_apKillInfos.AddToTail(new da::protobuf::KillInfo());
da::protobuf::KillInfo* pbKillInfo = d->m_apKillInfos.Tail();
CBaseEntity* pAttacker = info.GetAttacker();
da::protobuf::PlayerInfo* pbVictimInfo = pbKillInfo->mutable_victim();
FillPlayerInfo(pbVictimInfo, pVictim);
unsigned long long flags = pbVictimInfo->flags();
if (dynamic_cast<CBaseGrenadeProjectile*>(info.GetInflictor()))
{
flags |= 1<<da::protobuf::KILL_BY_GRENADE;
FillProtoBufVector(pbKillInfo->mutable_grenade_position(), info.GetInflictor()->GetAbsOrigin());
}
if (info.GetDamageType() == DMG_CLUB)
flags |= 1<<da::protobuf::KILL_BY_BRAWL;
if (pAttacker == pVictim)
flags |= 1<<da::protobuf::KILL_IS_SUICIDE;
pbVictimInfo->set_flags(flags);
CDAPlayer* pPlayerAttacker = ToDAPlayer(pAttacker);
if (pPlayerAttacker && pPlayerAttacker != pVictim)
FillPlayerInfo(pbKillInfo->mutable_killer(), pPlayerAttacker);
}
void CDataManager::AddCharacterChosen(const char* pszCharacter)
{
CUtlMap<CUtlString, int>::IndexType_t it = d->m_asCharactersChosen.Find(CUtlString(pszCharacter));
if (it == d->m_asCharactersChosen.InvalidIndex())
d->m_asCharactersChosen.Insert(CUtlString(pszCharacter), 1);
else
d->m_asCharactersChosen[it]++;
}
void CDataManager::AddWeaponChosen(DAWeaponID eWeapon)
{
d->m_aeWeaponsChosen.AddToTail(eWeapon);
}
void CDataManager::AddSkillChosen(SkillID eSkill)
{
d->m_aeSkillsChosen.AddToTail(eSkill);
}
da::protobuf::PlayerList* CDataManager::GetPlayerInList(CDAPlayer* pPlayer)
{
if (pPlayer->IsBot())
return NULL;
CSteamID ID;
pPlayer->GetSteamID(&ID);
if (!ID.IsValid())
return NULL;
if (ID.GetEUniverse() != k_EUniversePublic)
return NULL;
if (ID.GetEAccountType() != k_EAccountTypeIndividual)
return NULL;
CUtlMap<AccountID_t, class da::protobuf::PlayerList*>::IndexType_t it = d->m_apPlayerList.Find(ID.GetAccountID());
if (it == d->m_apPlayerList.InvalidIndex())
{
it = d->m_apPlayerList.Insert(ID.GetAccountID(), new da::protobuf::PlayerList());
da::protobuf::PlayerList* pbPlayerInfo = d->m_apPlayerList[it];
pbPlayerInfo->set_accountid(ID.GetAccountID());
pbPlayerInfo->set_name(pPlayer->GetPlayerName());
}
return d->m_apPlayerList[it];
}
void CDataManager::AddStyle(CDAPlayer* pPlayer, float flStyle)
{
da::protobuf::PlayerList* pbPlayerInfo = GetPlayerInList(pPlayer);
if (!pbPlayerInfo)
return;
pbPlayerInfo->set_style(pbPlayerInfo->style() + flStyle);
}
void CDataManager::ClientConnected(AccountID_t eAccountID)
{
// ClientConnected is called for every non-bot client every time a map loads, even with changelevel.
// So we have to eliminate duplicate connections.
CUtlMap<AccountID_t, char>::IndexType_t it = m_aiConnectedClients.Find(eAccountID);
if (it == m_aiConnectedClients.InvalidIndex() || m_aiConnectedClients[it] == 0)
{
// This client was not previously in the list, so he has truly connected.
if (it == m_aiConnectedClients.InvalidIndex())
{
// This client has not disconnected and reconnected.
// We want to eliminate repeated connections as extra information.
d->z.m_iConnections++;
d->z.m_iUniquePlayers++;
m_aiConnectedClients.Insert(eAccountID, 1);
}
else
m_aiConnectedClients[it] = 1;
}
}
void CDataManager::ClientDisconnected(AccountID_t eAccountID)
{
// This is called only once for each client, never just for changelevels.
CUtlMap<AccountID_t, char>::IndexType_t it = m_aiConnectedClients.Find(eAccountID);
if (it == m_aiConnectedClients.InvalidIndex())
m_aiConnectedClients.Insert(eAccountID, 0);
else
m_aiConnectedClients[it] = 0;
d->z.m_iDisconnections++;
}
void CDataManager::SetTeamplay(bool bOn)
{
d->z.m_bTeamplay = bOn;
}
void CDataManager::VotePassed(const char* pszIssue, const char* pszDetails)
{
int i = d->m_aVoteResults.AddToTail();
d->m_aVoteResults[i].m_bResult = true;
d->m_aVoteResults[i].m_sIssue = pszIssue;
d->m_aVoteResults[i].m_sDetails = pszDetails;
}
void CDataManager::VoteFailed(const char* pszIssue)
{
int i = d->m_aVoteResults.AddToTail();
d->m_aVoteResults[i].m_bResult = false;
d->m_aVoteResults[i].m_sIssue = pszIssue;
}
ConVar da_data_enabled("da_data_enabled", "1", 0, "Turn on and off data sending.");
void CDataManager::LevelShutdownPostEntity()
{
if (!gpGlobals->maxClients)
return;
if (!da_data_enabled.GetBool())
return;
// This function is sometimes called twice for every LevelInitPostEntity(), so remove duplicates.
if (!m_bLevelStarted)
return;
// If the thread is executing, then wait for it to finish
if ( m_pSendData )
m_pSendData->WaitForFinishAndRelease();
m_pSendData = ThreadExecute( &SendData, (CFunctor**)NULL, 0 );
m_bLevelStarted = false;
}
bool CDataManager::IsSendingData()
{
return !!m_pSendData;
}
void CDataManager::FillProtoBuffer(da::protobuf::GameData* pbGameData)
{
pbGameData->set_da_version(atoi(DA_VERSION));
pbGameData->set_map_name(STRING(gpGlobals->mapname));
pbGameData->set_map_time(gpGlobals->curtime - d->z.m_flStartTime);
#ifdef _DEBUG
pbGameData->set_debug(true);
#else
pbGameData->set_debug(false);
#endif
pbGameData->set_cheats(d->z.m_bCheated);
const ConVar* pHostname = cvar->FindVar( "hostname" );
pbGameData->set_server_name(pHostname->GetString());
pbGameData->set_timestamp((unsigned)time(NULL));
pbGameData->set_connections(d->z.m_iConnections);
pbGameData->set_disconnections(d->z.m_iDisconnections);
pbGameData->set_unique_players_this_map(d->z.m_iUniquePlayers);
pbGameData->set_teamplay(d->z.m_bTeamplay);
pbGameData->set_thirdperson_active(d->z.m_iThirdPersonActive);
pbGameData->set_thirdperson_inactive(d->z.m_iThirdPersonInactive);
pbGameData->set_vr_active(d->z.m_iVRActive);
pbGameData->set_vr_inactive(d->z.m_iVRInactive);
pbGameData->set_platform_windows(d->z.m_iWindows);
pbGameData->set_platform_linux(d->z.m_iLinux);
pbGameData->set_platform_osx(d->z.m_iMac);
google::protobuf::RepeatedPtrField<da::protobuf::Vector>* pPositions = pbGameData->mutable_positions()->mutable_position();
size_t iDataSize = d->m_avecPlayerPositions.Count();
pPositions->Reserve(iDataSize);
for (size_t i = 0; i < iDataSize; i++)
FillProtoBufVector(pPositions->Add(), d->m_avecPlayerPositions[i]);
google::protobuf::RepeatedPtrField<std::string>* pCharacters = pbGameData->mutable_characters_chosen();
iDataSize = d->m_asCharactersChosen.Count();
pCharacters->Reserve(iDataSize);
for (CUtlMap<CUtlString, int>::IndexType_t it = d->m_asCharactersChosen.FirstInorder(); it != d->m_asCharactersChosen.InvalidIndex(); it = d->m_asCharactersChosen.NextInorder(it))
{
for (int i = 0; i < d->m_asCharactersChosen[it]; i++)
pCharacters->Add()->assign(d->m_asCharactersChosen.Key(it).String());
}
google::protobuf::RepeatedPtrField<std::string>* pWeapons = pbGameData->mutable_weapons_chosen_s();
iDataSize = d->m_aeWeaponsChosen.Count();
pWeapons->Reserve(iDataSize);
for (size_t i = 0; i < iDataSize; i++)
pWeapons->Add()->assign(WeaponIDToAlias(d->m_aeWeaponsChosen[i]));
google::protobuf::RepeatedPtrField<std::string>* pSkills = pbGameData->mutable_skills_chosen_s();
iDataSize = d->m_aeSkillsChosen.Count();
pSkills->Reserve(iDataSize);
for (size_t i = 0; i < iDataSize; i++)
pSkills->Add()->assign(SkillIDToAlias(d->m_aeSkillsChosen[i]));
google::protobuf::RepeatedPtrField<da::protobuf::VoteResult>* pVotes = pbGameData->mutable_votes();
iDataSize = d->m_aVoteResults.Count();
pVotes->Reserve(iDataSize);
for (size_t i = 0; i < iDataSize; i++)
{
da::protobuf::VoteResult* pVR = pVotes->Add();
pVR->set_result(d->m_aVoteResults[i].m_bResult);
pVR->set_issue(d->m_aVoteResults[i].m_sIssue);
pVR->set_details(d->m_aVoteResults[i].m_sDetails);
}
google::protobuf::RepeatedPtrField<da::protobuf::KillInfo>* pKillInfos = pbGameData->mutable_kill_details();
iDataSize = d->m_apKillInfos.Count();
pKillInfos->Reserve(iDataSize);
for (size_t i = 0; i < iDataSize; i++)
pKillInfos->Add()->CopyFrom(*d->m_apKillInfos[i]);
google::protobuf::RepeatedPtrField<da::protobuf::PlayerList>* pPlayerList = pbGameData->mutable_player_list();
iDataSize = d->m_apPlayerList.Count();
pPlayerList->Reserve(iDataSize);
for (CUtlMap<AccountID_t, class da::protobuf::PlayerList*>::IndexType_t it = d->m_apPlayerList.FirstInorder(); it != d->m_apPlayerList.InvalidIndex(); it = d->m_apPlayerList.NextInorder(it))
pPlayerList->Add()->CopyFrom(*d->m_apPlayerList[it]);
ClearData();
}
void CDataManager::ClearData()
{
// Delete the data container and re-create it every level
// to remove the possibility of old data remaining.
delete d;
d = new CDataContainer();
}
CDataManager::CDataContainer::~CDataContainer()
{
m_apKillInfos.PurgeAndDeleteElements();
m_apPlayerList.PurgeAndDeleteElements();
}
#endif
| 28.732601 | 191 | 0.744327 | Black-Stormy |
21fa2ada2fcfcd2c34a4efcdaf37f072bb8e6e6f | 2,579 | cpp | C++ | test/test_preprocessor.cpp | sakshikakde/human-detector-and-tracker | 04e1fd08b858ababfa4fa91da8306890ef1d7d00 | [
"MIT"
] | null | null | null | test/test_preprocessor.cpp | sakshikakde/human-detector-and-tracker | 04e1fd08b858ababfa4fa91da8306890ef1d7d00 | [
"MIT"
] | 3 | 2021-10-16T05:46:37.000Z | 2021-10-18T22:16:20.000Z | test/test_preprocessor.cpp | sakshikakde/human-detector-and-tracker | 04e1fd08b858ababfa4fa91da8306890ef1d7d00 | [
"MIT"
] | 2 | 2021-10-06T02:52:31.000Z | 2021-10-06T05:16:28.000Z | /**
* MIT License
*
* Copyright (c) 2021 Anubhav Paras, Sakshi Kakde, Siddharth Telang
*
* 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 test_preprocessor.cpp
* @author Anubhav Paras (anubhav@umd.edu)
* @author Sakshi Kakde (sakshi@umd.edu)
* @author Siddharth Telang (stelang@umd.edu)
* @brief test file for preprocessor.cpp
* @version 0.1
* @date 2021-10-25
*
* @copyright Copyright (c) 2021
*
*/
#include <gtest/gtest.h>
#include <string>
#include <opencv2/opencv.hpp>
#include <preprocessor.hpp>
TEST(preprocessor_test, image_resize) {
std::string test_path =
"../data/testdata/unit_test_data/pos/FudanPed00028.png";
PreProcessor preProcessor;
cv::Mat image = cv::imread(test_path);
cv::Size originalSize = image.size();
cv::Size expectedSize = cv::Size(100, 100);
preProcessor.resize(image, image, expectedSize);
EXPECT_TRUE(image.size().height != originalSize.height);
EXPECT_EQ(image.size().height, expectedSize.height);
EXPECT_TRUE(image.size().width != originalSize.width);
EXPECT_EQ(image.size().width, expectedSize.width);
}
TEST(preprocessor_test, image_resize_no_resize) {
std::string test_path =
"../data/testdata/unit_test_data/pos/FudanPed00028.png";
PreProcessor preProcessor;
cv::Mat image = cv::imread(test_path);
cv::Size originalSize = image.size();
preProcessor.resize(image, image, cv::Size());
EXPECT_EQ(image.size().height, originalSize.height);
EXPECT_EQ(image.size().width, originalSize.width);
}
| 36.323944 | 81 | 0.724699 | sakshikakde |
21fae4fa506214d1580df4ba2c9ecb7631f6b632 | 21,586 | cpp | C++ | frame_tests.cpp | draghan/memoryframe | da573df30613759d61537ca78b5a41a248c2a811 | [
"MIT"
] | null | null | null | frame_tests.cpp | draghan/memoryframe | da573df30613759d61537ca78b5a41a248c2a811 | [
"MIT"
] | null | null | null | frame_tests.cpp | draghan/memoryframe | da573df30613759d61537ca78b5a41a248c2a811 | [
"MIT"
] | null | null | null | /*
This file is distributed under MIT License.
Copyright (c) 2019 draghan
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 "external/Catch2/single_include/catch2/catch.hpp"
#include "Frame.hpp"
FrameEntity getFrame()
{
byte_t value = 0b01010101;
FrameEntity x{value};
return x;
}
TEST_CASE("Memory: frame entity bitwise operators", "[memory][Frame]")
{
SECTION("~")
{
constexpr byte_t expectedValue = ~0b11110000u;
FrameEntity f{byte_t{0b11110000}};
f = ~f;
REQUIRE(f == expectedValue);
REQUIRE(f[0] == 1);
REQUIRE(f[7] == 0);
}
SECTION("&")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first & second;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f = f & g;
REQUIRE(f == expectedValue);
}
SECTION("|")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first | second;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f = f | g;
REQUIRE(f == expectedValue);
}
SECTION("^")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first ^second;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f = f ^ g;
REQUIRE(f == expectedValue);
}
SECTION(">>")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first >> 2;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f = f >> byte_t(2);
REQUIRE(f == expectedValue);
}
SECTION("<<")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first << 2;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f = f << byte_t(2);
REQUIRE(f == expectedValue);
}
SECTION("&=")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first & second;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f &= g;
REQUIRE(f == expectedValue);
}
SECTION("^=")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first ^second;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f ^= g;
REQUIRE(f == expectedValue);
}
SECTION("|=")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first | second;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f |= g;
REQUIRE(f == expectedValue);
}
SECTION(">>=")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first >> 2;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f >>= byte_t(2);
REQUIRE(f == expectedValue);
}
SECTION("<<=")
{
constexpr byte_t first = 0b11100011u;
constexpr byte_t second = 0b00100001u;
constexpr byte_t expectedValue = first << 2;
FrameEntity f{byte_t{first}};
FrameEntity g{byte_t{second}};
f <<= byte_t(2);
REQUIRE(f == expectedValue);
}
}
TEST_CASE("Memory: frame entity clip", "[memory][Frame]")
{
SECTION("Clipping - valid range")
{
// index: 7654 3210
constexpr byte_t original = 0b1110'0011;
constexpr byte_t expected_0_1 = 0b0000'0011;
constexpr byte_t expected_0_6 = 0b0110'0011;
constexpr byte_t expected_1_7 = 0b0111'0001;
constexpr byte_t expected_3_7 = 0b0001'1100;
constexpr byte_t expected_2_5 = 0b0000'1000;
constexpr byte_t expected_0_0 = 0b0000'0001;
constexpr byte_t expected_7_7 = 0b0000'0001;
constexpr byte_t expected_0_7 = 0b1110'0011;
const FrameEntity f{original};
REQUIRE(f(0, 1) == expected_0_1);
REQUIRE(f(0, 6) == expected_0_6);
REQUIRE(f(1, 7) == expected_1_7);
REQUIRE(f(3, 7) == expected_3_7);
REQUIRE(f(2, 5) == expected_2_5);
REQUIRE(f(2, 5) == expected_2_5);
REQUIRE(f(0, 0) == expected_0_0);
REQUIRE(f(7, 7) == expected_7_7);
REQUIRE(f(0, 7) == expected_0_7);
}
SECTION("Clipping - invalid range")
{
const FrameEntity f{};
REQUIRE_THROWS(f(-1, 5));
REQUIRE_THROWS(f(5, 4));
REQUIRE_THROWS(f(4, 8));
REQUIRE_THROWS(f(8, 8));
REQUIRE_THROWS(f(8, 15));
REQUIRE_THROWS(f(0, 8));
REQUIRE_THROWS(f(20, 15));
}
}
TEST_CASE("Memory: frame entity comparison", "[memory][Frame]")
{
SECTION("notEquality FrameEntities")
{
byte_t value = 0b01010101;
FrameEntity x{value};
FrameEntity y{x};
y[0] = 0;
y[1] = 0;
REQUIRE(x != y);
}
SECTION("Equality FrameEntities")
{
byte_t value = 0b01010101;
FrameEntity x{value};
FrameEntity y{x};
REQUIRE(x == y);
}
SECTION("Equality bitset")
{
byte_t value = 0b01010101;
FrameEntity x{value};
std::bitset<8> y;
y[0] = 1;
y[1] = 0;
y[2] = 1;
y[3] = 0;
y[4] = 1;
y[5] = 0;
y[6] = 1;
y[7] = 0;
REQUIRE(x == y);
}
}
TEST_CASE("Memory: frame entity assignment", "[memory][Frame]")
{
SECTION("value")
{
byte_t value = 0b01010101;
FrameEntity x;
x = value;
REQUIRE(x[0] == 1);
REQUIRE(x[1] == 0);
REQUIRE(x[2] == 1);
REQUIRE(x[3] == 0);
REQUIRE(x[4] == 1);
REQUIRE(x[5] == 0);
REQUIRE(x[6] == 1);
REQUIRE(x[7] == 0);
}
SECTION("bitset")
{
byte_exposed_t value = 0b01010101;
FrameEntity f{};
f = value;
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 0);
REQUIRE(f[2] == 1);
REQUIRE(f[3] == 0);
REQUIRE(f[4] == 1);
REQUIRE(f[5] == 0);
REQUIRE(f[6] == 1);
REQUIRE(f[7] == 0);
}
// SECTION("string")
// {
// std::string value = "0b01010101";
// FrameEntity f{};
// f = value;
// REQUIRE(f[0] == 1);
// REQUIRE(f[1] == 0);
// REQUIRE(f[2] == 1);
// REQUIRE(f[3] == 0);
// REQUIRE(f[4] == 1);
// REQUIRE(f[5] == 0);
// REQUIRE(f[6] == 1);
// REQUIRE(f[7] == 0);
// }
}
TEST_CASE("Memory: frame entity conversion", "[memory][Frame]")
{
SECTION("To value")
{
byte_t value = 0b01010101;
FrameEntity x{value};
byte_t converted = x;
REQUIRE(value == converted);
}
SECTION("To bitset")
{
byte_t value = 0b01010101;
FrameEntity x{value};
byte_exposed_t converted = x;
REQUIRE(value == converted.to_ulong());
}
// SECTION("To string")
// {
// byte_t value = 0xAF;
// FrameEntity x{value};
//
// std::string converted = x;
// REQUIRE(converted == "af");
// }
}
TEST_CASE("Memory: frame entity creation", "[memory][Frame]")
{
SECTION("Default ctor")
{
FrameEntity byteZero{};
FrameEntity byteOne{true};
REQUIRE(byteOne[0] == true);
REQUIRE(byteOne[1] == true);
REQUIRE(byteOne[2] == true);
REQUIRE(byteOne[3] == true);
REQUIRE(byteOne[4] == true);
REQUIRE(byteOne[5] == true);
REQUIRE(byteOne[6] == true);
REQUIRE(byteOne[7] == true);
REQUIRE_THROWS(byteOne[8]);
REQUIRE(byteZero[0] == false);
REQUIRE(byteZero[1] == false);
REQUIRE(byteZero[2] == false);
REQUIRE(byteZero[3] == false);
REQUIRE(byteZero[4] == false);
REQUIRE(byteZero[5] == false);
REQUIRE(byteZero[6] == false);
REQUIRE(byteZero[7] == false);
REQUIRE_THROWS(byteZero[8]);
}
SECTION("Creation from single value")
{
byte_t value = 0b01010101;
FrameEntity f{value};
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 0);
REQUIRE(f[2] == 1);
REQUIRE(f[3] == 0);
REQUIRE(f[4] == 1);
REQUIRE(f[5] == 0);
REQUIRE(f[6] == 1);
REQUIRE(f[7] == 0);
}
SECTION("Creation from bitset")
{
byte_exposed_t value = 0b01010101;
FrameEntity f{value};
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 0);
REQUIRE(f[2] == 1);
REQUIRE(f[3] == 0);
REQUIRE(f[4] == 1);
REQUIRE(f[5] == 0);
REQUIRE(f[6] == 1);
REQUIRE(f[7] == 0);
}
// SECTION("Creation from string")
// {
// std::string value = "0b01010101";
// FrameEntity f{value};
// REQUIRE(f[0] == 1);
// REQUIRE(f[1] == 0);
// REQUIRE(f[2] == 1);
// REQUIRE(f[3] == 0);
// REQUIRE(f[4] == 1);
// REQUIRE(f[5] == 0);
// REQUIRE(f[6] == 1);
// REQUIRE(f[7] == 0);
// }
SECTION("Copy constructor")
{
byte_t value = 0b01010101;
FrameEntity x{value};
FrameEntity f{x};
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 0);
REQUIRE(f[2] == 1);
REQUIRE(f[3] == 0);
REQUIRE(f[4] == 1);
REQUIRE(f[5] == 0);
REQUIRE(f[6] == 1);
REQUIRE(f[7] == 0);
REQUIRE(x[0] == 1);
REQUIRE(x[1] == 0);
REQUIRE(x[2] == 1);
REQUIRE(x[3] == 0);
REQUIRE(x[4] == 1);
REQUIRE(x[5] == 0);
REQUIRE(x[6] == 1);
REQUIRE(x[7] == 0);
}
SECTION("Move constructor")
{
FrameEntity f{getFrame()};
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 0);
REQUIRE(f[2] == 1);
REQUIRE(f[3] == 0);
REQUIRE(f[4] == 1);
REQUIRE(f[5] == 0);
REQUIRE(f[6] == 1);
REQUIRE(f[7] == 0);
}
}
TEST_CASE("Memory: frame insert", "[memory][Frame]")
{
SECTION("Insert array")
{
Frame f{1, 2};
uint8_t g[]{3, 4, 5};
f.insert(g, 2);
REQUIRE(f.size() == 4);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 3);
REQUIRE(f[3] == 4);
}
SECTION("Insert frame")
{
Frame f{1, 2};
Frame g{3, 4};
f.insert(g);
REQUIRE(f.size() == 4);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 3);
REQUIRE(f[3] == 4);
}
SECTION("Insert vector of values")
{
Frame f{1, 2};
std::vector<uint8_t> v{3, 4};
f.insert(v);
REQUIRE(f.size() == 4);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 3);
REQUIRE(f[3] == 4);
}
SECTION("Insert single value")
{
Frame f{1, 2};
f.insert(6);
REQUIRE(f.size() == 3);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 6);
}
}
void expect1_2_3(const uint8_t table[], size_t size)
{
REQUIRE(size == 3);
REQUIRE(table[0] == 1);
REQUIRE(table[1] == 2);
REQUIRE(table[2] == 3);
}
TEST_CASE("readme example")
{
// constructing from std-like containers:
const std::vector<uint8_t> v{0xDE, 0xAD, 0xBE, 0xEF};
const Frame f{v};
// access to byte range:
const Frame beef = f(2, 3);
REQUIRE(beef == Frame{0xBE, 0xEF}); // ...and constructing from initializer list
// access to single byte:
const FrameEntity ad = f[1];
REQUIRE(ad == 0xAD); // ...and comparing bytes
// access to single bit (0 - least significant bit):
REQUIRE(ad == 0b10101101);
REQUIRE(ad[0] == 1); // ...and comparing bits
REQUIRE(ad[1] == 0);
REQUIRE(ad[2] == 1);
REQUIRE(ad[3] == 1);
// access to range of bits:
REQUIRE(ad(0, 3) == 0b1101);
// appending frames:
auto fbeef = f + beef;
REQUIRE(fbeef == Frame{0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0xEF});
fbeef += 0;
REQUIRE(fbeef == Frame{0xDE, 0xAD, 0xBE, 0xEF, 0xBE, 0xEF, 0x00});
// get second, third and fourth bits from third byte:
auto foo = f[3](1, 3);
REQUIRE(foo == 0b111);
}
TEST_CASE("Memory: reverse", "[memory][Frame]")
{
SECTION("reverse")
{
Frame f{1, 2, 3};
f.reverse();
REQUIRE(f.size() == 3);
REQUIRE(f[0] == 3);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 1);
}
}
TEST_CASE("Memory: data access", "[memory][Frame]")
{
SECTION("Data access")
{
Frame f{1, 2, 3};
expect1_2_3(f.data(), f.size());
}
}
TEST_CASE("Memory: frame indexing", "[memory][Frame]")
{
SECTION("Bit indexing")
{
Frame f{0b11000000, 0b10000011};
REQUIRE(f[0][0] == 0);
REQUIRE(f[0][1] == 0);
REQUIRE(f[0][2] == 0);
REQUIRE(f[0][3] == 0);
REQUIRE(f[0][4] == 0);
REQUIRE(f[0][5] == 0);
REQUIRE(f[0][6] == 1);
REQUIRE(f[0][7] == 1);
REQUIRE(f[1][0] == 1);
REQUIRE(f[1][1] == 1);
REQUIRE(f[1][2] == 0);
REQUIRE(f[1][3] == 0);
REQUIRE(f[1][4] == 0);
REQUIRE(f[1][5] == 0);
REQUIRE(f[1][6] == 0);
REQUIRE(f[1][7] == 1);
}
SECTION("Byte indexing")
{
Frame f{0b11000000, 0b11000011};
REQUIRE(f[0] == 0b11000000);
REQUIRE(f[1] == 0b11000011);
}
}
TEST_CASE("Memory: frame splice", "[memory][Frame]")
{
SECTION("Valid splice")
{
Frame f{0, 1, 2, 3};
REQUIRE(f(0, 2) == Frame{0, 1, 2});
REQUIRE(f(1, 3) == Frame{1, 2, 3});
REQUIRE(f(0, 3) == Frame{0, 1, 2, 3});
REQUIRE(f(0, 0) == Frame{0});
}
SECTION("Checking splice")
{
Frame f{0, 1, 2, 3};
REQUIRE(f.spliceIsValid(0, 3));
REQUIRE(!f.spliceIsValid(3, 0));
REQUIRE(!f.spliceIsValid(0, 4));
REQUIRE(!f.spliceIsValid(4, 5));
REQUIRE(!f.spliceIsValid(4, 4));
}
SECTION("Invalid splice")
{
Frame f{0, 1, 2, 3};
REQUIRE_THROWS(f(3, 0));
REQUIRE_THROWS(f(0, 4));
REQUIRE_THROWS(f(4, 5));
REQUIRE_THROWS(f(4, 4));
}
}
TEST_CASE("Memory: frame place at", "[memory][Frame]")
{
SECTION("Insert array")
{
Frame f{1, 2};
uint8_t g[]{3, 4};
f.placeAt(1, g, 2);
REQUIRE(f.size() == 3);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 3);
REQUIRE(f[2] == 4);
}
SECTION("Insert frame")
{
Frame f{1, 2};
Frame g{3, 4};
f.placeAt(2, g);
REQUIRE(f.size() == 4);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 3);
REQUIRE(f[3] == 4);
}
SECTION("Insert vector of values")
{
Frame f{1, 2};
std::vector<uint8_t> v{3, 4};
f.placeAt(3, v);
REQUIRE(f.size() == 5);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 0);
REQUIRE(f[3] == 3);
REQUIRE(f[4] == 4);
}
SECTION("Insert single value")
{
Frame f{1, 2};
f.placeAt(2, 6);
REQUIRE(f.size() == 3);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 6);
f.placeAt(5, 55);
REQUIRE(f.size() == 6);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 6);
REQUIRE(f[3] == 0);
REQUIRE(f[4] == 0);
REQUIRE(f[5] == 55);
}
}
TEST_CASE("Memory: frame concatenation", "[memory][Frame]")
{
SECTION("+= single value")
{
Frame f{1, 2};
f += 5;
REQUIRE(f.size() == 3);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 5);
}
SECTION("+= braced")
{
Frame f{1, 2};
f += {3, 4};
REQUIRE(f.size() == 4);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 3);
REQUIRE(f[3] == 4);
}
SECTION("+= vector")
{
Frame f{1, 2};
std::vector<uint8_t> g{3, 4};
f += g;
REQUIRE(f.size() == 4);
REQUIRE(g.size() == 2);
REQUIRE(g[0] == 3);
REQUIRE(g[1] == 4);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 3);
REQUIRE(f[3] == 4);
}
SECTION("+= Frame")
{
Frame f{1, 2};
Frame g{3, 4};
f += g;
REQUIRE(f.size() == 4);
REQUIRE(g.size() == 2);
REQUIRE(g[0] == 3);
REQUIRE(g[1] == 4);
REQUIRE(f[0] == 1);
REQUIRE(f[1] == 2);
REQUIRE(f[2] == 3);
REQUIRE(f[3] == 4);
}
}
TEST_CASE("Memory: frame comparison", "[memory][Frame]")
{
SECTION("Frames equality")
{
Frame f{{1, 2}};
Frame g{1, 2};
REQUIRE(f.size() == 2);
REQUIRE(g.size() == 2);
REQUIRE(f == g);
}
SECTION("Equality with table")
{
Frame f{{1, 2}};
uint8_t v[] = {1, 2};
REQUIRE(f == Frame(v, 2));
}
SECTION("Equality with vector")
{
Frame f{{1, 2}};
std::vector<uint8_t> v{1, 2};
REQUIRE(f == v);
}
SECTION("Frames inequality")
{
Frame f{{1, 2}};
Frame g{2, 2};
REQUIRE(f.size() == 2);
REQUIRE(g.size() == 2);
REQUIRE(f != g);
}
SECTION("Inequality with table")
{
Frame f{{1, 2}};
uint8_t v[] = {2, 2};
REQUIRE(f != Frame(v, 2));
}
SECTION("Ineuality with vector")
{
Frame f{{1, 2}};
std::vector<uint8_t> v{2, 2};
REQUIRE(f != v);
}
}
TEST_CASE("Memory: frame creation", "[memory][Frame]")
{
SECTION("Default ctor")
{
Frame f{};
REQUIRE(f.size() == 0);
REQUIRE_THROWS(f[0] == static_cast<uint8_t>(1));
}
SECTION("Copy ctor")
{
Frame f{{1, 2}};
Frame g{f};
REQUIRE(f.size() == 2);
REQUIRE(g.size() == 2);
REQUIRE(f == g);
REQUIRE(f[0] == g[0]);
REQUIRE(f[1] == g[1]);
REQUIRE_THROWS(f[2]);
REQUIRE_THROWS(g[2]);
// change value in one of them:
REQUIRE_NOTHROW(g[0] = 15);
REQUIRE(f[0] != g[0]);
REQUIRE(f[0] == 1);
REQUIRE(g[0] == 15);
REQUIRE(f[1] == g[1]);
}
SECTION("Default filling")
{
Frame zero(5, false);
Frame one(5, true);
std::bitset<8> bits;
bool value = false;
bits[0] = value;
bits[1] = value;
bits[2] = value;
bits[3] = value;
bits[4] = value;
bits[5] = value;
bits[6] = value;
bits[7] = value;
REQUIRE(zero[0] == bits);
REQUIRE(zero[1] == bits);
REQUIRE(zero[2] == bits);
REQUIRE(zero[3] == bits);
REQUIRE(zero[4] == bits);
REQUIRE_THROWS(zero[5] == bits);
value = true;
bits[0] = value;
bits[1] = value;
bits[2] = value;
bits[3] = value;
bits[4] = value;
bits[5] = value;
bits[6] = value;
bits[7] = value;
REQUIRE(one[0] == bits);
REQUIRE(one[1] == bits);
REQUIRE(one[2] == bits);
REQUIRE(one[3] == bits);
REQUIRE(one[4] == bits);
REQUIRE_THROWS(one[5] == bits);
}
SECTION("From vector of bytes")
{
std::vector<uint8_t> bytes{10, 20, 50, 100};
Frame f{bytes};
REQUIRE(f.size() == bytes.size());
REQUIRE(f == bytes);
}
SECTION("From braced values")
{
Frame f{10, 20, 50, 100};
REQUIRE(f.size() == 4);
REQUIRE(f[0] == 10);
REQUIRE(f[1] == 20);
REQUIRE(f[2] == 50);
REQUIRE(f[3] == 100);
}
SECTION("From array")
{
uint8_t array[] = {10, 20, 50, 100};
Frame f{array, 4};
REQUIRE(f.size() == 4);
REQUIRE(f[0] == 10);
REQUIRE(f[1] == 20);
REQUIRE(f[2] == 50);
REQUIRE(f[3] == 100);
}
}
| 23.412148 | 84 | 0.493236 | draghan |
1d01a2f71775db78545546cad9c421aed8f3b28c | 2,021 | cpp | C++ | tests/test2.cpp | kosirev/lab5 | f898ac9253e01b45879fd75f05d6f348516d7762 | [
"MIT"
] | null | null | null | tests/test2.cpp | kosirev/lab5 | f898ac9253e01b45879fd75f05d6f348516d7762 | [
"MIT"
] | null | null | null | tests/test2.cpp | kosirev/lab5 | f898ac9253e01b45879fd75f05d6f348516d7762 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <Stack2.hpp>
TEST(Stack2, correct_primitive) {
Stack2<int> stack;
stack.push(10);
int value1 = 15, value2 = 33;
stack.push_emplace(value1);
EXPECT_EQ(value1, stack.pop());
EXPECT_EQ(10, stack.head());
stack.push_emplace(value2);
EXPECT_EQ(value2, stack.head());
stack.push(1200);
EXPECT_EQ(1200, stack.head());
}
class My_class {
public:
My_class() {
value_i = 0;
value_f = 0.1;
value_s = "0";
}
My_class(int a, double b, std::string c){
value_i = a;
value_f = b;
value_s = c;
}
int value_i;
double value_f;
std::string value_s;
};
TEST(Stack2, correct_my_class) {
Stack2<My_class> stack;
My_class my_class1;
My_class my_class2(15, 1.1, "1");
stack.push_emplace(my_class1);
EXPECT_EQ(my_class1.value_f, stack.head().value_f);
EXPECT_EQ(my_class1.value_s, stack.head().value_s);
EXPECT_EQ(my_class1.value_i, stack.head().value_i);
stack.push_emplace(my_class2);
EXPECT_EQ(my_class2.value_f, stack.head().value_f);
EXPECT_EQ(my_class2.value_s, stack.head().value_s);
EXPECT_EQ(my_class2.value_i, stack.pop().value_i);
EXPECT_EQ(my_class1.value_f, stack.head().value_f);
EXPECT_EQ(my_class1.value_s, stack.head().value_s);
EXPECT_EQ(my_class1.value_i, stack.head().value_i);
}
TEST(Stack2, emplace) {
Stack2<My_class> stack;
int value_i = 5;
double value_f = 5.5;
std::string value_s = "Hi";
stack.push_emplace(100, 10.1, "102");
stack.push_emplace(value_i, value_f, value_s);
EXPECT_EQ(value_i, stack.head().value_i);
EXPECT_EQ(value_f, stack.head().value_f);
EXPECT_EQ(value_s, stack.pop().value_s);
EXPECT_EQ(100, stack.head().value_i);
EXPECT_EQ(10.1, stack.head().value_f);
EXPECT_EQ("102", stack.head().value_s);
}
TEST(Stack2, type_traits) {
EXPECT_TRUE(std::is_move_constructible<int>::value);
EXPECT_TRUE(std::is_move_assignable<int>::value);
EXPECT_TRUE(std::is_move_constructible<My_class>::value);
EXPECT_TRUE(std::is_move_assignable<My_class>::value);
} | 28.464789 | 59 | 0.703117 | kosirev |
1d048fb4fbb4d23044d47e06cc09edf76f25e8c6 | 826 | cpp | C++ | OculusPlatformBP/Source/OculusPlatformBP/Private/OBP_TeamArray.cpp | InnerLoopLLC/OculusPlatformBP | d4bfb5568c56aa781e2ee76896d69a0ade1f57a2 | [
"MIT"
] | 29 | 2020-10-22T13:46:23.000Z | 2022-03-18T14:32:51.000Z | OculusPlatformBP/Source/OculusPlatformBP/Private/OBP_TeamArray.cpp | InnerLoopLLC/OculusPlatformBP | d4bfb5568c56aa781e2ee76896d69a0ade1f57a2 | [
"MIT"
] | 2 | 2021-05-06T18:14:39.000Z | 2021-05-25T01:12:15.000Z | OculusPlatformBP/Source/OculusPlatformBP/Private/OBP_TeamArray.cpp | InnerLoopLLC/OculusPlatformBP | d4bfb5568c56aa781e2ee76896d69a0ade1f57a2 | [
"MIT"
] | null | null | null | // OculusPlatformBP plugin by InnerLoop LLC 2020
#include "OBP_TeamArray.h"
// --------------------
// Initializers
// --------------------
UOBP_TeamArray::UOBP_TeamArray(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
}
// --------------------
// OVR_TeamArray.h
// --------------------
UOBP_Team* UOBP_TeamArray::GetElement(int32 Index)
{
#if PLATFORM_MINOR_VERSION >= 39
auto Team = NewObject<UOBP_Team>();
Team->ovrTeamHandle = ovr_TeamArray_GetElement(ovrTeamArrayHandle, Index);
return Team;
#else
OBP_PlatformVersionError("TeamArray::GetElement", "1.39");
return nullptr;
#endif
}
int32 UOBP_TeamArray::GetSize()
{
#if PLATFORM_MINOR_VERSION >= 39
return ovr_TeamArray_GetSize(ovrTeamArrayHandle);
#else
OBP_PlatformVersionError("TeamArray::GetSize", "1.39");
return 0;
#endif
} | 21.736842 | 75 | 0.690073 | InnerLoopLLC |
1d05d60365d501f0507835f1138b237bbb3d9428 | 4,123 | cc | C++ | src/core/CommandLine.cc | estepanov-lvk/runos | 9b856b8a829539bb667156178d283ffc4ef3cf32 | [
"Apache-2.0"
] | 41 | 2015-02-09T10:04:35.000Z | 2021-11-21T06:34:38.000Z | src/core/CommandLine.cc | estepanov-lvk/runos | 9b856b8a829539bb667156178d283ffc4ef3cf32 | [
"Apache-2.0"
] | 31 | 2015-03-04T14:02:36.000Z | 2020-12-11T09:23:16.000Z | src/core/CommandLine.cc | estepanov-lvk/runos | 9b856b8a829539bb667156178d283ffc4ef3cf32 | [
"Apache-2.0"
] | 42 | 2015-02-13T14:24:00.000Z | 2021-11-09T12:04:38.000Z | /*
* Copyright 2019 Applied Research Center for Computer Networks
*
* 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 "CommandLine.hpp"
#include <thread>
#include <iostream>
#include <utility> // pair
#include <cstdio>
#include <cctype> // isspace
#include <QCoreApplication>
#include <histedit.h>
#include "Config.hpp"
namespace runos {
REGISTER_APPLICATION(CommandLine, {""})
struct CommandLine::implementation {
std::unique_ptr<EditLine, decltype(&el_end)> el
{ nullptr, &el_end };
std::unique_ptr<History, decltype(&history_end)> hist
{ history_init(), &history_end };
std::vector< std::pair<cli_pattern, cli_command> >
commands;
HistEvent hev;
bool keep_reading { true };
bool handle(const char* cmd, int len);
void run();
};
struct command_error : public std::runtime_error
{
using std::runtime_error::runtime_error;
};
struct skip_command : public std::exception { };
CommandLine::CommandLine()
: impl(new implementation)
{ }
CommandLine::~CommandLine() = default;
static const char* prompt(EditLine*)
{
return "runos> ";
}
void CommandLine::init(Loader*, const Config& rootConfig)
{
const auto& config = config_cd(rootConfig, "cli");
history(impl->hist.get(), &impl->hev, H_SETSIZE,
config_get(config, "history-size", 800));
const char* argv0 = QCoreApplication::arguments().at(0).toLatin1().data();
impl->el.reset(el_init(argv0, stdin, stdout, stderr));
el_set(impl->el.get(), EL_PROMPT,
&prompt);
el_set(impl->el.get(), EL_EDITOR,
config_get(config, "editor", "emacs").c_str());
el_set(impl->el.get(), EL_HIST, history,
impl->hist.get());
}
void CommandLine::startUp(Loader*)
{
std::thread {&implementation::run, impl.get()}.detach();
}
void CommandLine::register_command(cli_pattern&& spec, cli_command&& fn)
{
impl->commands.emplace_back(std::move(spec), std::move(fn));
}
void CommandLine::error_impl(std::string && msg)
{
throw command_error(msg);
}
void CommandLine::skip()
{
throw skip_command();
}
void CommandLine::implementation::run()
{
for (;keep_reading;) {
int len;
const char* line = el_gets(el.get(), &len);
if (line == nullptr)
break;
if (handle(line, len)) {
if (not std::isspace(*line)) {
history(hist.get(), &hev, H_ENTER, line);
}
}
}
}
bool CommandLine::implementation::handle(const char* line, int len)
{
if (line == nullptr)
return false;
const char* end = line + len;
// skip whitespace
while (line < end && std::isspace(*line))
++line;
while (line < end && std::isspace(*(end-1)))
--end;
// empty line
if (line == end)
return false;
for (const auto & cmd : commands) {
std::cmatch match;
if (not std::regex_match(line, end, match, cmd.first))
continue;
try {
cmd.second(match);
return true;
} catch (skip_command&) {
continue;
} catch (command_error& ex) {
std::cerr << "Error: " << ex.what() << std::endl;
return false;
} catch (std::exception& ex) {
std::cerr << "Uncaught exception: " << ex.what() << std::endl;
return false;
} catch (...) {
std::cerr << "Uncaught exception";
return false;
}
}
std::cerr << std::string(line, end)
<< ": no such command" << std::endl;
return false;
}
} // namespace runos
| 24.541667 | 78 | 0.60878 | estepanov-lvk |
1d068c53c2c54186aaadfcfb5ac858ebc6ceb418 | 456 | hpp | C++ | include/VBE/graphics/RenderTarget.hpp | Dirbaio/VBE | 539d222dcbbf565ab64dc5d2463b310fd4b75873 | [
"MIT"
] | null | null | null | include/VBE/graphics/RenderTarget.hpp | Dirbaio/VBE | 539d222dcbbf565ab64dc5d2463b310fd4b75873 | [
"MIT"
] | null | null | null | include/VBE/graphics/RenderTarget.hpp | Dirbaio/VBE | 539d222dcbbf565ab64dc5d2463b310fd4b75873 | [
"MIT"
] | null | null | null | #ifndef RENDERTARGET_HPP
#define RENDERTARGET_HPP
#include <VBE/graphics/RenderTargetBase.hpp>
class RenderTarget : public RenderTargetBase {
public:
RenderTarget(unsigned int width, unsigned int height);
~RenderTarget();
void setTexture(RenderTargetBase::Attachment a, Texture2D* tex);
void setBuffer(RenderTargetBase::Attachment a, RenderBuffer* buff);
Texture2D* getTexture(RenderTargetBase::Attachment a);
};
#endif // RENDERTARGET_HPP
| 25.333333 | 69 | 0.787281 | Dirbaio |
1d096066ff2a26e8048c83dbe153adee14bb3153 | 4,233 | cpp | C++ | ironstack_agent/gui/output.cpp | zteo-phd-software/ironstack | 649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0 | [
"BSD-3-Clause"
] | null | null | null | ironstack_agent/gui/output.cpp | zteo-phd-software/ironstack | 649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0 | [
"BSD-3-Clause"
] | null | null | null | ironstack_agent/gui/output.cpp | zteo-phd-software/ironstack | 649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0 | [
"BSD-3-Clause"
] | null | null | null | #include <string.h>
#include "output.h"
weak_ptr<gui_controller> output::controller;
atomic_bool output::log_printf{false};
output::loglevel output::loglevel_threshold{output::loglevel::WARNING};
mutex output::fp_lock;
FILE* output::fp = nullptr;
// sets up output to point to a controller
void output::init(const shared_ptr<gui_controller>& controller_) {
controller = controller_;
}
// shuts down the gui controller, if any
void output::shutdown() {
shared_ptr<gui_controller> current_controller = controller.lock();
if (current_controller != nullptr) {
current_controller->shutdown();
current_controller = nullptr;
controller = current_controller;
}
}
// attempts to start logging output to file
bool output::start_log(const string& filename, bool log_printf_, loglevel loglevel_display_threshold) {
log_printf = log_printf_;
lock_guard<mutex> g(fp_lock);
if (fp != nullptr) {
fclose(fp);
}
fp = fopen(filename.c_str(), "a");
if (fp != nullptr) {
char timestamp[128];
get_timestamp(timestamp);
fprintf(fp, "### LOG STARTED [%s] ###\n", timestamp);
} else {
log_printf = false;
}
loglevel_threshold = loglevel_display_threshold;
return fp == nullptr;
}
// stops logging to file
void output::stop_log() {
lock_guard<mutex> g(fp_lock);
if (fp != nullptr) {
fclose(fp);
}
fp = nullptr;
log_printf = false;
}
// prints to either stdout or through the GUI controller
void output::printf(const char* fmt, ...) {
char buf[10240];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf)-1, fmt, args);
shared_ptr<gui_controller> current_controller = controller.lock();
if (current_controller != nullptr) {
current_controller->printf("%s", buf);
} else {
::printf("%s", buf);
}
// log to file if required
if (log_printf) {
log("%s", buf);
}
}
// logs directly to file. does not appear on display. no loglevel associated.
void output::log(const char* fmt, ...) {
char buf[10240];
char timestamp[128];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf)-33, fmt, args);
// get timestamp
get_timestamp(timestamp);
// write to file
lock_guard<mutex> g(fp_lock);
if (fp != nullptr) {
fprintf(fp, "[%s] %s", timestamp, buf);
// append a newline if it wasn't given
int len = strlen(buf);
if (len == 0 || buf[len-1] != '\n') {
fprintf(fp, "\n");
}
}
}
// logs directly to file, with loglevel
void output::log(const loglevel& level, const char* fmt, ...) {
char buf[10240];
char timestamp[128];
va_list args;
va_start(args, fmt);
vsnprintf(buf, sizeof(buf)-33, fmt, args);
// get timestamp
get_timestamp(timestamp);
// generate output string
char result[1024+128+2];
switch (level) {
case loglevel::VERBOSE:
{
snprintf(result, sizeof(result), "[%s] VERBOSE: %s", timestamp, buf);
break;
}
case loglevel::INFO:
{
snprintf(result, sizeof(result), "[%s] INFO: %s", timestamp, buf);
break;
}
case loglevel::WARNING:
{
snprintf(result, sizeof(result), "[%s] WARNING: %s", timestamp, buf);
break;
}
case loglevel::CRITICAL:
{
snprintf(result, sizeof(result), "[%s] CRITICAL: %s", timestamp, buf);
break;
}
case loglevel::ERROR:
{
snprintf(result, sizeof(result), "[%s] ERROR: %s", timestamp, buf);
break;
}
case loglevel::BUG:
{
snprintf(result, sizeof(result), "[%s] BUG: %s", timestamp, buf);
break;
}
}
// check if newline was written. if not, add one.
int len = strlen(buf);
if (len == 0 || buf[len-1] != '\n') {
strcat(buf, "\n");
}
// write to file
{
lock_guard<mutex> g(fp_lock);
if (fp != nullptr) {
fprintf(fp, "%s", result);
}
}
// display to output as required
int loglevel_threshold_num = (int) loglevel_threshold;
int loglevel_current_num = (int) level;
if (loglevel_current_num >= loglevel_threshold_num) {
shared_ptr<gui_controller> current_controller = controller.lock();
if (current_controller != nullptr) {
current_controller->printf("%s", result);
} else {
::printf("%s", result);
}
}
}
// generates a timestamp
void output::get_timestamp(char* timestamp) {
time_t rawtime;
struct tm* info;
time(&rawtime);
info = localtime(&rawtime);
strftime(timestamp, 128, "%d/%b %H:%M:%S", info);
}
| 22.396825 | 103 | 0.665722 | zteo-phd-software |
1d101c36e2656c2e2405b153d27510e444dc4552 | 2,730 | hpp | C++ | MATLAB/attitude_filter/helper_functions/conversion.hpp | kylekrol/psim | a4817117189f0f5597452076e6e138f70f51d4e8 | [
"MIT"
] | 5 | 2020-04-11T06:53:46.000Z | 2022-01-05T05:39:11.000Z | MATLAB/attitude_filter/helper_functions/conversion.hpp | kylekrol/psim | a4817117189f0f5597452076e6e138f70f51d4e8 | [
"MIT"
] | 201 | 2019-09-05T03:46:21.000Z | 2022-01-08T04:44:16.000Z | MATLAB/attitude_filter/helper_functions/conversion.hpp | kylekrol/psim | a4817117189f0f5597452076e6e138f70f51d4e8 | [
"MIT"
] | 10 | 2019-10-12T17:24:34.000Z | 2022-02-25T01:20:14.000Z | #include "mex.hpp"
#include "mexAdapter.hpp"
#include <gnc/attitude_estimator.hpp>
#include <lin.hpp>
using namespace matlab::data;
/**
* @brief Create a matlab array from lin vec object
*
* @tparam N the dimension of the lin::vector
* @tparam T the type of lin::vector
* @param f a matlab array factory
* @param lin_vec input lin::vector to be copied from
* @return TypedArray<T> a matlab array
*/
template<lin::size_t N, typename T>
TypedArray<T> create_from_lin_vec(ArrayFactory& f, const lin::Vector<T, N>& lin_vec){
TypedArray<T> ret = f.createArray<T>({N, 1});
for(int r = 0; r < N; r++){
ret[r][0] = lin_vec(r);
}
return ret;
}
/**
* @brief Create an array of matlab arrays from a list of lin::vec arrays
*
* @tparam N length of each sub array
* @tparam T type of input element
* @param f matlab array factory
* @param lin_vec input list of lin::vecs
* @param L number of lin::vecs
* @return TypedArray<T> returned array of arrays
*/
template<lin::size_t N, typename T>
TypedArray<T> create_from_lin_vec_arr(ArrayFactory& f, const lin::Vector<T, N>* lin_vec, size_t L){
TypedArray<T> ret = f.createArray<T>({N, 1, L});
for(int i = 0; i < L; i++){
for(int r = 0; r < N; r++){
ret[r][0][i] = (lin_vec[i])(r);
}
}
return ret;
}
/**
* @brief Create a from lin mat object
*
* @tparam R rows
* @tparam C columns
* @tparam T input element type
* @param f matlab array factory
* @param lin_mat input lin matrix
* @return TypedArray<T> matlab output matrix
*/
template<lin::size_t R, lin::size_t C, typename T>
TypedArray<T> create_from_lin_mat(ArrayFactory& f, const lin::Matrix<T, R, C>& lin_mat){
TypedArray<T> ret = f.createArray<T>({R, C});
for(int r = 0; r < R; r++){
for(int c = 0; c < C; c++)
ret[r][c] = lin_mat(r, c);
}
return ret;
}
/**
* @brief copy a matlab array into a lin::Vec
*
* @tparam N array length
* @tparam T element type
* @param lin_vec lin::vec output reference
* @param arr matlab array input
*/
template<lin::size_t N, typename T>
void typed_array_to_lin_vec(lin::Vector<T, N>& lin_vec, matlab::data::Array& arr){
for (int i = 0; i<N; i++) {
lin_vec(i) = arr[i];
}
}
/**
* @brief Copy a matlab matrix into a lin::matrix
*
* @tparam T element type
* @tparam R rows
* @tparam C columns
* @param lin_mat lin::matrix output reference
* @param arr matlab array input
*/
template<typename T, lin::size_t R, lin::size_t C>
void typed_array_to_lin_mat(lin::Matrix<T, R, C>& lin_mat, matlab::data::Array& arr){
for( int r = 0; r<R; r++){
for( int c = 0; c<C; c++){
lin_mat(r, c) = arr[r][c];
}
}
} | 27.575758 | 99 | 0.621978 | kylekrol |
1d151b23993319bc256654ed6eec6d324b07e039 | 448 | cpp | C++ | Framework/Sources/o2/Assets/Meta.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 181 | 2015-12-09T08:53:36.000Z | 2022-03-26T20:48:39.000Z | Framework/Sources/o2/Assets/Meta.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 29 | 2016-04-22T08:24:04.000Z | 2022-03-06T07:06:28.000Z | Framework/Sources/o2/Assets/Meta.cpp | zenkovich/o2 | cdbf10271f1bf0f3198c8005b13b66e6ca13a9db | [
"MIT"
] | 13 | 2018-04-24T17:12:04.000Z | 2021-11-12T23:49:53.000Z | #include "o2/stdafx.h"
#include "Meta.h"
#include "o2/Assets/Asset.h"
namespace o2
{
AssetMeta::AssetMeta() :
mId(0)
{}
AssetMeta::~AssetMeta()
{}
const Type* AssetMeta::GetAssetType() const
{
return &TypeOf(Asset);
}
bool AssetMeta::IsEqual(AssetMeta* other) const
{
return GetAssetType() == other->GetAssetType() && mId == other->mId;
}
const UID& AssetMeta::ID() const
{
return mId;
}
}
DECLARE_CLASS(o2::AssetMeta);
| 14 | 70 | 0.65625 | zenkovich |
1d175c9aa45e1dddb65d3437382488753a1d169f | 118 | cpp | C++ | StaticEx/Hello.cpp | jaespo/Nifty | 6114eb7250776c136d3ae7757b70388caa6930a5 | [
"Unlicense"
] | null | null | null | StaticEx/Hello.cpp | jaespo/Nifty | 6114eb7250776c136d3ae7757b70388caa6930a5 | [
"Unlicense"
] | null | null | null | StaticEx/Hello.cpp | jaespo/Nifty | 6114eb7250776c136d3ae7757b70388caa6930a5 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include "Hello.h"
void nsHello::CHello::SayHello()
{
std::cout << "Hello World" << std::endl;
}
| 16.857143 | 41 | 0.652542 | jaespo |
1d1e40bc0889f5eb9ae46d628d5a19c36b439b01 | 1,315 | cpp | C++ | C++_Mavros/amov_mavro service _3.cpp | Chentao2000/practice_code | aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c | [
"Apache-2.0"
] | 4 | 2022-01-07T13:07:48.000Z | 2022-02-08T04:46:02.000Z | C++_Mavros/amov_mavro service _3.cpp | Chentao2000/practice_code | aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c | [
"Apache-2.0"
] | null | null | null | C++_Mavros/amov_mavro service _3.cpp | Chentao2000/practice_code | aa4fb6bbc26ac1ea0fb40e6e0889050b7e9f096c | [
"Apache-2.0"
] | null | null | null | // 通过前面两节的学习,我们对mavros操作无人机有了深刻的理解,无非就是通过ROS去取得以下当前的飞行状态,然后发送控制让他执行
// 当前在控制的时候,你可以选取很多方式,加速度方式,位置方式,姿态方式,都是可行的
// 那么这一节,将会围绕两个服务进行我们讲解,(模式切换 解锁
// -------------------------------------------------------------------
// 1. arming Service 加解锁服务
// 消息名称 : mavros/cmd/arming
// 类型名称 : mavros_msgs::CommandBool
// 类型所在头文件 :mavros_msgs / CommandBool.h
// 服务请求参数 :
// bool success //是否能执行成功
// uint8 result // 错误信息
// 注意: 在ros中所有服务参数都在 xxx.request 中,所有返回状态都在 xxx.response 中
// 如果我们想要解锁,那么代码可以如下来写
// ros :: init ( argc ,argv,"offb_node " );
// ros :: NodeHandle nh;
// ros::SeviceClient arming_client
// nh.serviceClient < mavros_msgs ;; CommandBool >("mavros / cmd / arming")
// mavros_msgs::CommandBool>("mavros/cmd/arming");
// mavros_msgs::CommandBool arm_cmd;
// arm_cmd.request.value = true //注意这里是 arm_cmd.request.value ,不是arm_cmd.valuse
// arming_client.call (arm.cmd);
// 执行完毕以后返回信息在:
// arm_cmd.response.success
// arm_cmd.response.result
// 2. 模式切换
// 消息名称:mavros/set_mode
// 类型名称:mavros_msgs::SetMode
// 类型所在头文件 : mavros_msgs / SetMode.h
// 服务请求参数
// uint8 base_mode //基本参数 如果custom_mode 不为空 此项无效
// string custom_mode // 通常我们使用custom_mode 如果想进入offboard 模式
// 在PX4 中赋值 “OFFBOARD ”,在 APM 中 "GUIDED"
// 服务返回的结果:
// bool mode _sent // 为true 表示正确切换 | 26.836735 | 83 | 0.656274 | Chentao2000 |
918e4c89682e9fa1fa47324ffe0082c9e49a1df8 | 1,361 | hpp | C++ | library/ATF/CRecallRequest.hpp | lemkova/Yorozuya | f445d800078d9aba5de28f122cedfa03f26a38e4 | [
"MIT"
] | 29 | 2017-07-01T23:08:31.000Z | 2022-02-19T10:22:45.000Z | library/ATF/CRecallRequest.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 90 | 2017-10-18T21:24:51.000Z | 2019-06-06T02:30:33.000Z | library/ATF/CRecallRequest.hpp | kotopes/Yorozuya | 605c97d3a627a8f6545cc09f2a1b0a8afdedd33a | [
"MIT"
] | 44 | 2017-12-19T08:02:59.000Z | 2022-02-24T23:15:01.000Z | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <CCharacter.hpp>
#include <CPlayer.hpp>
#include <CUnmannedTraderSchedule.hpp>
START_ATF_NAMESPACE
#pragma pack(push, 8)
struct CRecallRequest
{
typedef CUnmannedTraderSchedule::STATE STATE;
unsigned __int16 m_usID;
STATE m_eState;
CPlayer *m_pkOwner;
unsigned int m_dwOwnerSerial;
CPlayer *m_pkDest;
unsigned int m_dwDestSerial;
unsigned int m_dwCloseTime;
bool m_bRecallParty;
bool m_bStone;
bool m_bBattleModeUse;
public:
CRecallRequest(uint16_t usID);
void ctor_CRecallRequest(uint16_t usID);
void Clear();
void Close(bool bDone);
uint16_t GetID();
struct CPlayer* GetOwner();
bool IsBattleModeUse();
bool IsClose();
bool IsRecallAfterStoneState();
bool IsRecallParty();
bool IsTimeOut();
bool IsWait();
char Recall(struct CPlayer* pkDest, bool bStone);
char Regist(struct CPlayer* pkObj, struct CCharacter* pkDest, bool bRecallParty, bool bStone, bool bBattleModeUse);
~CRecallRequest();
void dtor_CRecallRequest();
};
#pragma pack(pop)
END_ATF_NAMESPACE
| 30.244444 | 123 | 0.65687 | lemkova |
919fbd6e647511321d8ba925e23bfa04047ea51d | 132 | cpp | C++ | spoj/test.cpp | Shisir/Online-Judge | e58c32eeb7ca18a19cc2a83ef016f9c3b124370a | [
"MIT"
] | null | null | null | spoj/test.cpp | Shisir/Online-Judge | e58c32eeb7ca18a19cc2a83ef016f9c3b124370a | [
"MIT"
] | null | null | null | spoj/test.cpp | Shisir/Online-Judge | e58c32eeb7ca18a19cc2a83ef016f9c3b124370a | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
while(scanf("%d",&n) && n!=42)printf("%d\n",n);
return 0;
} | 13.2 | 48 | 0.568182 | Shisir |
91a1a16f9e4ff73019dab4dc11692cd1228714f1 | 1,579 | cpp | C++ | codebook/code/String/Suffix_Array.cpp | NCTU-PCCA/NCTU_Yggdrasill | 4f086c9737502f69044f574514cf191d536aaf22 | [
"MIT"
] | null | null | null | codebook/code/String/Suffix_Array.cpp | NCTU-PCCA/NCTU_Yggdrasill | 4f086c9737502f69044f574514cf191d536aaf22 | [
"MIT"
] | null | null | null | codebook/code/String/Suffix_Array.cpp | NCTU-PCCA/NCTU_Yggdrasill | 4f086c9737502f69044f574514cf191d536aaf22 | [
"MIT"
] | null | null | null | //should initialize s and n first
#define N 301000
using namespace std;
char s[N]; //string=s,suffix array=sar,longest common prefix=lcp
int rk[2][N],id[2][N];
int n,p;
int cnt[N];
int len[N],od[N],sar[N];
inline int sr(int i,int t){ //rank of shifted position
return i+t<n?rk[p][i+t]:-1;
}
inline bool check_same(int i,int j,int t){
return rk[p][i]==rk[p][j]&&sr(i,t)==sr(j,t);
}
bool cmp(int i,int j){
return s[i]<s[j];
}
void sa(){ //length of array s
int i,t,now,pre;
memset(cnt,0,sizeof(cnt));
for(i=0;i<n;i++){
id[p][i]=i;
rk[p][i]=s[i];
cnt[s[i]]++;
}
for(i=1;i<128;i++) cnt[i]+=cnt[i-1];
sort(id[p],id[p]+n,cmp);
for(t=1;t<n;t<<=1){
//least significant bit is already sorted
for(i=n-1;i>=0;i--){
now=id[p][i]-t;
if(now>=0) id[p^1][--cnt[rk[p][now]]]=now;
}
for(i=n-t;i<n;i++){
id[p^1][--cnt[rk[p][i]]]=i;
}
memset(cnt,0,sizeof(cnt));
now=id[p^1][0];
rk[p^1][now]=0;
cnt[0]++;
for(i=1;i<n;i++){
pre=now;
now=id[p^1][i];
if(check_same(pre,now,t)){
rk[p^1][now]=rk[p^1][pre];
}
else{
rk[p^1][now]=rk[p^1][pre]+1;
}
cnt[rk[p^1][now]]++;
}
p^=1;
if(rk[p][now]==n-1) break;
for(i=1;i<n;i++) cnt[i]+=cnt[i-1];
}
memcpy(sar,id[p],sizeof(sar));
}
void lcp(){
int i,l,pre;
for(i=0;i<n;i++) od[sar[i]]=i;
for(i=0;i<n;i++){
if(i) l=len[od[i-1]]?len[od[i-1]]-1:0;
else l=0;
if(od[i]){
pre=sar[od[i]-1];
while(pre+l<n&&i+l<n&&s[pre+l]==s[i+l]) l++;
len[od[i]]=l;
}
else len[0]=0;
}
}
| 21.930556 | 64 | 0.494617 | NCTU-PCCA |
91a3d0a576955b145efac47137e5976f3a2eb01a | 5,305 | cpp | C++ | learningC++/learningHandleClass.cpp | QiJunHu/newToCpp | 02988845fdb2e818608d4362e0d4ca0e91818509 | [
"MIT"
] | 2 | 2015-12-03T15:05:52.000Z | 2019-05-12T16:08:26.000Z | learningC++/learningHandleClass.cpp | QiJunHu/learningRecord | 02988845fdb2e818608d4362e0d4ca0e91818509 | [
"MIT"
] | null | null | null | learningC++/learningHandleClass.cpp | QiJunHu/learningRecord | 02988845fdb2e818608d4362e0d4ca0e91818509 | [
"MIT"
] | null | null | null | #include <iostream>
#include <iterator>
#include <algorithm>
#include <fstream>
#include <list>
#include <string>
#include <vector>
#include <set>
#include<utility>
#include<functional>
#include<stdexcept>
//base class
class Item_base
{
friend std::ostream& operator<<(std::ostream &, Item_base &);
public:
Item_base(const std::string& book="",double sale_price=0.0):isbn(book),price(sale_price) {}
std::string book() const { return isbn;}
virtual Item_base* clone() const
{
return new Item_base(*this);
}
virtual double net_price(std::size_t n) const
{
return price*n;
}
//debug function controlled by flag parameter
virtual void debug1(bool flag) const
{
if(flag)
std::cout<<"ISBN: "<<isbn<<std::endl
<<"Price: "<<price<<std::endl;
}
//debug function controlled by flag member
virtual void debug2() const
{
if(flag)
std::cout<<"ISBN: "<<isbn<<std::endl
<<"Price: "<<price<<std::endl;
}
virtual ~Item_base() {}
protected:
double price; // price of a book
bool flag;
private:
std::string isbn; // isbn of a book
};
std::ostream& operator<<(std::ostream & os,Item_base& ib)
{
os<<"\tUsing operator<<(std::ostream &,Item_base&);"<<std::endl
<<"\tVisit Item_base's book():\t"<<ib.isbn<<std::endl
<<"\tVisit Item_base's net_price():"
<<"3 "<<ib.book()<<" , the price is:\t"
<<ib.net_price(3)<<std::endl;
return os;
}
//derived class
class Bult_Item :public Item_base
{
friend std::ostream & operator<<(std::ostream & ,Bult_Item &);
public:
Bult_Item(const std::string& book="",double sale_price=0.0,std::size_t qty=0,double disc=0.0):Item_base(book,sale_price),min_qty(qty),discount(disc) {}
Bult_Item* clone() const
{
return new Bult_Item(*this);
}
double net_price(std::size_t cnt) const
{
if(cnt > min_qty)
return cnt*(1-discount)*price;
}
void debug1(bool flag) const
{
if(flag)
std::cout<<"ISBN: "<<book()<<std::endl
<<"PriceL "<<price<<std::endl
<<"Min_quantiry: "<<min_qty<<std::endl
<<"Discount Rate: "<<discount<<std::endl;
}
void debug2() const
{
if(flag)
std::cout<<"ISBN: "<<book()<<std::endl
<<"PriceL "<<price<<std::endl
<<"Min_quantiry: "<<min_qty<<std::endl
<<"Discount Rate: "<<discount<<std::endl;
}
~Bult_Item() {}
private:
std::size_t min_qty; // min quantity of books to have a discount
double discount; //discount rate
};
std::ostream & operator<<(std::ostream & os,Bult_Item & bi)
{
os<<"\tUsing operator<<(std::ostream &,Bulk_Item);"<<std::endl
<<"\tVisit Item_base's book():\t"<<bi.book()<<std::endl
<<"\tVisit Item_base's net_price():"
<<"5 "<<bi.book()<<" , the price is:\t"
<<bi.net_price(5)<<std::endl;
return os;
}
//handle class
class Sales_item
{
public:
//default constructor:unbound handle
Sales_item():p(0),use( new std::size_t(1)) {}
//attaches a handle to copy of the Item_base object
Sales_item(const Item_base & item):p(item.clone()),use(new std::size_t(1)) {}
//copy control members to manage the use count and pointers
Sales_item(const Sales_item & i):p(i.p),use(i.use) { ++ use; }
Sales_item& operator=(const Sales_item&);
~Sales_item() { decr_use();}
const Item_base* operator->() const
{
if(p)
return p;
else throw std::logic_error("unbound Sales_item");
}
const Item_base operator*() const
{
if(p)
return *p;
else throw std::logic_error("unbound Sales_item");
}
private:
Item_base *p; //pointer to shared item
std::size_t * use ; // pointer to a shared use count( reference count);
void decr_use()
{
if(--*use == 0)
{
delete p;
delete use;
}
}
};
Sales_item& Sales_item::operator=(const Sales_item& rhs)
{
++*rhs.use;
decr_use();
p = rhs.p;
use = rhs.use;
return * this;
}
//compare function of Sales_Item for multiset to use
inline bool compare(const Sales_item& rh1,const Sales_item& rh2)
{
return rh1->book() < rh2->book() ;
}
//really class used in real business
class Basket
{
typedef bool (*Comp) (const Sales_item&,const Sales_item&);
public:
typedef std::multiset<Sales_item,Comp> set_type;
typedef set_type::size_type size_type;
typedef set_type::const_iterator const_iter;
//constructor
Basket():items(compare) {}
void add_item(const Sales_item& item)
{
items.insert(item);
}
size_type size(const Sales_item& i) const
{
return items.count(i);
}
double total() const;
private:
std::multiset<Sales_item,Comp> items;
};
double Basket::total() const
{
double sum = 0.0;
for(const_iter i = items.begin() ; i != items.end() ; i = items.upper_bound(*i))
{
sum += (*i)->net_price(items.count(*i));
}
return sum;
}
//test code
int main()
{
return 0;
}
| 20.248092 | 155 | 0.575683 | QiJunHu |
91a932492725a8bcf00c640b3273c80c6f61e9ab | 2,291 | cpp | C++ | common-lib/modules/general/src/hebench_math_utils.cpp | hebench/frontend | 891652bbf7fd6e3aae1020f5cfc30b52e1c491f9 | [
"Apache-2.0"
] | 9 | 2021-12-16T18:34:15.000Z | 2022-03-29T08:45:35.000Z | common-lib/modules/general/src/hebench_math_utils.cpp | hebench/frontend | 891652bbf7fd6e3aae1020f5cfc30b52e1c491f9 | [
"Apache-2.0"
] | 13 | 2021-11-04T20:35:39.000Z | 2022-02-25T20:06:35.000Z | common-lib/modules/general/src/hebench_math_utils.cpp | hebench/frontend | 891652bbf7fd6e3aae1020f5cfc30b52e1c491f9 | [
"Apache-2.0"
] | 2 | 2021-12-14T20:09:50.000Z | 2022-02-02T17:17:55.000Z |
// Copyright (C) 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
#include <algorithm>
#include <stdexcept>
#include "../include/hebench_math_utils.h"
namespace hebench {
namespace Utilities {
namespace Math {
double computePercentile(const double *data, std::size_t count, double percentile)
{
// uses percentile formula from R
double rank = std::clamp(percentile, 0.0, 1.0) * (count - 1);
std::uint64_t rank_i = static_cast<std::uint64_t>(rank);
double rank_f = rank - rank_i;
return data[rank_i] + rank_f * (data[rank_i + 1] - data[rank_i]);
}
//------------------------
// class ComponentCounter
//------------------------
ComponentCounter::ComponentCounter(std::vector<std::size_t> component_sizes) :
m_count(component_sizes.size()), m_sizes(component_sizes)
{
for (std::size_t i = 0; i < component_sizes.size(); ++i)
if (component_sizes[i] <= 0)
throw std::invalid_argument("Invalid zero entry: 'component_sizes'.");
}
std::size_t ComponentCounter::getCountLinear() const
{
std::size_t retval = m_count.empty() ? 0 : m_count.back();
for (std::size_t i = m_count.size() - 1; i > 0; --i)
retval = m_count[i - 1] + m_sizes[i - 1] * retval;
return retval;
}
std::size_t ComponentCounter::getCountLinearReversed() const
{
std::size_t retval = m_count.empty() ? 0 : m_count[0];
for (std::size_t i = 1; i < m_count.size(); ++i)
retval = m_count[i] + m_sizes[i] * retval;
return retval;
}
bool ComponentCounter::inc()
{
bool overflow = true;
for (std::size_t i = 0; overflow && i < m_count.size(); ++i)
{
if (++m_count[i] >= m_sizes[i])
m_count[i] = 0;
else
overflow = false;
} // end for
return overflow;
}
bool ComponentCounter::dec()
{
bool overflow = true;
for (std::size_t i = 0; overflow && i < m_count.size(); ++i)
{
if (m_count[i] == 0)
m_count[i] = m_sizes[i] - 1;
else
{
--m_count[i];
overflow = false;
} // end else
} // end for
return overflow;
}
void ComponentCounter::reset()
{
std::fill(m_count.begin(), m_count.end(), 0);
}
} // namespace Math
} // namespace Utilities
} // namespace hebench
| 25.175824 | 82 | 0.591881 | hebench |
91ac4db899172ed17544ea028421e291f81a6353 | 3,788 | hpp | C++ | simpletest_signal.hpp | jonathanrlemos/simpletest | 0b0086279c756aa7bd14a40d907352233fc98313 | [
"MIT"
] | null | null | null | simpletest_signal.hpp | jonathanrlemos/simpletest | 0b0086279c756aa7bd14a40d907352233fc98313 | [
"MIT"
] | null | null | null | simpletest_signal.hpp | jonathanrlemos/simpletest | 0b0086279c756aa7bd14a40d907352233fc98313 | [
"MIT"
] | null | null | null | /** @file simpletest_signal.hpp
* @brief simpletest signal handler.
* @copyright Copyright (c) 2018 Jonathan Lemos
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
#ifndef __SIMPLETEST_SIGNAL_HPP
#define __SIMPLETEST_SIGNAL_HPP
#include <csetjmp>
#include <csignal>
#include <iostream>
namespace simpletest{
/**
* @brief An exception that indicates a signal was thrown.
*/
class SignalException : public std::runtime_error{
public:
/**
* @brief Constructs a SignalException.
*
* @param signo The signal code.
*/
SignalException(sig_atomic_t signo);
/**
* @brief Gets the signal code of this exception.
*/
sig_atomic_t getSignal() const;
private:
/**
* @brief The last signal code.
*/
sig_atomic_t signo;
};
/**
* @brief This class handles signals while it is active.
* Only one SignalHandler can be active in a thread at once.
*
* A singleton is not appropriate here, because this class's destructor is needed to stop capturing signals, and the destructor for a singleton is never called.
*/
class SignalHandler{
public:
/**
* @brief Instantiates a signal handler.
* Upon creation, this class will begin capturing SIGINT, SIGABRT, SIGSEGV, and SIGTERM.
*
* @exception std::logic_error A signal handler has already been instantiated in this thread.
*/
SignalHandler();
/**
* @brief Move constructor for SignalHandler.
*/
SignalHandler(SignalHandler&& other);
/**
* @brief Move assignment operator for SignalHandler.
*/
SignalHandler& operator=(SignalHandler&& other);
/**
* @brief Deleted copy constructor.
* There should only be one of this class, so it should not be copied;
*/
SignalHandler(const SignalHandler& other) = delete;
/**
* @brief Deleted copy assignment.
* There should only be one of this class, so it should not be copied.
*/
SignalHandler& operator=(const SignalHandler& val) = delete;
/**
* @brief Stops capturing signals.
*/
~SignalHandler();
/**
* @brief Gets the last signal thrown as an integer.
*
* @return 0 for no signal, SIG* for any of the other signals. The following is a list of signals caught. Any signal not on this list will have its default behavior.
* <br>
* <pre>
* 0 No signal
* SIGINT Interrupt from keyboard (Ctrl+C)
* SIGABRT abort() called
* SIGSEGV Invalid memory access.
* SIGTERM Default termination signal.
* </pre>
* <br>
*/
static sig_atomic_t lastSignal();
/**
* @brief Gets a string representation of a signal.
*/
static const char* signalToString(sig_atomic_t signo);
/**
* @brief Do not call directly. Use the ActivateSignalHandler() macro instead.
* Gets a reference to the jump buffer for use with the ActivateSignalHandler() macro.
*/
static jmp_buf& getBuf();
/**
* @brief Do not call this function directly. Use the ActivateSignalHandler() macro instead.
* True if the function should exit (a signal was called that should terminate the program.
*/
static bool shouldExit();
};
/**
* @brief Activates the signal handler, throwing an exception if a signal is thrown.
* This allows RAII cleanup to occur when a signal is thrown.
*/
#define ActivateSignalHandler(handler)\
/* returns 0 on its first call, returns signo (>0) when being jumped to through longjmp() */\
if (setjmp(simpletest::SignalHandler::getBuf())){\
/* SIGABRT, SIGINT, etc. */\
if (handler.shouldExit()){\
std::cerr << "Terminating program (" << simpletest::SignalHandler::signalToString(handler.lastSignal()) << ")" << std::endl;\
std::exit(1);\
}\
throw simpletest::SignalException(simpletest::SignalHandler::lastSignal());\
}\
/* requires the statement to have a semicolon at the end. */\
(void)0
}
#endif
| 27.057143 | 166 | 0.704329 | jonathanrlemos |
91b663f57316e5d21f13386e193c34792608dc8f | 29,467 | cpp | C++ | src/SyntaxTree.cpp | gitmodimo/cppgraphqlgen | bee89894653ad12f574f941d27c156354b1d497c | [
"MIT"
] | 52 | 2018-08-12T15:36:12.000Z | 2019-05-04T09:22:34.000Z | src/SyntaxTree.cpp | gitmodimo/cppgraphqlgen | bee89894653ad12f574f941d27c156354b1d497c | [
"MIT"
] | 30 | 2018-09-10T18:05:16.000Z | 2019-05-02T00:43:01.000Z | src/SyntaxTree.cpp | gitmodimo/cppgraphqlgen | bee89894653ad12f574f941d27c156354b1d497c | [
"MIT"
] | 13 | 2018-08-20T03:40:22.000Z | 2019-04-19T08:15:46.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "graphqlservice/GraphQLParse.h"
#include "graphqlservice/internal/Grammar.h"
#include "graphqlservice/internal/SyntaxTree.h"
#include <tao/pegtl/contrib/unescape.hpp>
#include <functional>
#include <iterator>
#include <memory>
#include <numeric>
#include <optional>
#include <sstream>
#include <utility>
using namespace std::literals;
namespace graphql {
namespace peg {
void ast_node::unescaped_view(std::string_view unescaped) noexcept
{
_unescaped = std::make_unique<unescaped_t>(unescaped);
}
std::string_view ast_node::unescaped_view() const
{
if (!_unescaped)
{
if (is_type<block_quote_content_lines>())
{
// Trim leading and trailing empty lines
const auto isNonEmptyLine = [](const std::unique_ptr<ast_node>& child) noexcept {
return child->is_type<block_quote_line>();
};
const auto itrEndRev = std::make_reverse_iterator(
std::find_if(children.cbegin(), children.cend(), isNonEmptyLine));
const auto itrRev = std::find_if(children.crbegin(), itrEndRev, isNonEmptyLine);
std::vector<std::optional<std::pair<std::string_view, std::string_view>>> lines(
std::distance(itrRev, itrEndRev));
std::transform(itrRev,
itrEndRev,
lines.rbegin(),
[](const std::unique_ptr<ast_node>& child) noexcept {
return (child->is_type<block_quote_line>() && !child->children.empty()
&& child->children.front()->is_type<block_quote_empty_line>()
&& child->children.back()->is_type<block_quote_line_content>())
? std::make_optional(std::make_pair(child->children.front()->string_view(),
child->children.back()->unescaped_view()))
: std::nullopt;
});
// Calculate the common indent
const auto commonIndent = std::accumulate(lines.cbegin(),
lines.cend(),
std::optional<size_t> {},
[](auto value, const auto& line) noexcept {
if (line)
{
const auto indent = line->first.size();
if (!value || indent < *value)
{
value = indent;
}
}
return value;
});
const auto trimIndent = commonIndent ? *commonIndent : 0;
std::string joined;
if (!lines.empty())
{
joined.reserve(std::accumulate(lines.cbegin(),
lines.cend(),
size_t {},
[trimIndent](auto value, const auto& line) noexcept {
if (line)
{
value += line->first.size() - trimIndent;
value += line->second.size();
}
return value;
})
+ lines.size() - 1);
bool firstLine = true;
for (const auto& line : lines)
{
if (!firstLine)
{
joined.append(1, '\n');
}
if (line)
{
joined.append(line->first.substr(trimIndent));
joined.append(line->second);
}
firstLine = false;
}
}
_unescaped = std::make_unique<unescaped_t>(std::move(joined));
}
else if (children.size() > 1)
{
std::string joined;
joined.reserve(std::accumulate(children.cbegin(),
children.cend(),
size_t(0),
[](size_t total, const std::unique_ptr<ast_node>& child) {
return total + child->string_view().size();
}));
for (const auto& child : children)
{
joined.append(child->string_view());
}
_unescaped = std::make_unique<unescaped_t>(std::move(joined));
}
else if (!children.empty())
{
_unescaped = std::make_unique<unescaped_t>(children.front()->string_view());
}
else if (has_content() && is_type<escaped_unicode>())
{
const auto content = string_view();
memory_input<> in(content.data(), content.size(), "escaped unicode");
std::string utf8;
utf8.reserve((content.size() + 1) / 2);
unescape::unescape_j::apply(in, utf8);
_unescaped = std::make_unique<unescaped_t>(std::move(utf8));
}
else
{
_unescaped = std::make_unique<unescaped_t>(std::string_view {});
}
}
return std::visit(
[](const auto& value) noexcept {
return std::string_view { value };
},
*_unescaped);
}
void ast_node::remove_content() noexcept
{
basic_node_t::remove_content();
_unescaped.reset();
}
using namespace tao::graphqlpeg;
template <typename Rule>
struct ast_selector : std::false_type
{
};
template <>
struct ast_selector<operation_type> : std::true_type
{
};
template <>
struct ast_selector<list_value> : std::true_type
{
};
template <>
struct ast_selector<object_field_name> : std::true_type
{
};
template <>
struct ast_selector<object_field> : std::true_type
{
};
template <>
struct ast_selector<object_value> : std::true_type
{
};
template <>
struct ast_selector<variable_value> : std::true_type
{
};
template <>
struct ast_selector<integer_value> : std::true_type
{
};
template <>
struct ast_selector<float_value> : std::true_type
{
};
template <>
struct ast_selector<escaped_unicode> : std::true_type
{
};
template <>
struct ast_selector<escaped_char> : std::true_type
{
static void transform(std::unique_ptr<ast_node>& n)
{
if (n->has_content())
{
const char ch = n->string_view().front();
switch (ch)
{
case '"':
n->unescaped_view("\""sv);
return;
case '\\':
n->unescaped_view("\\"sv);
return;
case '/':
n->unescaped_view("/"sv);
return;
case 'b':
n->unescaped_view("\b"sv);
return;
case 'f':
n->unescaped_view("\f"sv);
return;
case 'n':
n->unescaped_view("\n"sv);
return;
case 'r':
n->unescaped_view("\r"sv);
return;
case 't':
n->unescaped_view("\t"sv);
return;
default:
break;
}
}
throw parse_error("invalid escaped character sequence", n->begin());
}
};
template <>
struct ast_selector<string_quote_character> : std::true_type
{
static void transform(std::unique_ptr<ast_node>& n)
{
n->unescaped_view(n->string_view());
}
};
template <>
struct ast_selector<block_escape_sequence> : std::true_type
{
static void transform(std::unique_ptr<ast_node>& n)
{
n->unescaped_view(R"bq(""")bq"sv);
}
};
template <>
struct ast_selector<block_quote_content_lines> : std::true_type
{
};
template <>
struct ast_selector<block_quote_empty_line> : std::true_type
{
};
template <>
struct ast_selector<block_quote_line> : std::true_type
{
};
template <>
struct ast_selector<block_quote_line_content> : std::true_type
{
};
template <>
struct ast_selector<block_quote_character> : std::true_type
{
static void transform(std::unique_ptr<ast_node>& n)
{
n->unescaped_view(n->string_view());
}
};
template <>
struct ast_selector<string_value> : std::true_type
{
};
template <>
struct ast_selector<true_keyword> : std::true_type
{
};
template <>
struct ast_selector<false_keyword> : std::true_type
{
};
template <>
struct ast_selector<null_keyword> : std::true_type
{
};
template <>
struct ast_selector<enum_value> : std::true_type
{
};
template <>
struct ast_selector<field_name> : std::true_type
{
};
template <>
struct ast_selector<argument_name> : std::true_type
{
};
template <>
struct ast_selector<argument> : std::true_type
{
};
template <>
struct ast_selector<arguments> : std::true_type
{
};
template <>
struct ast_selector<directive_name> : std::true_type
{
};
template <>
struct ast_selector<directive> : std::true_type
{
};
template <>
struct ast_selector<directives> : std::true_type
{
};
template <>
struct ast_selector<variable> : std::true_type
{
};
template <>
struct ast_selector<scalar_name> : std::true_type
{
};
template <>
struct ast_selector<named_type> : std::true_type
{
};
template <>
struct ast_selector<list_type> : std::true_type
{
};
template <>
struct ast_selector<nonnull_type> : std::true_type
{
};
template <>
struct ast_selector<default_value> : std::true_type
{
};
template <>
struct ast_selector<operation_definition> : std::true_type
{
};
template <>
struct ast_selector<fragment_definition> : std::true_type
{
};
template <>
struct ast_selector<schema_definition> : std::true_type
{
};
template <>
struct ast_selector<scalar_type_definition> : std::true_type
{
};
template <>
struct ast_selector<object_type_definition> : std::true_type
{
};
template <>
struct ast_selector<interface_type_definition> : std::true_type
{
};
template <>
struct ast_selector<union_type_definition> : std::true_type
{
};
template <>
struct ast_selector<enum_type_definition> : std::true_type
{
};
template <>
struct ast_selector<input_object_type_definition> : std::true_type
{
};
template <>
struct ast_selector<directive_definition> : std::true_type
{
};
template <>
struct ast_selector<schema_extension> : std::true_type
{
};
template <>
struct ast_selector<scalar_type_extension> : std::true_type
{
};
template <>
struct ast_selector<object_type_extension> : std::true_type
{
};
template <>
struct ast_selector<interface_type_extension> : std::true_type
{
};
template <>
struct ast_selector<union_type_extension> : std::true_type
{
};
template <>
struct ast_selector<enum_type_extension> : std::true_type
{
};
template <>
struct ast_selector<input_object_type_extension> : std::true_type
{
};
template <typename Rule>
struct schema_selector : ast_selector<Rule>
{
};
template <>
struct schema_selector<description> : std::true_type
{
};
template <>
struct schema_selector<object_name> : std::true_type
{
};
template <>
struct schema_selector<interface_name> : std::true_type
{
};
template <>
struct schema_selector<union_name> : std::true_type
{
};
template <>
struct schema_selector<enum_name> : std::true_type
{
};
template <>
struct schema_selector<root_operation_definition> : std::true_type
{
};
template <>
struct schema_selector<interface_type> : std::true_type
{
};
template <>
struct schema_selector<input_field_definition> : std::true_type
{
};
template <>
struct schema_selector<input_fields_definition> : std::true_type
{
};
template <>
struct schema_selector<arguments_definition> : std::true_type
{
};
template <>
struct schema_selector<field_definition> : std::true_type
{
};
template <>
struct schema_selector<fields_definition> : std::true_type
{
};
template <>
struct schema_selector<union_type> : std::true_type
{
};
template <>
struct schema_selector<enum_value_definition> : std::true_type
{
};
template <>
struct schema_selector<repeatable_keyword> : std::true_type
{
};
template <>
struct schema_selector<directive_location> : std::true_type
{
};
template <>
struct schema_selector<operation_type_definition> : std::true_type
{
};
template <typename Rule>
struct executable_selector : ast_selector<Rule>
{
};
template <>
struct executable_selector<variable_name> : std::true_type
{
};
template <>
struct executable_selector<alias_name> : std::true_type
{
};
template <>
struct executable_selector<alias> : parse_tree::fold_one
{
};
template <>
struct executable_selector<operation_name> : std::true_type
{
};
template <>
struct executable_selector<fragment_name> : std::true_type
{
};
template <>
struct executable_selector<field> : std::true_type
{
};
template <>
struct executable_selector<fragment_spread> : std::true_type
{
};
template <>
struct executable_selector<inline_fragment> : std::true_type
{
};
template <>
struct executable_selector<selection_set> : std::true_type
{
};
template <>
struct executable_selector<type_condition> : std::true_type
{
};
template <typename Rule>
struct ast_action : nothing<Rule>
{
};
struct [[nodiscard]] depth_guard
{
explicit depth_guard(size_t& depth) noexcept
: _depth(depth)
{
++_depth;
}
~depth_guard()
{
--_depth;
}
depth_guard(depth_guard&&) noexcept = delete;
depth_guard(const depth_guard&) = delete;
depth_guard& operator=(depth_guard&&) noexcept = delete;
depth_guard& operator=(const depth_guard&) = delete;
private:
size_t& _depth;
};
template <>
struct ast_action<selection_set> : maybe_nothing
{
template <typename Rule, apply_mode A, rewind_mode M, template <typename...> class Action,
template <typename...> class Control, typename ParseInput, typename... States>
[[nodiscard]] static bool match(ParseInput& in, States&&... st)
{
depth_guard guard(in.selectionSetDepth);
if (in.selectionSetDepth > in.depthLimit())
{
std::ostringstream oss;
oss << "Exceeded nested depth limit: " << in.depthLimit()
<< " for https://spec.graphql.org/October2021/#SelectionSet";
throw parse_error(oss.str(), in);
}
return tao::graphqlpeg::template match<Rule, A, M, Action, Control>(in, st...);
}
};
template <typename Rule>
struct ast_control : normal<Rule>
{
static const char* error_message;
template <typename Input, typename... State>
[[noreturn]] static void raise(const Input& in, State&&...)
{
throw parse_error(error_message, in);
}
};
template <>
const char* ast_control<one<'}'>>::error_message = "Expected }";
template <>
const char* ast_control<one<']'>>::error_message = "Expected ]";
template <>
const char* ast_control<one<')'>>::error_message = "Expected )";
template <>
const char* ast_control<quote_token>::error_message = "Expected \"";
template <>
const char* ast_control<block_quote_token>::error_message = "Expected \"\"\"";
template <>
const char* ast_control<variable_name_content>::error_message =
"Expected https://spec.graphql.org/October2021/#Variable";
template <>
const char* ast_control<escaped_unicode_content>::error_message =
"Expected https://spec.graphql.org/October2021/#EscapedUnicode";
template <>
const char* ast_control<string_escape_sequence_content>::error_message =
"Expected https://spec.graphql.org/October2021/#EscapedCharacter";
template <>
const char* ast_control<string_quote_content>::error_message =
"Expected https://spec.graphql.org/October2021/#StringCharacter";
template <>
const char* ast_control<block_quote_content>::error_message =
"Expected https://spec.graphql.org/October2021/#BlockStringCharacter";
template <>
const char* ast_control<fractional_part_content>::error_message =
"Expected https://spec.graphql.org/October2021/#FractionalPart";
template <>
const char* ast_control<exponent_part_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ExponentPart";
template <>
const char* ast_control<argument_content>::error_message =
"Expected https://spec.graphql.org/October2021/#Argument";
template <>
const char* ast_control<arguments_content>::error_message =
"Expected https://spec.graphql.org/October2021/#Arguments";
template <>
const char* ast_control<list_value_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ListValue";
template <>
const char* ast_control<object_field_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ObjectField";
template <>
const char* ast_control<object_value_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ObjectValue";
template <>
const char* ast_control<input_value_content>::error_message =
"Expected https://spec.graphql.org/October2021/#Value";
template <>
const char* ast_control<default_value_content>::error_message =
"Expected https://spec.graphql.org/October2021/#DefaultValue";
template <>
const char* ast_control<list_type_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ListType";
template <>
const char* ast_control<type_name_content>::error_message =
"Expected https://spec.graphql.org/October2021/#Type";
template <>
const char* ast_control<variable_content>::error_message =
"Expected https://spec.graphql.org/October2021/#VariableDefinition";
template <>
const char* ast_control<variable_definitions_content>::error_message =
"Expected https://spec.graphql.org/October2021/#VariableDefinitions";
template <>
const char* ast_control<directive_content>::error_message =
"Expected https://spec.graphql.org/October2021/#Directive";
template <>
const char* ast_control<field_content>::error_message =
"Expected https://spec.graphql.org/October2021/#Field";
template <>
const char* ast_control<type_condition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#TypeCondition";
template <>
const char* ast_control<fragement_spread_or_inline_fragment_content>::error_message =
"Expected https://spec.graphql.org/October2021/#FragmentSpread or "
"https://spec.graphql.org/October2021/#InlineFragment";
template <>
const char* ast_control<selection_set_content>::error_message =
"Expected https://spec.graphql.org/October2021/#SelectionSet";
template <>
const char* ast_control<operation_definition_operation_type_content>::error_message =
"Expected https://spec.graphql.org/October2021/#OperationDefinition";
template <>
const char* ast_control<fragment_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#FragmentDefinition";
template <>
const char* ast_control<root_operation_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#RootOperationTypeDefinition";
template <>
const char* ast_control<schema_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#SchemaDefinition";
template <>
const char* ast_control<scalar_type_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ScalarTypeDefinition";
template <>
const char* ast_control<arguments_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ArgumentsDefinition";
template <>
const char* ast_control<field_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#FieldDefinition";
template <>
const char* ast_control<fields_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#FieldsDefinition";
template <>
const char* ast_control<implements_interfaces_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ImplementsInterfaces";
template <>
const char* ast_control<object_type_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ObjectTypeDefinition";
template <>
const char* ast_control<interface_type_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#InterfaceTypeDefinition";
template <>
const char* ast_control<union_member_types_content>::error_message =
"Expected https://spec.graphql.org/October2021/#UnionMemberTypes";
template <>
const char* ast_control<union_type_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#UnionTypeDefinition";
template <>
const char* ast_control<enum_value_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#EnumValueDefinition";
template <>
const char* ast_control<enum_values_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#EnumValuesDefinition";
template <>
const char* ast_control<enum_type_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#EnumTypeDefinition";
template <>
const char* ast_control<input_field_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#InputValueDefinition";
template <>
const char* ast_control<input_fields_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#InputFieldsDefinition";
template <>
const char* ast_control<input_object_type_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#InputObjectTypeDefinition";
template <>
const char* ast_control<directive_definition_content>::error_message =
"Expected https://spec.graphql.org/October2021/#DirectiveDefinition";
template <>
const char* ast_control<schema_extension_content>::error_message =
"Expected https://spec.graphql.org/October2021/#SchemaExtension";
template <>
const char* ast_control<scalar_type_extension_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ScalarTypeExtension";
template <>
const char* ast_control<object_type_extension_content>::error_message =
"Expected https://spec.graphql.org/October2021/#ObjectTypeExtension";
template <>
const char* ast_control<interface_type_extension_content>::error_message =
"Expected https://spec.graphql.org/October2021/#InterfaceTypeExtension";
template <>
const char* ast_control<union_type_extension_content>::error_message =
"Expected https://spec.graphql.org/October2021/#UnionTypeExtension";
template <>
const char* ast_control<enum_type_extension_content>::error_message =
"Expected https://spec.graphql.org/October2021/#EnumTypeExtension";
template <>
const char* ast_control<input_object_type_extension_content>::error_message =
"Expected https://spec.graphql.org/October2021/#InputObjectTypeExtension";
template <>
const char* ast_control<mixed_document_content>::error_message =
"Expected https://spec.graphql.org/October2021/#Document";
template <>
const char* ast_control<executable_document_content>::error_message =
"Expected executable https://spec.graphql.org/October2021/#Document";
template <>
const char* ast_control<schema_document_content>::error_message =
"Expected schema type https://spec.graphql.org/October2021/#Document";
namespace graphql_parse_tree {
namespace internal {
using ast_state = parse_tree::internal::state<ast_node>;
template <template <typename...> class Selector>
struct make_control
{
template <typename Rule, bool, bool>
struct state_handler;
template <typename Rule>
using type = state_handler<Rule, parse_tree::internal::is_selected_node<Rule, Selector>,
parse_tree::internal::is_leaf<8, typename Rule::subs_t, Selector>>;
};
template <template <typename...> class Selector>
template <typename Rule>
struct make_control<Selector>::state_handler<Rule, false, true> : ast_control<Rule>
{
};
template <template <typename...> class Selector>
template <typename Rule>
struct make_control<Selector>::state_handler<Rule, false, false> : ast_control<Rule>
{
static constexpr bool enable = true;
template <typename ParseInput>
static void start(const ParseInput& /*unused*/, ast_state& state)
{
state.emplace_back();
}
template <typename ParseInput>
static void success(const ParseInput& /*unused*/, ast_state& state)
{
auto n = std::move(state.back());
state.pop_back();
for (auto& c : n->children)
{
state.back()->children.emplace_back(std::move(c));
}
}
template <typename ParseInput>
static void failure(const ParseInput& /*unused*/, ast_state& state)
{
state.pop_back();
}
};
template <template <typename...> class Selector>
template <typename Rule, bool B>
struct make_control<Selector>::state_handler<Rule, true, B> : ast_control<Rule>
{
template <typename ParseInput>
static void start(const ParseInput& in, ast_state& state)
{
state.emplace_back();
state.back()->template start<Rule>(in);
}
template <typename ParseInput>
static void success(const ParseInput& in, ast_state& state)
{
auto n = std::move(state.back());
state.pop_back();
n->template success<Rule>(in);
parse_tree::internal::transform<Selector<Rule>>(in, n);
if (n)
{
state.back()->children.emplace_back(std::move(n));
}
}
template <typename ParseInput>
static void failure(const ParseInput& /*unused*/, ast_state& state)
{
state.pop_back();
}
};
} // namespace internal
template <typename Rule, template <typename...> class Action, template <typename...> class Selector,
typename ParseInput>
[[nodiscard]] std::unique_ptr<ast_node> parse(ParseInput&& in)
{
internal::ast_state state;
if (!tao::graphqlpeg::parse<Rule, Action, internal::make_control<Selector>::template type>(
std::forward<ParseInput>(in),
state))
{
return nullptr;
}
if (state.stack.size() != 1)
{
throw std::logic_error("Unexpected error parsing GraphQL");
}
return std::move(state.back());
}
} // namespace graphql_parse_tree
template <class ParseInput>
class [[nodiscard]] depth_limit_input : public ParseInput
{
public:
template <typename... Args>
explicit depth_limit_input(size_t depthLimit, Args&&... args) noexcept
: ParseInput(std::forward<Args>(args)...)
, _depthLimit(depthLimit)
{
}
size_t depthLimit() const noexcept
{
return _depthLimit;
}
size_t selectionSetDepth = 0;
private:
const size_t _depthLimit;
};
using ast_file = depth_limit_input<file_input<>>;
using ast_memory = depth_limit_input<memory_input<>>;
struct [[nodiscard]] ast_string
{
std::vector<char> input;
std::unique_ptr<ast_memory> memory {};
};
struct [[nodiscard]] ast_string_view
{
std::string_view input;
std::unique_ptr<memory_input<>> memory {};
};
struct [[nodiscard]] ast_input
{
std::variant<ast_string, std::unique_ptr<ast_file>, ast_string_view> data;
};
ast parseSchemaString(std::string_view input, size_t depthLimit)
{
ast result { std::make_shared<ast_input>(
ast_input { ast_string { { input.cbegin(), input.cend() } } }),
{} };
auto& data = std::get<ast_string>(result.input->data);
try
{
// Try a smaller grammar with only schema type definitions first.
data.memory = std::make_unique<ast_memory>(depthLimit,
data.input.data(),
data.input.size(),
"GraphQL"s);
result.root =
graphql_parse_tree::parse<schema_document, ast_action, schema_selector>(*data.memory);
}
catch (const peg::parse_error&)
{
// Try again with the full document grammar so validation can handle the unexepected
// executable definitions if this is a mixed document.
data.memory = std::make_unique<ast_memory>(depthLimit,
data.input.data(),
data.input.size(),
"GraphQL"s);
result.root =
graphql_parse_tree::parse<mixed_document, ast_action, schema_selector>(*data.memory);
}
return result;
}
ast parseSchemaFile(std::string_view filename, size_t depthLimit)
{
ast result;
try
{
result.input = std::make_shared<ast_input>(
ast_input { std::make_unique<ast_file>(depthLimit, filename) });
auto& in = *std::get<std::unique_ptr<ast_file>>(result.input->data);
// Try a smaller grammar with only schema type definitions first.
result.root =
graphql_parse_tree::parse<schema_document, ast_action, schema_selector>(std::move(in));
}
catch (const peg::parse_error&)
{
result.input = std::make_shared<ast_input>(
ast_input { std::make_unique<ast_file>(depthLimit, filename) });
auto& in = *std::get<std::unique_ptr<ast_file>>(result.input->data);
// Try again with the full document grammar so validation can handle the unexepected
// executable definitions if this is a mixed document.
result.root =
graphql_parse_tree::parse<mixed_document, ast_action, schema_selector>(std::move(in));
}
return result;
}
ast parseString(std::string_view input, size_t depthLimit)
{
ast result { std::make_shared<ast_input>(
ast_input { ast_string { { input.cbegin(), input.cend() } } }),
{} };
auto& data = std::get<ast_string>(result.input->data);
try
{
// Try a smaller grammar with only executable definitions first.
data.memory = std::make_unique<ast_memory>(depthLimit,
data.input.data(),
data.input.size(),
"GraphQL"s);
result.root =
graphql_parse_tree::parse<executable_document, ast_action, executable_selector>(
*data.memory);
}
catch (const peg::parse_error&)
{
// Try again with the full document grammar so validation can handle the unexepected type
// definitions if this is a mixed document.
data.memory = std::make_unique<ast_memory>(depthLimit,
data.input.data(),
data.input.size(),
"GraphQL"s);
result.root = graphql_parse_tree::parse<mixed_document, ast_action, executable_selector>(
*data.memory);
}
return result;
}
ast parseFile(std::string_view filename, size_t depthLimit)
{
ast result;
try
{
result.input = std::make_shared<ast_input>(
ast_input { std::make_unique<ast_file>(depthLimit, filename) });
auto& in = *std::get<std::unique_ptr<ast_file>>(result.input->data);
// Try a smaller grammar with only executable definitions first.
result.root =
graphql_parse_tree::parse<executable_document, ast_action, executable_selector>(
std::move(in));
}
catch (const peg::parse_error&)
{
result.input = std::make_shared<ast_input>(
ast_input { std::make_unique<ast_file>(depthLimit, filename) });
auto& in = *std::get<std::unique_ptr<ast_file>>(result.input->data);
// Try again with the full document grammar so validation can handle the unexepected type
// definitions if this is a mixed document.
result.root = graphql_parse_tree::parse<mixed_document, ast_action, executable_selector>(
std::move(in));
}
return result;
}
} // namespace peg
peg::ast operator"" _graphql(const char* text, size_t size)
{
peg::ast result { std::make_shared<peg::ast_input>(
peg::ast_input { peg::ast_string_view { { text, size } } }),
{} };
auto& data = std::get<peg::ast_string_view>(result.input->data);
try
{
// Try a smaller grammar with only executable definitions first.
data.memory =
std::make_unique<peg::memory_input<>>(data.input.data(), data.input.size(), "GraphQL"s);
result.root = peg::graphql_parse_tree::
parse<peg::executable_document, peg::nothing, peg::executable_selector>(*data.memory);
}
catch (const peg::parse_error&)
{
// Try again with the full document grammar so validation can handle the unexepected type
// definitions if this is a mixed document.
data.memory =
std::make_unique<peg::memory_input<>>(data.input.data(), data.input.size(), "GraphQL"s);
result.root = peg::graphql_parse_tree::
parse<peg::mixed_document, peg::nothing, peg::executable_selector>(*data.memory);
}
return result;
}
} // namespace graphql
| 24.972034 | 100 | 0.729562 | gitmodimo |
91bb15200a33975b5c004971acaccceed920bcfc | 97,774 | cpp | C++ | src/currency_core/blockchain_storage.cpp | UScrypto/boolberry-opencl | 1369c7a2cb012983a2fac7e78438bd9a7185e867 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/currency_core/blockchain_storage.cpp | UScrypto/boolberry-opencl | 1369c7a2cb012983a2fac7e78438bd9a7185e867 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | src/currency_core/blockchain_storage.cpp | UScrypto/boolberry-opencl | 1369c7a2cb012983a2fac7e78438bd9a7185e867 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | null | null | null | // Copyright (c) 2012-2013 The Cryptonote developers
// Copyright (c) 2012-2013 The Boolberry developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <algorithm>
#include <cstdio>
#include <boost/archive/binary_oarchive.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include "include_base_utils.h"
#include "currency_basic_impl.h"
#include "blockchain_storage.h"
#include "currency_format_utils.h"
#include "currency_boost_serialization.h"
#include "blockchain_storage_boost_serialization.h"
#include "currency_config.h"
#include "miner.h"
#include "misc_language.h"
#include "profile_tools.h"
#include "file_io_utils.h"
#include "common/boost_serialization_helper.h"
#include "warnings.h"
#include "crypto/hash.h"
#include "miner_common.h"
using namespace std;
using namespace epee;
using namespace currency;
DISABLE_VS_WARNINGS(4267)
//------------------------------------------------------------------
blockchain_storage::blockchain_storage(tx_memory_pool& tx_pool):m_tx_pool(tx_pool),
m_current_block_cumul_sz_limit(0),
m_is_in_checkpoint_zone(false),
m_donations_account(AUTO_VAL_INIT(m_donations_account)),
m_royalty_account(AUTO_VAL_INIT(m_royalty_account)),
m_is_blockchain_storing(false),
m_current_pruned_rs_height(0)
{
bool r = get_donation_accounts(m_donations_account, m_royalty_account);
CHECK_AND_ASSERT_THROW_MES(r, "failed to load donation accounts");
}
//------------------------------------------------------------------
bool blockchain_storage::have_tx(const crypto::hash &id)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_transactions.find(id) != m_transactions.end();
}
//------------------------------------------------------------------
bool blockchain_storage::have_tx_keyimg_as_spent(const crypto::key_image &key_im)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_spent_keys.find(key_im) != m_spent_keys.end();
}
//------------------------------------------------------------------
transaction *blockchain_storage::get_tx(const crypto::hash &id)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto it = m_transactions.find(id);
if (it == m_transactions.end())
return NULL;
return &it->second.tx;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_current_blockchain_height()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_blocks.size();
}
//------------------------------------------------------------------
void blockchain_storage::fill_addr_to_alias_dict()
{
for (const auto& a : m_aliases)
{
if (a.second.size())
{
m_addr_to_alias[a.second.back().m_address] = a.first;
}
}
}
//------------------------------------------------------------------
bool blockchain_storage::init(const std::string& config_folder)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
m_config_folder = config_folder;
LOG_PRINT_L0("Loading blockchain...");
const std::string filename = m_config_folder + "/" CURRENCY_BLOCKCHAINDATA_FILENAME;
if(!tools::unserialize_obj_from_file(*this, filename))
{
LOG_PRINT_L0("Can't load blockchain storage from file, generating genesis block.");
block bl = boost::value_initialized<block>();
block_verification_context bvc = boost::value_initialized<block_verification_context>();
generate_genesis_block(bl);
add_new_block(bl, bvc);
CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed && bvc.m_added_to_main_chain, false, "Failed to add genesis block to blockchain");
}
if(!m_blocks.size())
{
LOG_PRINT_L0("Blockchain not loaded, generating genesis block.");
block bl = boost::value_initialized<block>();
block_verification_context bvc = boost::value_initialized<block_verification_context>();
generate_genesis_block(bl);
add_new_block(bl, bvc);
CHECK_AND_ASSERT_MES(!bvc.m_verifivation_failed, false, "Failed to add genesis block to blockchain");
}
uint64_t timestamp_diff = time(NULL) - m_blocks.back().bl.timestamp;
if(!m_blocks.back().bl.timestamp)
timestamp_diff = time(NULL) - 1341378000;
fill_addr_to_alias_dict();
LOG_PRINT_GREEN("Blockchain initialized. last block: " << m_blocks.size()-1 << ", " << misc_utils::get_time_interval_string(timestamp_diff) << " time ago, current difficulty: " << get_difficulty_for_next_block(), LOG_LEVEL_0);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::store_blockchain()
{
m_is_blockchain_storing = true;
misc_utils::auto_scope_leave_caller scope_exit_handler = misc_utils::create_scope_leave_handler([&](){m_is_blockchain_storing=false;});
LOG_PRINT_L0("Storing blockchain...");
if (!tools::create_directories_if_necessary(m_config_folder))
{
LOG_PRINT_L0("Failed to create data directory: " << m_config_folder);
return false;
}
const std::string temp_filename = m_config_folder + "/" CURRENCY_BLOCKCHAINDATA_TEMP_FILENAME;
// There is a chance that temp_filename and filename are hardlinks to the same file
std::remove(temp_filename.c_str());
if(!tools::serialize_obj_to_file(*this, temp_filename))
{
//achtung!
LOG_ERROR("Failed to save blockchain data to file: " << temp_filename);
return false;
}
const std::string filename = m_config_folder + "/" CURRENCY_BLOCKCHAINDATA_FILENAME;
std::error_code ec = tools::replace_file(temp_filename, filename);
if (ec)
{
LOG_ERROR("Failed to rename blockchain data file " << temp_filename << " to " << filename << ": " << ec.message() << ':' << ec.value());
return false;
}
LOG_PRINT_L0("Blockchain stored OK.");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::deinit()
{
return store_blockchain();
}
//------------------------------------------------------------------
bool blockchain_storage::pop_block_from_blockchain()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(m_blocks.size() > 1, false, "pop_block_from_blockchain: can't pop from blockchain with size = " << m_blocks.size());
size_t h = m_blocks.size()-1;
block_extended_info& bei = m_blocks[h];
pop_block_scratchpad_data(bei.bl, m_scratchpad);
//crypto::hash id = get_block_hash(bei.bl);
bool r = purge_block_data_from_blockchain(bei.bl, bei.bl.tx_hashes.size());
CHECK_AND_ASSERT_MES(r, false, "Failed to purge_block_data_from_blockchain for block " << get_block_hash(bei.bl) << " on height " << h);
//remove from index
auto bl_ind = m_blocks_index.find(get_block_hash(bei.bl));
CHECK_AND_ASSERT_MES(bl_ind != m_blocks_index.end(), false, "pop_block_from_blockchain: blockchain id not found in index");
m_blocks_index.erase(bl_ind);
//pop block from core
m_blocks.pop_back();
m_tx_pool.on_blockchain_dec(m_blocks.size()-1, get_top_block_id());
return true;
}
//------------------------------------------------------------------
void blockchain_storage::set_checkpoints(checkpoints&& chk_pts)
{
m_checkpoints = chk_pts;
prune_ring_signatures_if_need();
}
//------------------------------------------------------------------
bool blockchain_storage::prune_ring_signatures(uint64_t height, uint64_t& transactions_pruned, uint64_t& signatures_pruned)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(height < m_blocks.size(), false, "prune_ring_signatures called with wrong parametr " << height << ", m_blocks.size() " << m_blocks.size());
for(const auto& h: m_blocks[height].bl.tx_hashes)
{
auto it = m_transactions.find(h);
CHECK_AND_ASSERT_MES(it != m_transactions.end(), false, "failed to find transaction " << h << " in blockchain index, in block on height = " << height);
CHECK_AND_ASSERT_MES(it->second.m_keeper_block_height == height, false,
"failed to validate extra check, it->second.m_keeper_block_height = " << it->second.m_keeper_block_height <<
"is mot equal to height = " << height << " in blockchain index, for block on height = " << height);
signatures_pruned += it->second.tx.signatures.size();
it->second.tx.signatures.clear();
++transactions_pruned;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::prune_ring_signatures_if_need()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(m_blocks.size() && m_checkpoints.get_top_checkpoint_height() && m_checkpoints.get_top_checkpoint_height() > m_current_pruned_rs_height)
{
LOG_PRINT_CYAN("Starting pruning ring signatues...", LOG_LEVEL_0);
uint64_t tx_count = 0, sig_count = 0;
for(uint64_t height = m_current_pruned_rs_height; height < m_blocks.size() && height <= m_checkpoints.get_top_checkpoint_height(); height++)
{
bool res = prune_ring_signatures(height, tx_count, sig_count);
CHECK_AND_ASSERT_MES(res, false, "filed to prune_ring_signatures for height = " << height);
}
m_current_pruned_rs_height = m_checkpoints.get_top_checkpoint_height();
LOG_PRINT_CYAN("Transaction pruning finished: " << sig_count << " signatures released in " << tx_count << " transactions.", LOG_LEVEL_0);
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::reset_and_set_genesis_block(const block& b)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
m_transactions.clear();
m_spent_keys.clear();
m_blocks.clear();
m_blocks_index.clear();
m_alternative_chains.clear();
m_outputs.clear();
m_scratchpad.clear();
block_verification_context bvc = boost::value_initialized<block_verification_context>();
add_new_block(b, bvc);
return bvc.m_added_to_main_chain && !bvc.m_verifivation_failed;
}
//------------------------------------------------------------------
//TODO: not the best way, add later update method instead of full copy
bool blockchain_storage::copy_scratchpad(std::vector<crypto::hash>& scr)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
scr = m_scratchpad;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::copy_scratchpad(std::string& dst)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if (m_scratchpad.size())
{
dst.append(reinterpret_cast<const char*>(&m_scratchpad[0]), m_scratchpad.size() * 32);
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::purge_transaction_keyimages_from_blockchain(const transaction& tx, bool strict_check)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
struct purge_transaction_visitor: public boost::static_visitor<bool>
{
blockchain_storage& m_bcs;
key_images_container& m_spent_keys;
bool m_strict_check;
purge_transaction_visitor(blockchain_storage& bcs, key_images_container& spent_keys, bool strict_check):
m_bcs(bcs),
m_spent_keys(spent_keys),
m_strict_check(strict_check){}
bool operator()(const txin_to_key& inp) const
{
//const crypto::key_image& ki = inp.k_image;
auto r = m_spent_keys.find(inp.k_image);
if(r != m_spent_keys.end())
{
m_spent_keys.erase(r);
}else
{
CHECK_AND_ASSERT_MES(!m_strict_check, false, "purge_block_data_from_blockchain: key image in transaction not found");
}
if(inp.key_offsets.size() == 1)
{
//direct spend detected
if(!m_bcs.update_spent_tx_flags_for_input(inp.amount, inp.key_offsets[0], false))
{
//internal error
LOG_PRINT_L0("Failed to update_spent_tx_flags_for_input");
return false;
}
}
return true;
}
bool operator()(const txin_gen& inp) const
{
return true;
}
bool operator()(const txin_to_script& tx) const
{
return false;
}
bool operator()(const txin_to_scripthash& tx) const
{
return false;
}
};
BOOST_FOREACH(const txin_v& in, tx.vin)
{
bool r = boost::apply_visitor(purge_transaction_visitor(*this, m_spent_keys, strict_check), in);
CHECK_AND_ASSERT_MES(!strict_check || r, false, "failed to process purge_transaction_visitor");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::purge_transaction_from_blockchain(const crypto::hash& tx_id)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto tx_index_it = m_transactions.find(tx_id);
CHECK_AND_ASSERT_MES(tx_index_it != m_transactions.end(), false, "purge_block_data_from_blockchain: transaction not found in blockchain index!!");
transaction& tx = tx_index_it->second.tx;
purge_transaction_keyimages_from_blockchain(tx, true);
bool r = unprocess_blockchain_tx_extra(tx);
CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_extra");
if(!is_coinbase(tx))
{
currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
bool r = m_tx_pool.add_tx(tx, tvc, true);
CHECK_AND_ASSERT_MES(r, false, "purge_block_data_from_blockchain: failed to add transaction to transaction pool");
}
bool res = pop_transaction_from_global_index(tx, tx_id);
m_transactions.erase(tx_index_it);
LOG_PRINT_L1("Removed transaction from blockchain history:" << tx_id << ENDL);
return res;
}
//------------------------------------------------------------------
bool blockchain_storage::purge_block_data_from_blockchain(const block& bl, size_t processed_tx_count)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
bool res = true;
CHECK_AND_ASSERT_MES(processed_tx_count <= bl.tx_hashes.size(), false, "wrong processed_tx_count in purge_block_data_from_blockchain");
for(size_t count = 0; count != processed_tx_count; count++)
{
res = purge_transaction_from_blockchain(bl.tx_hashes[(processed_tx_count -1)- count]) && res;
}
res = purge_transaction_from_blockchain(get_transaction_hash(bl.miner_tx)) && res;
return res;
}
//------------------------------------------------------------------
crypto::hash blockchain_storage::get_top_block_id(uint64_t& height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
height = get_current_blockchain_height()-1;
return get_top_block_id();
}
//------------------------------------------------------------------
crypto::hash blockchain_storage::get_top_block_id()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
crypto::hash id = null_hash;
if(m_blocks.size())
{
get_block_hash(m_blocks.back().bl, id);
}
return id;
}
//------------------------------------------------------------------
bool blockchain_storage::get_top_block(block& b)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(m_blocks.size(), false, "Wrong blockchain state, m_blocks.size()=0!");
b = m_blocks.back().bl;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_short_chain_history(std::list<crypto::hash>& ids)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
size_t i = 0;
size_t current_multiplier = 1;
size_t sz = m_blocks.size();
if(!sz)
return true;
size_t current_back_offset = 1;
bool genesis_included = false;
while(current_back_offset < sz)
{
ids.push_back(get_block_hash(m_blocks[sz-current_back_offset].bl));
if(sz-current_back_offset == 0)
genesis_included = true;
if(i < 10)
{
++current_back_offset;
}else
{
current_back_offset += current_multiplier *= 2;
}
++i;
}
if(!genesis_included)
ids.push_back(get_block_hash(m_blocks[0].bl));
return true;
}
//------------------------------------------------------------------
crypto::hash blockchain_storage::get_block_id_by_height(uint64_t height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(height >= m_blocks.size())
return null_hash;
return get_block_hash(m_blocks[height].bl);
}
//------------------------------------------------------------------
bool blockchain_storage::get_block_by_hash(const crypto::hash &h, block &blk) {
CRITICAL_REGION_LOCAL(m_blockchain_lock);
// try to find block in main chain
blocks_by_id_index::const_iterator it = m_blocks_index.find(h);
if (m_blocks_index.end() != it) {
blk = m_blocks[it->second].bl;
return true;
}
// try to find block in alternative chain
blocks_ext_by_hash::const_iterator it_alt = m_alternative_chains.find(h);
if (m_alternative_chains.end() != it_alt) {
blk = it_alt->second.bl;
return true;
}
return false;
}
//------------------------------------------------------------------
bool blockchain_storage::get_block_by_height(uint64_t h, block &blk)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(h >= m_blocks.size() )
return false;
blk = m_blocks[h].bl;
return true;
}
//------------------------------------------------------------------
void blockchain_storage::get_all_known_block_ids(std::list<crypto::hash> &main, std::list<crypto::hash> &alt, std::list<crypto::hash> &invalid) {
CRITICAL_REGION_LOCAL(m_blockchain_lock);
BOOST_FOREACH(blocks_by_id_index::value_type &v, m_blocks_index)
main.push_back(v.first);
BOOST_FOREACH(blocks_ext_by_hash::value_type &v, m_alternative_chains)
alt.push_back(v.first);
BOOST_FOREACH(blocks_ext_by_hash::value_type &v, m_invalid_blocks)
invalid.push_back(v.first);
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::get_difficulty_for_next_block()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
std::vector<uint64_t> timestamps;
std::vector<wide_difficulty_type> commulative_difficulties;
size_t offset = m_blocks.size() - std::min(m_blocks.size(), static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT));
if(!offset)
++offset;//skip genesis block
for(; offset < m_blocks.size(); offset++)
{
timestamps.push_back(m_blocks[offset].bl.timestamp);
commulative_difficulties.push_back(m_blocks[offset].cumulative_difficulty);
}
return next_difficulty(timestamps, commulative_difficulties);
}
//------------------------------------------------------------------
bool blockchain_storage::rollback_blockchain_switching(std::list<block>& original_chain, size_t rollback_height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
//remove failed subchain
for(size_t i = m_blocks.size()-1; i >=rollback_height; i--)
{
bool r = pop_block_from_blockchain();
CHECK_AND_ASSERT_MES(r, false, "PANIC!!! failed to remove block while chain switching during the rollback!");
}
//return back original chain
BOOST_FOREACH(auto& bl, original_chain)
{
block_verification_context bvc = boost::value_initialized<block_verification_context>();
bool r = handle_block_to_main_chain(bl, bvc);
CHECK_AND_ASSERT_MES(r && bvc.m_added_to_main_chain, false, "PANIC!!! failed to add (again) block while chain switching during the rollback!");
}
LOG_PRINT_L0("Rollback success.");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::switch_to_alternative_blockchain(std::list<blocks_ext_by_hash::iterator>& alt_chain)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(alt_chain.size(), false, "switch_to_alternative_blockchain: empty chain passed");
size_t split_height = alt_chain.front()->second.height;
CHECK_AND_ASSERT_MES(m_blocks.size() > split_height, false, "switch_to_alternative_blockchain: blockchain size is lower than split height");
//disconnecting old chain
std::list<block> disconnected_chain;
for(size_t i = m_blocks.size()-1; i >=split_height; i--)
{
block b = m_blocks[i].bl;
bool r = pop_block_from_blockchain();
CHECK_AND_ASSERT_MES(r, false, "failed to remove block on chain switching");
disconnected_chain.push_front(b);
}
//connecting new alternative chain
for(auto alt_ch_iter = alt_chain.begin(); alt_ch_iter != alt_chain.end(); alt_ch_iter++)
{
auto ch_ent = *alt_ch_iter;
block_verification_context bvc = boost::value_initialized<block_verification_context>();
bool r = handle_block_to_main_chain(ch_ent->second.bl, bvc);
if(!r || !bvc.m_added_to_main_chain)
{
LOG_PRINT_L0("Failed to switch to alternative blockchain");
rollback_blockchain_switching(disconnected_chain, split_height);
add_block_as_invalid(ch_ent->second, get_block_hash(ch_ent->second.bl));
LOG_PRINT_L0("The block was inserted as invalid while connecting new alternative chain, block_id: " << get_block_hash(ch_ent->second.bl));
m_alternative_chains.erase(ch_ent);
for(auto alt_ch_to_orph_iter = ++alt_ch_iter; alt_ch_to_orph_iter != alt_chain.end(); alt_ch_to_orph_iter++)
{
//block_verification_context bvc = boost::value_initialized<block_verification_context>();
add_block_as_invalid((*alt_ch_iter)->second, (*alt_ch_iter)->first);
m_alternative_chains.erase(*alt_ch_to_orph_iter);
}
return false;
}
}
//pushing old chain as alternative chain
BOOST_FOREACH(auto& old_ch_ent, disconnected_chain)
{
block_verification_context bvc = boost::value_initialized<block_verification_context>();
bool r = handle_alternative_block(old_ch_ent, get_block_hash(old_ch_ent), bvc);
if(!r)
{
LOG_ERROR("Failed to push ex-main chain blocks to alternative chain ");
rollback_blockchain_switching(disconnected_chain, split_height);
return false;
}
}
//removing all_chain entries from alternative chain
BOOST_FOREACH(auto ch_ent, alt_chain)
{
m_alternative_chains.erase(ch_ent);
}
LOG_PRINT_GREEN("REORGANIZE SUCCESS! on height: " << split_height << ", new blockchain size: " << m_blocks.size(), LOG_LEVEL_0);
return true;
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::get_next_difficulty_for_alternative_chain(const std::list<blocks_ext_by_hash::iterator>& alt_chain, block_extended_info& bei)
{
std::vector<uint64_t> timestamps;
std::vector<wide_difficulty_type> commulative_difficulties;
if(alt_chain.size()< DIFFICULTY_BLOCKS_COUNT)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
size_t main_chain_stop_offset = alt_chain.size() ? alt_chain.front()->second.height : bei.height;
size_t main_chain_count = DIFFICULTY_BLOCKS_COUNT - std::min(static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT), alt_chain.size());
main_chain_count = std::min(main_chain_count, main_chain_stop_offset);
size_t main_chain_start_offset = main_chain_stop_offset - main_chain_count;
if(!main_chain_start_offset)
++main_chain_start_offset; //skip genesis block
for(; main_chain_start_offset < main_chain_stop_offset; ++main_chain_start_offset)
{
timestamps.push_back(m_blocks[main_chain_start_offset].bl.timestamp);
commulative_difficulties.push_back(m_blocks[main_chain_start_offset].cumulative_difficulty);
}
CHECK_AND_ASSERT_MES((alt_chain.size() + timestamps.size()) <= DIFFICULTY_BLOCKS_COUNT, false, "Internal error, alt_chain.size()["<< alt_chain.size()
<< "] + vtimestampsec.size()[" << timestamps.size() << "] NOT <= DIFFICULTY_WINDOW[]" << DIFFICULTY_BLOCKS_COUNT );
BOOST_FOREACH(auto it, alt_chain)
{
timestamps.push_back(it->second.bl.timestamp);
commulative_difficulties.push_back(it->second.cumulative_difficulty);
}
}else
{
timestamps.resize(std::min(alt_chain.size(), static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT)));
commulative_difficulties.resize(std::min(alt_chain.size(), static_cast<size_t>(DIFFICULTY_BLOCKS_COUNT)));
size_t count = 0;
size_t max_i = timestamps.size()-1;
BOOST_REVERSE_FOREACH(auto it, alt_chain)
{
timestamps[max_i - count] = it->second.bl.timestamp;
commulative_difficulties[max_i - count] = it->second.cumulative_difficulty;
count++;
if(count >= DIFFICULTY_BLOCKS_COUNT)
break;
}
}
return next_difficulty(timestamps, commulative_difficulties);
}
//------------------------------------------------------------------
bool blockchain_storage::prevalidate_miner_transaction(const block& b, uint64_t height)
{
CHECK_AND_ASSERT_MES(b.miner_tx.vin.size() == 1, false, "coinbase transaction in the block has no inputs");
CHECK_AND_ASSERT_MES(b.miner_tx.vin[0].type() == typeid(txin_gen), false, "coinbase transaction in the block has the wrong type");
if(boost::get<txin_gen>(b.miner_tx.vin[0]).height != height)
{
LOG_PRINT_RED_L0("The miner transaction in block has invalid height: " << boost::get<txin_gen>(b.miner_tx.vin[0]).height << ", expected: " << height);
return false;
}
CHECK_AND_ASSERT_MES(b.miner_tx.unlock_time == height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW,
false,
"coinbase transaction transaction have wrong unlock time=" << b.miner_tx.unlock_time << ", expected " << height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW);
//check outs overflow
if(!check_outs_overflow(b.miner_tx))
{
LOG_PRINT_RED_L0("miner transaction have money overflow in block " << get_block_hash(b));
return false;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::lookfor_donation(const transaction& tx, uint64_t& donation, uint64_t& royalty)
{
crypto::public_key coin_base_tx_pub_key = null_pkey;
bool r = parse_and_validate_tx_extra(tx, coin_base_tx_pub_key);
CHECK_AND_ASSERT_MES(r, false, "Failed to validate coinbase extra");
if(tx.vout.size() >= 2)
{
//check donations value
size_t i = tx.vout.size()-2;
CHECK_AND_ASSERT_MES(tx.vout[i].target.type() == typeid(txout_to_key), false, "wrong type id in transaction out" );
if(is_out_to_acc(m_donations_account, boost::get<txout_to_key>(tx.vout[i].target), coin_base_tx_pub_key, i) )
{
donation = tx.vout[i].amount;
}
}
if(tx.vout.size() >= 1)
{
size_t i = tx.vout.size()-1;
CHECK_AND_ASSERT_MES(tx.vout[i].target.type() == typeid(txout_to_key), false, "wrong type id in transaction out" );
if(donation)
{
//donations already found, check royalty
if(is_out_to_acc(m_royalty_account, boost::get<txout_to_key>(tx.vout[i].target), coin_base_tx_pub_key, i) )
{
royalty = tx.vout[i].amount;
}
}else
{
//only donations, without royalty
if(is_out_to_acc(m_donations_account, boost::get<txout_to_key>(tx.vout[i].target), coin_base_tx_pub_key, i) )
{
donation = tx.vout[i].amount;
}
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_required_donations_value_for_next_block(uint64_t& don_am)
{
TRY_ENTRY();
CRITICAL_REGION_LOCAL(m_blockchain_lock);
uint64_t sz = get_current_blockchain_height();
if(sz < CURRENCY_DONATIONS_INTERVAL || sz%CURRENCY_DONATIONS_INTERVAL)
{
LOG_ERROR("internal error: validate_donations_value at wrong height: " << get_current_blockchain_height());
return false;
}
std::vector<bool> donation_votes;
for(size_t i = m_blocks.size() - CURRENCY_DONATIONS_INTERVAL; i!= m_blocks.size(); i++)
donation_votes.push_back(!(m_blocks[i].bl.flags&BLOCK_FLAGS_SUPPRESS_DONATION));
don_am = get_donations_anount_for_day(m_blocks.back().already_donated_coins, donation_votes);
return true;
CATCH_ENTRY_L0("blockchain_storage::validate_donations_value", false);
}
//------------------------------------------------------------------
bool blockchain_storage::validate_donations_value(uint64_t donation, uint64_t royalty)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
uint64_t expected_don_total = 0;
if(!get_required_donations_value_for_next_block(expected_don_total))
return false;
CHECK_AND_ASSERT_MES(donation + royalty == expected_don_total, false, "Wrong donations amount: " << donation + royalty << ", expected " << expected_don_total);
uint64_t expected_donation = 0;
uint64_t expected_royalty = 0;
get_donation_parts(expected_don_total, expected_royalty, expected_donation);
CHECK_AND_ASSERT_MES(expected_royalty == royalty && expected_donation == donation,
false,
"wrong donation parts: " << donation << "/" << royalty << ", expected: " << expected_donation << "/" << expected_royalty);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::validate_miner_transaction(const block& b, size_t cumulative_block_size, uint64_t fee, uint64_t& base_reward, uint64_t already_generated_coins, uint64_t already_donated_coins, uint64_t& donation_total)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
//validate reward
uint64_t money_in_use = 0;
uint64_t royalty = 0;
uint64_t donation = 0;
//donations should be last one
//size_t outs_total = b.miner_tx.vout.size();
BOOST_FOREACH(auto& o, b.miner_tx.vout)
{
money_in_use += o.amount;
}
uint64_t h = get_block_height(b);
//once a day, without
if(h && !(h%CURRENCY_DONATIONS_INTERVAL) /*&& h > 21600*/)
{
bool r = lookfor_donation(b.miner_tx, donation, royalty);
CHECK_AND_ASSERT_MES(r, false, "Failed to lookfor_donation");
r = validate_donations_value(donation, royalty);
CHECK_AND_ASSERT_MES(r, false, "Failed to validate donations value");
money_in_use -= donation + royalty;
}
std::vector<size_t> last_blocks_sizes;
get_last_n_blocks_sizes(last_blocks_sizes, CURRENCY_REWARD_BLOCKS_WINDOW);
uint64_t max_donation = 0;
if(!get_block_reward(misc_utils::median(last_blocks_sizes), cumulative_block_size, already_generated_coins, already_donated_coins, base_reward, max_donation))
{
LOG_PRINT_L0("block size " << cumulative_block_size << " is bigger than allowed for this blockchain");
return false;
}
if(base_reward + fee < money_in_use)
{
LOG_ERROR("coinbase transaction spend too much money (" << print_money(money_in_use) << "). Block reward is " << print_money(base_reward + fee) << "(" << print_money(base_reward) << "+" << print_money(fee) << ")");
return false;
}
if(base_reward + fee != money_in_use)
{
LOG_ERROR("coinbase transaction doesn't use full amount of block reward: spent: "
<< print_money(money_in_use) << ", block reward " << print_money(base_reward + fee) << "(" << print_money(base_reward) << "+" << print_money(fee) << ")");
return false;
}
donation_total = royalty + donation;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_backward_blocks_sizes(size_t from_height, std::vector<size_t>& sz, size_t count)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(from_height < m_blocks.size(), false, "Internal error: get_backward_blocks_sizes called with from_height=" << from_height << ", blockchain height = " << m_blocks.size());
size_t start_offset = (from_height+1) - std::min((from_height+1), count);
for(size_t i = start_offset; i != from_height+1; i++)
sz.push_back(m_blocks[i].block_cumulative_size);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_last_n_blocks_sizes(std::vector<size_t>& sz, size_t count)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(!m_blocks.size())
return true;
return get_backward_blocks_sizes(m_blocks.size() -1, sz, count);
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_current_comulative_blocksize_limit()
{
return m_current_block_cumul_sz_limit;
}
//------------------------------------------------------------------
bool blockchain_storage::create_block_template(block& b, const account_public_address& miner_address, wide_difficulty_type& diffic, uint64_t& height, const blobdata& ex_nonce, bool vote_for_donation, const alias_info& ai)
{
size_t median_size;
uint64_t already_generated_coins;
uint64_t already_donated_coins;
uint64_t donation_amount_for_this_block = 0;
CRITICAL_REGION_BEGIN(m_blockchain_lock);
b.major_version = CURRENT_BLOCK_MAJOR_VERSION;
b.minor_version = CURRENT_BLOCK_MINOR_VERSION;
b.prev_id = get_top_block_id();
b.timestamp = time(NULL);
b.flags = 0;
if(!vote_for_donation)
b.flags = BLOCK_FLAGS_SUPPRESS_DONATION;
height = m_blocks.size();
diffic = get_difficulty_for_next_block();
if(!(height%CURRENCY_DONATIONS_INTERVAL))
get_required_donations_value_for_next_block(donation_amount_for_this_block);
CHECK_AND_ASSERT_MES(diffic, false, "difficulty owverhead.");
median_size = m_current_block_cumul_sz_limit / 2;
already_generated_coins = m_blocks.back().already_generated_coins;
already_donated_coins = m_blocks.back().already_donated_coins;
CRITICAL_REGION_END();
size_t txs_size;
uint64_t fee;
if (!m_tx_pool.fill_block_template(b, median_size, already_generated_coins, already_donated_coins, txs_size, fee)) {
return false;
}
/*
two-phase miner transaction generation: we don't know exact block size until we prepare block, but we don't know reward until we know
block size, so first miner transaction generated with fake amount of money, and with phase we know think we know expected block size
*/
//make blocks coin-base tx looks close to real coinbase tx to get truthful blob size
bool r = construct_miner_tx(height, median_size, already_generated_coins, already_donated_coins,
txs_size,
fee,
miner_address,
m_donations_account.m_account_address,
m_royalty_account.m_account_address,
b.miner_tx, ex_nonce,
11, donation_amount_for_this_block, ai);
CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, first chance");
#ifdef _DEBUG
std::list<size_t> try_val;
try_val.push_back(get_object_blobsize(b.miner_tx));
#endif
size_t cumulative_size = txs_size + get_object_blobsize(b.miner_tx);
for (size_t try_count = 0; try_count != 10; ++try_count) {
r = construct_miner_tx(height, median_size, already_generated_coins, already_donated_coins,
cumulative_size,
fee,
miner_address,
m_donations_account.m_account_address,
m_royalty_account.m_account_address,
b.miner_tx, ex_nonce,
11,
donation_amount_for_this_block, ai);
#ifdef _DEBUG
try_val.push_back(get_object_blobsize(b.miner_tx));
#endif
CHECK_AND_ASSERT_MES(r, false, "Failed to construc miner tx, second chance");
size_t coinbase_blob_size = get_object_blobsize(b.miner_tx);
if (coinbase_blob_size > cumulative_size - txs_size) {
cumulative_size = txs_size + coinbase_blob_size;
continue;
}
if (coinbase_blob_size < cumulative_size - txs_size) {
size_t delta = cumulative_size - txs_size - coinbase_blob_size;
b.miner_tx.extra.insert(b.miner_tx.extra.end(), delta, 0);
//here could be 1 byte difference, because of extra field counter is varint, and it can become from 1-byte len to 2-bytes len.
if (cumulative_size != txs_size + get_object_blobsize(b.miner_tx)) {
CHECK_AND_ASSERT_MES(cumulative_size + 1 == txs_size + get_object_blobsize(b.miner_tx), false, "unexpected case: cumulative_size=" << cumulative_size << " + 1 is not equal txs_cumulative_size=" << txs_size << " + get_object_blobsize(b.miner_tx)=" << get_object_blobsize(b.miner_tx));
b.miner_tx.extra.resize(b.miner_tx.extra.size() - 1);
if (cumulative_size != txs_size + get_object_blobsize(b.miner_tx)) {
//fuck, not lucky, -1 makes varint-counter size smaller, in that case we continue to grow with cumulative_size
LOG_PRINT_RED("Miner tx creation have no luck with delta_extra size = " << delta << " and " << delta - 1 , LOG_LEVEL_2);
cumulative_size += delta - 1;
continue;
}
LOG_PRINT_GREEN("Setting extra for block: " << b.miner_tx.extra.size() << ", try_count=" << try_count, LOG_LEVEL_1);
}
}
CHECK_AND_ASSERT_MES(cumulative_size == txs_size + get_object_blobsize(b.miner_tx), false, "unexpected case: cumulative_size=" << cumulative_size << " is not equal txs_cumulative_size=" << txs_size << " + get_object_blobsize(b.miner_tx)=" << get_object_blobsize(b.miner_tx));
return true;
}
LOG_ERROR("Failed to create_block_template with " << 10 << " tries");
return false;
}
//------------------------------------------------------------------
bool blockchain_storage::print_transactions_statistics()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
LOG_PRINT_L0("Started to collect transaction statistics, pleas wait...");
size_t total_count = 0;
size_t coinbase_count = 0;
size_t total_full_blob = 0;
size_t total_cropped_blob = 0;
for(auto tx_entry: m_transactions)
{
++total_count;
if(is_coinbase(tx_entry.second.tx))
++coinbase_count;
else
{
total_full_blob += get_object_blobsize<transaction>(tx_entry.second.tx);
transaction tx = tx_entry.second.tx;
tx.signatures.clear();
total_cropped_blob += get_object_blobsize<transaction>(tx);
}
}
LOG_PRINT_L0("Done" << ENDL
<< "total transactions: " << total_count << ENDL
<< "coinbase transactions: " << coinbase_count << ENDL
<< "avarage size of transaction: " << total_full_blob/(total_count-coinbase_count) << ENDL
<< "avarage size of transaction without ring signatures: " << total_cropped_blob/(total_count-coinbase_count) << ENDL
);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::complete_timestamps_vector(uint64_t start_top_height, std::vector<uint64_t>& timestamps)
{
if(timestamps.size() >= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
return true;
CRITICAL_REGION_LOCAL(m_blockchain_lock);
size_t need_elements = BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW - timestamps.size();
CHECK_AND_ASSERT_MES(start_top_height < m_blocks.size(), false, "internal error: passed start_height = " << start_top_height << " not less then m_blocks.size()=" << m_blocks.size());
size_t stop_offset = start_top_height > need_elements ? start_top_height - need_elements:0;
do
{
timestamps.push_back(m_blocks[start_top_height].bl.timestamp);
if(start_top_height == 0)
break;
--start_top_height;
}while(start_top_height != stop_offset);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::handle_alternative_block(const block& b, const crypto::hash& id, block_verification_context& bvc)
{
if(m_checkpoints.is_height_passed_zone(get_block_height(b), get_current_blockchain_height()-1))
{
LOG_PRINT_RED_L0("Block with id: " << id << "[" << get_block_height(b) << "]" << ENDL << " for alternative chain, is under checkpoint zone, declined");
bvc.m_verifivation_failed = true;
return false;
}
TRY_ENTRY();
CRITICAL_REGION_LOCAL(m_blockchain_lock);
//block is not related with head of main chain
//first of all - look in alternative chains container
auto it_main_prev = m_blocks_index.find(b.prev_id);
auto it_prev = m_alternative_chains.find(b.prev_id);
if(it_prev != m_alternative_chains.end() || it_main_prev != m_blocks_index.end())
{
//we have new block in alternative chain
//build alternative subchain, front -> mainchain, back -> alternative head
blocks_ext_by_hash::iterator alt_it = it_prev; //m_alternative_chains.find()
std::list<blocks_ext_by_hash::iterator> alt_chain;
std::vector<crypto::hash> alt_scratchppad;
std::map<uint64_t, crypto::hash> alt_scratchppad_patch;
std::vector<uint64_t> timestamps;
while(alt_it != m_alternative_chains.end())
{
alt_chain.push_front(alt_it);
timestamps.push_back(alt_it->second.bl.timestamp);
alt_it = m_alternative_chains.find(alt_it->second.bl.prev_id);
}
if(alt_chain.size())
{
//make sure that it has right connection to main chain
CHECK_AND_ASSERT_MES(m_blocks.size() > alt_chain.front()->second.height, false, "main blockchain wrong height");
crypto::hash h = null_hash;
get_block_hash(m_blocks[alt_chain.front()->second.height - 1].bl, h);
CHECK_AND_ASSERT_MES(h == alt_chain.front()->second.bl.prev_id, false, "alternative chain have wrong connection to main chain");
complete_timestamps_vector(alt_chain.front()->second.height - 1, timestamps);
//build alternative scratchpad
for(auto& ach: alt_chain)
{
if(!push_block_scratchpad_data(ach->second.scratch_offset, ach->second.bl, alt_scratchppad, alt_scratchppad_patch))
{
LOG_PRINT_RED_L0("Block with id: " << id
<< ENDL << " for alternative chain, have invalid data");
bvc.m_verifivation_failed = true;
return false;
}
}
}else
{
CHECK_AND_ASSERT_MES(it_main_prev != m_blocks_index.end(), false, "internal error: broken imperative condition it_main_prev != m_blocks_index.end()");
complete_timestamps_vector(it_main_prev->second, timestamps);
}
//check timestamp correct
if(!check_block_timestamp(timestamps, b))
{
LOG_PRINT_RED_L0("Block with id: " << id
<< ENDL << " for alternative chain, have invalid timestamp: " << b.timestamp);
//add_block_as_invalid(b, id);//do not add blocks to invalid storage before proof of work check was passed
bvc.m_verifivation_failed = true;
return false;
}
block_extended_info bei = boost::value_initialized<block_extended_info>();
bei.bl = b;
bei.height = alt_chain.size() ? it_prev->second.height + 1 : it_main_prev->second + 1;
uint64_t connection_height = alt_chain.size() ? alt_chain.front()->second.height:bei.height;
CHECK_AND_ASSERT_MES(connection_height, false, "INTERNAL ERROR: Wrong connection_height==0 in handle_alternative_block");
bei.scratch_offset = m_blocks[connection_height].scratch_offset + alt_scratchppad.size();
CHECK_AND_ASSERT_MES(bei.scratch_offset, false, "INTERNAL ERROR: Wrong bei.scratch_offset==0 in handle_alternative_block");
//lets collect patchs from main line
std::map<uint64_t, crypto::hash> main_line_patches;
for(uint64_t i = connection_height; i != m_blocks.size(); i++)
{
std::vector<crypto::hash> block_addendum;
bool res = get_block_scratchpad_addendum(m_blocks[i].bl, block_addendum);
CHECK_AND_ASSERT_MES(res, false, "Failed to get_block_scratchpad_addendum for alt block");
get_scratchpad_patch(m_blocks[i].scratch_offset,
0,
block_addendum.size(),
block_addendum,
main_line_patches);
}
//apply only that patches that lay under alternative scratchpad offset
for(auto ml: main_line_patches)
{
if(ml.first < m_blocks[connection_height].scratch_offset)
alt_scratchppad_patch[ml.first] = crypto::xor_pod(alt_scratchppad_patch[ml.first], ml.second);
}
wide_difficulty_type current_diff = get_next_difficulty_for_alternative_chain(alt_chain, bei);
CHECK_AND_ASSERT_MES(current_diff, false, "!!!!!!! DIFFICULTY OVERHEAD !!!!!!!");
crypto::hash proof_of_work = null_hash;
// POW
#ifdef ENABLE_HASHING_DEBUG
size_t call_no = 0;
std::stringstream ss;
#endif
get_block_longhash(bei.bl, proof_of_work, bei.height, [&](uint64_t index) -> crypto::hash
{
uint64_t offset = index%bei.scratch_offset;
crypto::hash res;
if(offset >= m_blocks[connection_height].scratch_offset)
{
res = alt_scratchppad[offset - m_blocks[connection_height].scratch_offset];
}else
{
res = m_scratchpad[offset];
}
auto it = alt_scratchppad_patch.find(offset);
if(it != alt_scratchppad_patch.end())
{//apply patch
res = crypto::xor_pod(res, it->second);
}
#ifdef ENABLE_HASHING_DEBUG
ss << "[" << call_no << "][" << index << "%" << bei.scratch_offset <<"(" << index%bei.scratch_offset << ")]" << res << ENDL;
++call_no;
#endif
return res;
});
#ifdef ENABLE_HASHING_DEBUG
LOG_PRINT_L3("ID: " << get_block_hash(bei.bl) << "[" << bei.height << "]" << ENDL << "POW:" << proof_of_work << ENDL << ss.str());
#endif
if(!check_hash(proof_of_work, current_diff))
{
LOG_PRINT_RED_L0("Block with id: " << id
<< ENDL << " for alternative chain, have not enough proof of work: " << proof_of_work
<< ENDL << " expected difficulty: " << current_diff);
bvc.m_verifivation_failed = true;
return false;
}
//
if(!m_checkpoints.is_in_checkpoint_zone(bei.height))
{
m_is_in_checkpoint_zone = false;
}else
{
m_is_in_checkpoint_zone = true;
if(!m_checkpoints.check_block(bei.height, id))
{
LOG_ERROR("CHECKPOINT VALIDATION FAILED");
bvc.m_verifivation_failed = true;
return false;
}
}
if(!prevalidate_miner_transaction(b, bei.height))
{
LOG_PRINT_RED_L0("Block with id: " << string_tools::pod_to_hex(id)
<< " (as alternative) have wrong miner transaction.");
bvc.m_verifivation_failed = true;
return false;
}
bei.cumulative_difficulty = alt_chain.size() ? it_prev->second.cumulative_difficulty: m_blocks[it_main_prev->second].cumulative_difficulty;
bei.cumulative_difficulty += current_diff;
#ifdef _DEBUG
auto i_dres = m_alternative_chains.find(id);
CHECK_AND_ASSERT_MES(i_dres == m_alternative_chains.end(), false, "insertion of new alternative block returned as it already exist");
#endif
auto i_res = m_alternative_chains.insert(blocks_ext_by_hash::value_type(id, bei));
CHECK_AND_ASSERT_MES(i_res.second, false, "insertion of new alternative block returned as it already exist");
alt_chain.push_back(i_res.first);
//check if difficulty bigger then in main chain
if(m_blocks.back().cumulative_difficulty < bei.cumulative_difficulty)
{
//do reorganize!
LOG_PRINT_GREEN("###### REORGANIZE on height: " << alt_chain.front()->second.height << " of " << m_blocks.size() -1 << " with cum_difficulty " << m_blocks.back().cumulative_difficulty
<< ENDL << " alternative blockchain size: " << alt_chain.size() << " with cum_difficulty " << bei.cumulative_difficulty, LOG_LEVEL_0);
bool r = switch_to_alternative_blockchain(alt_chain);
if(r) bvc.m_added_to_main_chain = true;
else bvc.m_verifivation_failed = true;
return r;
}
LOG_PRINT_BLUE("----- BLOCK ADDED AS ALTERNATIVE ON HEIGHT " << bei.height
<< ENDL << "id:\t" << id
<< ENDL << "PoW:\t" << proof_of_work
<< ENDL << "difficulty:\t" << current_diff, LOG_LEVEL_0);
return true;
}else
{
//block orphaned
bvc.m_marked_as_orphaned = true;
LOG_PRINT_RED_L0("Block recognized as orphaned and rejected, id = " << id);
}
return true;
CATCH_ENTRY_L0("blockchain_storage::handle_alternative_block", false);
}
//------------------------------------------------------------------
bool blockchain_storage::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks, std::list<transaction>& txs)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(start_offset >= m_blocks.size())
return false;
for(size_t i = start_offset; i < start_offset + count && i < m_blocks.size();i++)
{
blocks.push_back(m_blocks[i].bl);
std::list<crypto::hash> missed_ids;
get_transactions(m_blocks[i].bl.tx_hashes, txs, missed_ids);
CHECK_AND_ASSERT_MES(!missed_ids.size(), false, "have missed transactions in own block in main blockchain");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_blocks(uint64_t start_offset, size_t count, std::list<block>& blocks)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(start_offset >= m_blocks.size())
return false;
for(size_t i = start_offset; i < start_offset + count && i < m_blocks.size();i++)
blocks.push_back(m_blocks[i].bl);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::handle_get_objects(NOTIFY_REQUEST_GET_OBJECTS::request& arg, NOTIFY_RESPONSE_GET_OBJECTS::request& rsp)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
rsp.current_blockchain_height = get_current_blockchain_height();
std::list<block> blocks;
get_blocks(arg.blocks, blocks, rsp.missed_ids);
BOOST_FOREACH(const auto& bl, blocks)
{
std::list<crypto::hash> missed_tx_id;
std::list<transaction> txs;
get_transactions(bl.tx_hashes, txs, rsp.missed_ids);
CHECK_AND_ASSERT_MES(!missed_tx_id.size(), false, "Internal error: have missed missed_tx_id.size()=" << missed_tx_id.size()
<< ENDL << "for block id = " << get_block_hash(bl));
rsp.blocks.push_back(block_complete_entry());
block_complete_entry& e = rsp.blocks.back();
//pack block
e.block = t_serializable_object_to_blob(bl);
//pack transactions
BOOST_FOREACH(transaction& tx, txs)
e.txs.push_back(t_serializable_object_to_blob(tx));
}
//get another transactions, if need
std::list<transaction> txs;
get_transactions(arg.txs, txs, rsp.missed_ids);
//pack aside transactions
BOOST_FOREACH(const auto& tx, txs)
rsp.txs.push_back(t_serializable_object_to_blob(tx));
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_transactions_daily_stat(uint64_t& daily_cnt, uint64_t& daily_volume)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
daily_cnt = daily_volume = 0;
for(size_t i = (m_blocks.size() > CURRENCY_BLOCK_PER_DAY ? m_blocks.size() - CURRENCY_BLOCK_PER_DAY:0 ); i!=m_blocks.size(); i++)
{
for(auto& h: m_blocks[i].bl.tx_hashes)
{
++daily_cnt;
auto tx_it = m_transactions.find(h);
CHECK_AND_ASSERT_MES(tx_it != m_transactions.end(), false, "Wrong transaction hash "<< h <<" in block on height " << i );
uint64_t am = 0;
bool r = get_inputs_money_amount(tx_it->second.tx, am);
CHECK_AND_ASSERT_MES(r, false, "failed to get_inputs_money_amount");
daily_volume += am;
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::check_keyimages(const std::list<crypto::key_image>& images, std::list<bool>& images_stat)
{
//true - unspent, false - spent
CRITICAL_REGION_LOCAL(m_blockchain_lock);
for (auto& ki : images)
{
images_stat.push_back(m_spent_keys.count(ki)?false:true);
}
return true;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_current_hashrate(size_t aprox_count)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(m_blocks.size() <= aprox_count)
return 0;
wide_difficulty_type w_hr = (m_blocks.back().cumulative_difficulty - m_blocks[m_blocks.size() - aprox_count].cumulative_difficulty)/
(m_blocks.back().bl.timestamp - m_blocks[m_blocks.size() - aprox_count].bl.timestamp);
return w_hr.convert_to<uint64_t>();
}
//------------------------------------------------------------------
bool blockchain_storage::extport_scratchpad_to_file(const std::string& path)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
export_scratchpad_file_header fh;
memset(&fh, 0, sizeof(fh));
fh.current_hi.prevhash = currency::get_block_hash(m_blocks.back().bl);
fh.current_hi.height = m_blocks.size()-1;
fh.scratchpad_size = m_scratchpad.size()*4;
try
{
std::string tmp_path = path + ".tmp";
std::ofstream fstream;
fstream.exceptions(std::ifstream::failbit | std::ifstream::badbit);
fstream.open(tmp_path, std::ios_base::binary | std::ios_base::out | std::ios_base::trunc);
fstream.write((const char*)&fh, sizeof(fh));
fstream.write((const char*)&m_scratchpad[0], m_scratchpad.size()*32);
fstream.close();
boost::filesystem::remove(path);
boost::filesystem::rename(tmp_path, path);
LOG_PRINT_L0("Scratchpad exported to " << path << ", " << (m_scratchpad.size()*32)/1024 << "kbytes" );
return true;
}
catch(const std::exception& e)
{
LOG_PRINT_L0("Failed to store scratchpad, error: " << e.what());
return false;
}
catch(...)
{
LOG_PRINT_L0("Failed to store scratchpad, unknown error" );
return false;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_alternative_blocks(std::list<block>& blocks)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
BOOST_FOREACH(const auto& alt_bl, m_alternative_chains)
{
blocks.push_back(alt_bl.second.bl);
}
return true;
}
//------------------------------------------------------------------
size_t blockchain_storage::get_alternative_blocks_count()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_alternative_chains.size();
}
//------------------------------------------------------------------
bool blockchain_storage::add_out_to_get_random_outs(std::vector<std::pair<crypto::hash, size_t> >& amount_outs, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& result_outs, uint64_t amount, size_t i, uint64_t mix_count, bool use_only_forced_to_mix)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
transactions_container::iterator tx_it = m_transactions.find(amount_outs[i].first);
CHECK_AND_ASSERT_MES(tx_it != m_transactions.end(), false, "internal error: transaction with id " << amount_outs[i].first << ENDL <<
", used in mounts global index for amount=" << amount << ": i=" << i << "not found in transactions index");
CHECK_AND_ASSERT_MES(tx_it->second.tx.vout.size() > amount_outs[i].second, false, "internal error: in global outs index, transaction out index="
<< amount_outs[i].second << " more than transaction outputs = " << tx_it->second.tx.vout.size() << ", for tx id = " << amount_outs[i].first);
transaction& tx = tx_it->second.tx;
CHECK_AND_ASSERT_MES(tx.vout[amount_outs[i].second].target.type() == typeid(txout_to_key), false, "unknown tx out type");
CHECK_AND_ASSERT_MES(tx_it->second.m_spent_flags.size() == tx.vout.size(), false, "internal error");
//do not use outputs that obviously spent for mixins
if(tx_it->second.m_spent_flags[amount_outs[i].second])
return false;
//check if transaction is unlocked
if(!is_tx_spendtime_unlocked(tx.unlock_time))
return false;
//use appropriate mix_attr out
uint8_t mix_attr = boost::get<txout_to_key>(tx.vout[amount_outs[i].second].target).mix_attr;
if(mix_attr == CURRENCY_TO_KEY_OUT_FORCED_NO_MIX)
return false; //COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS call means that ring signature will have more than one entry.
else if(use_only_forced_to_mix && mix_attr == CURRENCY_TO_KEY_OUT_RELAXED)
return false; //relaxed not allowed
else if(mix_attr != CURRENCY_TO_KEY_OUT_RELAXED && mix_attr > mix_count)
return false;//mix_attr set to specific minimum, and mix_count is less then desired count
COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry& oen = *result_outs.outs.insert(result_outs.outs.end(), COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry());
oen.global_amount_index = i;
oen.out_key = boost::get<txout_to_key>(tx.vout[amount_outs[i].second].target).key;
return true;
}
//------------------------------------------------------------------
size_t blockchain_storage::find_end_of_allowed_index(const std::vector<std::pair<crypto::hash, size_t> >& amount_outs)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(!amount_outs.size())
return 0;
size_t i = amount_outs.size();
do
{
--i;
transactions_container::iterator it = m_transactions.find(amount_outs[i].first);
CHECK_AND_ASSERT_MES(it != m_transactions.end(), 0, "internal error: failed to find transaction from outputs index with tx_id=" << amount_outs[i].first);
if(it->second.m_keeper_block_height + CURRENCY_MINED_MONEY_UNLOCK_WINDOW <= get_current_blockchain_height() )
return i+1;
} while (i != 0);
return 0;
}
//------------------------------------------------------------------
bool blockchain_storage::get_random_outs_for_amounts(const COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::request& req, COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::response& res)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
BOOST_FOREACH(uint64_t amount, req.amounts)
{
COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount& result_outs = *res.outs.insert(res.outs.end(), COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount());
result_outs.amount = amount;
auto it = m_outputs.find(amount);
if(it == m_outputs.end())
{
LOG_ERROR("COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS: not outs for amount " << amount << ", wallet should use some real outs when it lookup for some mix, so, at least one out for this amount should exist");
continue;//actually this is strange situation, wallet should use some real outs when it lookup for some mix, so, at least one out for this amount should exist
}
std::vector<std::pair<crypto::hash, size_t> >& amount_outs = it->second;
//it is not good idea to use top fresh outs, because it increases possibility of transaction canceling on split
//lets find upper bound of not fresh outs
size_t up_index_limit = find_end_of_allowed_index(amount_outs);
CHECK_AND_ASSERT_MES(up_index_limit <= amount_outs.size(), false, "internal error: find_end_of_allowed_index returned wrong index=" << up_index_limit << ", with amount_outs.size = " << amount_outs.size());
if(amount_outs.size() > req.outs_count)
{
std::set<size_t> used;
size_t try_count = 0;
for(uint64_t j = 0; j != req.outs_count && try_count < up_index_limit;)
{
size_t i = crypto::rand<size_t>()%up_index_limit;
if(used.count(i))
continue;
bool added = add_out_to_get_random_outs(amount_outs, result_outs, amount, i, req.outs_count, req.use_forced_mix_outs);
used.insert(i);
if(added)
++j;
++try_count;
}
}else
{
for(size_t i = 0; i != up_index_limit; i++)
add_out_to_get_random_outs(amount_outs, result_outs, amount, i, req.outs_count, req.use_forced_mix_outs);
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::update_spent_tx_flags_for_input(uint64_t amount, uint64_t global_index, bool spent)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto it = m_outputs.find(amount);
CHECK_AND_ASSERT_MES(it != m_outputs.end(), false, "Amount " << amount << " have not found during update_spent_tx_flags_for_input()");
CHECK_AND_ASSERT_MES(global_index < it->second.size(), false, "Global index" << global_index << " for amount " << amount << " bigger value than amount's vector size()=" << it->second.size());
auto tx_it = m_transactions.find(it->second[global_index].first);
CHECK_AND_ASSERT_MES(tx_it != m_transactions.end(), false, "Can't find transaction id: " << it->second[global_index].first << ", refferenced in amount=" << amount << ", global index=" << global_index);
CHECK_AND_ASSERT_MES(it->second[global_index].second < tx_it->second.m_spent_flags.size() , false, "Wrong input offset: " << it->second[global_index].second << " in transaction id: " << it->second[global_index].first << ", refferenced in amount=" << amount << ", global index=" << global_index);
tx_it->second.m_spent_flags[it->second[global_index].second] = spent;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::resync_spent_tx_flags()
{
LOG_PRINT_L0("Started re-building spent tx outputs data...");
CRITICAL_REGION_LOCAL(m_blockchain_lock);
for(auto& tx: m_transactions)
{
if(is_coinbase(tx.second.tx))
continue;
for(auto& in: tx.second.tx.vin)
{
CHECKED_GET_SPECIFIC_VARIANT(in, txin_to_key, in_to_key, false);
if(in_to_key.key_offsets.size() != 1)
continue;
//direct spending
if(!update_spent_tx_flags_for_input(in_to_key.amount, in_to_key.key_offsets[0], true))
return false;
}
}
LOG_PRINT_L0("Finished re-building spent tx outputs data");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, uint64_t& starter_offset)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(!qblock_ids.size() /*|| !req.m_total_height*/)
{
LOG_ERROR("Client sent wrong NOTIFY_REQUEST_CHAIN: m_block_ids.size()=" << qblock_ids.size() << /*", m_height=" << req.m_total_height <<*/ ", dropping connection");
return false;
}
//check genesis match
if(qblock_ids.back() != get_block_hash(m_blocks[0].bl))
{
LOG_ERROR("Client sent wrong NOTIFY_REQUEST_CHAIN: genesis block missmatch: " << ENDL << "id: "
<< qblock_ids.back() << ", " << ENDL << "expected: " << get_block_hash(m_blocks[0].bl)
<< "," << ENDL << " dropping connection");
return false;
}
/* Figure out what blocks we should request to get state_normal */
size_t i = 0;
auto bl_it = qblock_ids.begin();
auto block_index_it = m_blocks_index.find(*bl_it);
for(; bl_it != qblock_ids.end(); bl_it++, i++)
{
block_index_it = m_blocks_index.find(*bl_it);
if(block_index_it != m_blocks_index.end())
break;
}
if(bl_it == qblock_ids.end())
{
LOG_ERROR("Internal error handling connection, can't find split point");
return false;
}
if(block_index_it == m_blocks_index.end())
{
//this should NEVER happen, but, dose of paranoia in such cases is not too bad
LOG_ERROR("Internal error handling connection, can't find split point");
return false;
}
//we start to put block ids INCLUDING last known id, just to make other side be sure
starter_offset = block_index_it->second;
return true;
}
//------------------------------------------------------------------
wide_difficulty_type blockchain_storage::block_difficulty(size_t i)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(i < m_blocks.size(), false, "wrong block index i = " << i << " at blockchain_storage::block_difficulty()");
if(i == 0)
return m_blocks[i].cumulative_difficulty;
return m_blocks[i].cumulative_difficulty - m_blocks[i-1].cumulative_difficulty;
}
//------------------------------------------------------------------
void blockchain_storage::print_blockchain(uint64_t start_index, uint64_t end_index)
{
std::stringstream ss;
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(start_index >=m_blocks.size())
{
LOG_PRINT_L0("Wrong starter index set: " << start_index << ", expected max index " << m_blocks.size()-1);
return;
}
for(size_t i = start_index; i != m_blocks.size() && i != end_index; i++)
{
ss << "height " << i << ", timestamp " << m_blocks[i].bl.timestamp << ", cumul_dif " << m_blocks[i].cumulative_difficulty << ", cumul_size " << m_blocks[i].block_cumulative_size
<< "\nid\t\t" << get_block_hash(m_blocks[i].bl)
<< "\ndifficulty\t\t" << block_difficulty(i) << ", nonce " << m_blocks[i].bl.nonce << ", tx_count " << m_blocks[i].bl.tx_hashes.size() << ENDL;
}
LOG_PRINT_L1("Current blockchain:" << ENDL << ss.str());
LOG_PRINT_L0("Blockchain printed with log level 1");
}
//------------------------------------------------------------------
void blockchain_storage::print_blockchain_index()
{
std::stringstream ss;
CRITICAL_REGION_LOCAL(m_blockchain_lock);
BOOST_FOREACH(const blocks_by_id_index::value_type& v, m_blocks_index)
ss << "id\t\t" << v.first << " height" << v.second << ENDL << "";
LOG_PRINT_L0("Current blockchain index:" << ENDL << ss.str());
}
//------------------------------------------------------------------
void blockchain_storage::print_blockchain_outs(const std::string& file)
{
std::stringstream ss;
CRITICAL_REGION_LOCAL(m_blockchain_lock);
BOOST_FOREACH(const outputs_container::value_type& v, m_outputs)
{
const std::vector<std::pair<crypto::hash, size_t> >& vals = v.second;
if(vals.size())
{
ss << "amount: " << v.first << ENDL;
for(size_t i = 0; i != vals.size(); i++)
ss << "\t" << vals[i].first << ": " << vals[i].second << ENDL;
}
}
if(file_io_utils::save_string_to_file(file, ss.str()))
{
LOG_PRINT_L0("Current outputs index writen to file: " << file);
}else
{
LOG_PRINT_L0("Failed to write current outputs index to file: " << file);
}
}
//------------------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, NOTIFY_RESPONSE_CHAIN_ENTRY::request& resp)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(!find_blockchain_supplement(qblock_ids, resp.start_height))
return false;
resp.total_height = get_current_blockchain_height();
size_t count = 0;
for(size_t i = resp.start_height; i != m_blocks.size() && count < BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT; i++, count++)
resp.m_block_ids.push_back(get_block_hash(m_blocks[i].bl));
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::find_blockchain_supplement(const std::list<crypto::hash>& qblock_ids, std::list<std::pair<block, std::list<transaction> > >& blocks, uint64_t& total_height, uint64_t& start_height, size_t max_count)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(!find_blockchain_supplement(qblock_ids, start_height))
return false;
total_height = get_current_blockchain_height();
size_t count = 0;
for(size_t i = start_height; i != m_blocks.size() && count < max_count; i++, count++)
{
blocks.resize(blocks.size()+1);
blocks.back().first = m_blocks[i].bl;
std::list<crypto::hash> mis;
get_transactions(m_blocks[i].bl.tx_hashes, blocks.back().second, mis);
CHECK_AND_ASSERT_MES(!mis.size(), false, "internal error, transaction from block not found");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::add_block_as_invalid(const block& bl, const crypto::hash& h)
{
block_extended_info bei = AUTO_VAL_INIT(bei);
bei.bl = bl;
return add_block_as_invalid(bei, h);
}
//------------------------------------------------------------------
bool blockchain_storage::add_block_as_invalid(const block_extended_info& bei, const crypto::hash& h)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto i_res = m_invalid_blocks.insert(std::map<crypto::hash, block_extended_info>::value_type(h, bei));
CHECK_AND_ASSERT_MES(i_res.second, false, "at insertion invalid by tx returned status existed");
LOG_PRINT_L0("BLOCK ADDED AS INVALID: " << h << ENDL << ", prev_id=" << bei.bl.prev_id << ", m_invalid_blocks count=" << m_invalid_blocks.size());
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::have_block(const crypto::hash& id)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(m_blocks_index.count(id))
return true;
if(m_alternative_chains.count(id))
return true;
/*if(m_orphaned_blocks.get<by_id>().count(id))
return true;*/
/*if(m_orphaned_by_tx.count(id))
return true;*/
if(m_invalid_blocks.count(id))
return true;
return false;
}
//------------------------------------------------------------------
bool blockchain_storage::handle_block_to_main_chain(const block& bl, block_verification_context& bvc)
{
crypto::hash id = get_block_hash(bl);
return handle_block_to_main_chain(bl, id, bvc);
}
//------------------------------------------------------------------
bool blockchain_storage::push_transaction_to_global_outs_index(const transaction& tx, const crypto::hash& tx_id, std::vector<uint64_t>& global_indexes)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
size_t i = 0;
BOOST_FOREACH(const auto& ot, tx.vout)
{
outputs_container::mapped_type& amount_index = m_outputs[ot.amount];
amount_index.push_back(std::pair<crypto::hash, size_t>(tx_id, i));
global_indexes.push_back(amount_index.size()-1);
++i;
}
return true;
}
//------------------------------------------------------------------
size_t blockchain_storage::get_total_transactions()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_transactions.size();
}
//------------------------------------------------------------------
bool blockchain_storage::get_outs(uint64_t amount, std::list<crypto::public_key>& pkeys)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto it = m_outputs.find(amount);
if(it == m_outputs.end())
return true;
BOOST_FOREACH(const auto& out_entry, it->second)
{
auto tx_it = m_transactions.find(out_entry.first);
CHECK_AND_ASSERT_MES(tx_it != m_transactions.end(), false, "transactions outs global index consistency broken: wrong tx id in index");
CHECK_AND_ASSERT_MES(tx_it->second.tx.vout.size() > out_entry.second, false, "transactions outs global index consistency broken: index in tx_outx more then size");
CHECK_AND_ASSERT_MES(tx_it->second.tx.vout[out_entry.second].target.type() == typeid(txout_to_key), false, "transactions outs global index consistency broken: index in tx_outx more then size");
pkeys.push_back(boost::get<txout_to_key>(tx_it->second.tx.vout[out_entry.second].target).key);
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::pop_transaction_from_global_index(const transaction& tx, const crypto::hash& tx_id)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
size_t i = tx.vout.size()-1;
BOOST_REVERSE_FOREACH(const auto& ot, tx.vout)
{
auto it = m_outputs.find(ot.amount);
CHECK_AND_ASSERT_MES(it != m_outputs.end(), false, "transactions outs global index consistency broken");
CHECK_AND_ASSERT_MES(it->second.size(), false, "transactions outs global index: empty index for amount: " << ot.amount);
CHECK_AND_ASSERT_MES(it->second.back().first == tx_id , false, "transactions outs global index consistency broken: tx id missmatch");
CHECK_AND_ASSERT_MES(it->second.back().second == i, false, "transactions outs global index consistency broken: in transaction index missmatch");
it->second.pop_back();
//do not let to exist empty m_outputs entries - this will broke scratchpad selector
if(!it->second.size())
m_outputs.erase(it);
--i;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::unprocess_blockchain_tx_extra(const transaction& tx)
{
if(is_coinbase(tx))
{
tx_extra_info ei = AUTO_VAL_INIT(ei);
bool r = parse_and_validate_tx_extra(tx, ei);
CHECK_AND_ASSERT_MES(r, false, "failed to validate transaction extra on unprocess_blockchain_tx_extra");
if(ei.m_alias.m_alias.size())
{
r = pop_alias_info(ei.m_alias);
CHECK_AND_ASSERT_MES(r, false, "failed to pop_alias_info");
}
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_alias_info(const std::string& alias, alias_info_base& info)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto it = m_aliases.find(alias);
if(it != m_aliases.end())
{
if(it->second.size())
{
info = it->second.back();
return true;
}
}
return false;
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_aliases_count()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_aliases.size();
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_scratchpad_size()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
return m_scratchpad.size()*32;
}
//------------------------------------------------------------------
bool blockchain_storage::get_all_aliases(std::list<alias_info>& aliases)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
for(auto a: m_aliases)
{
if(a.second.size())
{
aliases.push_back(alias_info());
aliases.back().m_alias = a.first;
static_cast<alias_info_base&>(aliases.back()) = a.second.back();
}
}
return true;
}
//------------------------------------------------------------------
std::string blockchain_storage::get_alias_by_address(const account_public_address& addr)
{
auto it = m_addr_to_alias.find(addr);
if (it != m_addr_to_alias.end())
return it->second;
return "";
}
//------------------------------------------------------------------
bool blockchain_storage::pop_alias_info(const alias_info& ai)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(ai.m_alias.size(), false, "empty name in pop_alias_info");
aliases_container::mapped_type& alias_history = m_aliases[ai.m_alias];
CHECK_AND_ASSERT_MES(alias_history.size(), false, "empty name list in pop_alias_info");
auto it = m_addr_to_alias.find(alias_history.back().m_address);
if (it != m_addr_to_alias.end())
{
m_addr_to_alias.erase(it);
}
else
{
LOG_ERROR("In m_addr_to_alias not found " << get_account_address_as_str(alias_history.back().m_address));
}
alias_history.pop_back();
if (alias_history.size())
{
m_addr_to_alias[alias_history.back().m_address] = ai.m_alias;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::put_alias_info(const alias_info& ai)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
CHECK_AND_ASSERT_MES(ai.m_alias.size(), false, "empty name in put_alias_info");
aliases_container::mapped_type& alias_history = m_aliases[ai.m_alias];
if(ai.m_sign == null_sig)
{//adding new alias, check sat name is free
CHECK_AND_ASSERT_MES(!alias_history.size(), false, "alias " << ai.m_alias << " already in use");
alias_history.push_back(ai);
m_addr_to_alias[alias_history.back().m_address] = ai.m_alias;
}else
{
//update procedure
CHECK_AND_ASSERT_MES(alias_history.size(), false, "alias " << ai.m_alias << " can't be update becouse it doesn't exists");
std::string signed_buff;
make_tx_extra_alias_entry(signed_buff, ai, true);
bool r = crypto::check_signature(get_blob_hash(signed_buff), alias_history.back().m_address.m_spend_public_key, ai.m_sign);
CHECK_AND_ASSERT_MES(r, false, "Failed to check signature, alias update failed");
//update granted
auto it = m_addr_to_alias.find(alias_history.back().m_address);
if (it != m_addr_to_alias.end())
m_addr_to_alias.erase(it);
else
LOG_ERROR("Wromg m_addr_to_alias state: address not found " << get_account_address_as_str(alias_history.back().m_address));
alias_history.push_back(ai);
m_addr_to_alias[alias_history.back().m_address] = ai.m_alias;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::process_blockchain_tx_extra(const transaction& tx)
{
//check transaction extra
tx_extra_info ei = AUTO_VAL_INIT(ei);
bool r = parse_and_validate_tx_extra(tx, ei);
CHECK_AND_ASSERT_MES(r, false, "failed to validate transaction extra");
if(is_coinbase(tx) && ei.m_alias.m_alias.size())
{
r = put_alias_info(ei.m_alias);
CHECK_AND_ASSERT_MES(r, false, "failed to put_alias_info");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::add_transaction_from_block(const transaction& tx, const crypto::hash& tx_id, const crypto::hash& bl_id, uint64_t bl_height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
bool r = process_blockchain_tx_extra(tx);
CHECK_AND_ASSERT_MES(r, false, "failed to process_blockchain_tx_extra");
struct add_transaction_input_visitor: public boost::static_visitor<bool>
{
blockchain_storage& m_bcs;
key_images_container& m_spent_keys;
const crypto::hash& m_tx_id;
const crypto::hash& m_bl_id;
add_transaction_input_visitor(blockchain_storage& bcs, key_images_container& spent_keys, const crypto::hash& tx_id, const crypto::hash& bl_id):
m_bcs(bcs),
m_spent_keys(spent_keys),
m_tx_id(tx_id),
m_bl_id(bl_id)
{}
bool operator()(const txin_to_key& in) const
{
const crypto::key_image& ki = in.k_image;
auto r = m_spent_keys.insert(ki);
if(!r.second)
{
//double spend detected
LOG_PRINT_L0("tx with id: " << m_tx_id << " in block id: " << m_bl_id << " have input marked as spent with key image: " << ki << ", block declined");
return false;
}
if(in.key_offsets.size() == 1)
{
//direct spend detected
if(!m_bcs.update_spent_tx_flags_for_input(in.amount, in.key_offsets[0], true))
{
//internal error
LOG_PRINT_L0("Failed to update_spent_tx_flags_for_input");
return false;
}
}
return true;
}
bool operator()(const txin_gen& tx) const{return true;}
bool operator()(const txin_to_script& tx) const{return false;}
bool operator()(const txin_to_scripthash& tx) const{return false;}
};
BOOST_FOREACH(const txin_v& in, tx.vin)
{
if(!boost::apply_visitor(add_transaction_input_visitor(*this, m_spent_keys, tx_id, bl_id), in))
{
LOG_ERROR("critical internal error: add_transaction_input_visitor failed. but key_images should be already checked");
purge_transaction_keyimages_from_blockchain(tx, false);
bool r = unprocess_blockchain_tx_extra(tx);
CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_extra");
return false;
}
}
transaction_chain_entry ch_e;
ch_e.m_keeper_block_height = bl_height;
ch_e.m_spent_flags.resize(tx.vout.size(), false);
ch_e.tx = tx;
auto i_r = m_transactions.insert(std::pair<crypto::hash, transaction_chain_entry>(tx_id, ch_e));
if(!i_r.second)
{
LOG_ERROR("critical internal error: tx with id: " << tx_id << " in block id: " << bl_id << " already in blockchain");
purge_transaction_keyimages_from_blockchain(tx, true);
bool r = unprocess_blockchain_tx_extra(tx);
CHECK_AND_ASSERT_MES(r, false, "failed to unprocess_blockchain_tx_extra");
return false;
}
r = push_transaction_to_global_outs_index(tx, tx_id, i_r.first->second.m_global_output_indexes);
CHECK_AND_ASSERT_MES(r, false, "failed to return push_transaction_to_global_outs_index tx id " << tx_id);
LOG_PRINT_L2("Added transaction to blockchain history:" << ENDL
<< "tx_id: " << tx_id << ENDL
<< "inputs: " << tx.vin.size() << ", outs: " << tx.vout.size() << ", spend money: " << print_money(get_outs_money_amount(tx)) << "(fee: " << (is_coinbase(tx) ? "0[coinbase]" : print_money(get_tx_fee(tx))) << ")");
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_tx_outputs_gindexs(const crypto::hash& tx_id, std::vector<uint64_t>& indexs)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
auto it = m_transactions.find(tx_id);
if(it == m_transactions.end())
{
LOG_PRINT_RED_L0("warning: get_tx_outputs_gindexs failed to find transaction with id = " << tx_id);
return false;
}
CHECK_AND_ASSERT_MES(it->second.m_global_output_indexes.size(), false, "internal error: global indexes for transaction " << tx_id << " is empty");
indexs = it->second.m_global_output_indexes;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::check_tx_inputs(const transaction& tx, uint64_t& max_used_block_height, crypto::hash& max_used_block_id)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
bool res = check_tx_inputs(tx, &max_used_block_height);
if(!res) return false;
CHECK_AND_ASSERT_MES(max_used_block_height < m_blocks.size(), false, "internal error: max used block index=" << max_used_block_height << " is not less then blockchain size = " << m_blocks.size());
get_block_hash(m_blocks[max_used_block_height].bl, max_used_block_id);
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::have_tx_keyimges_as_spent(const transaction &tx)
{
BOOST_FOREACH(const txin_v& in, tx.vin)
{
CHECKED_GET_SPECIFIC_VARIANT(in, const txin_to_key, in_to_key, true);
if(have_tx_keyimg_as_spent(in_to_key.k_image))
return true;
}
return false;
}
//------------------------------------------------------------------
bool blockchain_storage::check_tx_inputs(const transaction& tx, uint64_t* pmax_used_block_height)
{
crypto::hash tx_prefix_hash = get_transaction_prefix_hash(tx);
return check_tx_inputs(tx, tx_prefix_hash, pmax_used_block_height);
}
//------------------------------------------------------------------
bool blockchain_storage::check_tx_inputs(const transaction& tx, const crypto::hash& tx_prefix_hash, uint64_t* pmax_used_block_height)
{
size_t sig_index = 0;
if(pmax_used_block_height)
*pmax_used_block_height = 0;
BOOST_FOREACH(const auto& txin, tx.vin)
{
CHECK_AND_ASSERT_MES(txin.type() == typeid(txin_to_key), false, "wrong type id in tx input at blockchain_storage::check_tx_inputs");
const txin_to_key& in_to_key = boost::get<txin_to_key>(txin);
CHECK_AND_ASSERT_MES(in_to_key.key_offsets.size(), false, "empty in_to_key.key_offsets in transaction with id " << get_transaction_hash(tx));
if(have_tx_keyimg_as_spent(in_to_key.k_image))
{
LOG_PRINT_L1("Key image already spent in blockchain: " << string_tools::pod_to_hex(in_to_key.k_image));
return false;
}
std::vector<crypto::signature> sig_stub;
const std::vector<crypto::signature>* psig = &sig_stub;
if (!m_is_in_checkpoint_zone)
{
CHECK_AND_ASSERT_MES(sig_index < tx.signatures.size(), false, "wrong transaction: not signature entry for input with index= " << sig_index);
psig = &tx.signatures[sig_index];
}
if (!check_tx_input(in_to_key, tx_prefix_hash, *psig, pmax_used_block_height))
{
LOG_PRINT_L0("Failed to check ring signature for tx " << get_transaction_hash(tx));
return false;
}
sig_index++;
}
if (!m_is_in_checkpoint_zone)
{
CHECK_AND_ASSERT_MES(tx.signatures.size() == sig_index, false, "tx signatures count differs from inputs");
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::is_tx_spendtime_unlocked(uint64_t unlock_time)
{
if(unlock_time < CURRENCY_MAX_BLOCK_NUMBER)
{
//interpret as block index
if(get_current_blockchain_height()-1 + CURRENCY_LOCKED_TX_ALLOWED_DELTA_BLOCKS >= unlock_time)
return true;
else
return false;
}else
{
//interpret as time
uint64_t current_time = static_cast<uint64_t>(time(NULL));
if(current_time + CURRENCY_LOCKED_TX_ALLOWED_DELTA_SECONDS >= unlock_time)
return true;
else
return false;
}
return false;
}
//------------------------------------------------------------------
bool blockchain_storage::check_tx_input(const txin_to_key& txin, const crypto::hash& tx_prefix_hash, const std::vector<crypto::signature>& sig, uint64_t* pmax_related_block_height)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
struct outputs_visitor
{
std::vector<const crypto::public_key *>& m_results_collector;
blockchain_storage& m_bch;
outputs_visitor(std::vector<const crypto::public_key *>& results_collector, blockchain_storage& bch):m_results_collector(results_collector), m_bch(bch)
{}
bool handle_output(const transaction& tx, const tx_out& out)
{
//check tx unlock time
if(!m_bch.is_tx_spendtime_unlocked(tx.unlock_time))
{
LOG_PRINT_L0("One of outputs for one of inputs have wrong tx.unlock_time = " << tx.unlock_time);
return false;
}
if(out.target.type() != typeid(txout_to_key))
{
LOG_PRINT_L0("Output have wrong type id, which=" << out.target.which());
return false;
}
m_results_collector.push_back(&boost::get<txout_to_key>(out.target).key);
return true;
}
};
//check ring signature
std::vector<const crypto::public_key *> output_keys;
outputs_visitor vi(output_keys, *this);
if(!scan_outputkeys_for_indexes(txin, vi, pmax_related_block_height))
{
LOG_PRINT_L0("Failed to get output keys for tx with amount = " << print_money(txin.amount) << " and count indexes " << txin.key_offsets.size());
return false;
}
if(txin.key_offsets.size() != output_keys.size())
{
LOG_PRINT_L0("Output keys for tx with amount = " << txin.amount << " and count indexes " << txin.key_offsets.size() << " returned wrong keys count " << output_keys.size());
return false;
}
if(m_is_in_checkpoint_zone)
return true;
CHECK_AND_ASSERT_MES(sig.size() == output_keys.size(), false, "internal error: tx signatures count=" << sig.size() << " mismatch with outputs keys count for inputs=" << output_keys.size());
return crypto::check_ring_signature(tx_prefix_hash, txin.k_image, output_keys, sig.data());
}
//------------------------------------------------------------------
uint64_t blockchain_storage::get_adjusted_time()
{
//TODO: add collecting median time
return time(NULL);
}
//------------------------------------------------------------------
bool blockchain_storage::check_block_timestamp_main(const block& b)
{
if(b.timestamp > get_adjusted_time() + CURRENCY_BLOCK_FUTURE_TIME_LIMIT)
{
LOG_PRINT_L0("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", bigger than adjusted time + 2 hours");
return false;
}
std::vector<uint64_t> timestamps;
size_t offset = m_blocks.size() <= BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW ? 0: m_blocks.size()- BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW;
for(;offset!= m_blocks.size(); ++offset)
timestamps.push_back(m_blocks[offset].bl.timestamp);
return check_block_timestamp(std::move(timestamps), b);
}
//------------------------------------------------------------------
bool blockchain_storage::check_block_timestamp(std::vector<uint64_t> timestamps, const block& b)
{
if(timestamps.size() < BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW)
return true;
uint64_t median_ts = epee::misc_utils::median(timestamps);
if(b.timestamp < median_ts)
{
LOG_PRINT_L0("Timestamp of block with id: " << get_block_hash(b) << ", " << b.timestamp << ", less than median of last " << BLOCKCHAIN_TIMESTAMP_CHECK_WINDOW << " blocks, " << median_ts);
return false;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::get_block_for_scratchpad_alt(uint64_t connection_height, uint64_t block_index, std::list<blockchain_storage::blocks_ext_by_hash::iterator>& alt_chain, block & b)
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(block_index >= connection_height)
{
//take it from alt chain
for(auto it: alt_chain)
{
if(it->second.height == block_index)
{
b = it->second.bl;
return true;
}
}
CHECK_AND_ASSERT_MES(false, false, "Failed to find alternative block with height=" << block_index);
}else
{
b = m_blocks[block_index].bl;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::prune_aged_alt_blocks()
{
CRITICAL_REGION_LOCAL(m_blockchain_lock);
uint64_t current_height = get_current_blockchain_height();
for(auto it = m_alternative_chains.begin(); it != m_alternative_chains.end();)
{
if( current_height > it->second.height && current_height - it->second.height > CURRENCY_ALT_BLOCK_LIVETIME_COUNT)
m_alternative_chains.erase(it++);
else
++it;
}
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::handle_block_to_main_chain(const block& bl, const crypto::hash& id, block_verification_context& bvc)
{
TIME_MEASURE_START(block_processing_time);
CRITICAL_REGION_LOCAL(m_blockchain_lock);
if(bl.prev_id != get_top_block_id())
{
LOG_PRINT_L0("Block with id: " << id << ENDL
<< "have wrong prev_id: " << bl.prev_id << ENDL
<< "expected: " << get_top_block_id());
return false;
}
if(!check_block_timestamp_main(bl))
{
LOG_PRINT_L0("Block with id: " << id << ENDL
<< "have invalid timestamp: " << bl.timestamp);
//add_block_as_invalid(bl, id);//do not add blocks to invalid storage befor proof of work check was passed
bvc.m_verifivation_failed = true;
return false;
}
//check proof of work
TIME_MEASURE_START(target_calculating_time);
wide_difficulty_type current_diffic = get_difficulty_for_next_block();
CHECK_AND_ASSERT_MES(current_diffic, false, "!!!!!!!!! difficulty overhead !!!!!!!!!");
TIME_MEASURE_FINISH(target_calculating_time);
TIME_MEASURE_START(longhash_calculating_time);
crypto::hash proof_of_work = null_hash;
proof_of_work = get_block_longhash(bl, m_blocks.size(), [&](uint64_t index) -> crypto::hash&
{
return m_scratchpad[index%m_scratchpad.size()];
});
if(!check_hash(proof_of_work, current_diffic))
{
LOG_PRINT_L0("Block with id: " << id << ENDL
<< "have not enough proof of work: " << proof_of_work << ENDL
<< "nexpected difficulty: " << current_diffic );
bvc.m_verifivation_failed = true;
return false;
}
if(m_checkpoints.is_in_checkpoint_zone(get_current_blockchain_height()))
{
m_is_in_checkpoint_zone = true;
if(!m_checkpoints.check_block(get_current_blockchain_height(), id))
{
LOG_ERROR("CHECKPOINT VALIDATION FAILED");
bvc.m_verifivation_failed = true;
return false;
}
}else
m_is_in_checkpoint_zone = false;
TIME_MEASURE_FINISH(longhash_calculating_time);
if(!prevalidate_miner_transaction(bl, m_blocks.size()))
{
LOG_PRINT_L0("Block with id: " << id
<< " failed to pass prevalidation");
bvc.m_verifivation_failed = true;
return false;
}
size_t coinbase_blob_size = get_object_blobsize(bl.miner_tx);
size_t cumulative_block_size = coinbase_blob_size;
//process transactions
if(!add_transaction_from_block(bl.miner_tx, get_transaction_hash(bl.miner_tx), id, get_current_blockchain_height()))
{
LOG_PRINT_L0("Block with id: " << id << " failed to add transaction to blockchain storage");
bvc.m_verifivation_failed = true;
return false;
}
size_t tx_processed_count = 0;
uint64_t fee_summary = 0;
BOOST_FOREACH(const crypto::hash& tx_id, bl.tx_hashes)
{
transaction tx;
size_t blob_size = 0;
uint64_t fee = 0;
if(!m_tx_pool.take_tx(tx_id, tx, blob_size, fee))
{
LOG_PRINT_L0("Block with id: " << id << "have at least one unknown transaction with id: " << tx_id);
purge_block_data_from_blockchain(bl, tx_processed_count);
//add_block_as_invalid(bl, id);
bvc.m_verifivation_failed = true;
return false;
}
//If we under checkpoints, ring signatures should be pruned
if(m_is_in_checkpoint_zone)
{
tx.signatures.clear();
}
if(!check_tx_inputs(tx))
{
LOG_PRINT_L0("Block with id: " << id << "have at least one transaction (id: " << tx_id << ") with wrong inputs.");
currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
bool add_res = m_tx_pool.add_tx(tx, tvc, true);
CHECK_AND_ASSERT_MES2(add_res, "handle_block_to_main_chain: failed to add transaction back to transaction pool");
purge_block_data_from_blockchain(bl, tx_processed_count);
add_block_as_invalid(bl, id);
LOG_PRINT_L0("Block with id " << id << " added as invalid becouse of wrong inputs in transactions");
bvc.m_verifivation_failed = true;
return false;
}
if(!add_transaction_from_block(tx, tx_id, id, get_current_blockchain_height()))
{
LOG_PRINT_L0("Block with id: " << id << " failed to add transaction to blockchain storage");
currency::tx_verification_context tvc = AUTO_VAL_INIT(tvc);
bool add_res = m_tx_pool.add_tx(tx, tvc, true);
CHECK_AND_ASSERT_MES2(add_res, "handle_block_to_main_chain: failed to add transaction back to transaction pool");
purge_block_data_from_blockchain(bl, tx_processed_count);
bvc.m_verifivation_failed = true;
return false;
}
fee_summary += fee;
cumulative_block_size += blob_size;
++tx_processed_count;
}
uint64_t base_reward = 0;
uint64_t already_generated_coins = m_blocks.size() ? m_blocks.back().already_generated_coins:0;
uint64_t already_donated_coins = m_blocks.size() ? m_blocks.back().already_donated_coins:0;
uint64_t donation_total = 0;
if(!validate_miner_transaction(bl, cumulative_block_size, fee_summary, base_reward, already_generated_coins, already_donated_coins, donation_total))
{
LOG_PRINT_L0("Block with id: " << id
<< " have wrong miner transaction");
purge_block_data_from_blockchain(bl, tx_processed_count);
bvc.m_verifivation_failed = true;
return false;
}
block_extended_info bei = boost::value_initialized<block_extended_info>();
bei.bl = bl;
bei.scratch_offset = m_scratchpad.size();
bei.block_cumulative_size = cumulative_block_size;
bei.cumulative_difficulty = current_diffic;
bei.already_generated_coins = already_generated_coins + base_reward;
bei.already_donated_coins = already_donated_coins + donation_total;
if(m_blocks.size())
bei.cumulative_difficulty += m_blocks.back().cumulative_difficulty;
bei.height = m_blocks.size();
auto ind_res = m_blocks_index.insert(std::pair<crypto::hash, size_t>(id, bei.height));
if(!ind_res.second)
{
LOG_ERROR("block with id: " << id << " already in block indexes");
purge_block_data_from_blockchain(bl, tx_processed_count);
bvc.m_verifivation_failed = true;
return false;
}
//append to scratchpad
if(!push_block_scratchpad_data(bl, m_scratchpad))
{
LOG_ERROR("Internal error for block id: " << id << ": failed to put_block_scratchpad_data");
purge_block_data_from_blockchain(bl, tx_processed_count);
bvc.m_verifivation_failed = true;
return false;
}
#ifdef ENABLE_HASHING_DEBUG
LOG_PRINT_L3("SCRATCHPAD_SHOT FOR H=" << bei.height+1 << ENDL << dump_scratchpad(m_scratchpad));
#endif
m_blocks.push_back(bei);
update_next_comulative_size_limit();
TIME_MEASURE_FINISH(block_processing_time);
LOG_PRINT_L1("+++++ BLOCK SUCCESSFULLY ADDED" << ENDL << "id:\t" << id
<< ENDL << "PoW:\t" << proof_of_work
<< ENDL << "HEIGHT " << bei.height << ", difficulty:\t" << current_diffic
<< ENDL << "block reward: " << print_money(fee_summary + base_reward) << "(" << print_money(base_reward) << " + " << print_money(fee_summary)
<< ")" << ( (bei.height%CURRENCY_DONATIONS_INTERVAL)?std::string(""):std::string("donation: ") + print_money(donation_total) ) << ", coinbase_blob_size: " << coinbase_blob_size << ", cumulative size: " << cumulative_block_size
<< ", " << block_processing_time << "("<< target_calculating_time << "/" << longhash_calculating_time << ")ms");
bvc.m_added_to_main_chain = true;
m_tx_pool.on_blockchain_inc(bei.height, id);
//LOG_PRINT_L0("BLOCK: " << ENDL << "" << dump_obj_as_json(bei.bl));
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::update_next_comulative_size_limit()
{
std::vector<size_t> sz;
get_last_n_blocks_sizes(sz, CURRENCY_REWARD_BLOCKS_WINDOW);
uint64_t median = misc_utils::median(sz);
if(median <= CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE)
median = CURRENCY_BLOCK_GRANTED_FULL_REWARD_ZONE;
m_current_block_cumul_sz_limit = median*2;
return true;
}
//------------------------------------------------------------------
bool blockchain_storage::add_new_block(const block& bl_, block_verification_context& bvc)
{
//copy block here to let modify block.target
block bl = bl_;
crypto::hash id = get_block_hash(bl);
CRITICAL_REGION_LOCAL(m_tx_pool);//to avoid deadlock lets lock tx_pool for whole add/reorganize process
CRITICAL_REGION_LOCAL1(m_blockchain_lock);
if(have_block(id))
{
LOG_PRINT_L3("block with id = " << id << " already exists");
bvc.m_already_exists = true;
return false;
}
//check that block refers to chain tail
if(!(bl.prev_id == get_top_block_id()))
{
//chain switching or wrong block
bvc.m_added_to_main_chain = false;
bool r = handle_alternative_block(bl, id, bvc);
return r;
//never relay alternative blocks
}
return handle_block_to_main_chain(bl, id, bvc);
} | 41.482393 | 297 | 0.663049 | UScrypto |
91beb4ae0b8f9ec855d9a00590a37a36cd0602a0 | 6,099 | cpp | C++ | src/sampling.cpp | Algebraicphylogenetics/Empar | 1c2b4eec4ac0917c65786acf36de4b906d95715c | [
"MIT"
] | null | null | null | src/sampling.cpp | Algebraicphylogenetics/Empar | 1c2b4eec4ac0917c65786acf36de4b906d95715c | [
"MIT"
] | null | null | null | src/sampling.cpp | Algebraicphylogenetics/Empar | 1c2b4eec4ac0917c65786acf36de4b906d95715c | [
"MIT"
] | null | null | null | /*
* sampling.cpp
*
* Created by Ania M. Kedzierska on 11/11/11.
* Copyright 2011 Politecnic University of Catalonia, Center for Genomic Regulation. This is program can be redistributed, modified or else as given by the terms of the GNU General Public License.
*
*/
#include <iostream>
#include <cstdlib>
#include "random.h"
#include "sampling.h"
#include "miscelania.h"
#include "em.h"
#include <stdexcept>
#include "boost/math/distributions/chi_squared.hpp"
Counts data;
// Produces random parameters without length restriction.
void random_parameters(Model &Mod, Parameters &Par){
long k;
if (Par.nalpha != Mod.nalpha) {
throw std::out_of_range( "Number of states in model does not match parameters");
}
for(k=0; k < Par.nedges; k++) {
Mod.random_edge(Par.tm[k]);
}
Mod.random_root(Par.r);
}
// Produces random parameters of given lengths (as given inside Par).
// The lengths are given as a vector matching the list of edges.
// The generated parameters are biologically meaningful ( DLC as in Chang, 1966), i.e. every diagonal entry is the largest in its column.
void random_parameters_length(Tree &T, Model &Mod, Parameters &Par){
long k;
if (Par.nalpha != Mod.nalpha) {
throw std::length_error("Number of states in model does not match parameters");
}
if (T.nedges != Par.nedges) {
throw std::length_error( "Number of edges in tree does not match parameters");
}
for(k=0; k < Par.nedges; k++) {
Mod.random_edge_bio_length((T.edges[k]).br, Par.tm[k]);
}
Mod.random_root(Par.r);
}
// Simulates the data used for testing. Stores the data in data and the parameters in Parsim.
Counts random_fake_counts(Tree &T, double N, Parameters &Parsim) {
long i;
// Fills in simulated counts
data.N = 0;
data.c.resize(T.nstleaves); // assigns memory
for (i=0; i < T.nstleaves; i++) {
data.c[i] = N*joint_prob_leaves(T, Parsim, i);
data.N = data.N + data.c[i];
}
// Copies species names.
data.species.resize(T.nleaves); // assigns memory
for (i=0; i < T.nleaves; i++) {
data.species[i] = T.names[i];
}
// Fills in the rest of the struct.
data.nalpha = 4;
data.nspecies = T.nleaves;
data.nstates = T.nstleaves;
return data;
}
// Puts a random state on st, following the given model and parameters.
void random_state(Tree &T, Model &Mod, Parameters &Par, State &st) {
long i, e;
bool updated;
if (st.len != T.nnodes) {
std::cout << "Tree and state are not compatible." << std::endl;
}
// reset the state to a negative value.
for(i=0; i < st.len; i++) st.s[i] = -1;
// random state on the root.
st.s[T.nleaves] = discrete(Par.r);
updated = true;
while(updated) {
updated = false;
// run over the edges, and update any states necessary
for(e=0; e < T.nedges; e++) {
// if there is something to be updated
if (st.s[T.edges[e].s] >= 0 && st.s[T.edges[e].t] < 0) {
updated = true;
st.s[T.edges[e].t] = discrete(Par.tm[e][st.s[T.edges[e].s]]);
}
}
}
}
// Simulates counts for the full observable and hidden state matrix F.
void random_full_counts(Tree &T, Model &Mod, Parameters &Par, long length, Matrix &F) {
long i, j, k;
long a, b;
State st, sth, stl;
create_state(st, T.nnodes, T.nalpha);
create_state(sth, T.nhidden, T.nalpha);
create_state(stl, T.nleaves, T.nalpha);
for(i=0; i < T.nstleaves; i++) {
for(j=0; j < T.nsthidden; j++) {
F.m[i][j] = 0;
}
}
for (k=0; k < length; k++) {
random_state(T, Mod, Par, st);
// the first nleaves nodes are the leaves
for (i=0; i < T.nleaves; i++) {
stl.s[i] = st.s[i];
}
for (i=T.nleaves; i < T.nnodes; i++) {
sth.s[i - T.nleaves] = st.s[i];
}
a = state2index(stl);
b = state2index(sth);
F.m[a][b] = F.m[a][b] + 1.;
}
}
// Simulates an alignment for a given tree, model and parameters.
void random_data(Tree &T, Model &Mod, Parameters &Par, long length, Alignment &align) {
if (T.nedges != Par.nedges) {
std::cout << "Error: Tree and Parameters are not compatible" << std::endl;
}
long i, j;
State st;
create_state(st, T.nnodes, T.nalpha);
// The 4 DNA bases:
align.nalpha = 4;
align.alpha.resize(align.nalpha);
align.alpha[0] = 'A';
align.alpha[1] = 'C';
align.alpha[2] = 'G';
align.alpha[3] = 'T';
align.nspecies = T.nleaves;
align.len = length;
align.seq.resize(align.nspecies);
align.name.resize(align.nspecies);
for (i=0; i < align.nspecies; i++) {
(align.seq[i]).resize(length);
align.name[i] = T.names[i];
}
for (i=0; i < length; i++) {
random_state(T, Mod, Par, st);
for (j=0; j < align.nspecies; j++) {
// the first nleaves nodes are the leaves
align.seq[j][i] = st.s[j];
}
}
}
// Checks if a matrix tm belongs to a given model( for matrices generated during sampling).
bool check_model_matrix(Model &Mod, TMatrix &tm) {
long i, j, k, l;
long a, b;
for(i=0; i < Mod.nalpha; i++) {
for(j=0; j < Mod.nalpha; j++) {
for(k=0; k < Mod.nalpha; k++) {
for(l=0; l < Mod.nalpha; l++) {
a = Mod.matrix_structure(i, j);
b = Mod.matrix_structure(k, l);
if (a == b && tm[i][j] != tm[k][l]) {
return false;
}
}
}
}
}
return true;
}
bool check_DLC_matrix(TMatrix &tm) {
long i0;
for (unsigned long i=0; i < tm[0].size(); i++) {
i0 = max_in_col(tm, i);
if (i0 != (long)i) return false;
}
return true;
}
bool check_matrix_length(double len, TMatrix &tm) {
double clen;
double eps = 1e-10;
clen = branch_length(tm, tm.size());
if (boost::math::isnan(clen)) return false;
if (fabs(clen - len) > eps) return false;
else return true;
}
bool check_matrix_stochastic(TMatrix &tm) {
double sum;
double eps = 1e-10;
for(unsigned long i=0; i < tm.size(); i++) {
sum = 0;
for(unsigned long j=0; j < tm[i].size(); j++) {
if (tm[i][j] < 0) return false;
sum = sum + tm[i][j];
}
if (fabs(sum - 1) > eps) return false;
}
return true;
}
| 24.493976 | 198 | 0.608296 | Algebraicphylogenetics |
91c4cbd4d21cadea7cd6e77cfe1d4d540c861c9b | 1,181 | cpp | C++ | c++/leetcode/0953-Verifying_an_Alien_Dictionary-E.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | 1 | 2020-03-02T10:56:22.000Z | 2020-03-02T10:56:22.000Z | c++/leetcode/0953-Verifying_an_Alien_Dictionary-E.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | c++/leetcode/0953-Verifying_an_Alien_Dictionary-E.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | // 953 Verifying an Alien Dictionary
// https://leetcode.com/problems/verifying-an-alien-dictionary
// version: 1; create time: 2020-01-14 22:54:25;
class Solution {
public:
bool isAlienSorted(vector<string>& words, string order) {
int order_index[26];
for (int i = 0; i < 26; ++i) {
const auto c = order[i];
order_index[c - 'a'] = i;
}
const int n = words.size();
const auto is_sorted = [&](const string& w0, const string& w1) {
const int m = std::min(w0.size(), w1.size());
for (int j = 0; j < m; ++j) {
const int idx0 = w0[j] - 'a';
const int idx1 = w1[j] - 'a';
if (order_index[idx0] > order_index[idx1]) {
return false;
} else if (order_index[idx0] < order_index[idx1]) {
return true;
}
}
return w0.size() <= w1.size();
};
if (n <= 1) return true;
for (int i = 1; i < n; ++i) {
if (!is_sorted(words[i-1], words[i])) {
return false;
}
}
return true;
}
};
| 31.918919 | 72 | 0.458933 | levendlee |
91c72ac9ce76c638fd476ad637785c2dc856d710 | 9,391 | cpp | C++ | dwarf/SB/Core/x/xMovePoint.cpp | stravant/bfbbdecomp | 2126be355a6bb8171b850f829c1f2731c8b5de08 | [
"OLDAP-2.7"
] | 1 | 2021-01-05T11:28:55.000Z | 2021-01-05T11:28:55.000Z | dwarf/SB/Core/x/xMovePoint.cpp | sonich2401/bfbbdecomp | 5f58b62505f8929a72ccf2aa118a1539eb3a5bd6 | [
"OLDAP-2.7"
] | null | null | null | dwarf/SB/Core/x/xMovePoint.cpp | sonich2401/bfbbdecomp | 5f58b62505f8929a72ccf2aa118a1539eb3a5bd6 | [
"OLDAP-2.7"
] | 1 | 2022-03-30T15:15:08.000Z | 2022-03-30T15:15:08.000Z | typedef struct xLinkAsset;
typedef struct xMovePoint;
typedef struct xMovePointAsset;
typedef struct xEnt;
typedef struct xBaseAsset;
typedef struct xVec3;
typedef struct xEnv;
typedef struct xSerial;
typedef struct xCoef;
typedef struct xSpline3;
typedef struct xCoef3;
typedef struct xScene;
typedef struct xMemPool;
typedef struct xBase;
typedef int32(*type_0)(xBase*, xBase*, uint32, float32*, xBase*);
typedef xBase*(*type_1)(uint32);
typedef int8*(*type_2)(xBase*);
typedef int8*(*type_3)(uint32);
typedef void(*type_6)(xMemPool*, void*);
typedef float32 type_4[4];
typedef uint8 type_5[2];
typedef float32 type_7[4];
typedef xVec3 type_8[2];
struct xLinkAsset
{
uint16 srcEvent;
uint16 dstEvent;
uint32 dstAssetID;
float32 param[4];
uint32 paramWidgetAssetID;
uint32 chkAssetID;
};
struct xMovePoint : xBase
{
xMovePointAsset* asset;
xVec3* pos;
xMovePoint** nodes;
xMovePoint* prev;
uint32 node_wt_sum;
uint8 on;
uint8 pad[2];
float32 delay;
xSpline3* spl;
};
struct xMovePointAsset : xBaseAsset
{
xVec3 pos;
uint16 wt;
uint8 on;
uint8 bezIndex;
uint8 flg_props;
uint8 pad;
uint16 numPoints;
float32 delay;
float32 zoneRadius;
float32 arenaRadius;
};
struct xEnt
{
};
struct xBaseAsset
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
};
struct xVec3
{
float32 x;
float32 y;
float32 z;
};
struct xEnv
{
};
struct xSerial
{
};
struct xCoef
{
float32 a[4];
};
struct xSpline3
{
uint16 type;
uint16 flags;
uint32 N;
uint32 allocN;
xVec3* points;
float32* time;
xVec3* p12;
xVec3* bctrl;
float32* knot;
xCoef3* coef;
uint32 arcSample;
float32* arcLength;
};
struct xCoef3
{
xCoef x;
xCoef y;
xCoef z;
};
struct xScene
{
uint32 sceneID;
uint16 flags;
uint16 num_ents;
uint16 num_trigs;
uint16 num_stats;
uint16 num_dyns;
uint16 num_npcs;
uint16 num_act_ents;
uint16 num_nact_ents;
float32 gravity;
float32 drag;
float32 friction;
uint16 num_ents_allocd;
uint16 num_trigs_allocd;
uint16 num_stats_allocd;
uint16 num_dyns_allocd;
uint16 num_npcs_allocd;
xEnt** trigs;
xEnt** stats;
xEnt** dyns;
xEnt** npcs;
xEnt** act_ents;
xEnt** nact_ents;
xEnv* env;
xMemPool mempool;
xBase*(*resolvID)(uint32);
int8*(*base2Name)(xBase*);
int8*(*id2Name)(uint32);
};
struct xMemPool
{
void* FreeList;
uint16 NextOffset;
uint16 Flags;
void* UsedList;
void(*InitCB)(xMemPool*, void*);
void* Buffer;
uint16 Size;
uint16 NumRealloc;
uint32 Total;
};
struct xBase
{
uint32 id;
uint8 baseType;
uint8 linkCount;
uint16 baseFlags;
xLinkAsset* link;
int32(*eventFunc)(xBase*, xBase*, uint32, float32*, xBase*);
};
uint32 gActiveHeap;
xVec3* xMovePointGetPos(xMovePoint* m);
float32 xMovePointGetNext(xMovePoint* m, xMovePoint* prev, xMovePoint** next, xVec3* hdng);
void xMovePointSplineDestroy(xMovePoint* m);
void xMovePointSplineSetup(xMovePoint* m);
void xMovePointSetup(xMovePoint* m, xScene* sc);
void xMovePointReset(xMovePoint* m);
void xMovePointLoad(xMovePoint* ent, xSerial* s);
void xMovePointSave(xMovePoint* ent, xSerial* s);
void xMovePointInit(xMovePoint* m, xMovePointAsset* asset);
// xMovePointGetPos__FPC10xMovePoint
// Start address: 0x1f2870
xVec3* xMovePointGetPos(xMovePoint* m)
{
// Line 271, Address: 0x1f2870, Func Offset: 0
// Func End, Address: 0x1f2878, Func Offset: 0x8
}
// xMovePointGetNext__FPC10xMovePointPC10xMovePointPP10xMovePointP5xVec3
// Start address: 0x1f2880
float32 xMovePointGetNext(xMovePoint* m, xMovePoint* prev, xMovePoint** next, xVec3* hdng)
{
int32 rnd;
uint16 idx;
xMovePoint* previousOption;
// Line 208, Address: 0x1f2880, Func Offset: 0
// Line 214, Address: 0x1f28a8, Func Offset: 0x28
// Line 216, Address: 0x1f28b8, Func Offset: 0x38
// Line 217, Address: 0x1f28c4, Func Offset: 0x44
// Line 222, Address: 0x1f28c8, Func Offset: 0x48
// Line 223, Address: 0x1f28e4, Func Offset: 0x64
// Line 226, Address: 0x1f28f0, Func Offset: 0x70
// Line 227, Address: 0x1f2908, Func Offset: 0x88
// Line 230, Address: 0x1f2910, Func Offset: 0x90
// Line 227, Address: 0x1f2914, Func Offset: 0x94
// Line 230, Address: 0x1f2918, Func Offset: 0x98
// Line 233, Address: 0x1f2920, Func Offset: 0xa0
// Line 241, Address: 0x1f2928, Func Offset: 0xa8
// Line 244, Address: 0x1f2930, Func Offset: 0xb0
// Line 247, Address: 0x1f2938, Func Offset: 0xb8
// Line 250, Address: 0x1f2940, Func Offset: 0xc0
// Line 252, Address: 0x1f2960, Func Offset: 0xe0
// Line 255, Address: 0x1f296c, Func Offset: 0xec
// Line 256, Address: 0x1f2974, Func Offset: 0xf4
// Line 258, Address: 0x1f2980, Func Offset: 0x100
// Line 259, Address: 0x1f298c, Func Offset: 0x10c
// Line 261, Address: 0x1f2990, Func Offset: 0x110
// Line 262, Address: 0x1f2998, Func Offset: 0x118
// Line 264, Address: 0x1f2a88, Func Offset: 0x208
// Line 265, Address: 0x1f2a90, Func Offset: 0x210
// Func End, Address: 0x1f2ab0, Func Offset: 0x230
}
// xMovePointSplineDestroy__FP10xMovePoint
// Start address: 0x1f2ab0
void xMovePointSplineDestroy(xMovePoint* m)
{
// Line 174, Address: 0x1f2ab0, Func Offset: 0
// Line 176, Address: 0x1f2abc, Func Offset: 0xc
// Line 178, Address: 0x1f2ac0, Func Offset: 0x10
// Func End, Address: 0x1f2ac8, Func Offset: 0x18
}
// xMovePointSplineSetup__FP10xMovePoint
// Start address: 0x1f2ad0
void xMovePointSplineSetup(xMovePoint* m)
{
xMovePoint* w0;
xMovePoint* w2;
xMovePoint* w3;
xVec3 points[2];
xVec3 p1;
xVec3 p2;
// Line 123, Address: 0x1f2ad0, Func Offset: 0
// Line 130, Address: 0x1f2ad4, Func Offset: 0x4
// Line 123, Address: 0x1f2ad8, Func Offset: 0x8
// Line 130, Address: 0x1f2ae4, Func Offset: 0x14
// Line 137, Address: 0x1f2b00, Func Offset: 0x30
// Line 139, Address: 0x1f2b04, Func Offset: 0x34
// Line 141, Address: 0x1f2b08, Func Offset: 0x38
// Line 139, Address: 0x1f2b0c, Func Offset: 0x3c
// Line 141, Address: 0x1f2b10, Func Offset: 0x40
// Line 144, Address: 0x1f2b28, Func Offset: 0x58
// Line 146, Address: 0x1f2b38, Func Offset: 0x68
// Line 147, Address: 0x1f2b3c, Func Offset: 0x6c
// Line 146, Address: 0x1f2b40, Func Offset: 0x70
// Line 147, Address: 0x1f2b44, Func Offset: 0x74
// Line 148, Address: 0x1f2b5c, Func Offset: 0x8c
// Line 149, Address: 0x1f2b78, Func Offset: 0xa8
// Line 150, Address: 0x1f2b90, Func Offset: 0xc0
// Line 157, Address: 0x1f2b98, Func Offset: 0xc8
// Line 158, Address: 0x1f2bd0, Func Offset: 0x100
// Line 159, Address: 0x1f2bec, Func Offset: 0x11c
// Line 160, Address: 0x1f2c08, Func Offset: 0x138
// Line 161, Address: 0x1f2c24, Func Offset: 0x154
// Line 162, Address: 0x1f2c40, Func Offset: 0x170
// Line 163, Address: 0x1f2c5c, Func Offset: 0x18c
// Line 167, Address: 0x1f2c78, Func Offset: 0x1a8
// Line 168, Address: 0x1f2c98, Func Offset: 0x1c8
// Line 169, Address: 0x1f2ca4, Func Offset: 0x1d4
// Line 170, Address: 0x1f2ca8, Func Offset: 0x1d8
// Func End, Address: 0x1f2cb8, Func Offset: 0x1e8
}
// xMovePointSetup__FP10xMovePointP6xScene
// Start address: 0x1f2cc0
void xMovePointSetup(xMovePoint* m, xScene* sc)
{
uint32* id;
uint16 idx;
// Line 98, Address: 0x1f2cc0, Func Offset: 0
// Line 106, Address: 0x1f2ce4, Func Offset: 0x24
// Line 107, Address: 0x1f2cec, Func Offset: 0x2c
// Line 109, Address: 0x1f2cf0, Func Offset: 0x30
// Line 113, Address: 0x1f2d08, Func Offset: 0x48
// Line 119, Address: 0x1f2d18, Func Offset: 0x58
// Line 118, Address: 0x1f2d20, Func Offset: 0x60
// Line 113, Address: 0x1f2d24, Func Offset: 0x64
// Line 116, Address: 0x1f2d2c, Func Offset: 0x6c
// Line 118, Address: 0x1f2d4c, Func Offset: 0x8c
// Line 119, Address: 0x1f2d5c, Func Offset: 0x9c
// Line 120, Address: 0x1f2d70, Func Offset: 0xb0
// Func End, Address: 0x1f2d90, Func Offset: 0xd0
}
// xMovePointReset__FP10xMovePoint
// Start address: 0x1f2d90
void xMovePointReset(xMovePoint* m)
{
// Line 85, Address: 0x1f2d90, Func Offset: 0
// Line 90, Address: 0x1f2d9c, Func Offset: 0xc
// Line 93, Address: 0x1f2da8, Func Offset: 0x18
// Line 94, Address: 0x1f2db4, Func Offset: 0x24
// Line 95, Address: 0x1f2dc0, Func Offset: 0x30
// Func End, Address: 0x1f2dd0, Func Offset: 0x40
}
// xMovePointLoad__FP10xMovePointP7xSerial
// Start address: 0x1f2dd0
void xMovePointLoad(xMovePoint* ent, xSerial* s)
{
// Line 78, Address: 0x1f2dd0, Func Offset: 0
// Func End, Address: 0x1f2dd8, Func Offset: 0x8
}
// xMovePointSave__FP10xMovePointP7xSerial
// Start address: 0x1f2de0
void xMovePointSave(xMovePoint* ent, xSerial* s)
{
// Line 59, Address: 0x1f2de0, Func Offset: 0
// Func End, Address: 0x1f2de8, Func Offset: 0x8
}
// xMovePointInit__FP10xMovePointP15xMovePointAsset
// Start address: 0x1f2df0
void xMovePointInit(xMovePoint* m, xMovePointAsset* asset)
{
// Line 24, Address: 0x1f2df0, Func Offset: 0
// Line 28, Address: 0x1f2e04, Func Offset: 0x14
// Line 30, Address: 0x1f2e0c, Func Offset: 0x1c
// Line 31, Address: 0x1f2e10, Func Offset: 0x20
// Line 34, Address: 0x1f2e1c, Func Offset: 0x2c
// Line 35, Address: 0x1f2e24, Func Offset: 0x34
// Line 36, Address: 0x1f2e2c, Func Offset: 0x3c
// Line 38, Address: 0x1f2e34, Func Offset: 0x44
// Line 39, Address: 0x1f2e3c, Func Offset: 0x4c
// Line 41, Address: 0x1f2e4c, Func Offset: 0x5c
// Line 44, Address: 0x1f2e58, Func Offset: 0x68
// Line 45, Address: 0x1f2e5c, Func Offset: 0x6c
// Line 46, Address: 0x1f2e60, Func Offset: 0x70
// Func End, Address: 0x1f2e74, Func Offset: 0x84
}
| 26.908309 | 91 | 0.728676 | stravant |
91ca9f6c30220237d286d7ad387f085e03f7dc47 | 9,163 | cpp | C++ | Plugins/UnLua/Source/UnLua/Private/Registries/ClassRegistry.cpp | xiejiangzhi/UnLua | 86ad978f939016caed1d11f803bb79bc73dbdfc1 | [
"MIT"
] | 1 | 2022-03-24T02:56:59.000Z | 2022-03-24T02:56:59.000Z | Plugins/UnLua/Source/UnLua/Private/Registries/ClassRegistry.cpp | xiejiangzhi/UnLua | 86ad978f939016caed1d11f803bb79bc73dbdfc1 | [
"MIT"
] | null | null | null | Plugins/UnLua/Source/UnLua/Private/Registries/ClassRegistry.cpp | xiejiangzhi/UnLua | 86ad978f939016caed1d11f803bb79bc73dbdfc1 | [
"MIT"
] | null | null | null | // Tencent is pleased to support the open source community by making UnLua available.
//
// Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// 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 "Registries/ClassRegistry.h"
#include "LuaEnv.h"
#include "Binding.h"
#include "LowLevel.h"
#include "LuaCore.h"
#include "UELib.h"
#include "ReflectionUtils/ClassDesc.h"
extern int32 UObject_Identical(lua_State* L);
extern int32 UObject_Delete(lua_State* L);
namespace UnLua
{
TMap<UStruct*, FClassDesc*> FClassRegistry::Classes;
TMap<FName, FClassDesc*> FClassRegistry::Name2Classes;
FClassRegistry::FClassRegistry(FLuaEnv* Env)
: Env(Env)
{
}
TSharedPtr<FClassRegistry> FClassRegistry::Find(const lua_State* L)
{
const auto Env = FLuaEnv::FindEnv(L);
if (Env == nullptr)
return nullptr;
return Env->GetClassRegistry();
}
FClassDesc* FClassRegistry::Find(const char* TypeName)
{
const FName Key = TypeName;
FClassDesc** Ret = Name2Classes.Find(Key);
return Ret ? *Ret : nullptr;
}
FClassDesc* FClassRegistry::Find(const UStruct* Type)
{
FClassDesc** Ret = Classes.Find(Type);
return Ret ? *Ret : nullptr;
}
FClassDesc* FClassRegistry::RegisterReflectedType(const char* MetatableName)
{
FClassDesc* Ret = Find(MetatableName);
if (Ret)
{
Classes.FindOrAdd(Ret->AsStruct(), Ret);
return Ret;
}
const char* TypeName = MetatableName[0] == 'U' || MetatableName[0] == 'A' || MetatableName[0] == 'F' ? MetatableName + 1 : MetatableName;
const auto Type = LoadReflectedType(TypeName);
if (!Type)
return nullptr;
const auto StructType = Cast<UStruct>(Type);
if (StructType)
{
Ret = RegisterInternal(StructType, UTF8_TO_TCHAR(MetatableName));
return Ret;
}
const auto EnumType = Cast<UEnum>(Type);
if (EnumType)
{
// TODO:
check(false);
}
return nullptr;
}
FClassDesc* FClassRegistry::RegisterReflectedType(UStruct* Type)
{
FClassDesc** Exists = Classes.Find(Type);
if (Exists)
return *Exists;
const auto MetatableName = LowLevel::GetMetatableName(Type);
Exists = Name2Classes.Find(FName(MetatableName));
if (Exists)
{
Classes.Add(Type, *Exists);
return *Exists;
}
const auto Ret = RegisterInternal(Type, MetatableName);
return Ret;
}
bool FClassRegistry::StaticUnregister(const UObjectBase* Type)
{
FClassDesc* ClassDesc;
if (!Classes.RemoveAndCopyValue((UStruct*)Type, ClassDesc))
return false;
ClassDesc->UnLoad();
for (auto Pair : FLuaEnv::AllEnvs)
{
auto Registry = Pair.Value->GetClassRegistry();
Registry->Unregister(ClassDesc);
}
return true;
}
bool FClassRegistry::PushMetatable(lua_State* L, const char* MetatableName)
{
int Type = luaL_getmetatable(L, MetatableName);
if (Type == LUA_TTABLE)
return true;
lua_pop(L, 1);
if (FindExportedNonReflectedClass(MetatableName))
return false;
FClassDesc* ClassDesc = RegisterReflectedType(MetatableName);
if (!ClassDesc)
return false;
luaL_newmetatable(L, MetatableName);
lua_pushstring(L, "__index");
lua_pushcfunction(L, Class_Index);
lua_rawset(L, -3);
lua_pushstring(L, "__newindex");
lua_pushcfunction(L, Class_NewIndex);
lua_rawset(L, -3);
uint64 TypeHash = (uint64)ClassDesc->AsStruct();
lua_pushstring(L, "TypeHash");
lua_pushnumber(L, TypeHash);
lua_rawset(L, -3);
UScriptStruct* ScriptStruct = ClassDesc->AsScriptStruct();
if (ScriptStruct)
{
lua_pushlightuserdata(L, ClassDesc);
lua_pushstring(L, "Copy");
lua_pushvalue(L, -2);
lua_pushcclosure(L, ScriptStruct_Copy, 1);
lua_rawset(L, -4);
lua_pushstring(L, "CopyFrom");
lua_pushvalue(L, -2);
lua_pushcclosure(L, ScriptStruct_CopyFrom, 1);
lua_rawset(L, -4);
lua_pushstring(L, "__eq");
lua_pushvalue(L, -2);
lua_pushcclosure(L, ScriptStruct_Compare, 1);
lua_rawset(L, -4);
lua_pushstring(L, "__gc");
lua_pushvalue(L, -2);
lua_pushcclosure(L, ScriptStruct_Delete, 1);
lua_rawset(L, -4);
lua_pushstring(L, "__call");
lua_pushvalue(L, -2);
lua_pushcclosure(L, ScriptStruct_New, 1); // closure
lua_rawset(L, -4);
lua_pop(L, 1);
}
else
{
UClass* Class = ClassDesc->AsClass();
if (Class != UObject::StaticClass() && Class != UClass::StaticClass())
{
lua_pushstring(L, "ClassDesc");
lua_pushlightuserdata(L, ClassDesc);
lua_rawset(L, -3);
lua_pushstring(L, "StaticClass");
lua_pushlightuserdata(L, ClassDesc);
lua_pushcclosure(L, Class_StaticClass, 1);
lua_rawset(L, -3);
lua_pushstring(L, "Cast");
lua_pushcfunction(L, Class_Cast);
lua_rawset(L, -3);
lua_pushstring(L, "__eq");
lua_pushcfunction(L, UObject_Identical);
lua_rawset(L, -3);
lua_pushstring(L, "__gc");
lua_pushcfunction(L, UObject_Delete);
lua_rawset(L, -3);
}
}
lua_pushvalue(L, -1); // set metatable to self
lua_setmetatable(L, -2);
TArray<FClassDesc*> ClassDescChain;
ClassDesc->GetInheritanceChain(ClassDescChain);
TArray<IExportedClass*> ExportedClasses;
for (int32 i = ClassDescChain.Num() - 1; i > -1; --i)
{
auto ExportedClass = FindExportedReflectedClass(*ClassDescChain[i]->GetName());
if (ExportedClass)
ExportedClass->Register(L);
}
UELib::SetTableForClass(L, MetatableName);
return true;
}
bool FClassRegistry::TrySetMetatable(lua_State* L, const char* MetatableName)
{
if (!PushMetatable(L, MetatableName))
return false;
lua_setmetatable(L, -2);
return true;
}
FClassDesc* FClassRegistry::Register(const char* MetatableName)
{
const auto L = Env->GetMainState();
if (!PushMetatable(L, MetatableName))
return nullptr;
// TODO: refactor
lua_pop(L, 1);
FName Key = FName(UTF8_TO_TCHAR(MetatableName));
return Name2Classes.FindChecked(Key);
}
FClassDesc* FClassRegistry::Register(const UStruct* Class)
{
const auto MetatableName = LowLevel::GetMetatableName(Class);
return Register(TCHAR_TO_UTF8(*MetatableName));
}
void FClassRegistry::Cleanup()
{
for (const auto Pair : Name2Classes)
delete Pair.Value;
Name2Classes.Empty();
Classes.Empty();
}
UField* FClassRegistry::LoadReflectedType(const char* InName)
{
FString Name = UTF8_TO_TCHAR(InName);
// find candidates in memory
UField* Ret = FindObject<UClass>(ANY_PACKAGE, *Name);
if (!Ret)
Ret = FindObject<UScriptStruct>(ANY_PACKAGE, *Name);
if (!Ret)
Ret = FindObject<UEnum>(ANY_PACKAGE, *Name);
// load candidates if not found
if (!Ret)
Ret = LoadObject<UClass>(nullptr, *Name);
if (!Ret)
Ret = LoadObject<UScriptStruct>(nullptr, *Name);
if (!Ret)
Ret = LoadObject<UEnum>(nullptr, *Name);
return Ret;
}
FClassDesc* FClassRegistry::RegisterInternal(UStruct* Type, const FString& Name)
{
check(Type);
check(!Classes.Contains(Type));
FClassDesc* ClassDesc = new FClassDesc(Type, Name);
Classes.Add(Type, ClassDesc);
Name2Classes.Add(FName(*Name), ClassDesc);
return ClassDesc;
}
void FClassRegistry::Unregister(const FClassDesc* ClassDesc)
{
const auto L = Env->GetMainState();
const auto MetatableName = ClassDesc->GetName();
lua_pushnil(L);
lua_setfield(L, LUA_REGISTRYINDEX, TCHAR_TO_UTF8(*MetatableName));
}
}
| 30.141447 | 145 | 0.58889 | xiejiangzhi |
91cadaf1f75cbf8a4c49b75247976a88e84dacc1 | 827 | cpp | C++ | soj/3845.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | soj/3845.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | soj/3845.cpp | huangshenno1/project_euler | 8a3c91fd11bcb6a6a830e963b1d5aed3f5ff787d | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <string.h>
int p[300];
int Parent(int n)
{
if (p[n]==-1)
return n;
return p[n]=Parent(p[n]);
}
void Swap(int &a,int &b)
{
int temp=a;
a=b;
b=temp;
}
int main()
{
int n,m;
int a,b;
int i,count;
while (scanf("%d%d",&n,&m)==2)
{
memset(p,-1,sizeof(p));
while (m--)
{
scanf("%d%d",&a,&b);
a=Parent(a);
b=Parent(b);
if (a==b)
continue;
if (b==1)
Swap(a,b);
p[b]=a;
}
count=0;
for (i=1;i<=n;i++)
{
if (Parent(i)!=1)
{
printf("%d\n",i);
count++;
}
}
if (!count)
printf("0\n");
}
return 0;
} | 15.903846 | 34 | 0.336155 | huangshenno1 |
91cd45520970a6e49e6d13c3fd9db0d37fbe06a9 | 7,968 | cpp | C++ | libs/ofxCloudPlatform/src/VisionDebug.cpp | SAIC/ofxCloudPlatform | 4a97b38cb9be1faf245b9421789e9b43b5645356 | [
"MIT"
] | 1 | 2017-11-17T01:20:54.000Z | 2017-11-17T01:20:54.000Z | libs/ofxCloudPlatform/src/VisionDebug.cpp | SAIC/ofxCloudPlatform | 4a97b38cb9be1faf245b9421789e9b43b5645356 | [
"MIT"
] | 3 | 2017-09-30T18:30:08.000Z | 2019-11-21T09:14:42.000Z | libs/ofxCloudPlatform/src/VisionDebug.cpp | SAIC/ofxCloudPlatform | 4a97b38cb9be1faf245b9421789e9b43b5645356 | [
"MIT"
] | 1 | 2017-11-06T12:14:43.000Z | 2017-11-06T12:14:43.000Z | //
// Copyright (c) 2016 Christopher Baker <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#include "ofx/CloudPlatform/VisionDebug.h"
#include "ofGraphics.h"
namespace ofx {
namespace CloudPlatform {
void VisionDebug::draw(const std::string& label,
float value,
float x,
float y,
float width,
float height)
{
draw(label, ofToString(value, 2), x, y, width, height);
}
void VisionDebug::draw(const std::string& label,
const std::string& value,
float x,
float y,
float width,
float height)
{
ofPushStyle();
ofFill();
ofSetColor(0, 200);
ofDrawRectangle(x, y, width, height);
// ofFill();
// ofSetColor(127, 200);
// ofDrawRectangle(x, y, width * value, height);
ofSetColor(255);
ofDrawBitmapStringHighlight(label + "(" + value + ")", x + 5, y + 14);
ofNoFill();
ofSetColor(255, 200);
ofDrawRectangle(x, y, width, height);
ofPopStyle();
}
void VisionDebug::draw(const std::string& label,
const Likelihood& likelihood,
float x,
float y,
float width,
float height)
{
draw(label + ": " + likelihood.name(), likelihood.value(), x, y, width, height);
}
void VisionDebug::draw(const FaceAnnotation::Landmark& landmark)
{
ofColor background= ofColor(0, 80);
ofColor foreground = ofColor(0, 0);
if (glm::distance(glm::vec3(ofGetMouseX(), ofGetMouseY(), 0), landmark.position()) < 5)
{
foreground = ofColor(255);
background = ofColor(0);
}
ofDrawBitmapStringHighlight(landmark.name(), landmark.position(), foreground, background);
ofNoFill();
ofDrawEllipse(landmark.position().x, landmark.position().y, 10, 10);
}
void VisionDebug::draw(const FaceAnnotation& annotation)
{
ofRectangle r = annotation.boundingPoly().getBoundingBox();
annotation.boundingPoly().draw();
annotation.fdBoundingPoly().draw();
for (auto& landmark : annotation.landmarks())
{
draw(landmark);
}
// /// \sa rollAngle()
// float _rollAngle;
//
// /// \sa panAngle()
// float _panAngle;
//
// /// \sa tiltAngle()
// float _tiltAngle;
if (r.inside(ofGetMouseX(), ofGetMouseY()))
{
ofPushMatrix();
ofPushStyle();
ofTranslate(ofGetMouseX(), ofGetMouseY());
int height = 25;
int yPosition = 10;
draw(" JOY", annotation.joyLikelihood(), 10, yPosition+=height);
draw(" SORROW", annotation.sorrowLikelihood(), 10, yPosition+=height);
draw(" ANGER", annotation.angerLikelihood(), 10, yPosition+=height);
draw(" SURPRISE", annotation.surpriseLikelihood(), 10, yPosition+=height);
draw("UNDEREXPOSED", annotation.underExposedLikelihood(), 10, yPosition+=height);
draw(" BLURRED", annotation.blurredLikelihood(), 10, yPosition+=height);
draw(" HEADWARE", annotation.headwearLikelihood(), 10, yPosition+=height);
yPosition += height;
draw(" Detection confidence: ", annotation.detectionConfidence(), 10, yPosition+=height);
draw(" Landmarking confidence: ", annotation.landmarkingConfidence(), 10, yPosition+=height);
ofPopStyle();
ofPopMatrix();
}
}
void VisionDebug::draw(const EntityAnnotation& annotation)
{
ofRectangle r = annotation.boundingPoly().getBoundingBox();
annotation.boundingPoly().draw();
int height = 25;
int yPosition = 10;
draw("DESCRIPTION", annotation.description(), 10, yPosition+=height);
draw(" LOCALE", annotation.locale(), 10, yPosition+=height);
draw(" MID", annotation.mid(), 10, yPosition+=height);
draw(" SCORE", annotation.score(), 10, yPosition+=height);
draw(" TOPICALITY", annotation.topicality(), 10, yPosition+=height);
ofDrawBitmapStringHighlight(annotation.description(), r.x + 14, r.y + 14);
}
void VisionDebug::draw(const SafeSearchAnnotation& annotation)
{
ofPushMatrix();
ofPushStyle();
ofTranslate(ofGetMouseX(), ofGetMouseY());
int height = 25;
int yPosition = 10;
draw(" ADULT", annotation.adult(), 10, yPosition+=height);
draw(" SPOOF", annotation.spoof(), 10, yPosition+=height);
draw(" MEDICAL", annotation.medical(), 10, yPosition+=height);
draw(" RACY", annotation.racy(), 10, yPosition+=height);
draw("VIOLENCE", annotation.violence(), 10, yPosition+=height);
ofPopStyle();
ofPopMatrix();
}
void VisionDebug::draw(const ImagePropertiesAnnotation& annotation)
{
}
void VisionDebug::draw(const std::vector<FaceAnnotation>& annotations)
{
for (auto& annotation: annotations) draw(annotation);
}
void VisionDebug::draw(const std::vector<EntityAnnotation>& annotations)
{
for (auto& annotation: annotations) draw(annotation);
}
void VisionDebug::draw(const AnnotateImageResponse& response)
{
draw(response.faceAnnotations());
draw(response.landmarkAnnotations());
draw(response.logoAnnotations());
draw(response.labelAnnotations());
draw(response.textAnnotations());
draw(response.safeSearchAnnotation());
draw(response.imagePropertiesAnnotation());
}
void VisionDebug::draw(const std::vector<AnnotateImageResponse>& responses)
{
for (auto& response: responses) draw(response);
}
void VisionDebug::draw(const AnnotateImageResponse& response,
VisionRequestItem::Feature::Type filterType)
{
switch (filterType)
{
case VisionRequestItem::Feature::Type::TYPE_UNSPECIFIED:
std::cout << "TYPE_UNSPECIFIED" << std::endl;
break;
case VisionRequestItem::Feature::Type::FACE_DETECTION:
std::cout << "FACE_DETECTION" << std::endl;
draw(response.faceAnnotations());
break;
case VisionRequestItem::Feature::Type::LANDMARK_DETECTION:
std::cout << "LANDMARK_DETECTION" << std::endl;
draw(response.landmarkAnnotations());
break;
case VisionRequestItem::Feature::Type::LOGO_DETECTION:
std::cout << "LOGO_DETECTION" << std::endl;
draw(response.logoAnnotations());
break;
case VisionRequestItem::Feature::Type::LABEL_DETECTION:
std::cout << "LABEL_DETECTION" << std::endl;
draw(response.labelAnnotations());
break;
case VisionRequestItem::Feature::Type::TEXT_DETECTION:
std::cout << "TEXT_DETECTION" << std::endl;
draw(response.textAnnotations());
break;
case VisionRequestItem::Feature::Type::DOCUMENT_TEXT_DETECTION:
std::cout << "DOCUMENT_TEXT_DETECTION" << std::endl;
break;
case VisionRequestItem::Feature::Type::SAFE_SEARCH_DETECTION:
std::cout << "SAFE_SEARCH_DETECTION" << std::endl;
draw(response.safeSearchAnnotation());
break;
case VisionRequestItem::Feature::Type::IMAGE_PROPERTIES:
std::cout << "IMAGE_PROPERTIES" << std::endl;
draw(response.imagePropertiesAnnotation());
break;
case VisionRequestItem::Feature::Type::CROP_HINTS:
std::cout << "CROP_HINTS" << std::endl;
break;
case VisionRequestItem::Feature::Type::WEB_DETECTION:
std::cout << "WEB_DETECTION" << std::endl;
break;
}
}
void VisionDebug::draw(const std::vector<AnnotateImageResponse>& responses,
VisionRequestItem::Feature::Type filterType)
{
for (auto& response: responses)
draw(response, filterType);
}
} } // namespace ofx::CloudPlatform
| 29.511111 | 101 | 0.609438 | SAIC |
91d1ad6ada1817bead4703de39514f46188fc341 | 20,599 | cpp | C++ | Systronix_M24C32.cpp | systronix/Systronix_M24C32 | 3d9e2e11fd17d7d54978a6dff50076561b9943dc | [
"MIT"
] | null | null | null | Systronix_M24C32.cpp | systronix/Systronix_M24C32 | 3d9e2e11fd17d7d54978a6dff50076561b9943dc | [
"MIT"
] | null | null | null | Systronix_M24C32.cpp | systronix/Systronix_M24C32 | 3d9e2e11fd17d7d54978a6dff50076561b9943dc | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <Systronix_M24C32.h>
//---------------------------< D E F A U L T C O N S R U C T O R >------------------------------------------
//
// default constructor assumes lowest base address
//
Systronix_M24C32::Systronix_M24C32 (void)
{
_base = EEP_BASE_MIN;
error.total_error_count = 0; // clear the error counter
}
//---------------------------< D E S T R U C T O R >----------------------------------------------------------
//
// destructor
//
Systronix_M24C32::~Systronix_M24C32 (void)
{
// Anything to do here? Leave I2C as master? Set flag?
}
//---------------------------< S E T U P >--------------------------------------------------------------------
//
// TODO: merge with begin()? This function doesn't actually do anything, it just sets some private values. It's
// redundant and some params must be effectively specified again in begin (Wire net and pins are not independent). what parameters are specified again? [wsk]
//
uint8_t Systronix_M24C32::setup (uint8_t base, i2c_t3 wire, char* name)
{
if ((EEP_BASE_MIN > base) || (EEP_BASE_MAX < base))
{
i2c_common.tally_transaction (SILLY_PROGRAMMER, &error);
return FAIL;
}
_base = base;
_wire = wire;
_wire_name = wire_name = name; // protected and public
return SUCCESS;
}
//---------------------------< B E G I N >--------------------------------------------------------------------
//
// I2C_PINS_18_19 or I2C_PINS_29_30
//
void Systronix_M24C32::begin (i2c_pins pins, i2c_rate rate)
{
_wire.begin (I2C_MASTER, 0x00, pins, I2C_PULLUP_EXT, rate); // join I2C as master
// Serial.printf ("275 lib begin %s\r\n", _wire_name);
_wire.setDefaultTimeout (200000); // 200ms
}
//---------------------------< D E F A U L T B E G I N >----------------------------------------------------
//
//
//
void Systronix_M24C32::begin (void)
{
_wire.begin(); // initialize I2C as master
}
//---------------------------< B A S E _ G E T >--------------------------------------------------------------
//
// return the I2C base address for this instance
//
uint8_t Systronix_M24C32::base_get(void)
{
return _base;
}
//---------------------------< I N I T >----------------------------------------------------------------------
//
// determines if there is a MB85RC256V at _base address by attempting to get an address ack from the device
//
uint8_t Systronix_M24C32::init (void)
{
error.exists = true; // necessary to presume that the device exists
if (SUCCESS != ping_eeprom())
{
error.exists = false; // only place in this file where this can be set false
return FAIL;
}
return SUCCESS;
}
//---------------------------< S E T _ A D D R 1 6 >----------------------------------------------------------
//
// byte order is important. In Teensy memory, a uint16_t is stored least-significant byte in the lower of two
// addresses. The eep_addr union allows access to a single eep address as a struct of two bytes (high and
// low), as an array of two bytes [0] and [1], or as a uint16_t.
//
// Given the address 0x123, this function stores it in the eep_addr union as:
// eep.control.addr_as_u16: 0x2301 (use get_eep_addr16() to retrieve a properly ordered address)
// eep.control.addr_as_struct.low: 0x23
// eep.control.addr_as_struct.high: 0x01
// eep.control.addr_as_array[0]: 0x01
// eep.control.addr_as_array[1]: 0x23
//
uint8_t Systronix_M24C32::set_addr16 (uint16_t addr)
{
if (addr & (ADDRESS_MAX+1))
{
i2c_common.tally_transaction (SILLY_PROGRAMMER, &error);
return DENIED; // memory address out of bounds
}
control.addr.as_u16 = __builtin_bswap16 (addr); // byte swap and set the address
return SUCCESS;
}
//---------------------------< G E T _ F R A M _ A D D R 1 6 >------------------------------------------------
//
// byte order is important. In Teensy memory, a uint16_t is stored least-significant byte in the lower of two
// addresses. The eep_addr union allows access to a single eep address as a struct of two bytes (high and
// low), as an array of two bytes [0] and [1], or as a uint16_t.
//
// Returns eep address as a uint16_t in proper byte order
//
// See set_addr16() for additional explanation.
//
uint16_t Systronix_M24C32::get_addr16 (void)
{
return __builtin_bswap16 (control.addr.as_u16);
}
//---------------------------< I N C _ A D D R 1 6 >----------------------------------------------------------
//
// byte order is important. In Teensy memory, a uint16_t is stored least-significant byte in the lower of two
// addresses. The eep_addr union allows access to a single eep address as a struct of two bytes (high and
// low), as an array of two bytes [0] and [1], or as a uint16_t.
//
// This function simplifies keeping track of the current eep address pointer when using current_address_read()
// which uses the eep's internal address pointer. Increments the address by one and makes sure that the address
// properly wraps from 0x0FFF to 0x0000 instead of going to 0x1000.
//
// See set_addr16() for additional explanation.
//
void Systronix_M24C32::inc_addr16 (void)
{
uint16_t addr = __builtin_bswap16 (control.addr.as_u16);
control.addr.as_u16 = __builtin_bswap16 ((++addr & ADDRESS_MAX));
}
//---------------------------< A D V _ A D D R 1 6 >----------------------------------------------------------
//
// This function advances the current eep address pointer by rd_wr_len when using page_read() or page_write()
// to track the eep's internal address pointer. Advances the address and makes sure that the address
// properly wraps from 0x0FFF to 0x0000 instead of going to 0x1000.
//
void Systronix_M24C32::adv_addr16 (void)
{
uint16_t addr = __builtin_bswap16 (control.addr.as_u16);
control.addr.as_u16 = __builtin_bswap16 ((addr + control.rd_wr_len) & ADDRESS_MAX);
}
//---------------------------< P I N G _ E E P R O M >--------------------------------------------------------
//
// send slave address to eeprom to determine if the device exists or is busy.
//
uint8_t Systronix_M24C32::ping_eeprom (void)
{
uint8_t ret_val;
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
_wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address
ret_val = _wire.endTransmission(); // xmit slave address
if (SUCCESS != ret_val)
return FAIL; // device did not ack the address
return SUCCESS; // device acked the address
}
//---------------------------< P I N G _ E E P R O M _ T I M E D >--------------------------------------------
//
// repeatedly send slave address to eeprom to determine when the device becomes unbusy. Timeout and return FAIL
// if device still busy after twait mS; default is 5mS; M24C32-X parts (1.6V-5.5V tW is 10mS max)
//
uint8_t Systronix_M24C32::ping_eeprom_timed (uint32_t t_wait)
{
uint8_t ret_val;
// uint32_t start_time = millis ();
uint32_t end_time = millis () + t_wait;
while (millis () <= end_time)
{ // spin
_wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address
ret_val = _wire.endTransmission(); // xmit slave address
if (SUCCESS == ret_val)
return SUCCESS;
}
return FAIL; // device did not ack the address within the allotted time
}
//---------------------------< B Y T E _ W R I T E >----------------------------------------------------------
// TODO: make this work
// i2c_t3 error returns
// beginTransmission: none, void function sets txBufferLength to 1
// write: two address bytes; txBufferLength = 3; return 0 if txBuffer overflow (tx buffer is 259 bytes)
// write: a byte; txBufferLength = 4; return zero if overflow
// endTransmission: does the write; returns:
// 0=success
// 1=data too long (as a result of Wire.write() causing an overflow)
// 2=recv addr NACK
// 3=recv data NACK
// 4=other error
//
// To use this function:
// 1. use set_addr16 (addr) to set the address in the control.addr union
// 2. write the byte to be transmitted into control.wr_byte
// 3. call this function
//
uint8_t Systronix_M24C32::byte_write (void)
{
uint8_t ret_val;
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
if (SUCCESS != ping_eeprom_timed ()) // device should become available within the next 5mS
{ // it didn't
i2c_common.tally_transaction (I2C_TIMEOUT, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
_wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address
control.bytes_written = _wire.write (control.addr.as_array, 2); // put the memory address in the tx buffer
control.bytes_written += _wire.write (control.wr_byte); // add data byte to the tx buffer
if (3 != control.bytes_written)
{
i2c_common.tally_transaction (WR_INCOMPLETE, &error); // only here 0 is error value since we expected to write more than 0 bytes
return FAIL;
}
ret_val = _wire.endTransmission(); // xmit memory address and data byte
if (SUCCESS != ret_val)
{
i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
i2c_common.tally_transaction (SUCCESS, &error);
return SUCCESS;
}
//---------------------------< I N T 1 6 _ W R I T E >--------------------------------------------------------
// TODO: make this work
// writes the two bytes of an int16_t or uint16_t to eep beginning at address in control.addr; ls byte is first.
//
// To use this function:
// 1. use set_addr16 (addr) to set the address in the control.addr union
// 2. write the 16-bit value to be transmitted into control.wr_int16 (there is no control.wr_uint16)
// 3. call this function
//
uint8_t Systronix_M24C32::int16_write (void)
{
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
control.wr_buf_ptr = (uint8_t*)(&control.wr_int16); // point to the int16 member of the control struct
control.rd_wr_len = sizeof(uint16_t); // set the write length
return page_write (); // do the write and done
}
//---------------------------< I N T 3 2 _ W R I T E >--------------------------------------------------------
// TODO: make this work
// writes the four bytes of an int32_t or uint32_t to eep beginning at address in control.addr; ls byte is first.
//
// To use this function:
// 1. use set_addr16 (addr) to set the address in the control.addr union
// 2. write the 32-bit value to be transmitted into control.wr_int32 (there is no control.wr_uint32)
// 3. call this function
//
uint8_t Systronix_M24C32::int32_write (void)
{
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
control.wr_buf_ptr = (uint8_t*)(&control.wr_int32); // point to the int32 member of the control struct
control.rd_wr_len = sizeof(uint32_t); // set the write length
return page_write (); // do the write and done
}
//---------------------------< P A G E _ W R I T E >----------------------------------------------------------
// TODO make this work
// writes an array of control.rd_wr_len number of bytes to eep beginning at address in control.addr. 32 bytes
// per page write max
//
// To use this function:
// 1. use set_addr16 (addr) to set the address in the control.addr union
// 2. set control.wr_buf_ptr to point at the array of bytes to be transmitted
// 3. set control.rd_wr_len to the number of bytes to be transmitted
// 4. call this function
//
uint8_t Systronix_M24C32::page_write (void)
{
uint8_t ret_val;
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
if (SUCCESS != ping_eeprom_timed ()) // device should become available within the next 5mS
{ // it didn't
i2c_common.tally_transaction (I2C_TIMEOUT, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
_wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address
control.bytes_written = _wire.write (control.addr.as_array, 2); // put the memory address in the tx buffer
control.bytes_written += _wire.write (control.wr_buf_ptr, control.rd_wr_len); // copy source to wire tx buffer data
if (control.bytes_written < (2 + control.rd_wr_len)) // did we try to write too many bytes to the i2c_t3 tx buf?
{
i2c_common.tally_transaction (WR_INCOMPLETE, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
ret_val = _wire.endTransmission(); // xmit memory address followed by data
if (SUCCESS != ret_val)
{
i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
adv_addr16 (); // advance our copy of the address
i2c_common.tally_transaction (SUCCESS, &error);
return SUCCESS;
}
//---------------------------< C U R R E N T _ A D D R E S S _ R E A D >--------------------------------------
//
// Read a byte from the eep's current address pointer; the eep's address pointer is bumped to the next
// location after the read. We presume that the eep's address pointer was previously set with byte_read().
// This function attempts to track the eep's internal pointer by incrementing control.addr.
//
// During the internal write cycle, SDA is disabled; the device will ack a slave address but does not respond to any requests.
//
// To use this function:
// 1. perform some operation that correctly sets the eep's internal address pointer
// 2. call this function
// 3. retrieve the byte read from control.rd_byte
//
// This function does not use ping_eeprom_timed () because other functions call this function and the ping in
// middle of all of that confuses the eeprom or perhaps the i2c_t3 library
uint8_t Systronix_M24C32::current_address_read (void)
{
uint8_t ret_val;
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
control.bytes_received = _wire.requestFrom(_base, 1, I2C_STOP);
if (1 != control.bytes_received) // if we got more than or less than 1 byte
{
ret_val = _wire.status(); // to get error value
i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
control.rd_byte = _wire.readByte(); // get the byte
inc_addr16 (); // bump our copy of the address
i2c_common.tally_transaction (SUCCESS, &error);
return SUCCESS;
}
//---------------------------< B Y T E _ R E A D >------------------------------------------------------------
//
// Read a byte from a specified address.
//
// To use this function:
// 1. use set_addr16 (addr) to set the address in the control.addr union
// 2. call this function
// 3. retrieve the byte read from control.rd_byte
//
uint8_t Systronix_M24C32::byte_read (void)
{
uint8_t ret_val;
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
if (SUCCESS != ping_eeprom_timed ()) // device should become available within the next 5mS
{ // it didn't
i2c_common.tally_transaction (I2C_TIMEOUT, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
_wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address
control.bytes_written = _wire.write (control.addr.as_array, 2); // put the memory address in the tx buffer
if (2 != control.bytes_written) // did we get correct number of bytes into the i2c_t3 tx buf?
{
i2c_common.tally_transaction (WR_INCOMPLETE, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
ret_val = _wire.endTransmission(); // xmit memory address; will fail if device is busy
if (SUCCESS != ret_val)
{
i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
return current_address_read (); // use current_address_read() to fetch the byte
}
//---------------------------< I N T 1 6 _ R E A D >----------------------------------------------------------
//
// reads the two bytes of an int16_t or uint16_t from eep beginning at address in control.addr; ls byte is first.
//
// To use this function:
// 1. use set_addr16 (addr) to set the address in the control.addr union
// 2. call this function
// 3. retrieve the 16-bit value from control.rd_int16
//
uint8_t Systronix_M24C32::int16_read (void)
{
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
control.rd_buf_ptr = (uint8_t*)(&control.rd_int16);
control.rd_wr_len = sizeof(uint16_t); // set the read length
return page_read (); // do the read and done
}
//---------------------------< I N T 3 2 _ R E A D >----------------------------------------------------------
//
// reads the four bytes of an int32_t or uint32_t from eep beginning at address in control.addr; ls byte is first.
//
// To use this function:
// 1. use set_addr16 (addr) to set the address in the control.addr union
// 2. call this function
// 3. retrieve the 32-bit value from control.rd_int32
//
uint8_t Systronix_M24C32::int32_read (void)
{
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
control.rd_buf_ptr = (uint8_t*)(&control.rd_int32);
control.rd_wr_len = sizeof(uint32_t); // set the read length
return page_read (); // do the read and done
}
//---------------------------< P A G E _ R E A D >------------------------------------------------------------
//
// Reads control.rd_wr_len bytes from eep beginning at control.addr. The number of bytes that can be read in
// a single operation is limited by the I2C_RX_BUFFER_LENGTH #define in i2c_t3.h. Setting control.rd_wr_len to
// 256 is a convenient max (max size of the i2c_t3 buffer).
//
// To use this function:
// 1. use set_addr16 (addr) to set the address in the control.addr union
// 2. set control.rd_wr_len to the number of bytes to be read
// 3. set control.rd_buf_ptr to point to the place where the data are to be stored
// 4. call this function
//
uint8_t Systronix_M24C32::page_read (void)
{
uint8_t ret_val;
size_t i;
uint8_t* ptr = control.rd_buf_ptr; // a copy so we don't disturb the original
if (!error.exists) // exit immediately if device does not exist
return ABSENT;
if (SUCCESS != ping_eeprom_timed ()) // device should become available within the next 5mS
{ // it didn't
i2c_common.tally_transaction (I2C_TIMEOUT, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
_wire.beginTransmission(_base); // init tx buff for xmit to slave at _base address
control.bytes_written = _wire.write (control.addr.as_array, 2); // put the memory address in the tx buffer
if (2 != control.bytes_written) // did we get correct number of bytes into the i2c_t3 tx buf?
{
i2c_common.tally_transaction (WR_INCOMPLETE, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
ret_val = _wire.endTransmission (I2C_NOSTOP); // xmit memory address
if (SUCCESS != ret_val)
{
i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
control.bytes_received = _wire.requestFrom(_base, control.rd_wr_len, I2C_STOP); // read the bytes
if (control.bytes_received != control.rd_wr_len)
{
ret_val = _wire.status(); // to get error value
i2c_common.tally_transaction (ret_val, &error); // increment the appropriate counter
return FAIL; // calling function decides what to do with the error
}
for (i=0;i<control.rd_wr_len; i++) // copy wire rx buffer data to destination
*ptr++ = _wire.readByte();
adv_addr16 (); // advance our copy of the address
i2c_common.tally_transaction (SUCCESS, &error);
return SUCCESS;
}
| 37.317029 | 157 | 0.633332 | systronix |
91d37878541358051b949781050b06f103150bc5 | 2,035 | hpp | C++ | test/unit/module/real/math/log1p/regular/log1p.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | test/unit/module/real/math/log1p/regular/log1p.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | test/unit/module/real/math/log1p/regular/log1p.hpp | orao/eve | a8bdc6a9cab06d905e8749354cde63776ab76846 | [
"MIT"
] | null | null | null | //==================================================================================================
/**
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
**/
//==================================================================================================
#include <eve/function/log1p.hpp>
#include <eve/constant/mzero.hpp>
#include <eve/constant/nan.hpp>
#include <eve/constant/inf.hpp>
#include <eve/constant/minf.hpp>
#include <eve/constant/smallestposval.hpp>
#include <eve/constant/mindenormal.hpp>
#include <eve/constant/eps.hpp>
#include <eve/constant/log_2.hpp>
#include <eve/constant/zero.hpp>
#include <eve/platform.hpp>
#include <cmath>
TTS_CASE_TPL("Check eve::log1p return type", EVE_TYPE)
{
TTS_EXPR_IS(eve::log1p(T(0)), T);
}
TTS_CASE_TPL("Check eve::log1p behavior", EVE_TYPE)
{
using v_t = eve::element_type_t<T>;
if constexpr(eve::platform::supports_invalids)
{
TTS_IEEE_EQUAL(eve::log1p(eve::inf(eve::as<T>())) , eve::inf(eve::as<T>()) );
TTS_IEEE_EQUAL(eve::log1p(eve::nan(eve::as<T>())) , eve::nan(eve::as<T>()) );
TTS_IEEE_EQUAL(eve::log1p(eve::mone(eve::as<T>())) , eve::minf(eve::as<T>()));
TTS_IEEE_EQUAL(eve::log1p(T( 0 )) , T( 0 ) );
}
if constexpr(eve::platform::supports_denormals)
{
TTS_IEEE_EQUAL(eve::log1p(eve::mindenormal(eve::as<T>())), T(std::log1p(eve::mindenormal(eve::as<v_t>()))));
}
auto epsi = eve::eps(eve::as<T>());
TTS_ULP_EQUAL(eve::log1p(epsi) , epsi , 0.5 );
TTS_ULP_EQUAL(eve::log1p(epsi) , epsi , 0.5 );
TTS_ULP_EQUAL(eve::log1p(T(1)) , eve::log_2(eve::as<T>()) , 0.5 );
TTS_ULP_EQUAL(eve::log1p(T(0)) , T(0) , 0.5 );
TTS_ULP_EQUAL(eve::log1p(eve::smallestposval(eve::as<T>())), eve::smallestposval(eve::as<T>()), 0.5 );
TTS_ULP_EQUAL(eve::log1p(epsi) , epsi , 0.5 );
}
| 39.134615 | 112 | 0.531695 | orao |
91d9e9e4de5c0d8d813ac48f2bf8192fa77c23b2 | 1,417 | cpp | C++ | mapchannel.cpp | chuanstudyup/TrackReplay | fdce9ee21c0fd9394968616f277cced7f23d7b7e | [
"Apache-2.0"
] | null | null | null | mapchannel.cpp | chuanstudyup/TrackReplay | fdce9ee21c0fd9394968616f277cced7f23d7b7e | [
"Apache-2.0"
] | null | null | null | mapchannel.cpp | chuanstudyup/TrackReplay | fdce9ee21c0fd9394968616f277cced7f23d7b7e | [
"Apache-2.0"
] | null | null | null | #include "mapchannel.h"
MapChannel::MapChannel(QObject *parent) : QObject(parent)
{
}
void MapChannel::getMousePoint(double lng, double lat)
{
emit mousePointChanged(lng,lat);
}
void MapChannel::addPoint(double lng, double lat)
{
emit addPointClicked(lng,lat);
}
void MapChannel::movePoint(int id, double lng, double lat)
{
emit movePointClicked(id,lng,lat);
}
void MapChannel::transTask(int type, int len)
{
emit taskCome(type,len);
}
void MapChannel::transPoints(int id, double lng, double lat)
{
emit pointsCome(id,lng,lat);
}
void MapChannel::updateBoatPos(double lng, double lat, double course)
{
emit boatPosUpdated(lng,lat,course);
}
void MapChannel::reloadMap()
{
emit reloadMapClicked();
}
void MapChannel::setOrigin(double lng, double lat)
{
emit setOriginPoint(lng,lat);
}
void MapChannel::clearWaypoints()
{
emit clearWaypointsClicked();
}
void MapChannel::clearAll()
{
emit clearAllClicked();
}
void MapChannel::addFencePoint(double lng, double lat)
{
emit addFencePointClicked(lng,lat);
}
void MapChannel::addFence()
{
emit addFenceClicked();
}
void MapChannel::clearFence()
{
emit clearFenceClicked();
}
void MapChannel::panTo(double lng, double lat)
{
emit panToClicked(lng,lat);
}
void MapChannel::clearTrack()
{
emit clearTrackClicked();
}
| 17.280488 | 70 | 0.673253 | chuanstudyup |
91eb3e744eea84991fb9e428fa2eaa64d4a37026 | 2,114 | cpp | C++ | src/listener.cpp | inani47/beginner_tutorials | 7b5b3ec6ab32b22ad77273087ad4b1d2aa9c5041 | [
"BSD-2-Clause"
] | null | null | null | src/listener.cpp | inani47/beginner_tutorials | 7b5b3ec6ab32b22ad77273087ad4b1d2aa9c5041 | [
"BSD-2-Clause"
] | null | null | null | src/listener.cpp | inani47/beginner_tutorials | 7b5b3ec6ab32b22ad77273087ad4b1d2aa9c5041 | [
"BSD-2-Clause"
] | 1 | 2018-10-27T06:17:24.000Z | 2018-10-27T06:17:24.000Z | /*
* BSD 2-Clause License
*
* Copyright (c) 2017, Pranav Inani
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file listner.cpp
*
* @brief Subscribes to the topic chatter
*
* In this implementation it receives messages
* from talker.cpp on the topic chatter
*
*
*
* @author Pranav Inani
* @copyright 2017
*/
#include "ros/ros.h"
#include "std_msgs/String.h"
/**
* @brief call back function for a subscriber node
* @param msg is the string received from talker on topic chatter
* @return none
*/
void chatterCallback(const std_msgs::String::ConstPtr& msg) {
ROS_INFO("I heard: [%s]", msg->data.c_str());
}
int main(int argc, char **argv) {
ros::init(argc, argv, "listener");
ros::NodeHandle n;
ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);
ros::spin();
return 0;
}
| 33.03125 | 81 | 0.733207 | inani47 |
91ebfc21408addb761be14b571a2954e3516c58e | 8,845 | cpp | C++ | src/frm/frmBackup.cpp | dpage/pgadmin3 | 6784e6281831a083fe5a0bbd49eac90e1a6ac547 | [
"Artistic-1.0"
] | 2 | 2021-07-16T21:45:41.000Z | 2021-08-14T15:54:17.000Z | src/frm/frmBackup.cpp | dpage/pgadmin3 | 6784e6281831a083fe5a0bbd49eac90e1a6ac547 | [
"Artistic-1.0"
] | null | null | null | src/frm/frmBackup.cpp | dpage/pgadmin3 | 6784e6281831a083fe5a0bbd49eac90e1a6ac547 | [
"Artistic-1.0"
] | 2 | 2017-11-18T15:00:24.000Z | 2021-08-14T15:54:30.000Z | //////////////////////////////////////////////////////////////////////////
//
// pgAdmin III - PostgreSQL Tools
// RCS-ID: $Id$
// Copyright (C) 2002 - 2010, The pgAdmin Development Team
// This software is released under the Artistic Licence
//
// frmBackup.cpp - Backup database dialogue
//
//////////////////////////////////////////////////////////////////////////
// wxWindows headers
#include <wx/wx.h>
#include <wx/settings.h>
// App headers
#include "pgAdmin3.h"
#include "frmMain.h"
#include "frmBackup.h"
#include "sysLogger.h"
#include "pgSchema.h"
#include "pgTable.h"
// Icons
#include "images/backup.xpm"
#define nbNotebook CTRL_NOTEBOOK("nbNotebook")
#define txtFilename CTRL_TEXT("txtFilename")
#define btnFilename CTRL_BUTTON("btnFilename")
#define rbxFormat CTRL_RADIOBOX("rbxFormat")
#define chkBlobs CTRL_CHECKBOX("chkBlobs")
#define chkOid CTRL_CHECKBOX("chkOid")
#define chkInsert CTRL_CHECKBOX("chkInsert")
#define chkDisableDollar CTRL_CHECKBOX("chkDisableDollar")
#define sbxPlainOptions CTRL_STATICBOX("sbxPlainOptions")
#define chkOnlyData CTRL_CHECKBOX("chkOnlyData")
#define chkOnlySchema CTRL_CHECKBOX("chkOnlySchema")
#define chkNoOwner CTRL_CHECKBOX("chkNoOwner")
#define chkCreateDb CTRL_CHECKBOX("chkCreateDb")
#define chkDropDb CTRL_CHECKBOX("chkDropDb")
#define chkDisableTrigger CTRL_CHECKBOX("chkDisableTrigger")
#define chkVerbose CTRL_CHECKBOX("chkVerbose")
BEGIN_EVENT_TABLE(frmBackup, ExternProcessDialog)
EVT_TEXT(XRCID("txtFilename"), frmBackup::OnChange)
EVT_BUTTON(XRCID("btnFilename"), frmBackup::OnSelectFilename)
EVT_RADIOBOX(XRCID("rbxFormat"), frmBackup::OnChangePlain)
EVT_CHECKBOX(XRCID("chkOnlyData"), frmBackup::OnChangePlain)
EVT_CHECKBOX(XRCID("chkOnlySchema"), frmBackup::OnChangePlain)
EVT_CHECKBOX(XRCID("chkNoOwner"), frmBackup::OnChangePlain)
EVT_CLOSE( ExternProcessDialog::OnClose)
END_EVENT_TABLE()
frmBackup::frmBackup(frmMain *form, pgObject *obj) : ExternProcessDialog(form)
{
object=obj;
wxLogInfo(wxT("Creating a backup dialogue for %s %s"), object->GetTypeName().c_str(), object->GetFullName().c_str());
wxWindowBase::SetFont(settings->GetSystemFont());
LoadResource(form, wxT("frmBackup"));
RestorePosition();
SetTitle(wxString::Format(_("Backup %s %s"), object->GetTranslatedTypeName().c_str(), object->GetFullIdentifier().c_str()));
canBlob = (obj->GetMetaType() == PGM_DATABASE);
chkBlobs->SetValue(canBlob);
chkDisableDollar->Enable(obj->GetConnection()->BackendMinimumVersion(7, 5));
if (!object->GetDatabase()->GetServer()->GetPasswordIsStored())
environment.Add(wxT("PGPASSWORD=") + object->GetDatabase()->GetServer()->GetPassword());
// Icon
SetIcon(wxIcon(backup_xpm));
// fix translation problem
wxString dollarLabel=wxGetTranslation(_("Disable $$ quoting"));
dollarLabel.Replace(wxT("$$"), wxT("$"));
chkDisableDollar->SetLabel(dollarLabel);
chkDisableDollar->SetSize(chkDisableDollar->GetBestSize());
txtMessages = CTRL_TEXT("txtMessages");
txtMessages->SetMaxLength(0L);
btnOK->Disable();
wxCommandEvent ev;
OnChangePlain(ev);
}
frmBackup::~frmBackup()
{
wxLogInfo(wxT("Destroying a backup dialogue"));
SavePosition();
}
wxString frmBackup::GetHelpPage() const
{
wxString page;
page = wxT("pg/app-pgdump");
return page;
}
void frmBackup::OnSelectFilename(wxCommandEvent &ev)
{
wxString title, prompt;
if (rbxFormat->GetSelection() == 2) // plain
{
title = _("Select output file");
prompt = _("Query files (*.sql)|*.sql|All files (*.*)|*.*");
}
else
{
title = _("Select backup filename");
prompt = _("Backup files (*.backup)|*.backup|All files (*.*)|*.*");
}
wxFileDialog file(this, title, wxGetHomeDir(), txtFilename->GetValue(), prompt, wxSAVE);
if (file.ShowModal() == wxID_OK)
{
txtFilename->SetValue(file.GetPath());
OnChange(ev);
}
}
void frmBackup::OnChange(wxCommandEvent &ev)
{
if (!process && !done)
btnOK->Enable(!txtFilename->GetValue().IsEmpty());
}
void frmBackup::OnChangePlain(wxCommandEvent &ev)
{
bool isPlain = (rbxFormat->GetSelection() == 2);
sbxPlainOptions->Enable(isPlain);
chkBlobs->Enable(canBlob && !isPlain);
chkOnlyData->Enable(isPlain && !chkOnlySchema->GetValue());
if (isPlain)
isPlain = !chkOnlyData->GetValue();
chkOnlySchema->Enable(isPlain);
chkNoOwner->Enable(isPlain);
chkDropDb->Enable(isPlain);
chkCreateDb->Enable(isPlain);
chkDisableTrigger->Enable(chkOnlyData->GetValue());
}
wxString frmBackup::GetCmd(int step)
{
wxString cmd = getCmdPart1();
return cmd + getCmdPart2();
}
wxString frmBackup::GetDisplayCmd(int step)
{
wxString cmd = getCmdPart1();
return cmd + getCmdPart2();
}
wxString frmBackup::getCmdPart1()
{
extern wxString backupExecutable;
wxString cmd=backupExecutable;
pgServer *server=object->GetDatabase()->GetServer();
cmd += wxT(" -i")
wxT(" -h ") + server->GetName()
+ wxT(" -p ") + NumToStr((long)server->GetPort())
+ wxT(" -U ") + server->GetUsername();
return cmd;
}
wxString frmBackup::getCmdPart2()
{
extern wxString backupExecutable;
wxString cmd;
// if (server->GetSSL())
// pg_dump doesn't support ssl
switch (rbxFormat->GetSelection())
{
case 0: // compressed
{
cmd.Append(wxT(" -F c"));
if (chkBlobs->GetValue())
cmd.Append(wxT(" -b"));
break;
}
case 1: // tar
{
cmd.Append(wxT(" -F t"));
if (chkBlobs->GetValue())
cmd.Append(wxT(" -b"));
break;
}
case 2:
{
cmd.Append(wxT(" -F p"));
if (chkOnlyData->GetValue())
{
cmd.Append(wxT(" -a"));
if (chkDisableTrigger->GetValue())
cmd.Append(wxT(" --disable-triggers"));
}
else
{
if (chkOnlySchema->GetValue())
cmd.Append(wxT(" -s"));
if (chkOnlySchema->GetValue())
cmd.Append(wxT(" -s"));
if (chkNoOwner->GetValue())
cmd.Append(wxT(" -O"));
if (chkCreateDb->GetValue())
cmd.Append(wxT(" -C"));
if (chkDropDb->GetValue())
cmd.Append(wxT(" -c"));
}
break;
}
}
if (chkOid->GetValue())
cmd.Append(wxT(" -o"));
if (chkInsert->GetValue())
cmd.Append(wxT(" -D"));
if (chkDisableDollar->GetValue())
cmd.Append(wxT(" --disable-dollar-quoting"));
if (chkVerbose->GetValue())
cmd.Append(wxT(" -v"));
cmd.Append(wxT(" -f \"") + txtFilename->GetValue() + wxT("\""));
if (object->GetMetaType() == PGM_SCHEMA)
#ifdef WIN32
cmd.Append(wxT(" -n \\\"") + ((pgSchema*)object)->GetIdentifier() + wxT("\\\""));
#else
cmd.Append(wxT(" -n '") + ((pgSchema*)object)->GetQuotedIdentifier() + wxT("'"));
#endif
else if (object->GetMetaType() == PGM_TABLE)
{
// The syntax changed in 8.2 :-(
if (pgAppMinimumVersion(backupExecutable + wxT(" --version"), 8, 2))
{
#ifdef WIN32
cmd.Append(wxT(" -t \"\\\"") + ((pgTable*)object)->GetSchema()->GetIdentifier() +
wxT("\\\".\\\"") + ((pgTable*)object)->GetIdentifier() + wxT("\\\"\""));
#else
cmd.Append(wxT(" -t '") + ((pgTable*)object)->GetSchema()->GetQuotedIdentifier() +
wxT(".") + ((pgTable*)object)->GetQuotedIdentifier() + wxT("'"));
#endif
}
else
{
cmd.Append(wxT(" -t ") + ((pgTable*)object)->GetQuotedIdentifier());
cmd.Append(wxT(" -n ") + ((pgTable*)object)->GetSchema()->GetQuotedIdentifier());
}
}
cmd.Append(wxT(" ") + object->GetDatabase()->GetQuotedIdentifier());
return cmd;
}
void frmBackup::Go()
{
txtFilename->SetFocus();
Show(true);
}
backupFactory::backupFactory(menuFactoryList *list, wxMenu *mnu, wxToolBar *toolbar) : contextActionFactory(list)
{
mnu->Append(id, _("&Backup..."), _("Creates a backup of the current database to a local file"));
}
wxWindow *backupFactory::StartDialog(frmMain *form, pgObject *obj)
{
frmBackup *frm=new frmBackup(form, obj);
frm->Go();
return 0;
}
bool backupFactory::CheckEnable(pgObject *obj)
{
extern wxString backupExecutable;
return obj && obj->CanBackup() && !backupExecutable.IsEmpty();
}
| 28.440514 | 128 | 0.59299 | dpage |
91ecc0f918c51550b90273cd61737bfc91e6d7a6 | 519 | cpp | C++ | src/lib/io/mipi_tx.cpp | kinglee1982/FaceRecognitionTerminalDemo | 5e197011a87403d2433f691b8390ec340432b2be | [
"Apache-2.0"
] | 2 | 2020-12-21T13:15:59.000Z | 2021-07-07T08:04:06.000Z | src/lib/io/mipi_tx.cpp | kinglee1982/FaceRecognitionTerminalDemo | 5e197011a87403d2433f691b8390ec340432b2be | [
"Apache-2.0"
] | null | null | null | src/lib/io/mipi_tx.cpp | kinglee1982/FaceRecognitionTerminalDemo | 5e197011a87403d2433f691b8390ec340432b2be | [
"Apache-2.0"
] | 1 | 2022-03-24T01:08:42.000Z | 2022-03-24T01:08:42.000Z | #include "mipi_tx.h"
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include "hi_mipi_tx.h"
#include "rp-lcd-mipi-8inch-800x1280.h"
Mipi_Tx::Mipi_Tx() {}
Mipi_Tx *Mipi_Tx::getInstance() {
static Mipi_Tx self;
return &self;
}
bool Mipi_Tx::startMipiTx(VO_INTF_SYNC_E voIntfSync) {
start_mipi_8inch_800x1280_mipiTx(voIntfSync);
return true;
}
bool Mipi_Tx::startDeviceWithUserSyncInfo(VO_DEV voDev) {
start_mipi_8inch_800x1280_userSyncInfo(voDev);
return true;
}
| 19.961538 | 58 | 0.716763 | kinglee1982 |
91ed58a6dc446a8afb77af133372d237d2d746b1 | 912 | cpp | C++ | Sorting and Searching/array_division.cpp | vjerin/CSES-Problem-Set | 68070812fa1d27e4653f58dcdabed56188a45110 | [
"Apache-2.0"
] | null | null | null | Sorting and Searching/array_division.cpp | vjerin/CSES-Problem-Set | 68070812fa1d27e4653f58dcdabed56188a45110 | [
"Apache-2.0"
] | 10 | 2020-10-02T10:28:22.000Z | 2020-10-09T18:30:56.000Z | Sorting and Searching/array_division.cpp | vjerin/CSES-Problem-Set | 68070812fa1d27e4653f58dcdabed56188a45110 | [
"Apache-2.0"
] | 10 | 2020-10-02T11:16:32.000Z | 2020-10-08T18:31:18.000Z | #include <bits/stdc++.h>
#define int long long
#define MOD 1000000007
using namespace std;
void solve() {
int n, k;
cin >> n >> k;
int x[n];
int sum = 0;
for(int i = 0; i < n; i++) {
cin >> x[i];
sum += x[i];
}
int l = sum / k, h = sum;
int m, ans = l;
while(l <= h) {
// cout << l << " " << h << endl;
m = (l + h) / 2;
int count = k, i = 0;
while(count--) {
int s = 0;
while(i < n) {
s += x[i];
if(s > m) {
break;
}
i++;
}
}
if(i != n) {
l = m + 1;
}
else {
ans = m;
h = m - 1;
}
}
cout << ans << endl;
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
} | 16.581818 | 41 | 0.326754 | vjerin |
91ef65ef4bbd6f4410d4498335a0703839a5517b | 3,829 | inl | C++ | src/core/reflection/include/meta_struct.inl | Caravetta/Engine | 6e2490a68727dc731b466335499f3204490acc5f | [
"MIT"
] | 2 | 2018-05-21T02:12:50.000Z | 2019-04-23T20:56:00.000Z | src/core/reflection/include/meta_struct.inl | Caravetta/Engine | 6e2490a68727dc731b466335499f3204490acc5f | [
"MIT"
] | 12 | 2018-05-30T13:15:25.000Z | 2020-02-02T21:29:42.000Z | src/core/reflection/include/meta_struct.inl | Caravetta/Engine | 6e2490a68727dc731b466335499f3204490acc5f | [
"MIT"
] | 2 | 2018-06-14T19:03:29.000Z | 2018-12-30T07:37:22.000Z | #include "crc32.h"
#include "reflection_system.h"
namespace Engine {
#define GET_FIELD_OFFSET( __struct, __field ) (uint32_t) (uintptr_t) &( ((__struct*)NULL)->*__field)
template<class T>
void Meta_Struct::create( Meta_Struct const*& meta_struct, const char* name, const char* base_name )
{
Meta_Struct* tmp_struct = Meta_Struct::create();
meta_struct = tmp_struct;
Meta_Struct::create<T>(name, base_name, &T::populate_meta_struct_func, tmp_struct);
}
template<class T>
void Meta_Struct::create( const char* name, const char* base_name, populate_meta_struct_func func, Meta_Struct* info )
{
info->__size = sizeof(T);
info->__name = name;
bool base_populate = false;
if ( base_name ) {
info->__base_struct = Reflection::get_meta_struct(base_name);
info->__base_struct->add_derived_struct(info);
}
const Meta_Struct* base_struct = info->__base_struct;
while ( base_populate == false && base_struct ) {
if ( base_struct ) {
base_populate = base_struct->__populate_func && base_struct->__populate_func == func;
base_struct = base_struct->__base_struct;
} else {
base_name = NULL;
}
}
if ( base_populate == false ) {
info->__populate_func = func;
}
if ( info->__populate_func ) {
info->__populate_func( *info );
}
}
template<class Struct_T, class Field_T>
void Meta_Struct::add_field( Field_T Struct_T::* field, const char* name, uint32_t flags )
{
Meta_Field* new_field = allocate_field();
new_field->__name = name;
new_field->__name_crc = crc32(name);
new_field->__size = sizeof(Field_T);
new_field->__offset = GET_FIELD_OFFSET(Struct_T, field);
}
template<class Class_T, class Base_T>
Meta_Struct_Registrar<Class_T, Base_T>::Meta_Struct_Registrar( const char* name )
: Meta_Base_Registrar( name )
{
Meta_Base_Registrar::add_to_list(Registrar_Base_Types::META_STRUCT_TYPE, this);
}
template<class Class_T, class Base_T>
Meta_Struct_Registrar<Class_T, Base_T>::~Meta_Struct_Registrar( void )
{
meta_unregister();
Meta_Base_Registrar::remove_from_list(Registrar_Base_Types::META_STRUCT_TYPE, this);
}
template<class Class_T, class Base_T>
void Meta_Struct_Registrar<Class_T, Base_T>::meta_register( void )
{
if ( Class_T::__s_meta_struct == NULL ) {
Base_T::__s_meta_struct.meta_register();
Meta_Base_Registrar::add_type_to_registry(Class_T::create_meta_struct());
}
}
template<class Class_T, class Base_T>
void Meta_Struct_Registrar<Class_T, Base_T>::meta_unregister( void )
{
if ( Class_T::__s_meta_struct != NULL ) {
Meta_Base_Registrar::remove_type_from_registry(Class_T::__s_meta_struct);
Class_T::__s_meta_struct = NULL;
}
}
template<class Class_T>
Meta_Struct_Registrar<Class_T, void>::Meta_Struct_Registrar( const char* name )
: Meta_Base_Registrar( name )
{
Meta_Base_Registrar::add_to_list(Registrar_Base_Types::META_STRUCT_TYPE, this);
}
template<class Class_T>
Meta_Struct_Registrar<Class_T, void>::~Meta_Struct_Registrar( void )
{
meta_unregister();
Meta_Base_Registrar::remove_from_list(Registrar_Base_Types::META_STRUCT_TYPE, this);
}
template<class Class_T>
void Meta_Struct_Registrar<Class_T, void>::meta_register( void )
{
if ( Class_T::__s_meta_struct == NULL ) {
Meta_Base_Registrar::add_type_to_registry((Meta_Base*)Class_T::create_meta_struct());
}
}
template<class Class_T>
void Meta_Struct_Registrar<Class_T, void>::meta_unregister( void )
{
if ( Class_T::__s_meta_struct != NULL ) {
Meta_Base_Registrar::remove_type_from_registry(Class_T::__s_meta_struct);
Class_T::__s_meta_struct = NULL;
}
}
} // end namespace Engine
| 30.149606 | 118 | 0.702533 | Caravetta |
91f41160c9460d2c15cc16e05173d23c1ac4c4ec | 1,240 | cpp | C++ | openscenario/openscenario_interpreter/src/syntax/private.cpp | autocore-ai/scenario_simulator_v2 | bb9569043e20649f0e4390e9225b6bb7b4de10b6 | [
"Apache-2.0"
] | null | null | null | openscenario/openscenario_interpreter/src/syntax/private.cpp | autocore-ai/scenario_simulator_v2 | bb9569043e20649f0e4390e9225b6bb7b4de10b6 | [
"Apache-2.0"
] | null | null | null | openscenario/openscenario_interpreter/src/syntax/private.cpp | autocore-ai/scenario_simulator_v2 | bb9569043e20649f0e4390e9225b6bb7b4de10b6 | [
"Apache-2.0"
] | null | null | null | // Copyright 2015-2021 Tier IV, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <openscenario_interpreter/syntax/private.hpp>
#include <openscenario_interpreter/utility/demangle.hpp>
namespace openscenario_interpreter
{
inline namespace syntax
{
nlohmann::json & operator<<(nlohmann::json & json, const Private & datum)
{
json["entityRef"] = datum.entity_ref;
json["PrivateAction"] = nlohmann::json::array();
for (const auto & private_action : datum.private_actions) {
nlohmann::json action;
action["type"] = makeTypename(private_action.type());
json["PrivateAction"].push_back(action);
}
return json;
}
} // namespace syntax
} // namespace openscenario_interpreter
| 32.631579 | 75 | 0.740323 | autocore-ai |
91fba7fbcbec3c3c1017da674cf1f51386ef9ded | 806 | cpp | C++ | Recursion and Backtracking/AllIndicesOfX.cpp | Ankitlenka26/IP2021 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | [
"MIT"
] | null | null | null | Recursion and Backtracking/AllIndicesOfX.cpp | Ankitlenka26/IP2021 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | [
"MIT"
] | null | null | null | Recursion and Backtracking/AllIndicesOfX.cpp | Ankitlenka26/IP2021 | 99322c9c84a8a9c9178a505afbffdcebd312b059 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
vector<int> *allIndices(vector<int> arr, int x, int idx, int fsf)
{
if (idx == arr.size())
{
vector<int> *res = new vector<int>(fsf);
return res;
}
if (arr[idx] == x)
{
vector<int> *iarr = allIndices(arr, x, idx + 1, fsf + 1);
iarr->at(fsf) = idx;
return iarr;
}
else
{
vector<int> *iarr = allIndices(arr, x, idx + 1, fsf);
return iarr;
}
}
int main()
{
int n;
cin >> n;
vector<int> arr(n);
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
int x;
cin >> x;
vector<int> *ans = allIndices(arr, x, 0, 0);
for (int i = 0; i < ans->size(); i++)
{
cout << ans->at(i) << endl;
}
return 0;
} | 17.521739 | 65 | 0.46402 | Ankitlenka26 |
91fd3fe0219c586b1d4a975467d4a9e5a93d7ec9 | 5,625 | cpp | C++ | Src/Files/MXFileMap.cpp | L-Spiro/MhsX | 9cc71fbbac93ba54a01839db129cd9b47a68f29e | [
"BSD-2-Clause"
] | 19 | 2016-09-07T18:22:09.000Z | 2022-03-25T23:05:39.000Z | Src/Files/MXFileMap.cpp | L-Spiro/MhsX | 9cc71fbbac93ba54a01839db129cd9b47a68f29e | [
"BSD-2-Clause"
] | 1 | 2021-09-30T14:24:54.000Z | 2021-11-13T14:58:02.000Z | Src/Files/MXFileMap.cpp | L-Spiro/MhsX | 9cc71fbbac93ba54a01839db129cd9b47a68f29e | [
"BSD-2-Clause"
] | 5 | 2018-04-10T16:52:25.000Z | 2021-05-11T02:40:17.000Z | #include "MXFileMap.h"
#include "../System/MXSystem.h"
#include <algorithm>
// == Macros.
#define MX_MAP_BUF_SIZE static_cast<UINT64>(mx::CSystem::GetSystemInfo().dwAllocationGranularity * 64)
namespace mx {
CFileMap::CFileMap() :
m_hFile( INVALID_HANDLE_VALUE ),
m_hMap( INVALID_HANDLE_VALUE ),
m_pbMapBuffer( nullptr ),
m_bIsEmpty( TRUE ),
m_bWritable( TRUE ),
m_ui64Size( 0 ),
m_ui64MapStart( MAXUINT64 ),
m_dwMapSize( 0 ) {
}
CFileMap::~CFileMap() {
Close();
}
// == Functions.
// Creates a file mapping. Always opens for read, may also open for write.
BOOL CFileMap::CreateMap( LPCSTR _lpcFile, BOOL _bOpenForWrite ) {
Close();
m_hFile = ::CreateFileA( _lpcFile,
_bOpenForWrite ? (GENERIC_READ | GENERIC_WRITE) : GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL );
if ( m_hFile == INVALID_HANDLE_VALUE ) {
return FALSE;
}
m_bWritable = _bOpenForWrite;
return CreateFileMap();
}
// Creates a file mapping. Always opens for read, may also open for write.
BOOL CFileMap::CreateMap( LPCWSTR _lpwFile, BOOL _bOpenForWrite ) {
Close();
m_hFile = ::CreateFileW( _lpwFile,
_bOpenForWrite ? (GENERIC_READ | GENERIC_WRITE) : GENERIC_READ,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL );
if ( m_hFile == INVALID_HANDLE_VALUE ) {
return FALSE;
}
m_bWritable = _bOpenForWrite;
return CreateFileMap();
}
// Closes the opened file map.
VOID CFileMap::Close() {
if ( m_pbMapBuffer ) {
::UnmapViewOfFile( m_pbMapBuffer );
m_pbMapBuffer = nullptr;
}
if ( m_hMap != INVALID_HANDLE_VALUE ) {
::CloseHandle( m_hMap );
m_hMap = INVALID_HANDLE_VALUE;
}
if ( m_hFile != INVALID_HANDLE_VALUE ) {
::CloseHandle( m_hFile );
m_hFile = INVALID_HANDLE_VALUE;
}
m_bIsEmpty = TRUE;
m_ui64Size = 0;
m_ui64MapStart = MAXUINT64;
m_dwMapSize = 0;
}
// Gets the size of the file.
UINT64 CFileMap::Size() const {
if ( !m_ui64Size ) {
m_ui64Size = CFile::Size( m_hFile );
}
return m_ui64Size;
}
// Reads from the opened file.
DWORD CFileMap::Read( LPVOID _lpvBuffer, UINT64 _ui64From, DWORD _dwNumberOfBytesToRead ) const {
_dwNumberOfBytesToRead = static_cast<DWORD>(std::min( static_cast<UINT64>(_dwNumberOfBytesToRead), Size() - _ui64From ));
// Read in 8-megabyte chunks.
PBYTE pbDst = static_cast<PBYTE>(_lpvBuffer);
DWORD dwWritten = 0;
while ( _dwNumberOfBytesToRead ) {
DWORD dwReadAmount = std::min( static_cast<DWORD>(8 * 1024 * 1024), _dwNumberOfBytesToRead );
if ( !MapRegion( _ui64From, dwReadAmount ) ) {
return dwWritten;
}
std::memcpy( pbDst, &m_pbMapBuffer[_ui64From-m_ui64MapStart], dwReadAmount );
_dwNumberOfBytesToRead -= dwReadAmount;
_ui64From += dwReadAmount;
pbDst += dwReadAmount;
}
return dwWritten;
}
// Writes to the opened file.
DWORD CFileMap::Write( LPCVOID _lpvBuffer, UINT64 _ui64From, DWORD _dwNumberOfBytesToWrite ) {
_dwNumberOfBytesToWrite = static_cast<DWORD>(std::min( static_cast<UINT64>(_dwNumberOfBytesToWrite), Size() - _ui64From ));
// Write in 8-megabyte chunks.
const BYTE * pbSrc = static_cast<const BYTE *>(_lpvBuffer);
DWORD dwWritten = 0;
while ( _dwNumberOfBytesToWrite ) {
DWORD dwWriteAmount = std::min( static_cast<DWORD>(8 * 1024 * 1024), _dwNumberOfBytesToWrite );
if ( !MapRegion( _ui64From, dwWriteAmount ) ) {
return dwWritten;
}
std::memcpy( &m_pbMapBuffer[_ui64From-m_ui64MapStart], pbSrc, dwWriteAmount );
_dwNumberOfBytesToWrite -= dwWriteAmount;
_ui64From += dwWriteAmount;
pbSrc += dwWriteAmount;
}
return dwWritten;
}
// Creates the file map.
BOOL CFileMap::CreateFileMap() {
if ( m_hFile == INVALID_HANDLE_VALUE ) { return FALSE; }
// Can't open 0-sized files. Emulate the successful mapping of such a file.
m_bIsEmpty = Size() == 0;
if ( m_bIsEmpty ) { return TRUE; }
m_hMap = ::CreateFileMappingW( m_hFile,
NULL,
m_bWritable ? PAGE_READWRITE : PAGE_READONLY,
0,
0,
NULL );
if ( m_hMap == NULL ) {
// For some reason ::CreateFileMapping() returns NULL rather than INVALID_HANDLE_VALUE.
m_hMap = INVALID_HANDLE_VALUE;
Close();
return FALSE;
}
m_ui64MapStart = MAXUINT64;
m_dwMapSize = 0;
return TRUE;
}
// Map a region of the file.
BOOL CFileMap::MapRegion( UINT64 _ui64Offset, DWORD _dwSize ) const {
if ( m_hMap == INVALID_HANDLE_VALUE ) { return FALSE; }
UINT64 ui64Adjusted = AdjustBase( _ui64Offset );
DWORD dwNewSize = static_cast<DWORD>((_ui64Offset - ui64Adjusted) + _dwSize);
dwNewSize = static_cast<DWORD>(std::min( static_cast<UINT64>(dwNewSize), Size() - ui64Adjusted ));
if ( m_pbMapBuffer && ui64Adjusted == m_ui64MapStart && dwNewSize == m_dwMapSize ) { return TRUE; }
if ( m_pbMapBuffer ) {
// Unmap existing buffer.
::UnmapViewOfFile( m_pbMapBuffer );
m_pbMapBuffer = nullptr;
m_ui64MapStart = MAXUINT64;
m_dwMapSize = 0;
}
m_pbMapBuffer = static_cast<PBYTE>(::MapViewOfFile( m_hMap,
(m_bWritable ? FILE_MAP_WRITE : 0) | FILE_MAP_READ,
static_cast<DWORD>(ui64Adjusted >> 32),
static_cast<DWORD>(ui64Adjusted),
dwNewSize ));
if ( !m_pbMapBuffer ) { return FALSE; }
m_ui64MapStart = ui64Adjusted;
m_dwMapSize = dwNewSize;
return TRUE;
}
// Adjusts the input to the nearest mapping offset.
UINT64 CFileMap::AdjustBase( UINT64 _ui64Offset ) const {
if ( _ui64Offset < (MX_MAP_BUF_SIZE >> 1) ) { return 0; }
if ( Size() <= MX_MAP_BUF_SIZE ) { return 0; }
return ((_ui64Offset + (MX_MAP_BUF_SIZE >> 2)) & (~((MX_MAP_BUF_SIZE >> 1) - 1))) - (MX_MAP_BUF_SIZE >> 1);
}
} // namespace mx
| 29.605263 | 125 | 0.692622 | L-Spiro |
62105e35a225e3ba313c25872bce921d49d03304 | 5,362 | hh | C++ | jpeg.hh | nurettin/libnuwen | 5b3012d9e75552c372a4d09b218b7af04a928e68 | [
"BSL-1.0"
] | 9 | 2019-09-17T10:33:58.000Z | 2021-07-29T10:03:42.000Z | jpeg.hh | nurettin/libnuwen | 5b3012d9e75552c372a4d09b218b7af04a928e68 | [
"BSL-1.0"
] | null | null | null | jpeg.hh | nurettin/libnuwen | 5b3012d9e75552c372a4d09b218b7af04a928e68 | [
"BSL-1.0"
] | 1 | 2019-10-05T04:31:22.000Z | 2019-10-05T04:31:22.000Z | // Copyright Stephan T. Lavavej, http://nuwen.net .
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://boost.org/LICENSE_1_0.txt .
#ifndef PHAM_JPEG_HH
#define PHAM_JPEG_HH
#include "compiler.hh"
#ifdef NUWEN_PLATFORM_MSVC
#pragma once
#endif
#include "typedef.hh"
#include "external_begin.hh"
#include <stdexcept>
#include <boost/format.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/utility.hpp>
#include <jerror.h>
#include <jpeglib.h>
#include "external_end.hh"
namespace nuwen {
inline boost::tuple<ul_t, ul_t, vuc_t> decompress_jpeg_insecurely(const vuc_t& input, ul_t max_width = 2048, ul_t max_height = 2048);
}
namespace pham {
inline void output_message(jpeg_common_struct * const p) {
if (p->client_data) {
p->err->format_message(p, static_cast<char *>(p->client_data));
p->client_data = NULL;
}
}
inline void do_nothing(jpeg_decompress_struct *) { }
const nuwen::uc_t fake_eoi_marker[] = { 0xFF, JPEG_EOI };
inline JPEG_boolean fill_input_buffer(jpeg_decompress_struct * const p) {
// Obnoxiously, WARNMS is a macro that contains an old-style cast.
p->err->msg_code = JWRN_JPEG_EOF;
p->err->emit_message(reinterpret_cast<jpeg_common_struct *>(p), -1);
p->src->next_input_byte = fake_eoi_marker;
p->src->bytes_in_buffer = 2;
return JPEG_TRUE;
}
inline void skip_input_data(jpeg_decompress_struct * const p, const long n) { // POISON_OK
if (n > 0) {
if (static_cast<nuwen::ul_t>(n) < p->src->bytes_in_buffer) {
p->src->next_input_byte += n;
p->src->bytes_in_buffer -= n;
} else {
p->src->next_input_byte = NULL;
p->src->bytes_in_buffer = 0;
}
}
}
namespace jpeg {
class decompressor_destroyer : public boost::noncopyable {
public:
explicit decompressor_destroyer(jpeg_decompress_struct& d) : m_p(&d) { }
~decompressor_destroyer() {
jpeg_destroy_decompress(m_p);
}
private:
jpeg_decompress_struct * const m_p;
};
}
}
inline boost::tuple<nuwen::ul_t, nuwen::ul_t, nuwen::vuc_t> nuwen::decompress_jpeg_insecurely(
const vuc_t& input, const ul_t max_width, const ul_t max_height) {
using namespace std;
using namespace boost;
using namespace pham;
using namespace pham::jpeg;
if (input.empty()) {
throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Empty input.");
}
jpeg_error_mgr error_manager;
jpeg_decompress_struct decompressor;
decompressor.err = jpeg_std_error(&error_manager);
vc_t warning_message(JMSG_LENGTH_MAX, 0);
decompressor.client_data = &warning_message[0];
decompressor.err->output_message = output_message;
// Obnoxiously, jpeg_create_decompress is a macro that contains an old-style cast.
jpeg_CreateDecompress(&decompressor, JPEG_LIB_VERSION, sizeof decompressor);
jpeg_source_mgr source_manager;
source_manager.next_input_byte = &input[0];
source_manager.bytes_in_buffer = input.size();
source_manager.init_source = do_nothing;
source_manager.fill_input_buffer = fill_input_buffer;
source_manager.skip_input_data = skip_input_data;
source_manager.resync_to_restart = jpeg_resync_to_restart; // Default method.
source_manager.term_source = do_nothing;
decompressor.src = &source_manager;
decompressor_destroyer destroyer(decompressor);
jpeg_read_header(&decompressor, JPEG_TRUE);
const ul_t width = decompressor.image_width;
const ul_t height = decompressor.image_height;
if (width == 0) {
throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Zero width.");
}
if (height == 0) {
throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Zero height.");
}
if (width > max_width) {
throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Huge width.");
}
if (height > max_height) {
throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Huge height.");
}
if (decompressor.num_components != 3) {
throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - Unexpected number of components.");
}
jpeg_start_decompress(&decompressor);
tuple<ul_t, ul_t, vuc_t> ret(width, height, vuc_t(width * height * decompressor.num_components, 0));
uc_t * scanptr = &ret.get<2>()[0];
// No scaling is being used.
while (decompressor.output_scanline < height) {
if (jpeg_read_scanlines(&decompressor, &scanptr, 1) != 1) {
throw runtime_error("RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - jpeg_read_scanlines() failed.");
}
scanptr += width * decompressor.num_components;
}
jpeg_finish_decompress(&decompressor);
if (decompressor.client_data == NULL) {
throw runtime_error(str(format(
"RUNTIME ERROR: nuwen::decompress_jpeg_insecurely() - libjpeg warned \"%1%\".") % &warning_message[0]));
}
return ret;
}
#endif // Idempotency
| 31.727811 | 137 | 0.666729 | nurettin |
621dd17616a19e6c168e308708aae90df1cc581d | 2,342 | cpp | C++ | tests/flvstream_unittest.cpp | plonk/peercast-0.1218 | 30fc2401dc798336429a979fe7aaca8883e63ed9 | [
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 28 | 2017-04-30T13:56:13.000Z | 2022-03-20T06:54:37.000Z | tests/flvstream_unittest.cpp | plonk/peercast-0.1218 | 30fc2401dc798336429a979fe7aaca8883e63ed9 | [
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 72 | 2017-04-25T03:42:58.000Z | 2021-12-04T06:35:28.000Z | tests/flvstream_unittest.cpp | plonk/peercast-0.1218 | 30fc2401dc798336429a979fe7aaca8883e63ed9 | [
"PSF-2.0",
"Apache-2.0",
"OpenSSL",
"MIT"
] | 12 | 2017-04-16T06:25:24.000Z | 2021-07-07T13:28:27.000Z | #include <gtest/gtest.h>
#include "flv.h"
#include "amf0.h"
class FLVStreamFixture : public ::testing::Test {
public:
FLVStreamFixture()
{
}
void SetUp()
{
}
void TearDown()
{
}
~FLVStreamFixture()
{
}
};
TEST_F(FLVStreamFixture, readMetaData_commonCase)
{
std::string buf;
buf += amf0::Value("onMetaData").serialize();
buf += amf0::Value::object(
{
{ "videodatarate", 100 },
{ "audiodatarate", 50 }
}).serialize();
bool success;
int bitrate;
std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size());
ASSERT_TRUE(success);
ASSERT_EQ(150, bitrate);
}
TEST_F(FLVStreamFixture, readMetaData_notOnMetaData)
{
std::string buf;
buf += amf0::Value("hoge").serialize();
buf += amf0::Value::object(
{
{ "videodatarate", 100 },
{ "audiodatarate", 50 }
}).serialize();
bool success;
int bitrate;
std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size());
ASSERT_FALSE(success);
}
TEST_F(FLVStreamFixture, readMetaData_onlyVideo)
{
std::string buf;
buf += amf0::Value("onMetaData").serialize();
buf += amf0::Value::object(
{
{ "videodatarate", 100 },
}).serialize();
bool success;
int bitrate;
std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size());
ASSERT_TRUE(success);
ASSERT_EQ(100, bitrate);
}
TEST_F(FLVStreamFixture, readMetaData_onlyAudio)
{
std::string buf;
buf += amf0::Value("onMetaData").serialize();
buf += amf0::Value::object(
{
{ "audiodatarate", 50 },
}).serialize();
bool success;
int bitrate;
std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size());
ASSERT_TRUE(success);
ASSERT_EQ(50, bitrate);
}
TEST_F(FLVStreamFixture, readMetaData_neitherRateIsSupplied)
{
std::string buf;
buf += amf0::Value("onMetaData").serialize();
buf += amf0::Value::object({}).serialize();
bool success;
int bitrate;
std::tie(success, bitrate) = FLVStream::readMetaData(const_cast<char*>(buf.data()), buf.size());
ASSERT_FALSE(success);
}
| 21.099099 | 100 | 0.60205 | plonk |
62261d6120f78d8884b5feef2b8fd8606c40a360 | 559 | hh | C++ | example/include/core/capture/real_sense/Image.hh | thingthing/smart-agent | f4c41432b1bab3283b00237b0208676acb0a00b1 | [
"MIT"
] | null | null | null | example/include/core/capture/real_sense/Image.hh | thingthing/smart-agent | f4c41432b1bab3283b00237b0208676acb0a00b1 | [
"MIT"
] | null | null | null | example/include/core/capture/real_sense/Image.hh | thingthing/smart-agent | f4c41432b1bab3283b00237b0208676acb0a00b1 | [
"MIT"
] | null | null | null | #ifndef _IMAGE_HH_
#define _IMAGE_HH_
class Image
{
public:
Image(const uint8_t* rgb_image, size_t height, size_t width,
double fx, double fy, double cx, double cy, const float *disto)
: _rgb(rgb_image), _height(height), _width(width),
_fx(fx), _fy(fy), _cx(cx), _cy(cy), _disto(disto) {}
~Image() {}
private:
Image();
public:
const uint8_t *_rgb;
size_t _height;
size_t _width;
//focal
double _fx;
double _fy;
//Center point
double _cx;
double _cy;
//Distortion matrice
const float *_disto;
};
#endif /*! _IMAGE_HH_ */ | 18.633333 | 65 | 0.67263 | thingthing |
622698bb9f169f8bf37060908f246b14927b1b47 | 11,535 | cpp | C++ | iceoryx_utils/test/moduletests/test_cxx_convert.cpp | Karsten1987/iceoryx | e5c23eaf5c351ef0095e43673282867b8d060026 | [
"Apache-2.0"
] | 2 | 2019-11-04T05:02:53.000Z | 2019-11-04T05:19:20.000Z | iceoryx_utils/test/moduletests/test_cxx_convert.cpp | Karsten1987/iceoryx | e5c23eaf5c351ef0095e43673282867b8d060026 | [
"Apache-2.0"
] | null | null | null | iceoryx_utils/test/moduletests/test_cxx_convert.cpp | Karsten1987/iceoryx | e5c23eaf5c351ef0095e43673282867b8d060026 | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "test.hpp"
#include "iceoryx_utils/cxx/convert.hpp"
#include <cstdint>
using namespace ::testing;
using NumberType = iox::cxx::convert::NumberType;
class convert_test : public Test
{
public:
void SetUp()
{
internal::CaptureStderr();
}
virtual void TearDown()
{
std::string output = internal::GetCapturedStderr();
if (Test::HasFailure())
{
std::cout << output << std::endl;
}
}
};
TEST_F(convert_test, toString_Integer)
{
EXPECT_THAT(iox::cxx::convert::toString(123), Eq("123"));
}
TEST_F(convert_test, toString_Float)
{
EXPECT_THAT(iox::cxx::convert::toString(12.3f), Eq("12.3"));
}
TEST_F(convert_test, toString_LongLongUnsignedInt)
{
EXPECT_THAT(iox::cxx::convert::toString(123LLU), Eq("123"));
}
TEST_F(convert_test, toString_Char)
{
EXPECT_THAT(iox::cxx::convert::toString('x'), Eq("x"));
}
TEST_F(convert_test, toString_String)
{
EXPECT_THAT(iox::cxx::convert::toString(std::string("hello")), Eq("hello"));
}
TEST_F(convert_test, toString_StringConvertableClass)
{
struct A
{
operator std::string() const
{
return "fuu";
}
};
EXPECT_THAT(iox::cxx::convert::toString(A()), Eq("fuu"));
}
TEST_F(convert_test, FromString_String)
{
std::string source = "hello";
std::string destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(source, Eq(destination));
}
TEST_F(convert_test, fromString_Char_Success)
{
std::string source = "h";
char destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(source[0], Eq(destination));
}
TEST_F(convert_test, fromString_Char_Fail)
{
std::string source = "hasd";
char destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, stringIsNumber_IsINTEGER)
{
EXPECT_THAT(iox::cxx::convert::stringIsNumber("123921301", NumberType::INTEGER), Eq(true));
}
TEST_F(convert_test, stringIsNumber_IsEmpty)
{
EXPECT_THAT(iox::cxx::convert::stringIsNumber("", NumberType::INTEGER), Eq(false));
}
TEST_F(convert_test, stringIsNumber_IsZero)
{
EXPECT_THAT(iox::cxx::convert::stringIsNumber("0", NumberType::INTEGER), Eq(true));
}
TEST_F(convert_test, stringIsNumber_INTEGERWithSign)
{
EXPECT_THAT(iox::cxx::convert::stringIsNumber("-123", NumberType::INTEGER), Eq(true));
}
TEST_F(convert_test, stringIsNumber_INTEGERWithSignPlacedWrongly)
{
EXPECT_THAT(iox::cxx::convert::stringIsNumber("2-3", NumberType::UNSIGNED_INTEGER), Eq(false));
}
TEST_F(convert_test, stringIsNumber_SimpleFLOAT)
{
EXPECT_THAT(iox::cxx::convert::stringIsNumber("123.123", NumberType::FLOAT), Eq(true));
}
TEST_F(convert_test, stringIsNumber_MultiDotFLOAT)
{
EXPECT_THAT(iox::cxx::convert::stringIsNumber("12.3.123", NumberType::FLOAT), Eq(false));
}
TEST_F(convert_test, stringIsNumber_FLOATWithSign)
{
EXPECT_THAT(iox::cxx::convert::stringIsNumber("+123.123", NumberType::FLOAT), Eq(true));
}
TEST_F(convert_test, stringIsNumber_NumberWithLetters)
{
EXPECT_THAT(iox::cxx::convert::stringIsNumber("+123a.123", NumberType::FLOAT), Eq(false));
}
TEST_F(convert_test, fromString_FLOAT_Success)
{
std::string source = "123.01";
float destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_FLOAT_EQ(destination, 123.01f);
}
TEST_F(convert_test, fromString_FLOAT_Fail)
{
std::string source = "hasd";
float destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_Double_Success)
{
std::string source = "123.04";
double destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(static_cast<double>(123.04)));
}
TEST_F(convert_test, fromString_Double_Fail)
{
std::string source = "hasd";
double destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_LongDouble_Success)
{
std::string source = "123.01";
long double destination;
long double verify = 123.01;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Ge(verify - 0.00001));
EXPECT_THAT(destination, Le(verify + 0.00001));
}
TEST_F(convert_test, fromString_LongDouble_Fail)
{
std::string source = "hasd";
double destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_UNSIGNED_Int_Success)
{
std::string source = "123";
unsigned int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(123u));
}
TEST_F(convert_test, fromString_UNSIGNED_Int_Fail)
{
std::string source = "-123";
unsigned int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_UNSIGNED_LongInt_Success)
{
std::string source = "123";
unsigned long int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(123lu));
}
TEST_F(convert_test, fromString_UNSIGNED_LongInt_Fail)
{
std::string source = "-a123";
unsigned long int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_UNSIGNED_LongLongInt_Success)
{
std::string source = "123";
unsigned long long int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(123llu));
}
TEST_F(convert_test, fromString_UNSIGNED_LongLongInt_Fail)
{
std::string source = "-a123";
unsigned long long int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_Int_Success)
{
std::string source = "123";
int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(123));
}
TEST_F(convert_test, fromString_Int_Fail)
{
std::string source = "-+123";
int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_ShortInt_Success)
{
std::string source = "123";
short destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(123));
}
TEST_F(convert_test, fromString_ShortInt_Fail)
{
std::string source = "-+123";
short destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_Bool_Success)
{
std::string source = "1";
bool destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(true));
}
TEST_F(convert_test, fromString_Bool_Fail)
{
std::string source = "-+123";
bool destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_UShortInt_Success)
{
std::string source = "123";
unsigned short destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(123));
}
TEST_F(convert_test, fromString_UShortInt_Fail)
{
std::string source = "-+123";
unsigned short destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_LongInt_Success)
{
std::string source = "-1123";
long int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(-1123l));
}
TEST_F(convert_test, fromString_LongInt_Fail)
{
std::string source = "-a123";
long int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_LongLongInt_Success)
{
std::string source = "-123";
long long int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
EXPECT_THAT(destination, Eq(-123ll));
}
TEST_F(convert_test, fromString_LongLongInt_Fail)
{
std::string source = "-a123";
long long int destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_MinMaxShort)
{
std::string source = "32767";
std::int16_t destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
source = "32768";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
source = "-32768";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
source = "-32769";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_MinMaxUNSIGNED_Short)
{
std::string source = "65535";
std::uint16_t destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
source = "65536";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
source = "0";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
source = "-1";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_MinMaxInt)
{
std::string source = "2147483647";
std::int32_t destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
source = "2147483648";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
source = "-2147483648";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
source = "-2147483649";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
TEST_F(convert_test, fromString_MinMaxUNSIGNED_Int)
{
std::string source = "4294967295";
std::uint32_t destination;
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
source = "4294967296";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
source = "0";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(true));
source = "-1";
EXPECT_THAT(iox::cxx::convert::fromString(source.c_str(), destination), Eq(false));
}
| 30.196335 | 99 | 0.705678 | Karsten1987 |
6229fd95e90e5a7f6062a97a2c0b9c8e009c4995 | 180 | cc | C++ | src/itensor/mps/localmpo_mps.h.cc | kyungminlee/PiTensor | f206fe5a384b52336e9f406c11dc492ff129791b | [
"MIT"
] | 10 | 2019-01-25T03:21:49.000Z | 2020-01-19T04:42:32.000Z | src/itensor/mps/localmpo_mps.h.cc | kyungminlee/PiTensor | f206fe5a384b52336e9f406c11dc492ff129791b | [
"MIT"
] | null | null | null | src/itensor/mps/localmpo_mps.h.cc | kyungminlee/PiTensor | f206fe5a384b52336e9f406c11dc492ff129791b | [
"MIT"
] | 2 | 2018-04-10T05:11:30.000Z | 2018-09-14T08:16:07.000Z | #include "../../pitensor.h"
#include "itensor/mps/localmpo_mps.h"
namespace py = pybind11;
using namespace itensor;
void pitensor::mps::localmpo_mps(pybind11::module& module) {
}
| 22.5 | 60 | 0.738889 | kyungminlee |
622dadbe497fbff44ca9d45118bcd93a6ab74f1b | 21,442 | hpp | C++ | source/RD/Engine/Engine.hpp | RobertDamerius/GroundControlStation | 7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f | [
"MIT"
] | 1 | 2021-12-26T12:48:18.000Z | 2021-12-26T12:48:18.000Z | source/RD/Engine/Engine.hpp | RobertDamerius/GroundControlStation | 7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f | [
"MIT"
] | null | null | null | source/RD/Engine/Engine.hpp | RobertDamerius/GroundControlStation | 7f0d896bd56e5ea0ee02d5738c2b497dc2956c2f | [
"MIT"
] | 1 | 2021-12-26T12:48:25.000Z | 2021-12-26T12:48:25.000Z | /**
* @file Engine.hpp
* @brief The engine header.
* @details Version 20210203.
* The OpenGL headers should be included in the following way:
* #define GLEW_STATIC
* #include <GL/glew.h>
* #ifdef _WIN32
* #define GLFW_EXPOSE_NATIVE_WGL
* #define GLFW_EXPOSE_NATIVE_WIN32
* #endif
* #include <GLFW/glfw3.h>
* #include <GLFW/glfw3native.h>
* #include <glm/glm.hpp>
* #include <glm/gtc/matrix_transform.hpp>
* #include <glm/gtc/type_ptr.hpp>
*/
#pragma once
#include <Core.hpp>
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Debug macros for GL
// Example: DEBUG_GLCHECK( glBindTexture(GL_TEXTURE_2D, 0); );
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#ifdef DEBUG
#define DEBUG_GLCHECK(stmt) \
do { \
GLenum e = glGetError(); \
stmt; \
if(GL_NO_ERROR != (e = glGetError())) \
RD::Core::Console::Message(stderr,"%s:%d in %s() \"%s\": %s\n", __FILE__, __LINE__, __func__, #stmt, RD::Engine::GLErrorToString(e).c_str()); \
} while(0)
#else
#define DEBUG_GLCHECK(stmt) stmt
#endif /* DEBUG */
/* Default module namespace */
namespace RD {
namespace Engine {
/**
* @brief Convert GL error to corresponding string.
* @param [in] error GL error enum.
* @return String that names the GL error.
*/
std::string GLErrorToString(GLenum error);
/**
* @brief Get OpenGL information.
* @param [out] versionGL GL version string.
* @param [out] versionGLSL GLSL version string.
* @param [out] vendor Vendor string.
* @param [out] renderer Renderer string.
*/
void GetGLInfo(std::string* versionGL, std::string* versionGLSL, std::string* vendor, std::string* renderer);
/* Camera Modes */
typedef enum{
CAMERA_MODE_PERSPECTIVE,
CAMERA_MODE_ORTHOGRAPHIC
} CameraMode;
/**
* @brief Class: Camera
*/
class Camera {
public:
CameraMode mode; ///< The camera mode. Either @ref CAMERA_MODE_ORTHOGRAPHIC or @ref CAMERA_MODE_PERSPECTIVE.
double left; ///< The left border limit for orthographic projection.
double right; ///< The right border limit for orthographic projection.
double bottom; ///< The bottom border limit for orthographic projection.
double top; ///< The top border limit for orthographic projection.
double clipNear; ///< The near clipping pane for perspective projection.
double clipFar; ///< The far clipping pane for perspective projection.
double aspect; ///< The aspect ratio for perspective projection.
double fov; ///< The field of view angle in radians for perspective projection.
glm::dvec3 position; ///< The position in world space coordinates.
glm::dvec3 view; ///< The view direction in world space coordinates.
glm::dvec3 up; ///< The up direction in world space coordinates.
/**
* @brief Update the projection matrix.
* @details Call this function if you changed the projection mode or projection parameters (left, right, bottom, top, fov, aspect, clipNear, clipFar).
*/
void UpdateProjectionMatrix(void);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// GENERAL
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* @brief Create a camera using a perspective projection. This is the default constructor.
* @param [in] clipNear Near clipping pane border. Defaults to 0.01.
* @param [in] clipFar Far clipping pane border. Defaults to 500.0.
* @param [in] aspect The aspect ratio (width / height). Defaults to 8.0 / 5.0.
* @param [in] fov The field of view in radians. Defaults to glm::radians(58.0).
* @param [in] position The initial position. Defaults to glm::dvec3(0.0).
* @param [in] view The initial view direction. Defaults to glm::dvec3(0.0, 0.0, -1.0).
* @param [in] up The initial up direction. Defaults to glm::dvec3(0.0, 1.0, 0.0).
* @details The private attribute @ref mode will be set to @ref CAMERA_MODE_PERSPECTIVE.
*/
Camera(double clipNear = 0.01, double clipFar = 500.0, double aspect = 8.0 / 5.0, double fov = glm::radians(70.0), glm::dvec3 position = glm::dvec3(0.0), glm::dvec3 view = glm::dvec3(0.0, 0.0, -1.0), glm::dvec3 up = glm::dvec3(0.0, 1.0, 0.0));
/**
* @brief Create a camera using an orthographic projection.
* @param [in] left Left border.
* @param [in] right Right border.
* @param [in] bottom Bottom border.
* @param [in] top Top border.
* @param [in] clipNear Near clipping pane border.
* @param [in] clipFar Far clipping pane border.
* @param [in] view The view direction vector. Defaults to glm::dvec3(0.0, 0.0, -1.0).
* @param [in] up The up direction vector. Defaults to glm::dvec3(0.0, 1.0, 0.0).
* @details The private attribute @ref mode will be set to @ref CAMERA_MODE_ORTHOGRAPHIC.
*/
Camera(double left, double right, double bottom, double top, double clipNear, double clipFar, glm::dvec3 view = glm::dvec3(0.0, 0.0, -1.0), glm::dvec3 up = glm::dvec3(0.0, 1.0, 0.0));
/**
* @brief Default copy constructor.
*/
Camera(const Camera& camera) = default;
/**
* @brief Delete the camera.
* @details @ref DeleteUniformBufferObject will NOT be called.
*/
~Camera();
/**
* @brief Assignment operator.
* @param [in] rhs The right hand side value.
* @details This will copy all private attributes from rhs to this camera instance. However, the UBO value will not be copied.
*/
Camera& operator=(const Camera& rhs);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// WORLD SPACE TRANSFORMATIONS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* @brief Rotate camera in world space coordinates beginning from the current orientation.
* @param [in] angle Angle in radians.
* @param [in] axis Rotation axis.
*/
void Rotate(double angle, glm::dvec3 axis);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// VIEW SPACE TRANSFORMATIONS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* @brief Roll around the forward (view) direction.
* @param [in] angle Roll angle in radians.
*/
void RollView(double angle);
/**
* @brief Pitch around the x-axis of the camera view frame.
* @param [in] angle Pitch angle in radians.
*/
void PitchView(double angle);
/**
* @brief Yaw around the down direction of the camera view frame.
* @param [in] angle Yaw angle in radians.
*/
void YawView(double angle);
/**
* @brief Move camera in the camera view frame.
* @param [in] xyz Movement vector.
*/
void MoveView(glm::dvec3 xyz);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// GET TRANSFORMATION MATRICES
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* @brief Get the view matrix only.
* @return The 4x4 view matrix.
*/
glm::dmat4 GetViewMatrix(void);
/**
* @brief Get the projection matrix only.
* @return The 4x4 projection matrix depending on the @ref mode.
*/
glm::dmat4 GetProjectionMatrix(void);
/**
* @brief Get the projection-view matrix.
* @return 4x4 projection-view matrix.
*/
glm::dmat4 GetProjectionViewMatrix(void);
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Uniform Buffer Object Management
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/**
* @brief Generate the uniform buffer object.
* @param [in] bindingPoint The bining point for the uniform buffer object. Must be the same in the shader.
* @details The shader must use the following uniform block:
* layout (std140, binding = bindingPoint) uniform Camera{
* mat4 camProjectionView;
* mat4 camProjectionViewTFree;
* vec3 camPosition;
* vec3 camViewDirection;
* };
* @note The buffer will be initialized using the @ref UpdateUniformBufferObject member function.
*/
void GenerateUniformBufferObject(GLuint bindingPoint);
/**
* @brief Delete the uniform buffer object.
*/
void DeleteUniformBufferObject(void);
/**
* @brief Update the uniform buffer object.
* @details This will update the complete uniform block buffer data.
*/
void UpdateUniformBufferObject(void);
private:
glm::dmat4 projectionMatrix; ///< The projection matrix. Use @ref UpdateProjectionMatrix to update the matrix.
GLuint ubo; ///< The uniform buffer object.
}; /* class: Camera */
/**
* @brief Class: CouboidFrustumCuller
* @details Check whether a cuboid is visible by the cameras frustum or not.
* @note The cuboid must be aligned to the world space axes.
*/
class CuboidFrustumCuller {
public:
/**
* @brief Create a cuboid frustum culler using the cameras projection view matrix.
* @param [in] cameraProjectionViewMatrix The projection view matrix of the camera.
*/
explicit CuboidFrustumCuller(const glm::mat4& cameraProjectionViewMatrix);
/**
* @brief Delete the cuboid frustum culler.
*/
~CuboidFrustumCuller();
/**
* @brief Check if a cuboid is visible.
* @param [in] blockLowestPosition The lowest position of the cuboid.
* @param [in] blockDimension The dimension of the cuboid.
* @return True if cuboid is visible, false otherwise.
*/
bool IsVisible(glm::vec3 blockLowestPosition, glm::vec3 blockDimension);
private:
GLfloat cullInfo[6][4]; ///< Culling information (generated by constructor).
}; /* class: CuboidFrustumCuller */
/**
* @brief Class: Shader
* @details Handles vertex + geometry (optional) + fragment shader.
*/
class Shader {
public:
/**
* @brief Create a shader object.
*/
Shader():id(0){}
/**
* @brief Get the GLSL-version string to be used to generate shader.
* @return The version string, e.g. "450".
* @details Make sure that the OpenGL context is initialized to obtain correct version information.
*/
static std::string GetShadingLanguageVersion(void);
/**
* @brief Generate the shader.
* @param [in] fileName The filename of the GLSL shader file.
* @return True if success, false otherwise.
* @details A zero terminator will be added to the shader source. The GLSL version will be assigned automatically using the @ref GetShadingLanguageVersion function.
*/
bool Generate(std::string fileName);
/**
* @brief Generate the shader.
* @param [in] fileName The filename of the GLSL shader file.
* @param [in] version The version string number, e.g. "450".
* @return True if success, false otherwise.
* @details A zero terminator will be added to the shader source.
*/
bool Generate(std::string fileName, std::string version);
/**
* @brief Generate the shader.
* @param [in] fileName The filename of the GLSL shader file.
* @param [in] version The version string number, e.g. "450".
* @param [in] replacement Text replacement data.
* @return True if success, false otherwise.
* @details A zero terminator will be added to the shader source.
*/
bool Generate(std::string fileName, std::string version, std::vector<std::pair<std::string, std::string>>& replacement);
/**
* @brief Generate the shader.
* @param [in] fileData Binary file data.
* @param [in] version The version string number, e.g. "450".
* @return True if success, false otherwise.
* @details A zero terminator will be added to the shader source.
*/
bool Generate(std::vector<uint8_t>& fileData, std::string version);
/**
* @brief Generate the shader.
* @param [in] fileData Binary file data.
* @param [in] version The version string number, e.g. "450".
* @param [in] replacement Text replacement data.
* @return True if success, false otherwise.
* @details A zero terminator will be added to the shader source.
*/
bool Generate(std::vector<uint8_t>& fileData, std::string version, std::vector<std::pair<std::string, std::string>>& replacement);
/**
* @brief Delete the shader program.
*/
void Delete(void);
/**
* @brief Use the shader.
*/
inline void Use(void){ DEBUG_GLCHECK( glUseProgram(id); ); }
/**
* @brief Get the uniform location.
* @param [in] name Name of the uniform.
* @return Location of the uniform.
*/
inline GLint GetUniformLocation(const GLchar* name){ return glGetUniformLocation(id, name); }
/* The uniforms */
inline void UniformMatrix4fv(const GLchar* name, GLboolean transpose, glm::mat4& matrix){ DEBUG_GLCHECK( glUniformMatrix4fv(glGetUniformLocation(id, name), 1, transpose, glm::value_ptr(matrix)); ); }
inline void UniformMatrix4fv(GLint location, GLboolean transpose, glm::mat4& matrix){ DEBUG_GLCHECK( glUniformMatrix4fv(location, 1, transpose, glm::value_ptr(matrix)); ); }
inline void UniformMatrix4fv(const GLchar* name, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix4fv(glGetUniformLocation(id, name), 1, transpose, matrix); ); }
inline void UniformMatrix4fv(GLint location, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix4fv(location, 1, transpose, matrix); ); }
inline void UniformMatrix3fv(const GLchar* name, GLboolean transpose, glm::mat3& matrix){ DEBUG_GLCHECK( glUniformMatrix3fv(glGetUniformLocation(id, name), 1, transpose, glm::value_ptr(matrix)); ); }
inline void UniformMatrix3fv(GLint location, GLboolean transpose, glm::mat3& matrix){ DEBUG_GLCHECK( glUniformMatrix3fv(location, 1, transpose, glm::value_ptr(matrix)); ); }
inline void UniformMatrix3fv(const GLchar* name, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix3fv(glGetUniformLocation(id, name), 1, transpose, matrix); ); }
inline void UniformMatrix3fv(GLint location, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix3fv(location, 1, transpose, matrix); ); }
inline void UniformMatrix2fv(const GLchar* name, GLboolean transpose, glm::mat2& matrix){ DEBUG_GLCHECK( glUniformMatrix2fv(glGetUniformLocation(id, name), 1, transpose, glm::value_ptr(matrix)); ); }
inline void UniformMatrix2fv(GLint location, GLboolean transpose, glm::mat2& matrix){ DEBUG_GLCHECK( glUniformMatrix2fv(location, 1, transpose, glm::value_ptr(matrix)); ); }
inline void UniformMatrix2fv(const GLchar* name, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix2fv(glGetUniformLocation(id, name), 1, transpose, matrix); ); }
inline void UniformMatrix2fv(GLint location, GLboolean transpose, GLfloat* matrix){ DEBUG_GLCHECK( glUniformMatrix2fv(location, 1, transpose, matrix); ); }
inline void Uniform4f(const GLchar* name, glm::vec4& value){ DEBUG_GLCHECK( glUniform4f(glGetUniformLocation(id, name), value.x, value.y, value.z, value.w); ); }
inline void Uniform4f(GLint location, glm::vec4& value){ DEBUG_GLCHECK( glUniform4f(location, value.x, value.y, value.z, value.w); ); }
inline void Uniform4fv(const GLchar* name, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform4fv(glGetUniformLocation(id, name), count, value); ); }
inline void Uniform4fv(GLint location, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform4fv(location, count, value); ); }
inline void Uniform3f(const GLchar* name, glm::vec3& value){ DEBUG_GLCHECK( glUniform3f(glGetUniformLocation(id, name), value.x, value.y, value.z); ); }
inline void Uniform3f(GLint location, glm::vec3& value){ DEBUG_GLCHECK( glUniform3f(location, value.x, value.y, value.z); ); }
inline void Uniform3fv(const GLchar* name, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform3fv(glGetUniformLocation(id, name), count, value); ); }
inline void Uniform3fv(GLint location, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform3fv(location, count, value); ); }
inline void Uniform2f(const GLchar* name, glm::vec2& value){ DEBUG_GLCHECK( glUniform2f(glGetUniformLocation(id, name), value.x, value.y); ); }
inline void Uniform2f(GLint location, glm::vec2& value){ DEBUG_GLCHECK( glUniform2f(location, value.x, value.y); ); }
inline void Uniform2fv(const GLchar* name, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform2fv(glGetUniformLocation(id, name), count, value); ); }
inline void Uniform2fv(GLint location, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform2fv(location, count, value); ); }
inline void Uniform1f(const GLchar* name, GLfloat value){ DEBUG_GLCHECK( glUniform1f(glGetUniformLocation(id, name), value); ); }
inline void Uniform1f(GLint location, GLfloat value){ DEBUG_GLCHECK( glUniform1f(location, value); ); }
inline void Uniform1fv(const GLchar* name, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform1fv(glGetUniformLocation(id, name), count, value); ); }
inline void Uniform1fv(GLint location, GLsizei count, const GLfloat* value){ DEBUG_GLCHECK( glUniform1fv(location, count, value); ); }
inline void Uniform4i(const GLchar* name, GLint value0, GLint value1, GLint value2, GLint value3){ DEBUG_GLCHECK( glUniform4i(glGetUniformLocation(id, name), value0, value1, value2, value3); ); }
inline void Uniform4i(GLint location, GLint value0, GLint value1, GLint value2, GLint value3){ DEBUG_GLCHECK( glUniform4i(location, value0, value1, value2, value3); ); }
inline void Uniform4iv(const GLchar* name, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform4iv(glGetUniformLocation(id, name), count, values); ); }
inline void Uniform4iv(GLint location, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform4iv(location, count, values); ); }
inline void Uniform3i(const GLchar* name, GLint value0, GLint value1, GLint value2){ DEBUG_GLCHECK( glUniform3i(glGetUniformLocation(id, name), value0, value1, value2); ); }
inline void Uniform3i(GLint location, GLint value0, GLint value1, GLint value2){ DEBUG_GLCHECK( glUniform3i(location, value0, value1, value2); ); }
inline void Uniform3iv(const GLchar* name, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform3iv(glGetUniformLocation(id, name), count, values); ); }
inline void Uniform3iv(GLint location, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform3iv(location, count, values); ); }
inline void Uniform2i(const GLchar* name, GLint value0, GLint value1){ DEBUG_GLCHECK( glUniform2i(glGetUniformLocation(id, name), value0, value1); ); }
inline void Uniform2i(GLint location, GLint value0, GLint value1){ DEBUG_GLCHECK( glUniform2i(location, value0, value1); ); }
inline void Uniform2iv(const GLchar* name, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform2iv(glGetUniformLocation(id, name), count, values); ); }
inline void Uniform2iv(GLint location, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform2iv(location, count, values); ); }
inline void Uniform1i(const GLchar* name, GLint value){ DEBUG_GLCHECK( glUniform1i(glGetUniformLocation(id, name), value); ); }
inline void Uniform1i(GLint location, GLint value){ DEBUG_GLCHECK( glUniform1i(location, value); ); }
inline void Uniform1iv(const GLchar* name, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform1iv(glGetUniformLocation(id, name), count, values); ); }
inline void Uniform1iv(GLint location, GLsizei count, const GLint* values){ DEBUG_GLCHECK( glUniform1iv(location, count, values); ); }
inline void UniformBlockBinding(const GLchar* name, GLuint value){ DEBUG_GLCHECK( glUniformBlockBinding(id, glGetUniformBlockIndex(id, name), value); ); }
inline void UniformBlockBinding(GLint location, GLuint value){ DEBUG_GLCHECK( glUniformBlockBinding(id, location, value); ); }
private:
GLuint id; ///< The program ID.
}; /* class: Shader */
} /* namespace: Engine */
} /* namespace: RD */
| 52.425428 | 251 | 0.623962 | RobertDamerius |
622e0dbff83d5e823a76f4fa0834f1b206977408 | 2,207 | hh | C++ | src/include/Token.hh | websurfer5/json-schema-enforcer | 99211a602b1c8177d9f9e67cd7773015f74a4080 | [
"Apache-2.0"
] | null | null | null | src/include/Token.hh | websurfer5/json-schema-enforcer | 99211a602b1c8177d9f9e67cd7773015f74a4080 | [
"Apache-2.0"
] | null | null | null | src/include/Token.hh | websurfer5/json-schema-enforcer | 99211a602b1c8177d9f9e67cd7773015f74a4080 | [
"Apache-2.0"
] | null | null | null | // Token.hh
//
// Copyright 2018 Jeffrey Kintscher <websurfer@surf2c.net>
//
// 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.
#ifndef __JSONSCHEMAENFORCER_TOKEN_HH
#define __JSONSCHEMAENFORCER_TOKEN_HH
#include "config.h"
#include "stddefs.hh"
#include <map>
#include <string>
namespace jsonschemaenforcer
{
class Token
{
public:
Token();
Token(const Token& _token);
Token(const std::string& _token_name,
const std::string& _type,
const std::string& _pattern,
const std::string& _input_string,
const std::string& _start_state,
const std::string& _new_start_state,
bool _pop_state,
const std::string& _rule_body);
Token& operator =(const Token& _token);
bool operator ==(const Token& _token) const;
inline bool operator !=(const Token& _token) const { return !(operator ==(_token)); };
void clear();
bool empty();
# define DEF_VAR(vtype, vname, value, test_value, flag_name, flag_value, func_set, func_get) \
void func_set(const vtype& _##vname); \
inline const vtype& func_get() const { return vname; }; \
inline bool has_##vname() const { return flag_name; };
# include "Token-vars.hh"
# undef DEF_VAR
// protected:
# define DEF_VAR(vtype, vname, value, test_value, flag_name, flag_value, func_set, func_get) \
vtype vname; \
bool flag_name;
# include "Token-vars.hh"
# undef DEF_VAR
};
typedef std::map<StdStringPair, Token> StdStringTokenMap;
}
#endif // __JSONSCHEMAENFORCER_TOKEN_HH
| 32.455882 | 100 | 0.643407 | websurfer5 |
622ebf7562d5cf93bb2cde67f1a33f516bcb3d0c | 7,017 | hpp | C++ | src/io.hpp | jewettaij/calc_writhe | 018ee05d802b7bf51182a8f7cb70b67194a09aba | [
"MIT"
] | null | null | null | src/io.hpp | jewettaij/calc_writhe | 018ee05d802b7bf51182a8f7cb70b67194a09aba | [
"MIT"
] | 1 | 2021-03-24T20:59:10.000Z | 2021-03-24T20:59:10.000Z | src/io.hpp | jewettaij/calc_writhe | 018ee05d802b7bf51182a8f7cb70b67194a09aba | [
"MIT"
] | null | null | null | /// @file io.hpp
/// @brief A series of (arguably unnecessary) functions that
/// read strings and numbers from a file.
/// @date 2007-4-13
#ifndef _IO_HPP
#define _IO_HPP
#include <iostream>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <cstring>
using namespace std;
#include "err.hpp"
/// When a syntax error occurs in a file, which file did it occur in?
string g_filename;
/// where in the file (did the error occur):
long long g_line;
/// comment indicator
char g_comments_begin_with ='#';
/// comment terminator
char g_comments_end_with = '\n';
/// @brief Does character c belong to aC?
template<class C>
inline bool
BelongsToCstring(C c, C const *aC, C terminating_char)
{
assert(aC);
while(*aC != terminating_char)
{
if (c == *aC) return true;
++aC;
}
return false;
}
/// @brief Skip over some characters if they are present at this location
/// in the file.
inline void
Skip(istream &in,
char const *aSkipTheseChars)
{
assert(aSkipTheseChars);
if (! in) {
stringstream err_msg;
err_msg << "Error in input: \"" << g_filename <<"\"\n"
" near line " << g_line <<": File ends prematurely." << endl;
throw InputErr(err_msg.str().c_str());
}
char c;
while(in.get(c))
{
if (c=='\n') g_line++; // <-- keep track of what line we are on
else if (c == g_comments_begin_with)
{
// skip past this comment (do not assume single-line comments)
do {
in.get(c);
if (in && (c=='\n')) g_line++;
} while (in && (c != '\0') && (c != EOF) && (c!=g_comments_end_with));
}
// Note: this code does not work with nested comments. fix this later..
if (in && (! BelongsToCstring(c, aSkipTheseChars, '\0')))
{
in.putback(c);
if (c=='\n') g_line--;
break;
}
}
} // Skip()
/// @brief Read a token from the stream.
/// (Tokens are words delimited by one of the characters
/// in the "terminators" argument, which are typically whitespace.)
inline void
ReadString(istream &in,
string &dest,
char const *terminators)
{
assert(terminators);
if (! in) {
stringstream err_msg;
err_msg << "Error in input: \"" << g_filename <<"\"\n"
" near line " << g_line <<": File ends prematurely." << endl;
throw InputErr(err_msg.str().c_str());
}
char c;
while(in.get(c))
{
if (BelongsToCstring(c, terminators, '\0') ||
(c == g_comments_begin_with))
{
in.putback(c);
break;
}
else
{
dest.push_back(c);
if (c=='\n')
g_line++; //keep track of the number of newlines read so far.
}
}
} // ReadString()
/// @brief Read a number from this location in the file.
template<class Scalar>
bool
ReadScalar(istream &in,
Scalar& dest,
char const *ac_terminators,
string *ps_dest,
string::const_iterator *pstopped_at=nullptr)
{
string s;
ReadString(in, s, ac_terminators);
// If requested, make a copy this string and return it to the caller
if (ps_dest != nullptr)
*ps_dest=s;
if (pstopped_at != nullptr)
*pstopped_at = ps_dest->begin();
if (s.size() != 0)
{
// I would prefer to use the standard ANSI C function: strtod()
// to parse the string and convert it to a floating point variable.
// But I have to copy this text into a c_string to get around strtod()'s
// syntax. strtod() requires an argument of type "char *". I could
// use s.c_str(), but this is a pointer of type "const char *".
// So, I need to copy the contents of s.c_str() into a temporary array,
// and then invoke strtod() on it.
char *ac = new char [s.size() + 1];
strcpy(ac, s.c_str());
char *pstart = ac;
char *pstop;
#ifdef STRTOLD_UNSUPPORTED
dest = strtod(pstart, &pstop);
#else
dest = strtold(pstart, &pstop);//Useful but not standard ANSI C
#endif
// Now pstop points past the last valid char
// If requested, inform the caller where the parsing stopped
if (pstopped_at != nullptr)
*pstopped_at = ps_dest->begin() + (pstop - pstart);
delete [] ac;
return (pstop - pstart == s.size()); //did parsing terminate prematurely?
}
else
return false; //no number was successfully read
} //ReadScalar()
/// @brief Read a number from this location in the file.
/// @overloaded
template<class Scalar>
Scalar
ReadScalar(istream &in,
char const *ac_terminators)
{
Scalar dest;
string s;
if (! ReadScalar(in, dest, ac_terminators, &s))
{
stringstream err_msg;
err_msg <<
"Error in input: \"" << g_filename << "\"\n"
" near line " << g_line;
if (! s.empty())
cerr << ": \""<<s<<"\"\n";
err_msg <<
" Expected a number." << endl;
throw InputErr(err_msg.str().c_str());
}
return dest;
} //ReadScalar()
/// @brief Read an integer from this location in the file.
bool
ReadInt(istream &in,
long long& dest,
char const *ac_terminators,
string *ps_dest,
string::const_iterator *pstopped_at = nullptr)
{
string s;
ReadString(in, s, ac_terminators);
// If requested, make a copy this string and return it to the caller
if (ps_dest != nullptr)
*ps_dest=s;
if (pstopped_at != nullptr)
*pstopped_at = ps_dest->begin();
if (s != "")
{
// I would prefer to use the standard ANSI C function: strtod()
// to parse the string and convert it to a floating point variable.
// But I have to copy this text into a c_string to get around strtod()'s
// syntax. strtod() requires an argument of type "char *". I could
// use s.c_str(), but this is a pointer of type "const char *".
// So, I need to copy the contents of s.c_str() into a temporary array,
// and then invoke strtod() on it.
char *ac = new char [s.size() + 1];
strcpy(ac, s.c_str());
char *pstart = ac;
char *pstop;
dest = strtol(pstart, &pstop, 10);
// Now pstop points past the last valid char
// If requested, inform the caller where the parsing stopped
if (pstopped_at != nullptr)
*pstopped_at = ps_dest->begin() + (pstop - pstart);
delete [] ac;
return (pstop - pstart == s.size()); //did parsing terminate prematurely?
}
else
return false; //no number was successfully read
} //ReadInt()
/// @brief Read an integer from this location in the file.
/// @overloaded
long long
ReadInt(istream &in,
char const *ac_terminators)
{
long long dest;
string s;
if (! ReadInt(in, dest, ac_terminators, &s))
{
stringstream err_msg;
err_msg <<
"Error in input: \"" << g_filename << "\"\n"
" near line " << g_line;
if (! s.empty())
cerr << ": \""<<s<<"\"\n";
err_msg <<
" Expected an integer." << endl;
throw InputErr(err_msg.str().c_str());
}
return dest;
} //ReadInt()
#endif //#ifndef _IO_HPP
| 24.882979 | 77 | 0.601254 | jewettaij |
622f49a80f31a99c173edbdef5a20effd5e494c9 | 695 | cpp | C++ | client/client_main.cpp | aejaz83/asio_server | 6b9bfbb9ca6954694ea08bfca0a9b1f4cf8741b4 | [
"BSL-1.0"
] | null | null | null | client/client_main.cpp | aejaz83/asio_server | 6b9bfbb9ca6954694ea08bfca0a9b1f4cf8741b4 | [
"BSL-1.0"
] | null | null | null | client/client_main.cpp | aejaz83/asio_server | 6b9bfbb9ca6954694ea08bfca0a9b1f4cf8741b4 | [
"BSL-1.0"
] | null | null | null | /*
* Author: Aehjaj Ahmed P
* Date: 1-July-2019
*/
#include <iostream>
#include <boost/asio.hpp>
#include "tcp_client.hpp"
using boost::asio::ip::tcp;
int main(int argc, char* argv[]){
try{
if(argc != 3){
std::cerr << "Usage: tcp_client <host> <port>\n";
return -1;
}
boost::asio::io_context io_context;
// boost::asio::io_service::work work(io_context);
tcp::resolver resolver(io_context);
auto endpoints = resolver.resolve(argv[1], argv[2]);
Tcp_Client client(io_context, endpoints);
io_context.run();
} catch (std::exception& e){
std::cerr << "Exception: " << e.what() << std::endl;
}
return 0;
} | 23.166667 | 58 | 0.58705 | aejaz83 |
62343debc4ea5eca48577fbaf39775d7dfdd40b5 | 589 | hpp | C++ | Kernel/syscalls.hpp | foragerDev/GevOS | f21c8432dd63ab583d9132422bf313ebf60557e8 | [
"Unlicense"
] | null | null | null | Kernel/syscalls.hpp | foragerDev/GevOS | f21c8432dd63ab583d9132422bf313ebf60557e8 | [
"Unlicense"
] | null | null | null | Kernel/syscalls.hpp | foragerDev/GevOS | f21c8432dd63ab583d9132422bf313ebf60557e8 | [
"Unlicense"
] | null | null | null | #ifndef SYSCALLS_HPP
#define SYSCALLS_HPP
#include "Exec/loader.hpp"
#include "Filesystem/vfs.hpp"
#include "Hardware/Drivers/keyboard.hpp"
#include "Hardware/Drivers/pcspk.hpp"
#include "Hardware/interrupts.hpp"
#include "LibC/stdio.hpp"
#include "LibC/types.hpp"
#include "Mem/mm.hpp"
#include "multitasking.hpp"
#include "tty.hpp"
extern "C" int shutdown();
class SyscallHandler : public InterruptHandler {
public:
SyscallHandler(InterruptManager* interruptManager, uint8_t InterruptNumber);
~SyscallHandler();
virtual uint32_t HandleInterrupt(uint32_t esp);
};
#endif
| 22.653846 | 80 | 0.765705 | foragerDev |
62361cc16c9ad5370189225d5253bad12c1f6e7f | 12,672 | hpp | C++ | src/cpp_lib/statistics/StatsTracker.hpp | hitbc/panSV | 273b13bf496593325778d926f763bed6d2de5be2 | [
"MIT"
] | null | null | null | src/cpp_lib/statistics/StatsTracker.hpp | hitbc/panSV | 273b13bf496593325778d926f763bed6d2de5be2 | [
"MIT"
] | null | null | null | src/cpp_lib/statistics/StatsTracker.hpp | hitbc/panSV | 273b13bf496593325778d926f763bed6d2de5be2 | [
"MIT"
] | 1 | 2021-09-25T10:35:46.000Z | 2021-09-25T10:35:46.000Z | /*
* StatsTracker.hpp
*
* Created on: 2020年5月1日
* Author: fenghe
*/
#pragma once
#include<iostream>
#include <cstring>
#include <cassert>
#include <functional>
#include <iosfwd>
#include <map>
#include <vector>
extern "C" {
#include "../clib/bam_file.h"
}
/****************PART ONE: Size Distribution***************************/
/// \brief Accumulate size observations and provide cdf/quantile/smoothed-pdf for the distribution
///
struct SizeData {
SizeData(unsigned initCount = 0, float initCprob = 0.) :
count(initCount), cprob(initCprob) {
}
unsigned count;
float cprob;
};
typedef std::map<int, SizeData, std::greater<int>> map_type;
struct SizeDistribution {
SizeDistribution() :
_isStatsComputed(false), _totalCount(0), _quantiles(_quantileNum, 0) {
}
/// \brief Implements the quantile function for this distribution
int quantile(const float prob) const; /// \return The size at which all sizes equal or less are observed with probability \p prob
float cdf(const int x) const;/// \return Probability of observing value <= \p x
float pdf(const int x) const;/// \return Probability of observing value \p x, (with a smoothing window)
unsigned totalObservations() const {
return _totalCount;
}
void addObservation(const int size) {
_isStatsComputed = false;
_totalCount++;
_sizeMap[size].count++;
}
void filterObservationsOverQuantile(const float prob);/// filter high value outliers:
bool isStatSetMatch(const SizeDistribution &pss2);/// compare distributions to determine stats convergence
int getSizeCount(int isize) const{
return _sizeMap[isize].count;
}
private:
void calcStats() const;
static const int _quantileNum = 1000;
mutable bool _isStatsComputed;
unsigned _totalCount;
mutable std::vector<int> _quantiles;
mutable map_type _sizeMap;
};
//********************************PART TWO: Read PAIR DIRECTION**************************/
typedef int32_t pos_t;
namespace PAIR_ORIENT {
enum index_t { UNKNOWN, Fm, Fp, Rm, Rp, SIZE};
inline const char* label(const index_t i) {
switch (i) {
case Fm: return "Fm";
case Fp: return "Fp";
case Rm: return "Rm";
case Rp: return "Rp";
default:
return "UNKNOWN";
}
}
inline index_t get_index(const pos_t pos1, const bool is_fwd_strand1,
const pos_t pos2, const bool is_fwd_strand2) {
const bool is_read1_left(pos1 < pos2);
if (is_fwd_strand1 != is_fwd_strand2) {
// special-case very short fragments as innies:
//
// a few bases of overhang are allowed to account for random matches of
// the reverse read to the primer
//
if (std::abs(pos1 - pos2) <= 2)
return Rp;
const bool left_strand(is_read1_left ? is_fwd_strand1 : is_fwd_strand2);
return (left_strand ? Rp : Rm);
} else {
return ((is_read1_left == is_fwd_strand1) ? Fp : Fm);
}
}
/// inefficient label to id lookup, returns SIZE for unknown string:
inline index_t get_index(const char *str) {
for (int i(0); i < SIZE; ++i) {
if (0 == strcmp(str, label(static_cast<index_t>(i))))
return static_cast<index_t>(i);
}
return SIZE;
}
} // END namespace PAIR_ORIENT
/// pair orientation status wrapper:
struct ReadPairOrient {
ReadPairOrient() :
_val(PAIR_ORIENT::UNKNOWN) {
}
PAIR_ORIENT::index_t val() const {
return _val;
}
void setVal(const unsigned newVal) {
assert(newVal < PAIR_ORIENT::SIZE);
_val = static_cast<PAIR_ORIENT::index_t>(newVal);
}
private:
PAIR_ORIENT::index_t _val;
};
//********************************PART Three: ReadCounter**************************/
/// \brief Accumulate read statistics scanned for insert size estimation
struct ReadCounter {
ReadCounter() :
_totalReadCount(0), _totalPairedReadCount(0), _totalUnpairedReadCount(
0), _totalPairedLowMapqReadCount(0), _totalHighConfidenceReadPairCount(
0) {}
unsigned totalReadCount() const { return _totalReadCount;}
unsigned totalPairedReadCount() const { return _totalPairedReadCount;}
unsigned totalUnpairedReadCount() const {return _totalUnpairedReadCount;}
unsigned totalPairedLowMapqReadCount() const {return _totalPairedLowMapqReadCount;}
unsigned totalHighConfidenceReadPairCount() const { return _totalHighConfidenceReadPairCount;}
void addReadCount() { _totalReadCount++;}
void addPairedReadCount() { _totalPairedReadCount++;}
void addUnpairedReadCount() { _totalUnpairedReadCount++;}
void addPairedLowMapqReadCount() { _totalPairedLowMapqReadCount++;}
void addHighConfidenceReadPairCount() { _totalHighConfidenceReadPairCount += 1;}
friend std::ostream& operator<<(std::ostream &os, const ReadCounter &rs) {
os << "\tTotal sampled reads: " + std::to_string(rs.totalReadCount()) + "\n"
<< "\tTotal sampled paired reads: "
+ std::to_string(rs.totalPairedReadCount()) + "\n"
<< "\tTotal sampled paired reads passing MAPQ filter: "
+ std::to_string(
rs.totalPairedReadCount()
- rs.totalPairedLowMapqReadCount()) + "\n"
<< "\tTotal sampled high-confidence read pairs passing all filters: "
+ std::to_string(rs.totalHighConfidenceReadPairCount())
+ "\n";
return os;
}
private:
///////////////////////////////////// data:
unsigned _totalReadCount;
unsigned _totalPairedReadCount;
unsigned _totalUnpairedReadCount;
unsigned _totalPairedLowMapqReadCount;
unsigned _totalHighConfidenceReadPairCount;
};
//********************************PART Four: Unique Stats**************************/
/// Read pair insert stats can be computed for each sample or read group, this
/// class represents the statistics for one group:
///
struct UniqueStats {
public:
SizeDistribution fragStats;
ReadPairOrient relOrients;
ReadCounter readCounter;
};
struct StatLabel {
/// if isCopyPtrs then the strings are copied and alloced/de-alloced by
/// the object, if false the client is responsible these pointers over
/// the lifetime of the label:
StatLabel(const char *bamLabelInit, const char *rgLabelInit,
const bool isCopyPtrsInit = true) :
isCopyPtrs(isCopyPtrsInit), bamLabel(
(isCopyPtrs && (nullptr != bamLabelInit)) ?
strdup(bamLabelInit) : bamLabelInit), rgLabel(
(isCopyPtrs && (nullptr != rgLabelInit)) ?
strdup(rgLabelInit) : rgLabelInit) {
assert(nullptr != bamLabel);
assert(nullptr != rgLabel);
}
StatLabel(const StatLabel &rhs) :
isCopyPtrs(rhs.isCopyPtrs), bamLabel(
isCopyPtrs ? strdup(rhs.bamLabel) : rhs.bamLabel), rgLabel(
isCopyPtrs ? strdup(rhs.rgLabel) : rhs.rgLabel) {
}
StatLabel& operator=(const StatLabel &rhs) {
if (this == &rhs)
return *this;
clear();
isCopyPtrs = rhs.isCopyPtrs;
bamLabel = (isCopyPtrs ? strdup(rhs.bamLabel) : rhs.bamLabel);
rgLabel = (isCopyPtrs ? strdup(rhs.rgLabel) : rhs.rgLabel);
return *this;
}
public:
~StatLabel() {
clear();
}
/// sort allowing for nullptr string pointers in primary and secondary key:
bool operator<(const StatLabel &rhs) const {
const int scval(strcmp(bamLabel, rhs.bamLabel));
if (scval < 0)
return true;
if (scval == 0) {
return (strcmp(rgLabel, rhs.rgLabel) < 0);
}
return false;
}
friend std::ostream& operator<<(std::ostream &os,
const StatLabel &rgl) {
os << "read group '" << rgl.rgLabel << "' in bam file '"
<< rgl.bamLabel;
return os;
}
private:
void clear() {
if (isCopyPtrs) {
if (nullptr != bamLabel)
free(const_cast<char*>(bamLabel));
if (nullptr != rgLabel)
free(const_cast<char*>(rgLabel));
}
}
bool isCopyPtrs;
public:
const char *bamLabel;
const char *rgLabel;
};
/// track pair orientation so that a consensus can be found for a read group
struct OrientTracker {
OrientTracker(const char *bamLabel, const char *rgLabel) :
_isFinalized(false), _totalOrientCount(0), _rgLabel(bamLabel,
rgLabel) {
std::fill(_orientCount.begin(), _orientCount.end(), 0);
}
void addOrient(const PAIR_ORIENT::index_t ori) {
static const unsigned maxOrientCount(100000);
if (_totalOrientCount >= maxOrientCount)
return;
if (ori == PAIR_ORIENT::UNKNOWN)
return;
addOrientImpl(ori);
}
const ReadPairOrient& getConsensusOrient(const ReadCounter &readCounter) {
finalize(readCounter);
return _finalOrient;
}
unsigned getMinCount() {
static const unsigned minCount(100);
return minCount;
}
bool isOrientCountGood() {
return (_totalOrientCount >= getMinCount());
}
private:
void addOrientImpl(const PAIR_ORIENT::index_t ori) {
assert(!_isFinalized);
assert(ori < PAIR_ORIENT::SIZE);
_orientCount[ori]++;
_totalOrientCount++;
}
void finalize(const ReadCounter &readCounter);
bool _isFinalized;
unsigned _totalOrientCount;
const StatLabel _rgLabel;
std::array<unsigned, PAIR_ORIENT::SIZE> _orientCount;
ReadPairOrient _finalOrient;
};
struct SimpleRead {
SimpleRead(PAIR_ORIENT::index_t ort, unsigned sz) :
_orient(ort), _insertSize(sz) {
}
PAIR_ORIENT::index_t _orient;
unsigned _insertSize;
};
struct ReadBuffer {
ReadBuffer() :
_abnormalRpCount(0), _observationRpCount(0) {
}
void updateBuffer(PAIR_ORIENT::index_t ort, unsigned sz) {
_readInfo.emplace_back(ort, sz);
if (ort == PAIR_ORIENT::Rp) {
_observationRpCount++;
if (sz >= 5000)
_abnormalRpCount++;
}
}
bool isBufferFull() const {
return (_observationRpCount >= 1000);
}
bool isBufferNormal() const {
if (_observationRpCount == 0)
return false;
return ((_abnormalRpCount / (float) _observationRpCount) < 0.01);
}
unsigned getAbnormalCount() {
return _abnormalRpCount;
}
unsigned getObservationCount() {
return _observationRpCount;
}
const std::vector<SimpleRead>& getBufferedReads() {
return _readInfo;
}
void clearBuffer() {
_abnormalRpCount = 0;
_observationRpCount = 0;
_readInfo.clear();
}
private:
unsigned _abnormalRpCount;
unsigned _observationRpCount;
std::vector<SimpleRead> _readInfo;
};
#define statsCheckCnt 100000
enum RGT_RETURN {
RGT_CONTINUE, RGT_BREAK, RGT_NORMAL
};
struct StatsTracker {
StatsTracker(const char *bamLabel = nullptr, const char *rgLabel =
nullptr, const std::string &defaultStatsFilename = "") :
_rgLabel(bamLabel, rgLabel), _orientInfo(bamLabel, rgLabel), _defaultStatsFilename(
defaultStatsFilename) {
}
unsigned insertSizeObservations() const { return _stats.fragStats.totalObservations();}
unsigned getMinObservationCount() const { static const unsigned minObservations(100); return minObservations; }
bool isObservationCountGood() const { return (insertSizeObservations() >= getMinObservationCount()); }
void checkInsertSizeCount() { if ((insertSizeObservations() % statsCheckCnt) == 0) _isChecked = true; }
bool isInsertSizeChecked() const { return _isChecked; }
void clearChecked() { _isChecked = false; }
bool isInsertSizeConverged() const { return _isInsertSizeConverged; }
bool isCheckedOrConverged() const { return (_isChecked || isInsertSizeConverged()); }
void updateInsertSizeConvergenceTest() { // check convergence
if (_oldInsertSize.totalObservations() > 0) {
_isInsertSizeConverged = _oldInsertSize.isStatSetMatch(
_stats.fragStats);
}
_oldInsertSize = _stats.fragStats;
}
ReadBuffer& getBuffer() { return _buffer; }
void addBufferedData();
const OrientTracker& getOrientInfo() const { return _orientInfo; }
const UniqueStats& getStats() const { assert(_isFinalized); return _stats; } /// getting a const ref of the stats forces finalization steps:
void addReadCount() { _stats.readCounter.addReadCount();}
void addPairedReadCount() { _stats.readCounter.addPairedReadCount();}
void addUnpairedReadCount() { _stats.readCounter.addUnpairedReadCount();}
void addPairedLowMapqReadCount() { _stats.readCounter.addPairedLowMapqReadCount();}
void addHighConfidenceReadPairCount() { _stats.readCounter.addHighConfidenceReadPairCount();}
/// Add one observation to the buffer
/// If the buffer is full, AND if the fragment size distribution in the buffer looks normal, add the buffered data;
/// otherwise, discard the buffer and move to the next region
bool addObservation(PAIR_ORIENT::index_t ori, unsigned sz);
void finalize();
void handleReadRecordBasic(bam1_t *b);
RGT_RETURN handleReadRecordCheck(bam1_t *b);
private:
void addOrient(const PAIR_ORIENT::index_t ori) {
assert(!_isFinalized);
_orientInfo.addOrient(ori);
}
void addInsertSize(const int size) {
assert(!_isFinalized);
_stats.fragStats.addObservation(size);
}
bool _isFinalized = false;
const StatLabel _rgLabel;
OrientTracker _orientInfo;
bool _isChecked = false;
bool _isInsertSizeConverged = false;
SizeDistribution _oldInsertSize; // previous fragment distribution is stored to determine convergence
ReadBuffer _buffer;
UniqueStats _stats;
const std::string _defaultStatsFilename;
};
| 29.746479 | 141 | 0.716461 | hitbc |
9a8c5628500474c3eb9bef147aaf32e1d349a862 | 935 | cpp | C++ | src/macro/macro203.cpp | chennachaos/stabfem | b3d1f44c45e354dc930203bda22efc800c377c6f | [
"MIT"
] | null | null | null | src/macro/macro203.cpp | chennachaos/stabfem | b3d1f44c45e354dc930203bda22efc800c377c6f | [
"MIT"
] | null | null | null | src/macro/macro203.cpp | chennachaos/stabfem | b3d1f44c45e354dc930203bda22efc800c377c6f | [
"MIT"
] | null | null | null | #include "Macro.h"
#include "DomainTree.h"
#include "StandardFEM.h"
extern DomainTree domain;
int macro203(Macro ¯o)
{
if (!macro)
{
macro.name = "erro";
macro.type = "chen";
macro.what = " Compute Error Norm ";
macro.sensitivity[INTER] = true;
macro.sensitivity[BATCH] = true;
macro.db.selectDomain();
macro.db.frameButtonBox();
macro.db.addTextField("index = ",1);
macro.db.addTextField("tol = ",0.001,6);
macro.db.frameRadioBox();
// and other stuff
return 0;
}
//--------------------------------------------------------------------------------------------------
int type, id, index;
double tol;
type = roundToInt(macro.p[0]);
id = roundToInt(macro.p[1]) - 1;
index = roundToInt(macro.p[2]);
tol = macro.p[3];
standardFEM(domain(type,id)).computeElementErrors(index);
return 0;
}
| 18.333333 | 101 | 0.517647 | chennachaos |
9a8ced79843ca7f82f63b1cd0046cfb6efaa5937 | 1,105 | hpp | C++ | source/Input/Mapper.hpp | kurocha/input | 619cbe901ebb2cfd9dd97235d30e596edc96aa14 | [
"MIT",
"Unlicense"
] | null | null | null | source/Input/Mapper.hpp | kurocha/input | 619cbe901ebb2cfd9dd97235d30e596edc96aa14 | [
"MIT",
"Unlicense"
] | null | null | null | source/Input/Mapper.hpp | kurocha/input | 619cbe901ebb2cfd9dd97235d30e596edc96aa14 | [
"MIT",
"Unlicense"
] | null | null | null | //
// Mapper.hpp
// This file is part of the "Input" project and released under the MIT License.
//
// Created by Samuel Williams on 23/2/2019.
// Copyright, 2019, by Samuel Williams. All rights reserved.
//
#pragma once
#include <unordered_map>
namespace Input
{
template <typename ActionT>
class Mapper {
protected:
using Actions = std::unordered_map<Key, ActionT>;
Actions _actions;
public:
void bind(const Key & key, ActionT action) {
_actions[key] = action;
}
void bind(DeviceT device, ButtonT button, ActionT action) {
bind(Key(device, button), action);
}
// mapper.invoke(key, ->(action){});
template <typename BlockT>
bool invoke(const Key & key, BlockT block) const {
auto action = _actions.find(key);
if (action != _actions.end()) {
block(action);
return true;
} else {
return false;
}
}
template <typename BlockT>
bool invoke(const Key & key) const {
auto action = _actions.find(key);
if (action != _actions.end()) {
action();
return true;
} else {
return false;
}
}
};
}
| 19.051724 | 80 | 0.630769 | kurocha |
9a8d5e604c6c9b2f1d4a8aecd6d8b8757fa165a7 | 4,853 | cpp | C++ | src/HashGenerator.cpp | kyberdrb/duplicate_finder | 4971830082b0248d2f5b434f1cdb53eb3da39b6d | [
"CC0-1.0"
] | null | null | null | src/HashGenerator.cpp | kyberdrb/duplicate_finder | 4971830082b0248d2f5b434f1cdb53eb3da39b6d | [
"CC0-1.0"
] | null | null | null | src/HashGenerator.cpp | kyberdrb/duplicate_finder | 4971830082b0248d2f5b434f1cdb53eb3da39b6d | [
"CC0-1.0"
] | null | null | null | #include "HashGenerator.h"
#include "openssl/sha.h"
#include <array>
#include <vector>
#include <fstream>
#include <iomanip>
#include <sstream>
// TODO maybe template this, or abstract this into virtual functions, according to the algorithm type - tested on SHA1 with SHA_CTX and with SHA256 with SHA256_CTX
// - maybe later, when I will create a library for hashing which will be much simpler to use than the raw Crypto++ or OpenSSL libraries, like this for example: std::string sha256HashOfFile = Hasher::sha256sum(filePath);
std::string HashGenerator::sha256_CPP_style(const std::string& filePath) {
SHA256_CTX sha256_context;
SHA256_Init(&sha256_context);
std::ifstream file(filePath, std::ios::binary);
const size_t CHUNK_SIZE = 1024;
// preferring array instead of vector because the size of the buffer will stay the same throughout the entire hashAsText creation process
//std::vector<char> chunkBuffer(CHUNK_SIZE, '\0');
std::array<char, CHUNK_SIZE> chunkBuffer{'\0'};
while ( file.read( chunkBuffer.data(), chunkBuffer.size() ) ) {
auto bytesRead = file.gcount();
SHA256_Update(&sha256_context, chunkBuffer.data(), bytesRead);
}
// Evaluate the last partial chunk
// `fin.read(...)` evaluates to false on the last partial block (or eof). You need to process partial reads outside of the while loop `gcount()!=0` - https://stackoverflow.com/questions/35905295/reading-a-file-in-chunks#comment59488065_35905524
if (file.gcount() != 0) {
SHA256_Update(&sha256_context, chunkBuffer.data(), file.gcount());
}
// preferring array instead of vector because the size of the buffer will stay the same throughout the entire hashAsText creation process
//std::vector<uint8_t> hashAsText(SHA256_DIGEST_LENGTH, '\0');
std::array<uint8_t, SHA256_DIGEST_LENGTH> hash{'\0'};
SHA256_Final(hash.data(), &sha256_context);
std::stringstream hashInHexadecimalFormat;
for(auto chunk : hash) {
hashInHexadecimalFormat << std::hex << std::setw(2) << std::setfill('0') << (uint32_t) chunk;
}
return hashInHexadecimalFormat.str();
}
void HashGenerator::sha1_C_style_static_alloc(const char* filePath) {
SHA_CTX sha1Context;
SHA1_Init(&sha1Context);
uint32_t bytesRead;
uint8_t chunkBuffer[1024];
const size_t CHUNK_SIZE = 1024;
FILE* file = fopen(filePath, "rb");
while( (bytesRead = fread(chunkBuffer, 1, CHUNK_SIZE, file) ) != 0 ) {
SHA1_Update(&sha1Context, chunkBuffer, bytesRead);
}
uint8_t hash[SHA_DIGEST_LENGTH];
SHA1_Final(hash, &sha1Context);
char hashInHexadecimalFormat[2 * SHA_DIGEST_LENGTH];
for(int32_t chunkPosition=0; chunkPosition < SHA_DIGEST_LENGTH; ++chunkPosition) {
sprintf(&(hashInHexadecimalFormat[chunkPosition * 2]), "%02x", hash[chunkPosition] );
}
printf("%s", hashInHexadecimalFormat);
fclose(file);
// no return because we would return a pointer to a local variable, which are discarded at the closing curly brace of this function; therefore we print the output to the terminal as a feedback and a side-effect
}
char* HashGenerator::sha1_C_style_dynamic_alloc(const char* filePath) {
SHA_CTX* sha1Context = (SHA_CTX*) calloc(1, sizeof(SHA_CTX) );
SHA1_Init(sha1Context);
uint32_t bytesRead;
uint8_t* chunkBuffer = (uint8_t*) calloc(1024, sizeof(uint8_t) );
const size_t CHUNK_SIZE = 1024;
FILE* file = fopen(filePath, "rb");
while( (bytesRead = fread(chunkBuffer, 1, CHUNK_SIZE, file) ) != 0 ) {
SHA1_Update(sha1Context, chunkBuffer, bytesRead);
}
free(chunkBuffer);
chunkBuffer = NULL; // sanitize dangling pointer
uint8_t* hash = (uint8_t*) calloc(SHA_DIGEST_LENGTH, sizeof(uint8_t) );
SHA1_Final(hash, sha1Context);
free(sha1Context);
sha1Context = NULL;
//char* hashInHexadecimalFormat = (char*) calloc(SHA_DIGEST_LENGTH * 2, sizeof(char)); // error: 'Corrupted size vs. prev_size' or 'malloc(): invalid next size (unsorted)'
char* hashInHexadecimalFormat = (char*) calloc(SHA_DIGEST_LENGTH * 2 + 1, sizeof(char)); // add one extra position at the end of the buffer '+ 1' for the 'null terminator' '\0' that terminates the string, in order to prevent error 'Corrupted size vs. prev_size' and other errors and undefined behaviors - https://cppsecrets.com/users/931049711497106109971151165748485664103109971051084699111109/C00-Program-to-Find-Hash-of-File.php
for(int32_t chunkPosition=0; chunkPosition < SHA_DIGEST_LENGTH; ++chunkPosition) {
sprintf( &(hashInHexadecimalFormat[chunkPosition * 2] ), "%02x", hash[chunkPosition] );
}
free(hash);
hash = NULL;
fclose(file);
return hashInHexadecimalFormat; // remember to free the pointer in the caller code, i. e. free the pointer on the client side
}
| 43.720721 | 437 | 0.712343 | kyberdrb |
9a901d305711cf12167bd8866b489ce1e756f783 | 4,969 | cpp | C++ | tuw_multi_robot_test/src/goal_generator.cpp | JakubHazik/tuw_multi_robot | 9c5c8a2ed87e0bf6f9a573e38b4d5790dfc25aba | [
"BSD-3-Clause"
] | null | null | null | tuw_multi_robot_test/src/goal_generator.cpp | JakubHazik/tuw_multi_robot | 9c5c8a2ed87e0bf6f9a573e38b4d5790dfc25aba | [
"BSD-3-Clause"
] | null | null | null | tuw_multi_robot_test/src/goal_generator.cpp | JakubHazik/tuw_multi_robot | 9c5c8a2ed87e0bf6f9a573e38b4d5790dfc25aba | [
"BSD-3-Clause"
] | null | null | null | #include <ros/ros.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <cmath>
#include <geometry_msgs/Pose.h>
#include <geometry_msgs/PoseStamped.h>
#include <nav_msgs/Odometry.h>
#include <tf/transform_datatypes.h>
#include <tf/transform_listener.h>
#include <std_msgs/Bool.h>
#include <tuw_multi_robot_msgs/RobotGoals.h>
geometry_msgs::PoseStamped pose_odom_frame;
void odomCallback(const nav_msgs::Odometry::ConstPtr& msg)
{
pose_odom_frame.header=msg->header;
pose_odom_frame.pose=msg->pose.pose;
}
double distance2d(const double & x1, const double & y1, const double & x2, const double & y2) {
return sqrt(pow(x1-x2,2)+pow(y1-y2,2));
}
void parseWaypointsFile(ros::NodeHandle& nh, std::vector<geometry_msgs::PoseStamped>& goals_list, const std::string & _world_frame)
{
//csv file containing one waypoint/line in the formalism : x,y (meter),yaw (degree)
//in frame map
ROS_INFO("Going to parse");
std::string goals_file;
if (nh.getParam("file", goals_file))
{ROS_INFO("Loaded %s as goals file", goals_file.c_str());}
else
{ROS_ERROR("No waypoints file specified");}
std::ifstream data(goals_file.c_str(), std::ifstream::in);
if (!data.is_open()){ROS_ERROR("Could not open input CSV file");}
else {
std::string line;
while(std::getline(data,line))
{
if (line.empty()){ROS_INFO( "Empty line");}
geometry_msgs::PoseStamped next_point;
std::stringstream lineStream(line);
std::string cell;
std::getline(lineStream,cell,',');
next_point.pose.position.x = std::stof(cell);
std::getline(lineStream,cell,',');
next_point.pose.position.y = std::stof(cell);
std::getline(lineStream,cell);
next_point.pose.orientation = tf::createQuaternionMsgFromYaw(std::stof(cell));
next_point.header.frame_id = _world_frame;
goals_list.push_back(next_point);
}
}
ROS_INFO("Parsing completed");
}
int main(int argc, char** argv){
ros::init(argc, argv, "goal_generator");
ros::NodeHandle nh("~");
std::vector<geometry_msgs::PoseStamped> goals_list;
// ID of the robot associated with the goal generator
std::string robot_id;
nh.param<std::string>("robot_id", robot_id, "robot_0");
bool use_tf;
nh.param<bool>("use_tf", use_tf, false);
// Frames
std::string odom_frame;
nh.param<std::string>("odom_frame", odom_frame, "odom");
std::string world_frame;
nh.param<std::string>("world_frame", world_frame, "map");
// Run in loop or not
bool run_once;
nh.param<bool>("run_once", run_once, true);
parseWaypointsFile(nh, goals_list, world_frame);
ros::Subscriber robotPoseSub = nh.subscribe("/" + robot_id + "/odom", 1, odomCallback);
ros::Publisher goalPub = nh.advertise<tuw_multi_robot_msgs::RobotGoals>("/labelled_goal",1);
// Transform
tf::TransformListener tf_listener;
geometry_msgs::PoseStamped pose_world_frame;
// Create the goal structure
tuw_multi_robot_msgs::RobotGoals labeled_goal;
labeled_goal.robot_name=robot_id;
ros::Rate loop_rate(2);
unsigned goal_index=0;
geometry_msgs::Pose goal = goals_list.at(goal_index).pose;
labeled_goal.destinations.push_back(goal);
bool goal_published=false;
int n_time_publish=0;
ros::spinOnce();
while(ros::ok()) {
ros::spinOnce();
if(use_tf) {
try {
tf_listener.waitForTransform(pose_odom_frame.header.frame_id, world_frame,
ros::Time::now(), ros::Duration(1.0));
pose_world_frame.header.stamp=ros::Time::now();
tf_listener.transformPose(world_frame, pose_odom_frame, pose_world_frame);
} catch (tf::TransformException ex) {
ROS_ERROR("%s",ex.what());
ros::Duration(1.0).sleep();
}
} else {
if(pose_odom_frame.header.frame_id != world_frame) {
ROS_ERROR("Odometry frame (\"%s\") is not equal to the world frame (\"%s\"), please enable use_tf or publish in the right frame",odom_frame.c_str(),world_frame.c_str());
break;
}
}
ROS_ERROR("%f",distance2d(goal.position.x,goal.position.y,pose_odom_frame.pose.position.x,pose_odom_frame.pose.position.y));
if(distance2d(goal.position.x,goal.position.y,pose_odom_frame.pose.position.x,pose_odom_frame.pose.position.y) < 1.0) {
ros::Duration(2.0).sleep();
goal_index++;
// If we reach the end of the list
if(goal_index>=goals_list.size()) {
if(run_once)
break;
else
goal_index=0;
}
goal = goals_list.at(goal_index).pose;
labeled_goal.destinations.at(0) = goal;
goal_published=false;
n_time_publish=0;
}
// Republish several times to be sure that the goal is sent
if(!goal_published || n_time_publish<5) {
goalPub.publish(labeled_goal);
ROS_ERROR("Goal published");
goal_published=true;
n_time_publish++;
}
loop_rate.sleep();
}
return 0;
}
| 29.229412 | 177 | 0.674784 | JakubHazik |
9a93b9f0558350f01e0429a0954ddcd5a9f2caa1 | 1,323 | cpp | C++ | src/wolf3d_shaders/ws_shaders.cpp | Daivuk/wolf3d-shaders | 0f3c0ab82422d068f6440af6649603774f0543b2 | [
"DOC",
"Unlicense"
] | 5 | 2019-09-14T14:08:46.000Z | 2021-04-27T11:21:43.000Z | src/wolf3d_shaders/ws_shaders.cpp | Daivuk/wolf3d-shaders | 0f3c0ab82422d068f6440af6649603774f0543b2 | [
"DOC",
"Unlicense"
] | null | null | null | src/wolf3d_shaders/ws_shaders.cpp | Daivuk/wolf3d-shaders | 0f3c0ab82422d068f6440af6649603774f0543b2 | [
"DOC",
"Unlicense"
] | 1 | 2019-10-19T04:19:46.000Z | 2019-10-19T04:19:46.000Z | #include "ws.h"
static void checkShader(GLuint handle)
{
GLint bResult;
glGetShaderiv(handle, GL_COMPILE_STATUS, &bResult);
if (bResult == GL_FALSE)
{
GLchar infoLog[1024];
glGetShaderInfoLog(handle, 1023, NULL, infoLog);
Quit((char *)(std::string("shader compile failed: ") + infoLog).c_str());
}
}
GLuint ws_create_program(const GLchar *vs, const GLchar *ps, const std::vector<const char *> &attribs)
{
const GLchar *vertex_shader_with_version[2] = { "#version 120\n", vs };
const GLchar *fragment_shader_with_version[2] = { "#version 120\n", ps };
auto vertHandle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertHandle, 2, vertex_shader_with_version, NULL);
glCompileShader(vertHandle);
checkShader(vertHandle);
auto fragHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragHandle, 2, fragment_shader_with_version, NULL);
glCompileShader(fragHandle);
checkShader(fragHandle);
GLuint program = glCreateProgram();
glAttachShader(program, vertHandle);
glAttachShader(program, fragHandle);
int i = 0;
for (auto attrib : attribs)
{
glBindAttribLocation(program, i, attrib);
++i;
}
glLinkProgram(program);
return program;
}
| 30.767442 | 103 | 0.664399 | Daivuk |
9a97c9bb78b98356e6c59f1881cc8cbd28877248 | 29,999 | cc | C++ | libs/core/tests/Logging/LogTest.cc | v8App/v8App | 96c5278ae9078d508537f2e801b9ba0272ab1168 | [
"MIT"
] | null | null | null | libs/core/tests/Logging/LogTest.cc | v8App/v8App | 96c5278ae9078d508537f2e801b9ba0272ab1168 | [
"MIT"
] | null | null | null | libs/core/tests/Logging/LogTest.cc | v8App/v8App | 96c5278ae9078d508537f2e801b9ba0272ab1168 | [
"MIT"
] | null | null | null | // Copyright 2020 The v8App Authors. All rights reserved.
// Use of this source code is governed by a MIT license that can be
// found in the LICENSE file.
#include "gtest/gtest.h"
#include "gmock/gmock.h"
#include "Logging/Log.h"
#include "Logging/ILogSink.h"
#include "Logging/LogMacros.h"
#include "TestLogSink.h"
namespace v8App
{
namespace Log
{
namespace LogTest
{
class LogDouble : public Log
{
public:
static bool IsSinksEmpty() { return m_LogSinks.empty(); }
static void TestInternalLog(LogMessage &inMessage, LogLevel inLevel, std::string File, std::string Function, int Line)
{
InternalLog(inMessage, inLevel, File, Function, Line);
}
static void TestInternalLog(LogMessage &inMessage, LogLevel inLevel)
{
InternalLog(inMessage, inLevel);
}
static void ResetLog()
{
m_LogSinks.clear();
m_AppName = "v8App";
m_LogLevel = LogLevel::Error;
m_UseUTC = true;
}
};
TestUtils::TestLogSink *SetupGlobalSink(TestUtils::WantsLogLevelsVector inLevels)
{
TestUtils::TestLogSink *sink = TestUtils::TestLogSink::GetGlobalSink();
sink->SetWantsLogLevels(inLevels);
sink->FlushMessages();
return sink;
}
} // namespace LogTest
TEST(LogTest, LogLevelToString)
{
EXPECT_EQ("Fatal", LogLevelToString(LogLevel::Fatal));
EXPECT_EQ("Off", LogLevelToString(LogLevel::Off));
EXPECT_EQ("Error", LogLevelToString(LogLevel::Error));
EXPECT_EQ("General", LogLevelToString(LogLevel::General));
EXPECT_EQ("Warn", LogLevelToString(LogLevel::Warn));
EXPECT_EQ("Debug", LogLevelToString(LogLevel::Debug));
EXPECT_EQ("Trace", LogLevelToString(LogLevel::Trace));
}
TEST(LogTest, GetSetLogLevel)
{
EXPECT_EQ(LogLevel::Error, Log::GetLogLevel());
Log::SetLogLevel(LogLevel::Off);
EXPECT_EQ(LogLevel::Off, Log::GetLogLevel());
Log::SetLogLevel(LogLevel::Fatal);
EXPECT_EQ(LogLevel::Off, Log::GetLogLevel());
}
TEST(LogTest, GetSetAppName)
{
EXPECT_EQ("v8App", Log::GetAppName());
std::string testName("TestAppName");
Log::SetAppName(testName);
EXPECT_EQ(testName, Log::GetAppName());
}
TEST(LogTest, UseUTC)
{
EXPECT_TRUE(Log::IsUsingUTC());
Log::UseUTC(false);
EXPECT_FALSE(Log::IsUsingUTC());
Log::UseUTC(true);
EXPECT_TRUE(Log::IsUsingUTC());
}
TEST(LogTest, AddRemoveLogSink)
{
//NOTE: the unique_ptr owns this and will delete it when it's removed
TestUtils::WantsLogLevelsVector warns = {LogLevel::Warn};
TestUtils::TestLogSink *testSink = new TestUtils::TestLogSink("TestLogSink", warns);
std::unique_ptr<ILogSink> sinkObj(testSink);
TestUtils::WantsLogLevelsVector emptyWants;
std::unique_ptr<ILogSink> sink2(new TestUtils::TestLogSink("TestLogSink", emptyWants));
//need to change the log level so we can see the warn
Log::SetLogLevel(LogLevel::Warn);
ASSERT_TRUE(Log::AddLogSink(sinkObj));
ASSERT_FALSE(Log::AddLogSink(sink2));
EXPECT_TRUE(testSink->WantsLogMessage(LogLevel::Warn));
//there are other keys in the message but we are only concerned with the msg for this test.
LogMessage expected = {
{MsgKey::Msg, "Sink with name:" + testSink->GetName() + " already exists"},
{MsgKey::LogLevel, "Warn"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::AppName, MsgKey::TimeStamp };
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//ok time to remove it.
Log::RemoveLogSink(testSink->GetName());
//at this point the sinkObj isn't valid;
sinkObj = nullptr;
ASSERT_TRUE(LogTest::LogDouble::IsSinksEmpty());
}
TEST(LogTest, GenerateISO8601Time)
{
std::string time = Log::GenerateISO8601Time(true);
//utc version
//EXPECT_THAT(Log::GenerateISO8601Time(true), ::testing::MatchesRegex("\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\dZ"));
//non utc version
//EXPECT_THAT(Log::GenerateISO8601Time(false), ::testing::MatchesRegex("\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d"));
}
TEST(LogTest, testInternalLogExtended)
{
LogTest::LogDouble::ResetLog();
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
Log::SetLogLevel(LogLevel::General);
::testing::internal::CaptureStderr();
LogTest::LogDouble::TestInternalLog(message, LogLevel::General, "File", "Function", 10);
std::string output = ::testing::internal::GetCapturedStderr();
EXPECT_THAT(output, ::testing::HasSubstr(Log::GetAppName() + " Log {"));
EXPECT_THAT(output, ::testing::HasSubstr("Message:Test"));
EXPECT_THAT(output, ::testing::HasSubstr("File:File"));
EXPECT_THAT(output, ::testing::HasSubstr("Function:Function"));
EXPECT_THAT(output, ::testing::HasSubstr("Line:10"));
EXPECT_THAT(output, ::testing::HasSubstr("}"));
//test with the test sink
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::General});
LogTest::LogDouble::TestInternalLog(message, LogLevel::General, "File", "Function", 10);
LogMessage expected = {
{MsgKey::AppName, Log::GetAppName()},
{MsgKey::LogLevel, "General"},
{MsgKey::Msg, "Test"},
{MsgKey::File, "File"},
{MsgKey::Function, "Function"},
{MsgKey::Line, "10"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testInternalLog)
{
LogTest::LogDouble::ResetLog();
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
Log::SetLogLevel(LogLevel::General);
//first test with no sinks
::testing::internal::CaptureStderr();
LogTest::LogDouble::TestInternalLog(message, LogLevel::General);
std::string output = ::testing::internal::GetCapturedStderr();
EXPECT_THAT(output, ::testing::HasSubstr(Log::GetAppName() + " Log {"));
EXPECT_THAT(output, ::testing::HasSubstr("Message:Test"));
EXPECT_THAT(output, ::testing::HasSubstr("}"));
//test with the test sink
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::General});
LogTest::LogDouble::TestInternalLog(message, LogLevel::General);
LogMessage expected = {
{MsgKey::AppName, Log::GetAppName()},
{MsgKey::LogLevel, "General"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//test not logged to sink cause it doesn't want level
testSink->FlushMessages();
LogTest::LogDouble::TestInternalLog(message, LogLevel::Error);
ASSERT_TRUE(testSink->NoMessages());
}
TEST(LogTest, testError)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::Error(message);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::Error);
Log::Error(message);
LogMessage expected = {
{MsgKey::LogLevel, "Error"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//test that the message logged on higher level
Log::SetLogLevel(LogLevel::General);
testSink->FlushMessages();
Log::Error(message);
ASSERT_FALSE(testSink->NoMessages());
}
TEST(LogTest, testGeneral)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//first test the message doesn't get logged on lower level
Log::SetLogLevel(LogLevel::Error);
Log::General(message);
EXPECT_TRUE(testSink->NoMessages());
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::General(message);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::General);
Log::General(message);
LogMessage expected = {
{MsgKey::LogLevel, "General"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//test that the message logged on higher level
Log::SetLogLevel(LogLevel::Warn);
testSink->FlushMessages();
Log::General(message);
ASSERT_FALSE(testSink->NoMessages());
}
TEST(LogTest, testWarn)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Warn, LogLevel::General});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//first test the message doesn't get logged on lower level
Log::SetLogLevel(LogLevel::General);
Log::Warn(message);
EXPECT_TRUE(testSink->NoMessages());
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::Warn(message);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::Warn);
Log::Warn(message);
LogMessage expected = {
{MsgKey::LogLevel, "Warn"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//test that the message logged on higher level
Log::SetLogLevel(LogLevel::Debug);
testSink->FlushMessages();
Log::Warn(message);
ASSERT_FALSE(testSink->NoMessages());
}
TEST(LogTest, testDebug)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Debug, LogLevel::Warn});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//first test the message doesn't get logged on lower level
Log::SetLogLevel(LogLevel::Warn);
Log::Debug(message);
EXPECT_TRUE(testSink->NoMessages());
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::Debug(message);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::Debug);
Log::Debug(message);
LogMessage expected = {
{MsgKey::LogLevel, "Debug"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//test that the message logged on higher level
Log::SetLogLevel(LogLevel::Trace);
testSink->FlushMessages();
Log::Debug(message);
ASSERT_FALSE(testSink->NoMessages());
}
TEST(LogTest, testTrace)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Trace, LogLevel::Debug});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//first test the message doesn't get logged on lower level
Log::SetLogLevel(LogLevel::Debug);
Log::Trace(message);
EXPECT_TRUE(testSink->NoMessages());
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::Trace(message);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::Trace);
Log::Trace(message);
LogMessage expected = {
{MsgKey::LogLevel, "Trace"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testFatal)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Trace});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//test sends message even though off and sink doesn't want it.
Log::SetLogLevel(LogLevel::Off);
Log::Fatal(message);
LogMessage expected = {
{MsgKey::LogLevel, "Fatal"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testErrorExtended)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::Error(message, "File", "Function", 10);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::Error);
Log::Error(message, "File", "Function", 10);
LogMessage expected = {
{MsgKey::LogLevel, "Error"},
{MsgKey::Msg, "Test"},
{MsgKey::File, "File"},
{MsgKey::Function, "Function"},
{MsgKey::Line, "10"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//test that the message logged on higher level
Log::SetLogLevel(LogLevel::General);
testSink->FlushMessages();
Log::Error(message, "File", "Function", 10);
ASSERT_FALSE(testSink->NoMessages());
}
TEST(LogTest, testGeneralExtended)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//first test the message doesn't get logged on lower level
Log::SetLogLevel(LogLevel::Error);
Log::General(message, "File", "Function", 10);
EXPECT_TRUE(testSink->NoMessages());
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::General(message, "File", "Function", 10);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::General);
Log::General(message, "File", "Function", 10);
LogMessage expected = {
{MsgKey::LogLevel, "General"},
{MsgKey::Msg, "Test"},
{MsgKey::File, "File"},
{MsgKey::Function, "Function"},
{MsgKey::Line, "10"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//test that the message logged on higher level
Log::SetLogLevel(LogLevel::Warn);
testSink->FlushMessages();
Log::General(message, "File", "Function", 10);
ASSERT_FALSE(testSink->NoMessages());
}
TEST(LogTest, testWarnExtended)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Warn, LogLevel::General});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//first test the message doesn't get logged on lower level
Log::SetLogLevel(LogLevel::General);
Log::Warn(message, "File", "Function", 10);
EXPECT_TRUE(testSink->NoMessages());
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::Warn(message, "File", "Function", 10);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::Warn);
Log::Warn(message, "File", "Function", 10);
LogMessage expected = {
{MsgKey::LogLevel, "Warn"},
{MsgKey::Msg, "Test"},
{MsgKey::File, "File"},
{MsgKey::Function, "Function"},
{MsgKey::Line, "10"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//test that the message logged on higher level
Log::SetLogLevel(LogLevel::Debug);
testSink->FlushMessages();
Log::Warn(message, "File", "Function", 10);
ASSERT_FALSE(testSink->NoMessages());
}
TEST(LogTest, testDebugExtended)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Debug, LogLevel::Warn});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//first test the message doesn't get logged on lower level
Log::SetLogLevel(LogLevel::Warn);
Log::Debug(message, "File", "Function", 10);
EXPECT_TRUE(testSink->NoMessages());
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::Debug(message, "File", "Function", 10);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::Debug);
Log::Debug(message, "File", "Function", 10);
LogMessage expected = {
{MsgKey::LogLevel, "Debug"},
{MsgKey::Msg, "Test"},
{MsgKey::File, "File"},
{MsgKey::Function, "Function"},
{MsgKey::Line, "10"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
//test that the message logged on higher level
Log::SetLogLevel(LogLevel::Trace);
testSink->FlushMessages();
Log::Debug(message, "File", "Function", 10);
ASSERT_FALSE(testSink->NoMessages());
}
TEST(LogTest, testTraceExtended)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Trace, LogLevel::Debug});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//first test the message doesn't get logged on lower level
Log::SetLogLevel(LogLevel::Debug);
Log::Trace(message, "File", "Function", 10);
EXPECT_TRUE(testSink->NoMessages());
//test no message when level is set to off.
Log::SetLogLevel(LogLevel::Off);
Log::Trace(message, "File", "Function", 10);
EXPECT_TRUE(testSink->NoMessages());
//test message gets logged on level
Log::SetLogLevel(LogLevel::Trace);
Log::Trace(message, "File", "Function", 10);
LogMessage expected = {
{MsgKey::LogLevel, "Trace"},
{MsgKey::Msg, "Test"},
{MsgKey::File, "File"},
{MsgKey::Function, "Function"},
{MsgKey::Line, "10"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testFatalExtended)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Trace});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
//test message gets ent even though off and sink doesn't want it
Log::SetLogLevel(LogLevel::Trace);
Log::Fatal(message, "File", "Function", 10);
LogMessage expected = {
{MsgKey::LogLevel, "Fatal"},
{MsgKey::Msg, "Test"},
{MsgKey::File, "File"},
{MsgKey::Function, "Function"},
{MsgKey::Line, "10"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testLogMacroError)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
Log::SetLogLevel(LogLevel::Trace);
testSink->FlushMessages();
LOG_ERROR(message);
//so the checks aren't as brittle
size_t line = __LINE__ - 2;
std::string sLine = std::to_string(line);
const char *file = __FILE__;
const char *func = __func__;
ASSERT_FALSE(testSink->NoMessages());
LogMessage expected = {
{MsgKey::LogLevel, "Error"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
#ifdef V8APP_DEBUG
expected.emplace(MsgKey::File, file);
expected.emplace(MsgKey::Function, func);
expected.emplace(MsgKey::Line, sLine);
#endif
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testLogMacroGeneral)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
Log::SetLogLevel(LogLevel::Trace);
LOG_GENERAL(message);
//so the checks aren't as brittle
size_t line = __LINE__ - 2;
std::string sLine = std::to_string(line);
const char *file = __FILE__;
const char *func = __func__;
LogMessage expected = {
{MsgKey::LogLevel, "General"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
#ifdef V8APP_DEBUG
expected.emplace(MsgKey::File, file);
expected.emplace(MsgKey::Function, func);
expected.emplace(MsgKey::Line, sLine);
#endif
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testLogMacroWarn)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
Log::SetLogLevel(LogLevel::Trace);
testSink->FlushMessages();
LOG_WARN(message);
//so the checks aren't as brittle
size_t line = __LINE__ - 2;
std::string sLine = std::to_string(line);
const char *file = __FILE__;
const char *func = __func__;
LogMessage expected = {
{MsgKey::LogLevel, "Warn"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
#ifdef V8APP_DEBUG
expected.emplace(MsgKey::File, file);
expected.emplace(MsgKey::Function, func);
expected.emplace(MsgKey::Line, sLine);
#endif
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testLogMacroDebug)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
Log::SetLogLevel(LogLevel::Trace);
LOG_DEBUG(message);
//so the checks aren't as brittle
size_t line = __LINE__ - 2;
std::string sLine = std::to_string(line);
const char *file = __FILE__;
const char *func = __func__;
LogMessage expected = {
{MsgKey::LogLevel, "Debug"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
#ifdef V8APP_DEBUG
expected.emplace(MsgKey::File, file);
expected.emplace(MsgKey::Function, func);
expected.emplace(MsgKey::Line, sLine);
#endif
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testLogMacroTrace)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
Log::SetLogLevel(LogLevel::Trace);
LOG_TRACE(message);
//so the checks aren't as brittle
size_t line = __LINE__ - 2;
std::string sLine = std::to_string(line);
const char *file = __FILE__;
const char *func = __func__;
LogMessage expected = {
{MsgKey::LogLevel, "Trace"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
#ifdef V8APP_DEBUG
expected.emplace(MsgKey::File, file);
expected.emplace(MsgKey::Function, func);
expected.emplace(MsgKey::Line, sLine);
#endif
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
TEST(LogTest, testLogMacroFatal)
{
LogTest::LogDouble::ResetLog();
TestUtils::TestLogSink *testSink = LogTest::SetupGlobalSink({LogLevel::Error, LogLevel::General, LogLevel::Warn, LogLevel::Debug, LogLevel::Trace});
LogMessage message;
message.emplace(MsgKey::Msg, "Test");
Log::SetLogLevel(LogLevel::Trace);
LOG_FATAL(message);
//so the checks aren't as brittle
size_t line = __LINE__ - 2;
std::string sLine = std::to_string(line);
const char *file = __FILE__;
const char *func = __func__;
LogMessage expected = {
{MsgKey::LogLevel, "Fatal"},
{MsgKey::Msg, "Test"},
};
TestUtils::IgnoreMsgKeys ignore = {MsgKey::TimeStamp, MsgKey::AppName};
#ifdef V8APP_DEBUG
expected.emplace(MsgKey::File, file);
expected.emplace(MsgKey::Function, func);
expected.emplace(MsgKey::Line, sLine);
#endif
ASSERT_TRUE(testSink->validateMessage(expected, ignore));
}
} // namespace Log
} // namespace v8App | 34.923166 | 160 | 0.555852 | v8App |
9a97eb315751fbcc82f4df4a2637e3039cea497e | 706 | hpp | C++ | srcs/deque/common.hpp | tristiisch/containers_test | 5a4a0c098b69e79fa62348074ca0ccaeda5dde73 | [
"MIT"
] | null | null | null | srcs/deque/common.hpp | tristiisch/containers_test | 5a4a0c098b69e79fa62348074ca0ccaeda5dde73 | [
"MIT"
] | null | null | null | srcs/deque/common.hpp | tristiisch/containers_test | 5a4a0c098b69e79fa62348074ca0ccaeda5dde73 | [
"MIT"
] | null | null | null | #include "../base.hpp"
#if !defined(USING_STD)
# include "deque.hpp"
#else
# include <deque>
#endif /* !defined(STD) */
template <typename T>
void printSize(TESTED_NAMESPACE::deque<T> const &deq, bool print_content = 1)
{
std::cout << "size: " << deq.size() << std::endl;
std::cout << "max_size: " << deq.max_size() << std::endl;
if (print_content)
{
typename TESTED_NAMESPACE::deque<T>::const_iterator it = deq.begin();
typename TESTED_NAMESPACE::deque<T>::const_iterator ite = deq.end();
std::cout << std::endl << "Content is:" << std::endl;
for (; it != ite; ++it)
std::cout << "- " << *it << std::endl;
}
std::cout << "###############################################" << std::endl;
}
| 30.695652 | 77 | 0.575071 | tristiisch |
9a9ae4d19d7c9dacabe4dacbf24219d9ea5e3e0b | 907 | cpp | C++ | Plugins/StoryGraphPlugin/Source/StoryGraphPluginEditor/Commands_StoryGraph.cpp | Xian-Yun-Jun/StoryGraph | 36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b | [
"MIT"
] | 126 | 2016-12-24T13:58:18.000Z | 2022-03-10T03:20:47.000Z | Plugins/StoryGraphPlugin/Source/StoryGraphPluginEditor/Commands_StoryGraph.cpp | Xian-Yun-Jun/StoryGraph | 36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b | [
"MIT"
] | 5 | 2017-01-05T08:23:30.000Z | 2018-01-30T19:38:33.000Z | Plugins/StoryGraphPlugin/Source/StoryGraphPluginEditor/Commands_StoryGraph.cpp | Xian-Yun-Jun/StoryGraph | 36b4a9a24e86e963b1d1d61d4fd5bdfe2eabef9b | [
"MIT"
] | 45 | 2016-12-25T02:21:45.000Z | 2022-02-14T16:06:58.000Z | // Copyright 2016 Dmitriy Pavlov
#include "Commands_StoryGraph.h"
void FCommands_StoryGraph::RegisterCommands()
{
#define LOCTEXT_NAMESPACE "Commands_StoryGraphCommands"
UI_COMMAND(CheckObjects, "Check Objects", "Check Objects", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(SaveAsset, "Save Asset", "Save Asset", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(ExportInXML, "Export in XML", "Export in XML file", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(ImportFromXML, "Import from XML", "Import from XML file", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(FindInContentBrowser, "Find in CB", "Find in Content Browser...", EUserInterfaceActionType::Button, FInputChord());
UI_COMMAND(UnlinkAllObjects, "Unlink objects", "Unlink all StoryGraph Objects", EUserInterfaceActionType::Button, FInputChord());
#undef LOCTEXT_NAMESPACE
}
| 47.736842 | 130 | 0.790518 | Xian-Yun-Jun |
9a9bf1f263300b076fa07a5f58592f044b637a84 | 687 | cpp | C++ | src/Games/TicTacToe/ActGens/DefaultActGen.cpp | ClubieDong/BoardGameAI | 588506278f606fa6bef2864875bf8f78557ef03b | [
"MIT"
] | 2 | 2021-05-26T07:17:24.000Z | 2021-05-26T07:21:16.000Z | src/Games/TicTacToe/ActGens/DefaultActGen.cpp | ClubieDong/ChessAI | 588506278f606fa6bef2864875bf8f78557ef03b | [
"MIT"
] | null | null | null | src/Games/TicTacToe/ActGens/DefaultActGen.cpp | ClubieDong/ChessAI | 588506278f606fa6bef2864875bf8f78557ef03b | [
"MIT"
] | null | null | null | #include "DefaultActGen.hpp"
#include <cassert>
namespace tictactoe
{
bool DefaultActGen::NextAction(const ActGenDataBase *, ActionBase &_act) const
{
// Assert and convert polymorphic types
assert(_act.GetGameType() == GameType::TicTacToe);
auto &act = dynamic_cast<Action &>(_act);
auto &state = *dynamic_cast<const State *>(_State);
do
{
++act._Col;
if (act._Col >= 3)
{
++act._Row;
act._Col = 0;
}
if (act._Row >= 3)
return false;
} while (state._Board[act._Row][act._Col] != 2);
return true;
}
}
| 25.444444 | 82 | 0.512373 | ClubieDong |
9a9f4a5d68efc52dedec28e95460c67e41801baa | 1,990 | cpp | C++ | tree_traversal.cpp | ivan18m/cpp-practice | 1e9ae7d55a77f72a297e1ceb69fadf1cc4e7dfc6 | [
"BSD-3-Clause"
] | null | null | null | tree_traversal.cpp | ivan18m/cpp-practice | 1e9ae7d55a77f72a297e1ceb69fadf1cc4e7dfc6 | [
"BSD-3-Clause"
] | null | null | null | tree_traversal.cpp | ivan18m/cpp-practice | 1e9ae7d55a77f72a297e1ceb69fadf1cc4e7dfc6 | [
"BSD-3-Clause"
] | null | null | null | /**
* @file tree_traversal.cpp
* @author Ivan Mercep
* @brief
* This program contains_
* Binary Tree traversal methods: preorder, inorder, postorder.
* Functions to print and swap the binary tree.
* @version 0.1
* @date 2021-09-06
*
* @copyright Copyright (c) 2021
*
*/
#include <iostream>
struct Node
{
int data;
Node *left;
Node *right;
};
// <root> <left> <right>
void preorder(Node *pRoot)
{
if (pRoot == nullptr)
return;
std::cout << pRoot->data << " ";
preorder(pRoot->left);
preorder(pRoot->right);
}
// <left> <root> <right>
void inorder(Node *pRoot)
{
if (pRoot == nullptr)
return;
inorder(pRoot->left);
std::cout << pRoot->data << " ";
inorder(pRoot->right);
}
// <left> <right> <root>
void postorder(Node *pRoot)
{
if (pRoot == nullptr)
return;
postorder(pRoot->left);
postorder(pRoot->right);
std::cout << pRoot->data << " ";
}
Node *getNewNode(int data)
{
Node *newNode = new Node();
newNode->data = data;
newNode->left = newNode->right = nullptr;
return newNode;
}
Node *insert(Node *pRoot, int data)
{
if (pRoot == nullptr)
pRoot = getNewNode(data);
else if (data <= pRoot->data)
pRoot->left = insert(pRoot->left, data);
else
pRoot->right = insert(pRoot->right, data);
return pRoot;
}
Node *swap(Node *pRoot)
{
if (pRoot == nullptr)
return pRoot;
Node *temp = pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = temp;
swap(pRoot->left);
swap(pRoot->right);
return pRoot;
}
int main()
{
Node *root = nullptr;
root = insert(root, 15);
root = insert(root, 20);
root = insert(root, 25);
root = insert(root, 18);
root = insert(root, 1);
/*
15
/\
1 20
/\
18 25
*/
inorder(root);
std::cout << "\n";
swap(root);
inorder(root);
std::cout << "\n";
delete root;
return 0;
} | 17.155172 | 63 | 0.556281 | ivan18m |
9aa555ee9e29a90c226a3125471700e640942b3e | 5,415 | hpp | C++ | include/RootMotion/FinalIK/FullBodyBipedIK.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/FullBodyBipedIK.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/RootMotion/FinalIK/FullBodyBipedIK.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: RootMotion.FinalIK.IK
#include "RootMotion/FinalIK/IK.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: RootMotion
namespace RootMotion {
// Forward declaring type: BipedReferences
class BipedReferences;
}
// Forward declaring namespace: RootMotion::FinalIK
namespace RootMotion::FinalIK {
// Forward declaring type: IKSolverFullBodyBiped
class IKSolverFullBodyBiped;
// Forward declaring type: IKSolver
class IKSolver;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
}
// Completed forward declares
// Type namespace: RootMotion.FinalIK
namespace RootMotion::FinalIK {
// Size: 0x48
#pragma pack(push, 1)
// Autogenerated type: RootMotion.FinalIK.FullBodyBipedIK
// [HelpURLAttribute] Offset: E0618C
// [AddComponentMenu] Offset: E0618C
class FullBodyBipedIK : public RootMotion::FinalIK::IK {
public:
// Writing base type padding for base size: 0x33 to desired offset: 0x38
char ___base_padding[0x5] = {};
// public RootMotion.BipedReferences references
// Size: 0x8
// Offset: 0x38
RootMotion::BipedReferences* references;
// Field size check
static_assert(sizeof(RootMotion::BipedReferences*) == 0x8);
// public RootMotion.FinalIK.IKSolverFullBodyBiped solver
// Size: 0x8
// Offset: 0x40
RootMotion::FinalIK::IKSolverFullBodyBiped* solver;
// Field size check
static_assert(sizeof(RootMotion::FinalIK::IKSolverFullBodyBiped*) == 0x8);
// Creating value type constructor for type: FullBodyBipedIK
FullBodyBipedIK(RootMotion::BipedReferences* references_ = {}, RootMotion::FinalIK::IKSolverFullBodyBiped* solver_ = {}) noexcept : references{references_}, solver{solver_} {}
// private System.Void OpenSetupTutorial()
// Offset: 0x1C3CD54
void OpenSetupTutorial();
// private System.Void OpenInspectorTutorial()
// Offset: 0x1C3CDA0
void OpenInspectorTutorial();
// private System.Void SupportGroup()
// Offset: 0x1C3CDEC
void SupportGroup();
// private System.Void ASThread()
// Offset: 0x1C3CE38
void ASThread();
// public System.Void SetReferences(RootMotion.BipedReferences references, UnityEngine.Transform rootNode)
// Offset: 0x1C3CE84
void SetReferences(RootMotion::BipedReferences* references, UnityEngine::Transform* rootNode);
// public System.Boolean ReferencesError(ref System.String errorMessage)
// Offset: 0x1C3CEB0
bool ReferencesError(::Il2CppString*& errorMessage);
// public System.Boolean ReferencesWarning(ref System.String warningMessage)
// Offset: 0x1C3D06C
bool ReferencesWarning(::Il2CppString*& warningMessage);
// private System.Void Reinitiate()
// Offset: 0x1C3D3C0
void Reinitiate();
// private System.Void AutoDetectReferences()
// Offset: 0x1C3D3E0
void AutoDetectReferences();
// protected override System.Void OpenUserManual()
// Offset: 0x1C3CCBC
// Implemented from: RootMotion.FinalIK.IK
// Base method: System.Void IK::OpenUserManual()
void OpenUserManual();
// protected override System.Void OpenScriptReference()
// Offset: 0x1C3CD08
// Implemented from: RootMotion.FinalIK.IK
// Base method: System.Void IK::OpenScriptReference()
void OpenScriptReference();
// public override RootMotion.FinalIK.IKSolver GetIKSolver()
// Offset: 0x1C3CEA8
// Implemented from: RootMotion.FinalIK.IK
// Base method: RootMotion.FinalIK.IKSolver IK::GetIKSolver()
RootMotion::FinalIK::IKSolver* GetIKSolver();
// public System.Void .ctor()
// Offset: 0x1C3D4BC
// Implemented from: RootMotion.FinalIK.IK
// Base method: System.Void IK::.ctor()
// Base method: System.Void SolverManager::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static FullBodyBipedIK* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("RootMotion::FinalIK::FullBodyBipedIK::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<FullBodyBipedIK*, creationType>()));
}
}; // RootMotion.FinalIK.FullBodyBipedIK
#pragma pack(pop)
static check_size<sizeof(FullBodyBipedIK), 64 + sizeof(RootMotion::FinalIK::IKSolverFullBodyBiped*)> __RootMotion_FinalIK_FullBodyBipedIKSizeCheck;
static_assert(sizeof(FullBodyBipedIK) == 0x48);
}
DEFINE_IL2CPP_ARG_TYPE(RootMotion::FinalIK::FullBodyBipedIK*, "RootMotion.FinalIK", "FullBodyBipedIK");
| 44.752066 | 180 | 0.708218 | darknight1050 |
9aaa45337a7ce537f2c6b688feefc10d63137e47 | 7,836 | cxx | C++ | HLT/TPCLib/HWCFemulator/AliHLTTPCHWCFEmulator.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | HLT/TPCLib/HWCFemulator/AliHLTTPCHWCFEmulator.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | HLT/TPCLib/HWCFemulator/AliHLTTPCHWCFEmulator.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | // $Id$
//****************************************************************************
//* This file is property of and copyright by the ALICE HLT Project *
//* ALICE Experiment at CERN, All rights reserved. *
//* *
//* Primary Authors: Sergey Gorbunov, Torsten Alt *
//* Developers: Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de> *
//* Torsten Alt <talt@cern.ch> *
//* for The ALICE HLT Project. *
//* *
//* 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. *
//****************************************************************************
// @file AliHLTTPCHWCFEmulator.cxx
// @author Sergey Gorbunov <sergey.gorbunov@fias.uni-frankfurt.de>
// @author Torsten Alt <talt@cern.ch>
// @brief FPGA ClusterFinder Emulator for TPC
// @note
#include "AliHLTTPCHWCFDataTypes.h"
#include "AliHLTTPCHWCFEmulator.h"
#include "AliHLTTPCClusterMCData.h"
#include "AliHLTTPCHWCFData.h"
#include <iostream>
#if __GNUC__ >= 3
using namespace std;
#endif
AliHLTTPCHWCFEmulator::AliHLTTPCHWCFEmulator()
:
fDebug(0),
fkMapping(0),
fChannelExtractor(),
fPeakFinderUnit(),
fChannelProcessor(),
fChannelMerger(),
fDivisionUnit()
{
//constructor
}
AliHLTTPCHWCFEmulator::~AliHLTTPCHWCFEmulator()
{
//destructor
}
AliHLTTPCHWCFEmulator::AliHLTTPCHWCFEmulator(const AliHLTTPCHWCFEmulator&)
:
fDebug(0),
fkMapping(0),
fChannelExtractor(),
fPeakFinderUnit(),
fChannelProcessor(),
fChannelMerger(),
fDivisionUnit()
{
// dummy
}
AliHLTTPCHWCFEmulator& AliHLTTPCHWCFEmulator::operator=(const AliHLTTPCHWCFEmulator&)
{
// dummy
return *this;
}
void AliHLTTPCHWCFEmulator::Init( const AliHLTUInt32_t *mapping, AliHLTUInt32_t config1, AliHLTUInt32_t config2 )
{
// Initialisation
fkMapping = mapping;
fPeakFinderUnit.SetChargeFluctuation( (config2>>4) & 0xF );
fChannelProcessor.SetSingleSeqLimit( (config1) & 0xFF );
fChannelProcessor.SetDeconvolutionTime( (config1>>24) & 0x1 );
fChannelProcessor.SetUseTimeBinWindow( (config2>>8) & 0x1 );
fChannelMerger.SetByPassMerger( (config1>>27) & 0x1 );
fChannelMerger.SetDeconvolution( (config1>>25) & 0x1 );
fChannelMerger.SetMatchDistance( (config2) & 0xF );
fChannelMerger.SetMatchTimeFollow( (config2>>9) & 0x1 );
fDivisionUnit.SetClusterLowerLimit( (config1>>8) & 0xFFFF );
fDivisionUnit.SetSinglePadSuppression( (config1>>26) & 0x1 );
fPeakFinderUnit.SetDebugLevel(fDebug);
fChannelProcessor.SetDebugLevel(fDebug);
fChannelMerger.SetDebugLevel(fDebug);
fDivisionUnit.SetDebugLevel(fDebug);
}
int AliHLTTPCHWCFEmulator::FindClusters( const AliHLTUInt32_t *rawEvent,
AliHLTUInt32_t rawEventSize32,
AliHLTUInt32_t *output,
AliHLTUInt32_t &outputSize32,
const AliHLTTPCClusterMCLabel *mcLabels,
AliHLTUInt32_t nMCLabels,
AliHLTTPCClusterMCData *outputMC
)
{
// Loops over all rows finding the clusters
AliHLTUInt32_t maxOutputSize32 = outputSize32;
outputSize32 = 0;
if( outputMC ) outputMC->fCount = 0;
AliHLTUInt32_t maxNMCLabels = nMCLabels;
if( !rawEvent ) return -1;
// Initialise
int ret = 0;
fChannelExtractor.Init( fkMapping, mcLabels, 3*rawEventSize32 );
fPeakFinderUnit.Init();
fChannelProcessor.Init();
fChannelMerger.Init();
fDivisionUnit.Init();
// Read the data, word by word
for( AliHLTUInt32_t iWord=0; iWord<=rawEventSize32; iWord++ ){
const AliHLTTPCHWCFBunch *bunch1=0;
const AliHLTTPCHWCFBunch *bunch2=0;
const AliHLTTPCHWCFClusterFragment *fragment=0;
const AliHLTTPCHWCFClusterFragment *candidate=0;
const AliHLTTPCHWCFCluster *cluster = 0;
if( iWord<rawEventSize32 ) fChannelExtractor.InputStream(ReadBigEndian(rawEvent[iWord]));
else fChannelExtractor.InputEndOfData();
while( (bunch1 = fChannelExtractor.OutputStream()) ){
fPeakFinderUnit.InputStream(bunch1);
while( (bunch2 = fPeakFinderUnit.OutputStream() )){
fChannelProcessor.InputStream(bunch2);
while( (fragment = fChannelProcessor.OutputStream() )){
fChannelMerger.InputStream( fragment );
while( (candidate = fChannelMerger.OutputStream()) ){
fDivisionUnit.InputStream(candidate);
while( (cluster = fDivisionUnit.OutputStream()) ){
if( cluster->fFlag==1 ){
if( outputSize32+AliHLTTPCHWCFData::fgkAliHLTTPCHWClusterSize > maxOutputSize32 ){ // No space in the output buffer
ret = -2;
break;
}
AliHLTUInt32_t *co = &output[outputSize32];
int i=0;
co[i++] = WriteBigEndian(cluster->fRowQ);
co[i++] = WriteBigEndian(cluster->fQ);
co[i++] = cluster->fP;
co[i++] = cluster->fT;
co[i++] = cluster->fP2;
co[i++] = cluster->fT2;
outputSize32+=AliHLTTPCHWCFData::fgkAliHLTTPCHWClusterSize;
if( mcLabels && outputMC && outputMC->fCount < maxNMCLabels){
outputMC->fLabels[outputMC->fCount++] = cluster->fMC;
}
}
else if( cluster->fFlag==2 ){
if( outputSize32+1 > maxOutputSize32 ){ // No space in the output buffer
ret = -2;
break;
}
output[outputSize32++] = cluster->fRowQ;
}
}
}
}
}
}
}
return ret;
}
AliHLTUInt32_t AliHLTTPCHWCFEmulator::ReadBigEndian ( AliHLTUInt32_t word )
{
// read the word written in big endian format (lowest byte first)
const AliHLTUInt8_t *bytes = reinterpret_cast<const AliHLTUInt8_t *>( &word );
AliHLTUInt32_t i[4] = {bytes[0],bytes[1],bytes[2],bytes[3]};
return (i[3]<<24) | (i[2]<<16) | (i[1]<<8) | i[0];
}
AliHLTUInt32_t AliHLTTPCHWCFEmulator::WriteBigEndian ( AliHLTUInt32_t word )
{
// write the word in big endian format (least byte first)
AliHLTUInt32_t ret = 0;
AliHLTUInt8_t *bytes = reinterpret_cast<AliHLTUInt8_t *>( &ret );
bytes[0] = (word ) & 0xFF;
bytes[1] = (word >> 8) & 0xFF;
bytes[2] = (word >> 16) & 0xFF;
bytes[3] = (word >> 24) & 0xFF;
return ret;
}
void AliHLTTPCHWCFEmulator::CreateConfiguration
(
bool doDeconvTime, bool doDeconvPad, bool doFlowControl,
bool doSinglePadSuppression, bool bypassMerger,
AliHLTUInt32_t clusterLowerLimit, AliHLTUInt32_t singleSeqLimit,
AliHLTUInt32_t mergerDistance, bool useTimeBinWindow, AliHLTUInt32_t chargeFluctuation, bool useTimeFollow,
AliHLTUInt32_t &configWord1, AliHLTUInt32_t &configWord2
)
{
// static method to create configuration word
configWord1 = 0;
configWord2 = 0;
configWord1 |= ( (AliHLTUInt32_t)doFlowControl & 0x1 ) << 29;
configWord1 |= ( (AliHLTUInt32_t)bypassMerger & 0x1 ) << 27;
configWord1 |= ( (AliHLTUInt32_t)doSinglePadSuppression & 0x1 ) << 26;
configWord1 |= ( (AliHLTUInt32_t)doDeconvPad & 0x1 ) << 25;
configWord1 |= ( (AliHLTUInt32_t)doDeconvTime & 0x1 ) << 24;
configWord1 |= ( (AliHLTUInt32_t)clusterLowerLimit & 0xFFFF )<<8;
configWord1 |= ( (AliHLTUInt32_t)singleSeqLimit & 0xFF );
configWord2 |= ( (AliHLTUInt32_t)mergerDistance & 0xF );
configWord2 |= ( (AliHLTUInt32_t)chargeFluctuation & 0xF )<<4;
configWord2 |= ( (AliHLTUInt32_t)useTimeBinWindow & 0x1 )<<8;
configWord2 |= ( (AliHLTUInt32_t)useTimeFollow & 0x1 )<<9;
}
| 33.20339 | 117 | 0.662711 | AllaMaevskaya |
9ab275d54314d22f77d0f51a27d325d4d8fa4bd0 | 1,145 | cpp | C++ | ToneArmEngine/OpenGLTransparencyPass.cpp | Mertank/ToneArm | 40c62b0de89ac506bea6674e43578bf4e2631f93 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | ToneArmEngine/OpenGLTransparencyPass.cpp | Mertank/ToneArm | 40c62b0de89ac506bea6674e43578bf4e2631f93 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | ToneArmEngine/OpenGLTransparencyPass.cpp | Mertank/ToneArm | 40c62b0de89ac506bea6674e43578bf4e2631f93 | [
"Zlib",
"BSD-2-Clause"
] | null | null | null | /*
========================
Copyright (c) 2014 Vinyl Games Studio
OpenGLTransparencyPass
Created by: Karl Merten
Created on: 04/08/2014
========================
*/
#include "OpenGLTransparencyPass.h"
#include "Renderable.h"
#include <GL\glew.h>
namespace vgs {
OpenGLTransparencyPass* OpenGLTransparencyPass::CreateWithPriority( unsigned int priority ) {
OpenGLTransparencyPass* pass = new OpenGLTransparencyPass();
if ( pass && pass->InitializePass( priority ) ) {
return pass;
}
delete pass;
return NULL;
}
bool OpenGLTransparencyPass::InitializePass( unsigned int priority ) {
RenderPass::InitializePass( NULL );
m_passType = PassType::TRANSPARENCY;
m_priority = priority;
return true;
}
void OpenGLTransparencyPass::BeginPass( void ) {
glEnable( GL_BLEND );
glEnable( GL_DEPTH_TEST );
glAlphaFunc( GL_GREATER, 0.05f );
glEnable( GL_ALPHA_TEST );
}
void OpenGLTransparencyPass::FinishPass( void ) {
glDisable( GL_BLEND );
glDisable( GL_ALPHA_TEST );
glDisable( GL_DEPTH_TEST );
}
void OpenGLTransparencyPass::ProcessRenderable( Renderable* obj ) {
obj->PreRender();
obj->Render();
obj->PostRender();
}
} | 20.087719 | 93 | 0.710917 | Mertank |
9abc64573b83e2dd51fd9bbc4cd10c7dd3a0b0b4 | 78 | cpp | C++ | sem11-mmap-instrumentation/ub.cpp | karmashka/caos_2019-2020 | ecfeb944a6a8d8392ac05e833d0d77cafdd3e88d | [
"MIT"
] | 32 | 2019-10-04T20:02:32.000Z | 2020-07-21T17:18:06.000Z | sem11-mmap-instrumentation/ub.cpp | karmashka/caos_2019-2020 | ecfeb944a6a8d8392ac05e833d0d77cafdd3e88d | [
"MIT"
] | 2 | 2020-04-05T12:52:13.000Z | 2020-05-04T23:42:02.000Z | sem11-mmap-instrumentation/ub.cpp | karmashka/caos_2019-2020 | ecfeb944a6a8d8392ac05e833d0d77cafdd3e88d | [
"MIT"
] | 10 | 2020-09-03T17:25:42.000Z | 2022-02-18T23:36:51.000Z | // %%cpp ub.cpp
int main(int argc, char** argv) {
return -argc << 31;
}
| 11.142857 | 33 | 0.538462 | karmashka |
9abe9a4e62c41a2cf187b1940fe6d37969a3bf51 | 4,709 | cpp | C++ | cpp/pipesquare/pipesquare.cpp | jakvrh1/paralelni-milkshake | 42b8151482b0e831ab1f2f6058cd389193372022 | [
"MIT"
] | null | null | null | cpp/pipesquare/pipesquare.cpp | jakvrh1/paralelni-milkshake | 42b8151482b0e831ab1f2f6058cd389193372022 | [
"MIT"
] | null | null | null | cpp/pipesquare/pipesquare.cpp | jakvrh1/paralelni-milkshake | 42b8151482b0e831ab1f2f6058cd389193372022 | [
"MIT"
] | null | null | null | /**
* Uporaba cevovoda s štirimi stopnjami;
* posamezno stopnjo lahko opravlja več niti
*/
#include <iostream>
#include <random>
#include <pthread.h>
#include <unistd.h>
#include "../input.hpp"
#include "../rle.hpp"
#include "../huffman.hpp"
#include "../output.hpp"
#include "../stream.hpp"
#define REPS 1000
#define READ_THREADS 2
#define RLE_THREADS 1
#define HUFFMAN_THREADS 1
#define WRITE_THREADS 1
using namespace std;
struct huffman_data {
Huffman *hf;
Vec<string> *encoded;
};
// ker vec niti pise, moramo uporabiti mutex,
// da povecujemo stevec [writes], dokler
// ne dosezemo stevila REPS
pthread_mutex_t mutex_write;
int writes = 0;
// Funkcija za niti, ki berejo.
void* read(void* arg) {
PipelineStage<int, string, struct image>* stage = (PipelineStage<int, string, struct image>*) arg;
while (true) {
auto p = stage->consume();
auto key = p.first;
auto filename = p.second;
try {
auto image_data = Input::read_image(filename.c_str());
stage->produce(key, image_data);
} catch(const std::exception& e) {
std::cerr << "Read image " << filename << ": " << e.what() << '\n';
}
}
return nullptr;
}
// Funkcija za niti, ki prebrane podatke kodirajo z RLE.
void* rle(void* arg) {
PipelineStage<int, struct image, Vec<int_bool>*>* stage = (PipelineStage<int, struct image, Vec<int_bool>*>*) arg;
while (true) {
auto p = stage->consume();
auto key = p.first;
auto image_data = p.second;
auto rle_data = RLE::encode(image_data);
stage->produce(key, rle_data);
}
}
// Funkcija za niti, ki RLE podatke kodirajo s huffmanom.
void* huffman(void* arg) {
PipelineStage<int, Vec<int_bool>*, huffman_data> *stage = (PipelineStage<int, Vec<int_bool>*, huffman_data>*) arg;
while (true) {
auto p = stage->consume();
auto key = p.first;
auto rle_data = p.second;
Huffman *hf = Huffman::initialize(rle_data);
auto encoded = hf->encode();
huffman_data data;
data.hf = hf;
data.encoded = encoded;
stage->produce(key, data);
}
}
// Funkcija za niti, ki pisejo
void* write(void* arg) {
PipelineStage<int, huffman_data, void>* stage = (PipelineStage<int, huffman_data, void>*) arg;
while (true) {
pthread_mutex_lock(&mutex_write);
if (writes < REPS) {
writes++;
} else {
pthread_mutex_unlock(&mutex_write);
break;
}
pthread_mutex_unlock(&mutex_write);
auto p = stage->consume();
auto key = p.first;
auto data = p.second;
auto header = data.hf->header();
auto filename = "../../out_encoded/out" + std::to_string(key) + ".txt";
try {
Output::write_encoded(filename, header, data.encoded);
} catch(const std::exception& e) {
std::cerr << "Write encoded " << key << ": " << e.what() << '\n';
}
data.hf->finalize();
delete data.encoded;
}
// S tem se bo program zaključil (glavna nit čaka na join)
return nullptr;
}
/*
* Glavna nit
*/
int main(int argc, char const *argv[]) {
mutex_write = PTHREAD_MUTEX_INITIALIZER;
FifoStream<int, string> input_stream(0);
FifoStream<int, struct image> image_stream(0);
FifoStream<int, Vec<int_bool>*> encoded_stream(0);
FifoStream<int, huffman_data> output_stream(0);
// Prva stopnja cevovoda, image reading
PipelineStage<int, string, struct image> read_stage(&input_stream, &image_stream);
pthread_t read_threads[READ_THREADS];
for (int i = 0; i < READ_THREADS; i++)
pthread_create(&read_threads[i], NULL, read, &read_stage);
// Druga stopnja cevovoda, run length encoding
PipelineStage<int, struct image, Vec<int_bool>*> rle_stage(&image_stream, &encoded_stream);
pthread_t rle_threads[RLE_THREADS];
for (int i = 0; i < RLE_THREADS; i++)
pthread_create(&rle_threads[i], NULL, rle, &rle_stage);
// Tretja stopnja cevovoda, huffman encoding
PipelineStage<int, Vec<int_bool>*, huffman_data> huffman_stage(&encoded_stream, &output_stream);
pthread_t huffman_threads[HUFFMAN_THREADS];
for (int i = 0; i < HUFFMAN_THREADS; i++)
pthread_create(&huffman_threads[i], NULL, huffman, &huffman_stage);
// Cetrta stopnja cevovoda, writing
PipelineStage<int, huffman_data, void> write_stage(&output_stream);
pthread_t write_threads[WRITE_THREADS];
for (int i = 0; i < WRITE_THREADS; i++)
pthread_create(&write_threads[i], NULL, write, &write_stage);
// V cevovod posljemo delo
for (int i = 1; i <= REPS; i++) {
int file_id = (i % 10) + 1;
input_stream.produce(i, "../../assets/" + std::to_string(file_id) + ".png");
}
// Pocakamo, da se pisanje zakljuci
for (int i = 0; i < WRITE_THREADS; i++)
pthread_join(write_threads[i], NULL);
return 0;
}
| 27.219653 | 116 | 0.661712 | jakvrh1 |
9ac1b7250246294f2497523086d456027f7f9314 | 19,860 | cpp | C++ | Samples/Win7Samples/netds/wirelessdiagnostics/WlExtHC.cpp | windows-development/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 8 | 2017-04-30T17:38:27.000Z | 2021-11-29T00:59:03.000Z | Samples/Win7Samples/netds/wirelessdiagnostics/WlExtHC.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | null | null | null | Samples/Win7Samples/netds/wirelessdiagnostics/WlExtHC.cpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 2 | 2020-08-11T13:21:49.000Z | 2021-09-01T10:41:51.000Z | // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (C) 2006 Microsoft Corporation. All Rights Reserved.
//
// Module:
// WlExtHC.cpp
//
// Abstract:
// This sample shows how to create a sample Extensible Helper Class for Wireless Diagnostics
// This sample is post-Windows 2006 only.
//
// Usage:
// WlExtHC.exe [/RegServer]
// /RegServer Register the HC
//
// Author:
// Mohammad Shabbir Alam
//
#include "precomp.h"
#pragma hdrstop
GUID gWirelessHelperExtensionRepairId = { /* cb2a064e-b691-4a63-9e7e-7d2970bbe025 */
0xcb2a064e,
0xb691,
0x4a63,
{0x9e, 0x7e, 0x7d, 0x29, 0x70, 0xbb, 0xe0, 0x25}};
__inline
HRESULT
StringCchCopyWithAlloc (
__deref_out_opt PWSTR* Dest,
size_t cchMaxLen,
__in PCWSTR Src
)
{
size_t cchSize = 0;
if (NULL == Dest || NULL == Src || cchMaxLen > USHRT_MAX)
{
return E_INVALIDARG;
}
HRESULT hr = StringCchLength (Src, cchMaxLen - 1, &cchSize);
if (FAILED(hr))
{
return hr;
}
size_t cbSize = (cchSize + 1)*sizeof(WCHAR);
*Dest = (PWSTR) CoTaskMemAlloc(cbSize);
if (NULL == *Dest)
{
return E_OUTOFMEMORY;
}
SecureZeroMemory(*Dest, cbSize);
return StringCchCopy((STRSAFE_LPWSTR)*Dest, cchSize + 1, Src);
}
HRESULT
CWirelessHelperExtension::GetAttributeInfo(
__RPC__out ULONG *pcelt,
__RPC__deref_out_ecount_full_opt(*pcelt) HelperAttributeInfo **pprgAttributeInfos
)
{
HRESULT hr = S_OK;
LogEntry (this);
do
{
if (pcelt==NULL || pprgAttributeInfos==NULL)
{
hr = E_INVALIDARG;
break;
}
HelperAttributeInfo *info = (HelperAttributeInfo *)CoTaskMemAlloc(3*sizeof(HelperAttributeInfo));
if (info==NULL)
{
hr = E_OUTOFMEMORY;
break;
}
SecureZeroMemory(info,3*sizeof(HelperAttributeInfo));
StringCchCopyWithAlloc(&info[0].pwszName, MAX_PATH, L"IfType");
info[0].type=AT_UINT32;
StringCchCopyWithAlloc(&info[1].pwszName, MAX_PATH, L"LowHealthAttributeType");
info[1].type=AT_UINT32;
StringCchCopyWithAlloc(&info[2].pwszName, MAX_PATH, L"ReturnRepair");
info[2].type=AT_BOOLEAN;
*pcelt=3;
*pprgAttributeInfos=info;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::Initialize(
ULONG celt,
__RPC__in_ecount_full(celt) HELPER_ATTRIBUTE rgAttributes[ ]
)
{
WDIAG_IHV_WLAN_ID WDiagID = {0};
HRESULT hr = S_OK;
LogEntry (this);
do
{
if (celt == 0)
{
break;
}
if (rgAttributes == NULL)
{
hr = E_INVALIDARG;
break;
}
for (UINT i = 0; i < celt; i++)
{
switch (rgAttributes[i].type)
{
case (AT_GUID):
{
LogInfo ("\t[%d] GUID Attribute <%ws>, value=<%!guid!>\n",
i+1, rgAttributes[i].pwszName, &rgAttributes[i].Guid);
break;
}
case (AT_UINT32):
{
LogInfo ("\t[%d] UINT Attribute <%ws>, value=<%d>\n",
i+1, rgAttributes[i].pwszName, rgAttributes[i].DWord);
break;
}
case (AT_BOOLEAN):
{
LogInfo ("\t[%d] BOOLEAN Attribute <%ws>, value=<%d>\n",
i+1, rgAttributes[i].pwszName, rgAttributes[i].Boolean);
break;
}
case (AT_STRING):
{
LogInfo ("\t[%d] STRING Attribute <%ws>, value=<%ws>\n",
i+1, rgAttributes[i].pwszName, rgAttributes[i].PWStr);
break;
}
case (AT_OCTET_STRING):
{
LogInfo ("\t[%d] AT_OCTET_STRING Attribute <%ws>, Length=<%d>\n",
i+1, rgAttributes[i].pwszName, rgAttributes[i].OctetString.dwLength);
if (rgAttributes[i].OctetString.dwLength < sizeof(WDIAG_IHV_WLAN_ID))
{
LogInfo ("\t\tLength=<%d> < sizeof(WDIAG_IHV_WLAN_ID)=<%d>\n",
rgAttributes[i].OctetString.dwLength, sizeof(WDIAG_IHV_WLAN_ID));
break;
}
RtlCopyMemory (&WDiagID, rgAttributes[i].OctetString.lpValue, sizeof (WDIAG_IHV_WLAN_ID));
LogInfo ("\t\tProfileName=<%ws>\n", WDiagID.strProfileName);
LogInfo ("\t\tSsidLength=<%d>\n", WDiagID.Ssid.uSSIDLength);
LogInfo ("\t\tBssType=<%d>\n", WDiagID.BssType);
LogInfo ("\t\tReasonCode=<%d>\n", WDiagID.dwReasonCode);
LogInfo ("\t\tFlags=<0x%x>\n", WDiagID.dwFlags);
break;
}
default:
{
LogInfo ("\t[%d] Attribute <%ws>, Unknown type=<%d>\n",
i+1, rgAttributes[i].pwszName, rgAttributes[i].type);
break;
}
}
}
if (S_OK != hr)
{
break;
}
InterlockedCompareExchange(&m_initialized, 1, 0);
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetDiagnosticsInfo(
__RPC__deref_out_opt DiagnosticsInfo **ppInfo
)
{
HRESULT hr = S_OK;
LogEntry (this);
do
{
if (NULL == ppInfo)
{
break;
}
*ppInfo = (DiagnosticsInfo *)CoTaskMemAlloc(sizeof(DiagnosticsInfo));
if (*ppInfo == NULL)
{
hr = E_OUTOFMEMORY;
break;
}
(*ppInfo)->cost = 0;
(*ppInfo)->flags = DF_TRACELESS;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetKeyAttributes(
__RPC__out ULONG *pcelt,
__RPC__deref_out_ecount_full_opt(*pcelt) HELPER_ATTRIBUTE **pprgAttributes
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (pcelt);
UNREFERENCED_PARAMETER (pprgAttributes);
LogEntry (this);
do
{
hr = E_NOTIMPL;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::LowHealth(
__RPC__in_opt LPCWSTR pwszInstanceDescription,
__RPC__deref_out_opt_string LPWSTR *ppwszDescription,
__RPC__out long *pDeferredTime,
__RPC__out DIAGNOSIS_STATUS *pStatus
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (pwszInstanceDescription);
LogEntry (this);
do
{
if (m_initialized <= 0)
{
hr = E_UNEXPECTED;
break;
}
if (pDeferredTime == NULL || pStatus == NULL || ppwszDescription == NULL)
{
hr = E_INVALIDARG;
break;
}
//
// this class will always confirm. this way we know the class
// was instantiated and was called successfully
//
*pStatus = DS_CONFIRMED;
m_ReturnRepair = TRUE;
hr = StringCchCopyWithAlloc(ppwszDescription, 256, L"Helper Extension LowHealth call succeeded.");
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::HighUtilization(
__RPC__in_opt LPCWSTR pwszInstanceDescription,
__RPC__deref_out_opt_string LPWSTR *ppwszDescription,
__RPC__out long *pDeferredTime,
__RPC__out DIAGNOSIS_STATUS *pStatus
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (pwszInstanceDescription);
UNREFERENCED_PARAMETER (ppwszDescription);
UNREFERENCED_PARAMETER (pDeferredTime);
UNREFERENCED_PARAMETER (pStatus);
LogEntry (this);
do
{
hr = E_NOTIMPL;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetLowerHypotheses(
__RPC__out ULONG *pcelt,
__RPC__deref_out_ecount_full_opt(*pcelt) HYPOTHESIS **pprgHypotheses
)
{
HYPOTHESIS *hypothses = NULL;
HELPER_ATTRIBUTE *attributes = NULL;
size_t size = sizeof(HYPOTHESIS);
HRESULT hr = S_OK;
LogEntry (this);
do
{
if (m_initialized <= 0)
{
hr = E_UNEXPECTED;
break;
}
if (pcelt == NULL)
{
hr = E_INVALIDARG;
break;
}
//if no attribute type specified we don't perform a lower hypotheses
if(m_LowHealthAttributeType==0)
{
*pcelt = 0;
*pprgHypotheses=NULL;
hr = S_OK;
break;
}
// check to see if additional storage is needed for attributes.
hypothses = (HYPOTHESIS*)CoTaskMemAlloc(size);
if (hypothses == NULL)
{
hr = E_OUTOFMEMORY;
break;
}
SecureZeroMemory(hypothses, size);
hr = StringCchCopyWithAlloc(&(hypothses->pwszClassName), MAX_PATH, L"LowHealthHypotheses");
if (FAILED (hr))
{
break;
}
hr = StringCchCopyWithAlloc(&(hypothses->pwszDescription), MAX_PATH, L"TestHypotheses");
if (FAILED (hr))
{
break;
}
hypothses->celt = 1;
attributes = hypothses->rgAttributes = (PHELPER_ATTRIBUTE)CoTaskMemAlloc(sizeof HELPER_ATTRIBUTE);
if (attributes == NULL)
{
hr = E_OUTOFMEMORY;
break;
}
switch(m_LowHealthAttributeType)
{
case AT_BOOLEAN:
attributes->type = AT_BOOLEAN;
break;
case AT_INT8:
attributes->type = AT_INT8;
break;
case AT_UINT8:
attributes->type = AT_UINT8;
break;
case AT_INT16:
attributes->type = AT_INT16;
break;
case AT_UINT16:
attributes->type = AT_UINT16;
break;
case AT_INT32:
attributes->type = AT_INT32;
break;
case AT_UINT32:
attributes->type = AT_UINT32;
break;
case AT_INT64:
attributes->type = AT_INT64;
break;
case AT_UINT64:
attributes->type = AT_UINT64;
break;
case AT_STRING:
attributes->type = AT_STRING;
StringCchCopyWithAlloc(&(attributes->PWStr), MAX_PATH, L"String Attribute Value");
break;
case AT_GUID:
attributes->type = AT_GUID;
break;
case AT_LIFE_TIME:
attributes->type = AT_LIFE_TIME;
break;
case AT_SOCKADDR:
attributes->type = AT_SOCKADDR;
break;
case AT_OCTET_STRING:
attributes->type = AT_OCTET_STRING;
attributes->OctetString.dwLength = 32;
attributes->OctetString.lpValue = (BYTE *)CoTaskMemAlloc(32*sizeof(BYTE));
if(attributes->OctetString.lpValue==NULL)
{
hr = E_OUTOFMEMORY;
break;
}
SecureZeroMemory(attributes->OctetString.lpValue,32*sizeof(BYTE));
break;
}
if (FAILED (hr))
{
break;
}
if (hypothses->celt!=0)
{
hr = StringCchCopyWithAlloc(&(attributes->pwszName), MAX_PATH, L"TestAttribute");
if (FAILED (hr))
{
break;
}
}
*pcelt = 1;
if (pprgHypotheses)
{
*pprgHypotheses = hypothses;
}
} while (FALSE);
if ((FAILED (hr)) &&
(hypothses))
{
CoTaskMemFree(hypothses->pwszClassName);
attributes = hypothses->rgAttributes;
if (attributes)
{
for (UINT i = 0; i < hypothses->celt; i++, ++attributes)
{
CoTaskMemFree(attributes->pwszName);
switch(attributes->type)
{
case AT_STRING:
if(attributes->PWStr!=NULL) CoTaskMemFree(attributes->PWStr);
case AT_OCTET_STRING:
if(attributes->OctetString.lpValue!=NULL) CoTaskMemFree(attributes->OctetString.lpValue);
}
}
CoTaskMemFree(attributes);
}
CoTaskMemFree(hypothses);
}
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetDownStreamHypotheses(
__RPC__out ULONG *pcelt,
__RPC__deref_out_ecount_full_opt(*pcelt) HYPOTHESIS **pprgHypotheses
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (pcelt);
UNREFERENCED_PARAMETER (pprgHypotheses);
LogEntry (this);
do
{
hr = E_NOTIMPL;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetHigherHypotheses(
__RPC__out ULONG *pcelt,
__RPC__deref_out_ecount_full_opt(*pcelt) HYPOTHESIS **pprgHypotheses
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (pcelt);
UNREFERENCED_PARAMETER (pprgHypotheses);
LogEntry (this);
do
{
hr = E_NOTIMPL;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetUpStreamHypotheses(
__RPC__out ULONG *pcelt,
__RPC__deref_out_ecount_full_opt(*pcelt) HYPOTHESIS **pprgHypotheses
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (pcelt);
UNREFERENCED_PARAMETER (pprgHypotheses);
LogEntry (this);
do
{
hr = E_NOTIMPL;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::Repair(
__RPC__in RepairInfo *pInfo,
__RPC__out long *pDeferredTime,
__RPC__out REPAIR_STATUS *pStatus
)
{
HRESULT hr = S_OK;
LogEntry (this);
do
{
if (m_initialized <= 0)
{
hr = E_UNEXPECTED;
break;
}
if (pInfo == NULL || pDeferredTime == NULL || pStatus == NULL)
{
hr = E_INVALIDARG;
break;
}
if (!IsEqualGUID(pInfo->guid, gWirelessHelperExtensionRepairId))
{
hr = E_NOTIMPL;
break;
}
*pDeferredTime = 0;
*pStatus = RS_REPAIRED;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::Validate(
PROBLEM_TYPE problem,
__RPC__out long *pDeferredTime,
__RPC__out REPAIR_STATUS *pStatus
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (problem);
UNREFERENCED_PARAMETER (pDeferredTime);
UNREFERENCED_PARAMETER (pStatus);
LogEntry (this);
do
{
if (m_initialized <= 0)
{
hr = E_UNEXPECTED;
break;
}
hr = E_NOTIMPL;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetRepairInfo(
PROBLEM_TYPE problem,
__RPC__out ULONG *pcelt,
__RPC__deref_out_ecount_full_opt(*pcelt) RepairInfo **ppInfo
)
{
RepairInfo *info = NULL;
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (problem);
LogEntry (this);
do
{
if (m_initialized <= 0)
{
hr = E_UNEXPECTED;
break;
}
if (pcelt == NULL)
{
hr = E_INVALIDARG;
break;
}
if (ppInfo == NULL)
{
hr = S_OK;
break;
}
if(!m_ReturnRepair)
{
*pcelt=0;
*ppInfo=NULL;
hr = S_OK;
break;
}
info = (RepairInfo *)CoTaskMemAlloc(sizeof(RepairInfo));
if (info == NULL)
{
hr = E_OUTOFMEMORY;
break;
}
SecureZeroMemory(info, sizeof(RepairInfo));
info->guid = gWirelessHelperExtensionRepairId;
hr = StringCchCopyWithAlloc(&(info->pwszClassName), MAX_PATH, L"SampleWirelessHelperExtension");
if (FAILED (hr))
{
break;
}
hr = StringCchCopyWithAlloc(&(info->pwszDescription), MAX_PATH, L"Sample repair from SampleWirelessHelperExtension");
if (FAILED (hr))
{
break;
}
info->cost = 5;
info->sidType = WinBuiltinNetworkConfigurationOperatorsSid;
info->flags = RF_INFORMATION_ONLY;
info->scope = RS_SYSTEM;
info->risk = RR_NORISK;
info->UiInfo.type = UIT_NONE;
*pcelt = 1;
*ppInfo = info;
} while (FALSE);
if ((FAILED (hr)) &&
(info))
{
CoTaskMemFree(info->pwszClassName);
CoTaskMemFree(info->pwszDescription);
CoTaskMemFree(info);
}
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetLifeTime(
__RPC__out LIFE_TIME *pLifeTime
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (pLifeTime);
LogEntry (this);
do
{
hr = E_NOTIMPL;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::SetLifeTime(
LIFE_TIME lifeTime
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (lifeTime);
LogEntry (this);
do
{
hr = E_NOTIMPL;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetCacheTime(
__RPC__out FILETIME *pCacheTime
)
{
HRESULT hr = S_OK;
LogEntry (this);
do
{
SecureZeroMemory (pCacheTime, sizeof(FILETIME));
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::GetAttributes(
__RPC__out ULONG *pcelt,
__RPC__deref_out_ecount_full_opt(*pcelt) HELPER_ATTRIBUTE **pprgAttributes
)
{
HRESULT hr = S_OK;
UNREFERENCED_PARAMETER (pcelt);
UNREFERENCED_PARAMETER (pprgAttributes);
LogEntry (this);
do
{
hr = E_NOTIMPL;
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::Cancel(
)
{
HRESULT hr = S_OK;
LogEntry (this);
do
{
} while (FALSE);
LogExit (hr);
return (hr);
}
HRESULT
CWirelessHelperExtension::Cleanup(
)
{
HRESULT hr = S_OK;
LogEntry (this);
do
{
} while (FALSE);
LogExit (hr);
return (hr);
}
| 23.146853 | 126 | 0.512739 | windows-development |
9acd71e8de724a3ce78857d7a32b50b495be5614 | 858 | cpp | C++ | outbound_place/src/mosaic.cpp | ManuelBeschi/manipulation | 0caddd6dc78dc6d00a39b2e674093d1eafdc7221 | [
"BSD-3-Clause"
] | null | null | null | outbound_place/src/mosaic.cpp | ManuelBeschi/manipulation | 0caddd6dc78dc6d00a39b2e674093d1eafdc7221 | [
"BSD-3-Clause"
] | null | null | null | outbound_place/src/mosaic.cpp | ManuelBeschi/manipulation | 0caddd6dc78dc6d00a39b2e674093d1eafdc7221 | [
"BSD-3-Clause"
] | 1 | 2021-03-12T09:50:37.000Z | 2021-03-12T09:50:37.000Z | #include <ros/ros.h>
#include <outbound_place/outbound_mosaic.h>
#include <moveit_msgs/GetPlanningScene.h>
int main(int argc, char **argv)
{
ros::init(argc, argv, "outbound_mosaic");
ros::NodeHandle nh;
ros::NodeHandle pnh("~");
ros::ServiceClient ps_client=nh.serviceClient<moveit_msgs::GetPlanningScene>("/get_planning_scene");
ps_client.waitForExistence();
moveit_msgs::GetPlanningScene ps_srv;
ros::AsyncSpinner spinner(8);
spinner.start();
pickplace::OutboundMosaic pallet(nh,pnh) ;
if (!pallet.init())
{
ROS_ERROR_NAMED(nh.getNamespace(),"unable to load parameter");
return -1;
}
while (ros::ok())
{
if (!ps_client.call(ps_srv))
ROS_ERROR("call to get_planning_scene srv not ok");
else
pallet.updatePlanningScene(ps_srv.response.scene);
ros::Duration(0.1).sleep();
}
return 0;
}
| 22.578947 | 102 | 0.693473 | ManuelBeschi |
9ad1d5d732e096c5ce1dfba081bf6fde98c5a130 | 3,713 | cpp | C++ | src/navigation/camera.cpp | h4k1m0u/first-person-shooter | b1e60d77edb3144daf252f65c28a340aa63e6945 | [
"MIT"
] | null | null | null | src/navigation/camera.cpp | h4k1m0u/first-person-shooter | b1e60d77edb3144daf252f65c28a340aa63e6945 | [
"MIT"
] | null | null | null | src/navigation/camera.cpp | h4k1m0u/first-person-shooter | b1e60d77edb3144daf252f65c28a340aa63e6945 | [
"MIT"
] | null | null | null | #include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/constants.hpp>
#include <algorithm>
#include <iostream>
#include "navigation/camera.hpp"
// not declared as private members as constants cause class's implicit copy-constructor to be deleted (prevents re-assignment)
// movement constants
const float SPEED = 0.1f;
const float SENSITIVITY = 0.25e-2;
Camera::Camera(const glm::vec3& pos, const glm::vec3& dir, const glm::vec3& up):
position(pos),
direction(dir),
m_up(up),
m_forward_dir(dir),
pitch(0.0f),
yaw(0.0f),
fov(45.0f)
{
}
/**
* View matrix orients a scene in such a way to simulate camera's movement (inversion of camera's transformation matrix)
* i.e. translation/rotation of scene in opposite directions to camera
* Important: pitch/yaw angles rotate scene's object not camera
*/
glm::mat4 Camera::get_view() {
// only camera direction is rotated by mouse in `rotate()`
glm::mat4 view = glm::lookAt(position, position + direction, m_up);
return view;
}
void Camera::zoom(Zoom z) {
if (z == Zoom::IN) {
fov -= 5.0f;
} else if (z == Zoom::OUT) {
fov += 5.0f;
}
}
/**
* Check if future camera position is too close from its distance to closest wall tile
* Used to prevent camera from going through walls
* @param position_future Next position of camera
*/
bool Camera::is_close_to_boundaries(const glm::vec3& position_future) {
std::vector<float> distances;
std::transform(boundaries.begin(), boundaries.end(), std::back_inserter(distances),
[position_future](const glm::vec3& position_wall) { return glm::length(position_future - position_wall); });
float min_distance = *std::min_element(distances.begin(), distances.end());
return min_distance < 1.2f;
}
void Camera::move(Direction d) {
// move forward/backward & sideways
glm::vec3 right_dir = glm::normalize(glm::cross(m_forward_dir, m_up));
glm::vec3 position_future;
if (d == Direction::FORWARD) {
position_future = position + SPEED*m_forward_dir;
} else if (d == Direction::BACKWARD) {
position_future = position - SPEED*m_forward_dir;
} else if (d == Direction::RIGHT) {
position_future = position + SPEED*right_dir;
} else if (d == Direction::LEFT) {
position_future = position - SPEED*right_dir;
}
// only move camera if not too close to walls
std::vector<Direction> dirs = {
Direction::FORWARD, Direction::BACKWARD, Direction::RIGHT, Direction::LEFT};
if (std::find(dirs.begin(), dirs.end(), d) != dirs.end() && !is_close_to_boundaries(position_future))
position = position_future;
}
void Camera::rotate(float x_offset, float y_offset) {
// increment angles accord. to 2D mouse movement
float PI = glm::pi<float>();
float yaw_offset = SENSITIVITY * x_offset;
float pitch_offset = SENSITIVITY * y_offset;
yaw += yaw_offset;
pitch += pitch_offset;
// yaw in [-2pi, 2pi] & clamp pitch angle to prevent weird rotation of camera when pitch ~ pi/2
yaw = std::fmod(yaw, 2 * PI);
pitch = std::clamp(pitch, glm::radians(-60.0f), glm::radians(60.0f));
if (pitch == glm::radians(-60.0f) || pitch == glm::radians(60.0f)) {
return;
}
// fps camera navigation by rotating its direction vector around x/y-axis
glm::vec3 right_dir = glm::normalize(glm::cross(m_forward_dir, m_up));
glm::mat4 rotation_yaw_mat = glm::rotate(glm::mat4(1.0f), yaw_offset, glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 rotation_pitch_mat = glm::rotate(glm::mat4(1.0f), pitch_offset, right_dir);
direction = glm::vec3(rotation_pitch_mat * rotation_yaw_mat * glm::vec4(direction, 1.0f));
// forward dir. of movement unaffected by vertical angle (sticks camera to ground)
m_forward_dir = {direction.x, 0.0f, direction.z};
}
| 35.361905 | 126 | 0.699973 | h4k1m0u |
9ad2e36a016ddc139c298b984b4c0c4d6e1d7c53 | 10,937 | hpp | C++ | external/boost_1_60_0/qsboost/preprocessor/slot/detail/slot3.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | 1 | 2019-06-27T17:54:13.000Z | 2019-06-27T17:54:13.000Z | external/boost_1_60_0/qsboost/preprocessor/slot/detail/slot3.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | external/boost_1_60_0/qsboost/preprocessor/slot/detail/slot3.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | # /* **************************************************************************
# * *
# * (C) Copyright Paul Mensonides 2002.
# * 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)
# * *
# ************************************************************************** */
#
# /* See http://www.boost.org for most recent version. */
#
# include <qsboost/preprocessor/slot/detail/shared.hpp>
#
# undef QSBOOST_PP_SLOT_3
#
# undef QSBOOST_PP_SLOT_3_DIGIT_1
# undef QSBOOST_PP_SLOT_3_DIGIT_2
# undef QSBOOST_PP_SLOT_3_DIGIT_3
# undef QSBOOST_PP_SLOT_3_DIGIT_4
# undef QSBOOST_PP_SLOT_3_DIGIT_5
# undef QSBOOST_PP_SLOT_3_DIGIT_6
# undef QSBOOST_PP_SLOT_3_DIGIT_7
# undef QSBOOST_PP_SLOT_3_DIGIT_8
# undef QSBOOST_PP_SLOT_3_DIGIT_9
# undef QSBOOST_PP_SLOT_3_DIGIT_10
#
# if QSBOOST_PP_SLOT_TEMP_10 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_10 0
# elif QSBOOST_PP_SLOT_TEMP_10 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_10 1
# elif QSBOOST_PP_SLOT_TEMP_10 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_10 2
# elif QSBOOST_PP_SLOT_TEMP_10 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_10 3
# elif QSBOOST_PP_SLOT_TEMP_10 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_10 4
# elif QSBOOST_PP_SLOT_TEMP_10 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_10 5
# elif QSBOOST_PP_SLOT_TEMP_10 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_10 6
# elif QSBOOST_PP_SLOT_TEMP_10 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_10 7
# elif QSBOOST_PP_SLOT_TEMP_10 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_10 8
# elif QSBOOST_PP_SLOT_TEMP_10 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_10 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_9 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_9 0
# elif QSBOOST_PP_SLOT_TEMP_9 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_9 1
# elif QSBOOST_PP_SLOT_TEMP_9 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_9 2
# elif QSBOOST_PP_SLOT_TEMP_9 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_9 3
# elif QSBOOST_PP_SLOT_TEMP_9 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_9 4
# elif QSBOOST_PP_SLOT_TEMP_9 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_9 5
# elif QSBOOST_PP_SLOT_TEMP_9 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_9 6
# elif QSBOOST_PP_SLOT_TEMP_9 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_9 7
# elif QSBOOST_PP_SLOT_TEMP_9 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_9 8
# elif QSBOOST_PP_SLOT_TEMP_9 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_9 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_8 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_8 0
# elif QSBOOST_PP_SLOT_TEMP_8 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_8 1
# elif QSBOOST_PP_SLOT_TEMP_8 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_8 2
# elif QSBOOST_PP_SLOT_TEMP_8 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_8 3
# elif QSBOOST_PP_SLOT_TEMP_8 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_8 4
# elif QSBOOST_PP_SLOT_TEMP_8 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_8 5
# elif QSBOOST_PP_SLOT_TEMP_8 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_8 6
# elif QSBOOST_PP_SLOT_TEMP_8 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_8 7
# elif QSBOOST_PP_SLOT_TEMP_8 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_8 8
# elif QSBOOST_PP_SLOT_TEMP_8 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_8 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_7 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_7 0
# elif QSBOOST_PP_SLOT_TEMP_7 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_7 1
# elif QSBOOST_PP_SLOT_TEMP_7 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_7 2
# elif QSBOOST_PP_SLOT_TEMP_7 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_7 3
# elif QSBOOST_PP_SLOT_TEMP_7 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_7 4
# elif QSBOOST_PP_SLOT_TEMP_7 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_7 5
# elif QSBOOST_PP_SLOT_TEMP_7 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_7 6
# elif QSBOOST_PP_SLOT_TEMP_7 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_7 7
# elif QSBOOST_PP_SLOT_TEMP_7 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_7 8
# elif QSBOOST_PP_SLOT_TEMP_7 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_7 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_6 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_6 0
# elif QSBOOST_PP_SLOT_TEMP_6 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_6 1
# elif QSBOOST_PP_SLOT_TEMP_6 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_6 2
# elif QSBOOST_PP_SLOT_TEMP_6 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_6 3
# elif QSBOOST_PP_SLOT_TEMP_6 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_6 4
# elif QSBOOST_PP_SLOT_TEMP_6 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_6 5
# elif QSBOOST_PP_SLOT_TEMP_6 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_6 6
# elif QSBOOST_PP_SLOT_TEMP_6 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_6 7
# elif QSBOOST_PP_SLOT_TEMP_6 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_6 8
# elif QSBOOST_PP_SLOT_TEMP_6 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_6 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_5 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_5 0
# elif QSBOOST_PP_SLOT_TEMP_5 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_5 1
# elif QSBOOST_PP_SLOT_TEMP_5 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_5 2
# elif QSBOOST_PP_SLOT_TEMP_5 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_5 3
# elif QSBOOST_PP_SLOT_TEMP_5 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_5 4
# elif QSBOOST_PP_SLOT_TEMP_5 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_5 5
# elif QSBOOST_PP_SLOT_TEMP_5 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_5 6
# elif QSBOOST_PP_SLOT_TEMP_5 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_5 7
# elif QSBOOST_PP_SLOT_TEMP_5 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_5 8
# elif QSBOOST_PP_SLOT_TEMP_5 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_5 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_4 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_4 0
# elif QSBOOST_PP_SLOT_TEMP_4 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_4 1
# elif QSBOOST_PP_SLOT_TEMP_4 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_4 2
# elif QSBOOST_PP_SLOT_TEMP_4 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_4 3
# elif QSBOOST_PP_SLOT_TEMP_4 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_4 4
# elif QSBOOST_PP_SLOT_TEMP_4 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_4 5
# elif QSBOOST_PP_SLOT_TEMP_4 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_4 6
# elif QSBOOST_PP_SLOT_TEMP_4 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_4 7
# elif QSBOOST_PP_SLOT_TEMP_4 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_4 8
# elif QSBOOST_PP_SLOT_TEMP_4 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_4 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_3 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_3 0
# elif QSBOOST_PP_SLOT_TEMP_3 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_3 1
# elif QSBOOST_PP_SLOT_TEMP_3 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_3 2
# elif QSBOOST_PP_SLOT_TEMP_3 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_3 3
# elif QSBOOST_PP_SLOT_TEMP_3 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_3 4
# elif QSBOOST_PP_SLOT_TEMP_3 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_3 5
# elif QSBOOST_PP_SLOT_TEMP_3 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_3 6
# elif QSBOOST_PP_SLOT_TEMP_3 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_3 7
# elif QSBOOST_PP_SLOT_TEMP_3 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_3 8
# elif QSBOOST_PP_SLOT_TEMP_3 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_3 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_2 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_2 0
# elif QSBOOST_PP_SLOT_TEMP_2 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_2 1
# elif QSBOOST_PP_SLOT_TEMP_2 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_2 2
# elif QSBOOST_PP_SLOT_TEMP_2 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_2 3
# elif QSBOOST_PP_SLOT_TEMP_2 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_2 4
# elif QSBOOST_PP_SLOT_TEMP_2 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_2 5
# elif QSBOOST_PP_SLOT_TEMP_2 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_2 6
# elif QSBOOST_PP_SLOT_TEMP_2 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_2 7
# elif QSBOOST_PP_SLOT_TEMP_2 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_2 8
# elif QSBOOST_PP_SLOT_TEMP_2 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_2 9
# endif
#
# if QSBOOST_PP_SLOT_TEMP_1 == 0
# define QSBOOST_PP_SLOT_3_DIGIT_1 0
# elif QSBOOST_PP_SLOT_TEMP_1 == 1
# define QSBOOST_PP_SLOT_3_DIGIT_1 1
# elif QSBOOST_PP_SLOT_TEMP_1 == 2
# define QSBOOST_PP_SLOT_3_DIGIT_1 2
# elif QSBOOST_PP_SLOT_TEMP_1 == 3
# define QSBOOST_PP_SLOT_3_DIGIT_1 3
# elif QSBOOST_PP_SLOT_TEMP_1 == 4
# define QSBOOST_PP_SLOT_3_DIGIT_1 4
# elif QSBOOST_PP_SLOT_TEMP_1 == 5
# define QSBOOST_PP_SLOT_3_DIGIT_1 5
# elif QSBOOST_PP_SLOT_TEMP_1 == 6
# define QSBOOST_PP_SLOT_3_DIGIT_1 6
# elif QSBOOST_PP_SLOT_TEMP_1 == 7
# define QSBOOST_PP_SLOT_3_DIGIT_1 7
# elif QSBOOST_PP_SLOT_TEMP_1 == 8
# define QSBOOST_PP_SLOT_3_DIGIT_1 8
# elif QSBOOST_PP_SLOT_TEMP_1 == 9
# define QSBOOST_PP_SLOT_3_DIGIT_1 9
# endif
#
# if QSBOOST_PP_SLOT_3_DIGIT_10
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_10(QSBOOST_PP_SLOT_3_DIGIT_10, QSBOOST_PP_SLOT_3_DIGIT_9, QSBOOST_PP_SLOT_3_DIGIT_8, QSBOOST_PP_SLOT_3_DIGIT_7, QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1)
# elif QSBOOST_PP_SLOT_3_DIGIT_9
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_9(QSBOOST_PP_SLOT_3_DIGIT_9, QSBOOST_PP_SLOT_3_DIGIT_8, QSBOOST_PP_SLOT_3_DIGIT_7, QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1)
# elif QSBOOST_PP_SLOT_3_DIGIT_8
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_8(QSBOOST_PP_SLOT_3_DIGIT_8, QSBOOST_PP_SLOT_3_DIGIT_7, QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1)
# elif QSBOOST_PP_SLOT_3_DIGIT_7
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_7(QSBOOST_PP_SLOT_3_DIGIT_7, QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1)
# elif QSBOOST_PP_SLOT_3_DIGIT_6
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_6(QSBOOST_PP_SLOT_3_DIGIT_6, QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1)
# elif QSBOOST_PP_SLOT_3_DIGIT_5
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_5(QSBOOST_PP_SLOT_3_DIGIT_5, QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1)
# elif QSBOOST_PP_SLOT_3_DIGIT_4
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_4(QSBOOST_PP_SLOT_3_DIGIT_4, QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1)
# elif QSBOOST_PP_SLOT_3_DIGIT_3
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_3(QSBOOST_PP_SLOT_3_DIGIT_3, QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1)
# elif QSBOOST_PP_SLOT_3_DIGIT_2
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_CC_2(QSBOOST_PP_SLOT_3_DIGIT_2, QSBOOST_PP_SLOT_3_DIGIT_1)
# else
# define QSBOOST_PP_SLOT_3() QSBOOST_PP_SLOT_3_DIGIT_1
# endif
| 40.809701 | 324 | 0.782481 | wouterboomsma |
9ad3840865e3e2067328758f90a58750f42428df | 45,140 | cpp | C++ | wbs/src/Basic/UtilMath.cpp | RNCan/WeatherBasedSimulationFramework | 19df207d11b1dddf414d78e52bece77f31d45df8 | [
"MIT"
] | 6 | 2017-05-26T21:19:41.000Z | 2021-09-03T14:17:29.000Z | wbs/src/Basic/UtilMath.cpp | RNCan/WeatherBasedSimulationFramework | 19df207d11b1dddf414d78e52bece77f31d45df8 | [
"MIT"
] | 5 | 2016-02-18T12:39:58.000Z | 2016-03-13T12:57:45.000Z | wbs/src/Basic/UtilMath.cpp | RNCan/WeatherBasedSimulationFramework | 19df207d11b1dddf414d78e52bece77f31d45df8 | [
"MIT"
] | 1 | 2019-06-16T02:49:20.000Z | 2019-06-16T02:49:20.000Z | //******************************************************************************
// project: Weather-based simulation framework (WBSF)
// Programmer: Rémi Saint-Amant
//
// It under the terms of the GNU General Public License as published by
// the Free Software Foundation
// It is provided "as is" without express or implied warranty.
//******************************************************************************
// 01-01-2016 Rémi Saint-Amant Creation
//******************************************************************************
#include "stdafx.h"
#include <time.h>
#include <float.h>
#include <limits>
#include "Basic/UtilMath.h"
#include "Basic/psychrometrics_SI.h"
using namespace std;
namespace WBSF
{
double InvLogistic(double y, double k1, double k2)
{
// Eq. [3] in Regniere, J. 1984. Canadian Entomologist 116: 1367-1376
// inverted y = f(x)
double x = 1.0 - log((pow(y, -k2) - 1) / (pow(0.5, -k2) - 1)) / k1;
return x;
}
double InvWeibull(double y, double alpha, double beta, double gamma)
{
//inverted y = 1 - e( - ((x-gamma)/beta)^alpha)
//Note that Gray et al's (2001) equ. [9] is in error, as alpha is exponent of negative sign as well...
//Gray et al (1991) had their equ. right.
double x = gamma + beta * pow((-log(1 - y)), (1 / alpha)); //Inverted Weibull function
return x;
}
double Weibull(double t, double tb, double tm,
double b1, double b2, double b3, double b4)
{
double w;
double tau;
double x, y;
x = (t - tb);
y = (tm - tb);
_ASSERTE(y != 0);
_ASSERTE(b4 != 0);
_ASSERTE(/*(x!=0)&&*/(y != 0));
tau = x / y;
if ((tau >= .01) && (tau <= .99)) {
w = (double)(b1*(1 / (1 + exp(b2 - tau * b3)) - exp((tau - 1) / b4)));
}
else w = 0;
return w;
}
double Linearize(double x2, double x1, double y1, double x3, double y3)
{
_ASSERTE(x1 != x3); // x1 = x3 => not a function
double m, b, y2 = 0;
m = (y3 - y1) / (x3 - x1);
b = y1 - m * x1;
y2 = m * x2 + b;
return y2;
}
double zScore(void)
{
//Polar method for producing two normal deviates via polar method by D. Knuth,
// volume 3, p. 117
double u1, u2, v1, v2, s, x, a;
do {
u1 = Randu();
u2 = Randu();
v1 = 2 * u1 - 1;
v2 = 2 * u2 - 1;
s = (double)(pow(v1, 2) + pow(v2, 2));
} while (s >= 1);
_ASSERTE(s > 0);
a = (double)sqrt(-2 * log(s) / s);
x = v1 * a;
return x;
}
double Polynom(double x, int degree, const double *coeffs)
{
double sum = 0.0;
while (degree >= 0) {
sum += (double)(coeffs[degree] * pow(x, degree));
degree--;
}
return sum;
}
double Schoolfield(const double p[NB_SCHOOLFIELD_PARAMETERS], double T)
{
const double R = 1.987;
double Tk = T + 273.15;
double a1 = p[SF_PRHO25] * Tk / 298.15;
double a2 = exp(p[SF_PHA] / R * (1 / 298.15 - 1 / Tk));
double b1 = exp(p[SF_PHL] / R * (1 / p[SF_PTL] - 1 / Tk));
double b2 = exp(p[SF_PHH] / R * (1 / p[SF_PTH] - 1 / Tk));
double r = (a1*a2) / (1 + b1 + b2);
ASSERT(r >= 0);
return r;
}
// Visit http://www.johndcook.com/stand_alone_code.html for the source of this code and more like it.
// We require x > 0
double Gamma(double x)
{
ASSERT(x > 0);
// Split the function domain into three intervals:
// (0, 0.001), [0.001, 12), and (12, infinity)
///////////////////////////////////////////////////////////////////////////
// First interval: (0, 0.001)
//
// For small x, 1/Gamma(x) has power series x + gamma x^2 - ...
// So in this range, 1/Gamma(x) = x + gamma x^2 with error on the order of x^3.
// The relative error over this interval is less than 6e-7.
const double gamma = 0.577215664901532860606512090; // Euler's gamma constant
if (x < 0.001)
return 1.0 / (x*(1.0 + gamma * x));
///////////////////////////////////////////////////////////////////////////
// Second interval: [0.001, 12)
if (x < 12.0)
{
// The algorithm directly approximates gamma over (1,2) and uses
// reduction identities to reduce other arguments to this interval.
double y = x;
int n = 0;
bool arg_was_less_than_one = (y < 1.0);
// Add or subtract integers as necessary to bring y into (1,2)
// Will correct for this below
if (arg_was_less_than_one)
{
y += 1.0;
}
else
{
n = static_cast<int> (floor(y)) - 1; // will use n later
y -= n;
}
// numerator coefficients for approximation over the interval (1,2)
static const double p[] =
{
-1.71618513886549492533811E+0,
2.47656508055759199108314E+1,
-3.79804256470945635097577E+2,
6.29331155312818442661052E+2,
8.66966202790413211295064E+2,
-3.14512729688483675254357E+4,
-3.61444134186911729807069E+4,
6.64561438202405440627855E+4
};
// denominator coefficients for approximation over the interval (1,2)
static const double q[] =
{
-3.08402300119738975254353E+1,
3.15350626979604161529144E+2,
-1.01515636749021914166146E+3,
-3.10777167157231109440444E+3,
2.25381184209801510330112E+4,
4.75584627752788110767815E+3,
-1.34659959864969306392456E+5,
-1.15132259675553483497211E+5
};
double num = 0.0;
double den = 1.0;
int i;
double z = y - 1;
for (i = 0; i < 8; i++)
{
num = (num + p[i])*z;
den = den * z + q[i];
}
double result = num / den + 1.0;
// Apply correction if argument was not initially in (1,2)
if (arg_was_less_than_one)
{
// Use identity gamma(z) = gamma(z+1)/z
// The variable "result" now holds gamma of the original y + 1
// Thus we use y-1 to get back the orginal y.
result /= (y - 1.0);
}
else
{
// Use the identity gamma(z+n) = z*(z+1)* ... *(z+n-1)*gamma(z)
for (i = 0; i < n; i++)
result *= y++;
}
return result;
}
///////////////////////////////////////////////////////////////////////////
// Third interval: [12, infinity)
if (x > 171.624)
{
// Correct answer too large to display. Force +infinity.
//double temp = DBL_MAX;
return std::numeric_limits<double>::infinity();
}
return exp(LogGamma(x));
}
// x must be positive
double LogGamma(double x)
{
ASSERT(x > 0);
if (x < 12.0)
{
return log(fabs(Gamma(x)));
}
// Abramowitz and Stegun 6.1.41
// Asymptotic series should be good to at least 11 or 12 figures
// For error analysis, see Whittiker and Watson
// A Course in Modern Analysis (1927), page 252
static const double c[8] =
{
1.0 / 12.0,
-1.0 / 360.0,
1.0 / 1260.0,
-1.0 / 1680.0,
1.0 / 1188.0,
-691.0 / 360360.0,
1.0 / 156.0,
-3617.0 / 122400.0
};
double z = 1.0 / (x*x);
double sum = c[7];
for (int i = 6; i >= 0; i--)
{
sum *= z;
sum += c[i];
}
double series = sum / x;
static const double halfLogTwoPi = 0.91893853320467274178032973640562;
double logGamma = (x - 0.5)*log(x) - x + halfLogTwoPi + series;
return logGamma;
}
double StringToCoord(const std::string& coordStr)
{
double coord = 0;
double a = 0, b = 0, c = 0;
int nbVal = sscanf(coordStr.c_str(), "%lf %lf %lf", &a, &b, &c);
if (nbVal == 1)
{
//decimal degree
coord = a;
}
else if (nbVal >= 2 && nbVal <= 3)
{
//degree minute
if (a >= -360 && a <= 360 &&
b >= 0 && b <= 60 &&
c >= 0 && c <= 60)
coord = GetDecimalDegree((long)a, (long)b, c);
}
return coord;
}
std::string CoordToString(double coord, int prec)
{
double mult = pow(10.0, prec);
std::string deg = ToString(GetDegrees(coord, mult));
std::string min = ToString(GetMinutes(coord, mult));
std::string sec = ToString(GetSeconds(coord, mult), prec);
if (sec == "0" || sec == "-0")
sec.clear();
if (sec.empty() && (min == "0" || min == "-0"))
min.clear();
std::string str = deg + " " + min + " " + sec;
Trim(str);
return str;
}
//**************************************************************************************************************************
//Humidity function
//latent heat of vaporisation (J/kg)
//Tair: dry bulb air temperature [°C]
//L: J kg-1 at T = 273.15 K
double GetL(double Tair)
{
double T = Tair + 273.15;
double a = (2.501E6 - 2.257E6) / (273.15 - 373.15);
double b = 2.501E6 - a * 273.15;
double L = a * T + b;
return L; //J kg-1
}
void GetWindUV(double windSpeed, double windDir, double& U, double &V, bool from)
{
ASSERT(windSpeed >= 0 && windSpeed < 150);
ASSERT(windDir >= 0 && windDir <= 360);
double d = Deg2Rad(90 - windDir);
double x = cos(d)*windSpeed;
double y = sin(d)*windSpeed;
ASSERT(fabs(sqrt(Square(x) + Square(y)) - windSpeed) < 0.0001);
U = from ? -x : x;
V = from ? -y : y;
if (fabs(U) < 0.1)
U = 0;
if (fabs(V) < 0.1)
V = 0;
}
double GetWindDirection(double u, double v, bool from)
{
double d = (180 / PI)*(atan2(u, v));
ASSERT(d >= -180 && d <= 180);
if (from)
d = int(d + 360 + 180) % 360;
else
d = int(d + 360) % 360;
return d;
}
//
//Excel = 0.6108 * exp(17.27*T / (T + 237.3))
//hourly vapor pressure
//T : temperature [°C]
//e°: saturation vapor pressure function [kPa]
double eᵒ(double T)
{
return 0.6108 * exp(17.27*T / (T + 237.3));//Same as CASCE_ETsz
}
//daily vapor pressure
double eᵒ(double Tmin, double Tmax)
{
return (eᵒ(Tmax) + eᵒ(Tmin)) / 2;
}
//Relative humidity [%] to dew point [°C]
//Excel formula: =Min( T, (1/(1/(T+273.15) - (461*ln(max(0.0,Min(100,RH))/100))/2.5E6))-273.15)
//Tair: temperature of dry bulb [°C]
//Hr: relative humidity [%]
double Hr2Td(double Tair, double Hr)
{
_ASSERTE(Tair > -999);
_ASSERTE(Hr >= 0 && Hr <= 101);
Hr = max(1.0, Hr);//limit to avoid division by zero
double L = GetL(Tair); //(J/kg)
//static const double L = 2.453E6;
static const double Rv = 461; //constant for moist air (J/kg)
double T = Tair + 273.15;
double Td = 1 / (1 / T - (Rv*log(Hr / 100)) / L);
_ASSERTE(Td - 273.15 > -99 && Td - 273.15 < 99);
return min(Tair, Td - 273.15);
}
//Dew point teprature [°C] to relative humidity [%]
//Excel formula: =max(0.0, Min(100, exp( 2.5E6/461*(1/(T+273.15) - 1/Min(T+273.15, Td+273.15)))*100))
//Tair: Temperature of dry bulb [°C]
//Tdew: Dew point temperature [°C]
double Td2Hr(double Tair, double Tdew)
{
double L = GetL(Tair); //J/kg
static const double Rv = 461; //J/kg
double T = Tair + 273.15;
double Td = min(T, Tdew + 273.15);
double Hr = exp(L / Rv * (1 / T - 1 / Td));
_ASSERTE(Hr >= 0 && Hr <= 1);
return Hr * 100;
}
static const double Ra = 287.058; // Specific gas constant for dry air J/(kg·K)
static const double Rw = 461.495; // Specific gas constant for water vapor J/(kg·K)
static const double Ma = 0.028964;//Molar mass of dry air, kg/mol
static const double Mw = 0.018016;//Molar mass of water vapor, kg/mol
static const double R = 8.314; //Universal gas constant J/(K·mol)
static const double M = Mw / Ma; // 0.6220135
//Td : dew point temperature [°C]
//Pv : vapor pressure [kPa]
double Td2Pv(double Td)
{
//return Pv(Td) * 1000;
//from : http://www.conservationphysics.org/atmcalc/atmoclc2.pdf
return 0.61078 * exp(17.2694*Td / (Td + 238.3));
}
//Pv : vapor pressure [kPa]
//Td : dew point temperature [°C]
double Pv2Td(double Pv)
{
//from : http://www.conservationphysics.org/atmcalc/atmoclc2.pdf
return (241.88 * log(Pv / 0.61078)) / (17.558 - log(Pv / 0.61078));
}
//mixing ratio ( kg[H2O]/kg[dry air] ) to specific humidity ( g(H²O)/kg(air) )
//MR: g[H2O]/kg[dry air]
//Hs: g(H²O)/kg(air)
double MR2Hs(double MR)
{
return 1000 * (MR / (1000 * (1 + MR / 1000)));//Mixing ratio to Specific humidity [ g(H²O)/kg(air) ]
}
//specific humidity ( g(H²O)/kg(air) ) to mixing ratio ( g[H2O]/kg[dry air] )
//Hs: specific humidity g(H²O)/kg(air)
//MR: mixing ratio g[H2O]/kg[dry air]
double Hs2MR(double Hs)
{
return 1000 * (Hs / (1000 * (1 - Hs / 1000))); //specific humidity g(H²O)/kg(air) to mixing ratio g[H2O]/kg[dry air]
}
//Relative humidity [%] to specific humidity [ g(H²O)/kg(air) ]
//From wikipedia : http://en.wikipedia.org/wiki/Humidity
//validation was made with RH WMO without correction of the site : http://www.humidity-calculator.com/index.php
//and also http://www.cactus2000.de/uk/unit/masshum.shtml
//Tair: Dry bulb temperature [°C]
//Hr: Relative humidity WMO (over water) [%]
//altitude: altitude [m]
double Hr2Hs(double Tair, double Hr)
{
_ASSERTE(Hr >= 0 && Hr <= 100);
double Pv = Hr2Pv(Tair, Hr);
return Pv2Hs(Pv);
//double Psat = GetPsat(Tair);//Vapor pressure of water [Pa]
//double Pv = Psat*Hr/100; //Vapor pressure [Pa]
//double MR = M*Pv/(P-Pv);//Mixing ratio [ kg[H2O]/kg[dry air] ]
//double Hs = MR/(1+MR);//Mixing ratio to Specific humidity [ kg(H²O)/kg(air) ]
//return Hs*1000; //convert to [ g(H²O)/kg(air) ]
}
//hourly specific humidity [ g(H²O)/kg(air) ] to relative humidity [%]
//Tair: air temperature °C
//Hs: specific humidity g(H²O)/kg(air)
double Hs2Hr(double Tair, double Hs)
{
_ASSERTE(Hs > 0);
double Pv = Hs2Pv(Hs);
return Pv2Hr(Tair, Pv);
}
//daily specific humidity [ g(H²O)/kg(air) ] to relative humidity [%]
//Tmin: Daily minimum air temperature °C
//Tmax: Daily maximum air temperature °C
//Hs: Specific humidity g(H²O)/kg(air)
double Hs2Hr(double Tmin, double Tmax, double Hs)
{
_ASSERTE(Hs > 0);
double Pv = Hs2Pv(Hs);
return Pv2Hr(Tmin, Tmax, Pv);
}
//Daily relative humidity [%] to specific humidity [ g(H²O)/kg(air) ]
//Tmin: Daily minimum air temperature °C
//Tmax: Daily maximum air temperature °C
//Hr: Relative humidity (over water) [%]
double Hr2Hs(double Tmin, double Tmax, double Hr)
{
_ASSERTE(Hr >= 0 && Hr <= 100);
double Pv = Hr2Pv(Tmin, Tmax, Hr);
return Pv2Hs(Pv);
}
//Pv : vapor pressure [Pa]
double Pv2Hr(double Tair, double Pv)
{
double Psat = eᵒ(Tair) * 1000;//kPa --> Pa
double Hr = 100 * Pv / Psat;
return max(0.0, min(100.0, Hr));
}
//Tair: air temperature [°C]
//Hr: relativce humidity [%]
//Pv : vapor pressure [Pa]
double Hr2Pv(double Tair, double Hr)
{
ASSERT(Hr >= 0 && Hr <= 100);
double Psat = eᵒ(Tair) * 1000;//kPa --> Pa
double Pv = Psat * Hr / 100.0;
return Pv;
}
double Pv2Hr(double Tmin, double Tmax, double Pv)
{
double Psat = eᵒ(Tmin, Tmax) * 1000;//kPa --> Pa
double Hr = 100 * Pv / Psat;
return max(0.0, min(100.0, Hr));
}
//Tmin: Daily minimum air temperature [°C]
//Tmax: Daily maximum air temperature [°C]
//Hr: Relative humidity [%]
double Hr2Pv(double Tmin, double Tmax, double Hr)
{
ASSERT(Hr >= 0 && Hr <= 100);
double Psat = eᵒ(Tmin, Tmax) * 1000;//kPa --> Pa
double Pv = Hr * Psat / 100;
return Pv;
}
//Pv2Hs: vapor pressure [Pa] to Specific Humidity (g(H²O)/kg(air))
//Pv: partial pressure of water vapor in moist air [Pa]
double Pv2Hs(double Pv)
{
double P = 101325;//[Pa]
double Hs = (M*Pv) / (P - Pv * (1 - M));
ASSERT(Hs >= 0);
return Hs * 1000;//Convert to g(H²O)/kg(air)
}
//Pv2Hs: vapor pressure ([Pa]) to Specific Humidity ( g(H²O)/kg(air) )
//Pv: partial pressure of water vapor in moist air [Pa]
//Excel formala: = (101325 * (Hs/1000)) / (0.6220135 + (Hs /1000 )* (1 - 0.6220135))
double Hs2Pv(double Hs)
{
double P = 101325;//Pa
Hs /= 1000;//Convert to kg(H²O)/kg(air)
double Pv = (P*Hs) / (M + Hs * (1 - M));
return Pv;
}
//Tair: dry bulb air temperature [°C]
//Hs: specific humidity ( g(H²O)/kg(air) )
//Out: Dew point temperature [°C]
double Hs2Td(double Tair, double Hs)
{
double Hr = Hs2Hr(Tair, Hs);
return Hr2Td(Tair, Hr);
}
//Tair: dry bulb air temperature [°C]
//Tdew: dewpoint temperature [°C]
double Td2Hs(double Tair, double Tdew)
{
double Hr = Td2Hr(Tair, Tdew);
return Hr2Hs(Tair, Hr);
}
//Wet-Bulb Temperature from Relative Humidity and Air Temperature
//Roland Stull
//University of British Columbia, Vancouver, British Columbia, Canada
//T: dry air temperature [°C]
//Hr: relativce humidity [%]
//Twb: wet bulb temperature [°C]
double Hr2Twb(double T, double RH)
{
ASSERT(RH >= 0 && RH <= 100);
double Twb = T * atan(0.151977*sqrt(RH + 18.313659)) + atan(T + RH) - atan(RH - 1.676331) + 0.00391838*pow(RH, 3.0 / 2)*atan(0.023101*RH) - 4.686035;
return Twb;
}
//Relative humidity from temperature and wet bulb temperature
//Tair: dry bulb temperature of air [°C]
//Twet : wet bulb temperature [°C]
double Twb2Hr(double Tair, double Twet)
{
static const double Cp = 1.005; //specific heat of dry air at constant pressure(J/g) ~1.005 J/g
static const double Cpv = 4.186; //specific heat of water vapor at constant pressure(J/g) ~4.186 J/g
static const double P = 1013; //atmospheric pressure at surface ~1013 mb at sea-level
//Latent heat of vaporization(J/g) ~2500 J/g
double Lv = GetL(Tair) / 1000;
//saturation vapor pressure at the wet bulb temperature(hPa)
double Eswb = 6.11*pow(10.0, 7.5*Twet / (237.7 + Twet));
//If you know the air temperature and the wet bulb temperature, you first want to calculate the actual mixing ratio of the air(W) using the following formula.
//W=actual mixing ratio of air
//(12) W=[(Tair-Twb)(Cp)-Lv(Eswb/P)]/[-(Tc-Twb)(Cpv)-Lv]
double W = ((Tair - Twet)*Cp - Lv * (Eswb / P)) / (-(Tair - Twet)*Cpv - Lv);
//Once you have the actual vapor pressure, you can use the following formula to calculate the saturation mixing ratio for the air.
//(13) Ws=Es/P
double Es = 6.11*pow(10.0, 7.5*Tair / (237.7 + Tair));
double Ws = Es / P;
//Once you have the actual mixing ratio and the saturation mixing ratio, you can use the following formula to calculate relative humidity.
//(14) Relative Humidity(RH) in percent=(W/Ws)*100
double RH = (W / Ws) * 100;
//Note: The latent heat of vaporization(Lv) varies slightly with temperature. The value given above is an approximate value for the standard atmosphere at 0 degrees Celsius.
//Note: Due to the large numbers of approximations using these formulas, your final answer may vary by as much as 10 percent.
return RH;
}
//alt : altitude [m]
//P : normal atmoshpheric pressure [Pa]
double GetPressure(double alt)
{
// daily atmospheric pressure (Pa) as a function of elevation (m)
// From the discussion on atmospheric statics in:
// Iribane, J.V., and W.L. Godson, 1981. Atmospheric Thermodynamics, 2nd
// Edition. D. Reidel Publishing Company, Dordrecht, The Netherlands. (p. 168)
static const double MA = 28.9644e-3; // (kg mol-1) molecular weight of air
static const double R = 8.3143; // (m3 Pa mol-1 K-1) gas law constant
static const double LR_STD = 0.0065; // (-K m-1) standard temperature lapse rate
static const double G_STD = 9.80665; // (m s-2) standard gravitational accel.
static const double P_STD = 101325.0; // (Pa) standard pressure at 0.0 m elevation
static const double T_STD = 288.15; // (K) standard temp at 0.0 m elevation
double t1 = 1.0 - (LR_STD * alt) / T_STD;
double t2 = G_STD / (LR_STD * (R / MA));
double P = P_STD * pow(t1, t2);
return P;
}
//P : normal atmoshpheric pressure [Pa]
//alt : altitude [m]
double GetAltitude(double P)
{
// daily atmospheric pressure (Pa) as a function of elevation (m)
// From the discussion on atmospheric statics in:
// Iribane, J.V., and W.L. Godson, 1981. Atmospheric Thermodynamics, 2nd
// Edition. D. Reidel Publishing Company, Dordrecht, The Netherlands. (p. 168)
static const double MA = 28.9644e-3; // (kg mol-1) molecular weight of air
static const double R = 8.3143; // (m3 Pa mol-1 K-1) gas law constant
static const double LR_STD = 0.0065; // (-K m-1) standard temperature lapse rate
static const double G_STD = 9.80665; // (m s-2) standard gravitational accel.
static const double P_STD = 101325.0; // (Pa) standard pressure at 0.0 m elevation
static const double T_STD = 288.15; // (K) standard temp at 0.0 m elevation
double t2 = G_STD / (LR_STD * (R / MA));
double t1 = pow(P / P_STD, 1 / t2);
double alt = (1.0 - t1)*T_STD / LR_STD;
return alt;
}
double GetPolarInterpol(double T0, double T1, double T2, double h)
{
double Tair = 0;
if (h < 12)
{
Tair = T0 + h * (T1 - T0) / 11.0;
}
else
{
Tair = T1 + (h - 12)*(T2 - T1) / 11.0;
}
return Round(Tair, 1);
}
double GetPolarSummer(double Tmin[3], double Tmax[3], double h)
{
return WBSF::GetDoubleSine(Tmin, Tmax, h, 05, 16);
}
double GetPolarWinter(double Tmin[3], double Tmax[3], double h)
{
double Tair[3] = { (Tmin[0] + Tmax[0]) / 2, (Tmin[1] + Tmax[1]) / 2, (Tmin[2] + Tmax[2]) / 2 };
double T[3] =
{
(Tair[0] < Tair[1]) ? Tmin[1] : Tmax[1],
(Tair[0] < Tair[1]) ? Tmax[1] : Tmin[1],
(Tair[1] < Tair[2]) ? Tmin[2] : Tmax[2],
};
return GetPolarInterpol(T[0], T[1], T[2], h);
}
// original from Parton (1981), corrected by Brandsma (2006)
//from : Application of nearest-neighbor resampling for homogenizing temperature records on a daily to sub - daily level
//Brandsma (2006)
double GetSineExponential(double Tmin[3], double Tmax[3], double t, double Tsr, double Tss, size_t method)
{
ASSERT(method < NB_SINE_EXP);
double Tair = 0;
double D = Tss - Tsr;
if (D > 22)
{
//because of the correction, SineExponential can be use when day is 24 hour
//we used Ebrs instead
Tair = WBSF::GetSinePower(Tmin, Tmax, t, Tsr, Tss);
}
else
{
//Tsr = ceil(Tsr);
//Tss = floor(Tss);
//Tsr = floor(Tsr);
//Tss = ceil(Tss);
//Tsr = Round(Tsr);
//Tss = Round(Tss);
//D = Tss - Tsr;
static const double ALPHA[NB_SINE_EXP] = { 2.59, 1.86 };
static const double BETA[NB_SINE_EXP] = { 1.55, 0.00 };
static const double GAMMA[NB_SINE_EXP] = { 2.20, 2.20 };
double alpha = ALPHA[method];
double beta = BETA[method];
double gamma = GAMMA[method];
//double Tn = Tsr;// +beta;
if (t < Tsr)
{
//compute temperature at nightime before midnight
//double fs = D / (D + 2 * a);
double fs = (Tss - Tsr - beta) / (D + 2 * (alpha - beta));
assert(sin(PI*fs) >= 0);
double Tsun = float(Tmin[0] + (Tmax[0] - Tmin[0])*sin(PI*fs));
double f = min(0.0, -gamma * (t + 24 - Tss) / (24 - D + beta));
double fo = min(0.0, -gamma * (Tsr + 24 - Tss) / (24 - D + beta));
//double f = min(0.0, -b*(t + 24 - Tss) / (24 - D));
//double f° = min(0.0, -b*(Tsr + 24 - Tss) / (24 - D));
double rho = (Tmin[1] - Tsun * exp(fo)) / (1 - exp(fo));
Tair = rho + (Tsun - rho)*exp(f);
ASSERT(Tair >= rho || Tair >= Tsun);
ASSERT(f <= 0);
ASSERT(f <= 0);
}
else if (t <= Tss)
{
//compute daylight (equation 3a)
double f = max(0.0, (t - Tsr - beta) / (D + 2 * (alpha - beta)));
//double f = (t - Tsr) / (D + 2 * a);
assert(sin(PI*f) >= 0);
Tair = Tmin[1] + (Tmax[1] - Tmin[1])*sin(PI*f);
ASSERT(Tair >= Tmin[1]);
}
else //compute nightime (equation 1)
{
double fs = (Tss - Tsr - beta) / (D + 2 * (alpha - beta));
//double fs = D / (D + 2 * a);
assert(sin(PI*fs) >= 0);
double Tsun = Tmin[1] + (Tmax[1] - Tmin[1])*sin(PI*fs);
double f = min(0.0, -gamma * (t - Tss) / (24 - D + beta));
double fo = min(0.0, -gamma * (Tsr + 24 - Tss) / (24 - D + beta));
//double f = min(0.0, -b*(t - Tss) / (24 - D));
//double f° = min(0.0, -b*(Tsr + 24 - Tss) / (24 - D));
ASSERT(f <= 0 && fo <= 0);
double rho = (Tmin[2] - Tsun * exp(fo)) / (1 - exp(fo));
Tair = rho + (Tsun - rho)*exp(f);
ASSERT(Tair >= rho || Tair >= Tsun);
}
}
return Round(Tair, 1);
}
double GetErbs(double Tmin[3], double Tmax[3], double t)
{
size_t i = t < 14 ? 1 : 2;
size_t ii = t < 05 ? 0 : 1;
double Tmin² = Tmin[i];
double Tmax² = Tmax[ii];
double mean = (Tmin² + Tmax²) / 2;
double range = Tmax² - Tmin²;
double a = 2 * PI*t / 24;
double c = 0.4632*cos(a - 3.805) + 0.0984*cos(2 * a - 0.36) + 0.0168*cos(3 * a - 0.822) + 0.0138*cos(4 * a - 3.513);
double Tair = mean + range * c;
return Round(Tair, 1);
}
double GetSinePower(double Tmin[3], double Tmax[3], double t, double Tsr, double Tss)
{
double Tair = 0;
double D = Tss - Tsr;
//Tsr = Round(Tsr);
//Tss = Round(Tss);
//Tsr = ceil(Tsr);
//Tss = floor(Tss);
//D = Tss - Tsr;
static const double a = 1.86;//savage2015
static const double b = 1.0 / 2.0;
//compute nightime (modified equation 1)
if (t < Tsr || t > Tss)
{
size_t i = t < Tsr ? 0 : 1;
size_t ii = t < Tsr ? 1 : 2;
double fs = D / (D + 2 * a);
assert(sin(PI*fs) >= 0);
double Tsun = float(Tmin[i] + (Tmax[i] - Tmin[i])*sin(PI*fs));
if (t < Tsr)
t += 24;
double f = max(0.0, (t - Tss) / (24 - D));
Tair = Tsun + (Tmin[ii] - Tsun)*pow(f, b);
ASSERT(Tair >= Tmin[ii] || Tair >= Tsun);
}
else
{
double f = (t - Tsr) / (D + 2 * a);
assert(sin(PI*f) >= 0);
Tair = Tmin[1] + (Tmax[1] - Tmin[1])*sin(PI*f);
ASSERT(Tair >= Tmin[1]);
}
//else //compute nightime (equation 1)
//{
// double fs = D / (D + 2 * a);
// assert(sin(PI*fs) >= 0);
// double Tsun = Tmin[1] + (Tmax[1] - Tmin[1])*sin(PI*fs);
// double f = max(0.0, (t - Tss) / (24 - D));
// Tair = Tsun + (Tmin[2] - Tsun)*pow(f, 1.0 / 2);
// ASSERT(Tair >= Tmin[2] || Tair >= Tsun);
//}
//}
return Round(Tair, 1);
}
//compute AllenWave temperature for one hour
double GetDoubleSine(double Tmin[3], double Tmax[3], double h, double hourTmin, double hourTmax)
{
_ASSERTE(hourTmin < hourTmax);
//force to arrive on extrem
if (fabs(h - hourTmin) <= 0.5)
h = hourTmin;
if (fabs(h - hourTmax) <= 0.5)
h = hourTmax;
size_t i = h < hourTmin ? 0 : 1;
size_t ii = h <= hourTmax ? 1 : 2;
double Tmax² = Tmax[i];
double Tmin² = Tmin[ii];
double mean = (Tmin² + Tmax²) / 2;
double range = Tmax² - Tmin²;
//double theta = ((int)h - time_factor)*r_hour;
double theta = 0;
if (h >= hourTmin && h <= hourTmax)
{
//from Tmin to Tmax
//size_t hh = (24 + h - hourTmin) % 24;
double hh = h - hourTmin;
double nbh = hourTmax - hourTmin;
theta = PI * (-0.5 + hh / nbh);
}
else
{
//From Tmax to Tmin
//size_t hh = (24 + h - hourTmax) % 24;
if (h < hourTmax)
h += 24;
double hh = h - hourTmax;
double nbh = 24 - (hourTmax - hourTmin);
theta = PI * (0.5 - hh / nbh);
}
//round at .1
return Round(mean + range / 2 * sin(theta), 1);
}
//mean_sea_level to atmospheric pressure (at elevation)
//po : mean sea level [kPa]
double msl2atp(double po, double h)
{
//https://en.wikipedia.org/wiki/Atmospheric_pressure
static const double M = 28.9644e-3; // (kg mol-1) molecular weight of air
static const double R = 8.3143; // (m3 Pa mol-1 K-1) gas law constant
static const double L = 0.0065; // (K/m) standard temperature lapse rate
static const double g = 9.80665; // (m s-2) standard gravitational accel.
static const double To = 288.15; // (K) standard temp at 0.0 m elevation
const double a = 1 - (L*h) / To;
const double b = (g*M) / (R*L);
return po * pow(a, b);
//return 1013 * pow((293 - 0.0065*elev) / 293, 5.26);//pressure at elevation [hPa] or [mbar]
}
//p : atmospheric pressure [kPa]
double atp2msl(double p, double h)
{//https://en.wikipedia.org/wiki/Atmospheric_pressure
static const double M = 28.9644e-3; // (kg mol-1) molecular weight of air
static const double R = 8.3143; // (m3 Pa mol-1 K-1) gas law constant
static const double L = 0.0065; // (K/m) standard temperature lapse rate
static const double g = 9.80665; // (m s-2) standard gravitational accel.
static const double To = 288.15; // (K) standard temp at 0.0 m elevation
const double a = 1 - (L*h) / To;
const double b = (g*M) / (R*L);
return p / pow(a, b);
}
//Constants:
//NL = 6.0221415·1023 mol-1 Avogadro constant NIST
//R = 8.31447215 J mol-1 K-1 Universal gas constant NIST
//MH2O = 18.01534 g mol-1 molar mass of water
//Mdry 28.9644 g mol-1 molar mass of dry air
//http://www.gorhamschaffler.com/humidity_formulas.htm
//E: actual vapor pressure(kPa)
//double GetTd(double E)
//{
// double Td=(-430.22+237.7*log(E*10))/(-log(E*10)+19.08);
// return Td;
////}
//\begin{ align }P_{ s:m }(T) &= a\exp\bigg(\left(b - \frac{ T }{d}\right)\left(\frac{ T }{c + T}\right)\bigg); \\[8pt]
//\gamma_m(T, R\!H) &= \ln\Bigg(\frac{ R\!H }{100}\exp
//\bigg(\left(b - \frac{ T }{d}\right)\left(\frac{ T }{c + T}\right)\bigg)
//\Bigg); \\
//T_{ dp } &= \frac{ c\gamma_m(T, R\!H) }{b - \gamma_m(T, R\!H)}; \end{ align }
//(where \scriptstyle{
//a = 6.1121 [hKa]
//b = 18.678
//c = 257.14 [°C]
//d = 234.5 [°C]
//There are several different constant sets in use.The ones used in NOAA's
//*******************************************************************
//Randomize
void Randomize(unsigned rand)
{
//time_t t;
//srand((unsigned) time(&t));
if (rand == unsigned(0))
srand((unsigned)time(NULL));
else
srand((unsigned)rand);
}
//returns a double on the interval [0,1]
/*double Randu(void)
{
double u,x;
x = (double) rand();
u = x/RAND_MAX;
_ASSERTE ((u>=0)&&(u<=1));
return u;
}*/
//returns a double on the interval
//[0,1] : rand()/RAND_MAX
//]0,1] : (rand()+1)/(RAND_MAX+1)
//[0,1[ : rand()/(RAND_MAX+1)
//]0,1[ : (rand()+1)/(RAND_MAX+2)
double Randu(bool bExcLower, bool bExcUpper)
{
double numerator = (double)rand();
double denominator = (double)RAND_MAX;
if (bExcLower)
{
numerator++;
denominator++;
}
if (bExcUpper)
denominator++;
double u = numerator / denominator;
_ASSERTE(bExcLower || (u >= 0));
_ASSERTE(!bExcLower || (u > 0));
_ASSERTE(bExcUpper || (u <= 1));
_ASSERTE(!bExcUpper || (u < 1));
return u;
}
//special case of randu
double RanduExclusif(void)
{
return Randu(true, true);
}
//returns an integer on the range [0,num]
int Rand(int num)
{
double x = (num + 1)*Randu(false, true);
return (int)x;
}
//returns an integer on the interval [l,u] or [l,u[ or ]l,u] or ]l,u[
int Rand(int l, int u)
{
if (l > u)
Switch(l, u);
_ASSERTE(l <= u);
//get a number [0, u-l] and add l
return l + Rand(u - l);
}
double Rand(double l, double u)
{
if (l > u)
Switch(l, u);
_ASSERTE(l <= u);
//get a number [0, u-l] and add l
return l + (u - l)*Randu();
}
double RandNormal(const double x, const double s)
{
return x + (zScore()*s);
}
double RandLogNormal(double x, double s)
{
return exp(RandNormal(x - Square(s) / 2.0, s));
}
/**************************
* erf.cpp
* author: Steve Strand
* written: 29-Jan-04
***************************/
//#include <iostream.h>
//#include <iomanip.h>
//#include <strstream.h>
//#include <math.h>
/*
static const double rel_error= 1E-12; //calculate 12 significant figures
//you can adjust rel_error to trade off between accuracy and speed
//but don't ask for > 15 figures (assuming usual 52 bit mantissa in a double)
double erf(double x)
//erf(x) = 2/sqrt(pi)*integral(exp(-t^2),t,0,x)
// = 2/sqrt(pi)*[x - x^3/3 + x^5/5*2! - x^7/7*3! + ...]
// = 1-erfc(x)
{
static const double two_sqrtpi= 1.128379167095512574; // 2/sqrt(pi)
if (fabs(x) > 2.2) {
return 1.0 - erfc(x); //use continued fraction when fabs(x) > 2.2
}
double sum= x, term= x, xsqr= x*x;
int j= 1;
do {
term*= xsqr/j;
sum-= term/(2*j+1);
++j;
term*= xsqr/j;
sum+= term/(2*j+1);
++j;
} while (fabs(term)/sum > rel_error);
return two_sqrtpi*sum;
}
double erfc(double x)
//erfc(x) = 2/sqrt(pi)*integral(exp(-t^2),t,x,inf)
// = exp(-x^2)/sqrt(pi) * [1/x+ (1/2)/x+ (2/2)/x+ (3/2)/x+ (4/2)/x+
// = 1-erf(x)
//expression inside [] is a continued fraction so '+' means add to denominator only
{
static const double one_sqrtpi= 0.564189583547756287; // 1/sqrt(pi)
if (fabs(x) < 2.2) {
return 1.0 - erf(x); //use series when fabs(x) < 2.2
}
//if (signbit(x)) { //continued fraction only valid for x>0
if (x>-DBL_MAX && x<-DBL_MIN) {
return 2.0 - erfc(-x);
}
double a=1, b=x; //last two convergent numerators
double c=x, d=x*x+0.5; //last two convergent denominators
double q1=0,q2=b/d; //last two convergents (a/c and b/d)
double n= 1.0, t;
do {
t= a*n+b*x;
a= b;
b= t;
t= c*n+d*x;
c= d;
d= t;
n+= 0.5;
q1= q2;
q2= b/d;
} while (fabs(q1-q2)/q2 > rel_error);
return one_sqrtpi*exp(-x*x)*q2;
}
*/
static const double rel_error = 1E-12; //calculate 12 significant figures
//you can adjust rel_error to trade off between accuracy and speed
//but don't ask for > 15 figures (assuming usual 52 bit mantissa in a double)
double erf(double x)
//erf(x) = 2/sqrt(pi)*integral(exp(-t^2),t,0,x)
// = 2/sqrt(pi)*[x - x^3/3 + x^5/5*2! - x^7/7*3! + ...]
// = 1-erfc(x)
{
static const double two_sqrtpi = 1.128379167095512574; // 2/sqrt(pi)
if (fabs(x) > 2.2) {
return 1.0 - erfc(x); //use continued fraction when fabs(x) > 2.2
}
double sum = x, term = x, xsqr = x * x;
int j = 1;
do {
term *= xsqr / j;
sum -= term / (2 * j + 1);
++j;
term *= xsqr / j;
sum += term / (2 * j + 1);
++j;
} while (fabs(term / sum) > rel_error); // CORRECTED LINE
return two_sqrtpi * sum;
}
double erfc(double x)
//erfc(x) = 2/sqrt(pi)*integral(exp(-t^2),t,x,inf)
// = exp(-x^2)/sqrt(pi) * [1/x+ (1/2)/x+ (2/2)/x+ (3/2)/x+ (4/2)/x+ ...]
// = 1-erf(x)
//expression inside [] is a continued fraction so '+' means add to denominator only
{
static const double one_sqrtpi = 0.564189583547756287; // 1/sqrt(pi)
if (fabs(x) < 2.2) {
return 1.0 - erf(x); //use series when fabs(x) < 2.2
}
if (x > -DBL_MAX && x < -DBL_MIN) { //continued fraction only valid for x>0
return 2.0 - erfc(-x);
}
double a = 1, b = x; //last two convergent numerators
double c = x, d = x * x + 0.5; //last two convergent denominators
double q1, q2 = b / d; //last two convergents (a/c and b/d)
double n = 1.0, t;
do {
t = a * n + b * x;
a = b;
b = t;
t = c * n + d * x;
c = d;
d = t;
n += 0.5;
q1 = q2;
q2 = b / d;
} while (fabs(q1 - q2) / q2 > rel_error);
return one_sqrtpi * exp(-x * x)*q2;
}
/*double TestExposure(double latDeg, double slopeDeg, double aspectDeg)
{
ASSERT( latDeg>=-90 && latDeg<=90);
ASSERT( slopeDeg>=0 && slopeDeg<=90);
ASSERT( aspectDeg>=0 && aspectDeg<=360);
double latitude = Deg2Rad(latDeg);
double slope = Deg2Rad(slopeDeg);
double aspect = Deg2Rad(180-aspectDeg);
double SRI = cos(latitude)*cos(slope) + sin(latitude)*sin(slope)*cos(aspect);
return SRI;
}
*/
double GetExposition(double latDeg, double slopePourcent, double aspectDeg)
{
double SRI = 0;
if (slopePourcent != -999 && aspectDeg != -999 && slopePourcent != 0 && aspectDeg != 0)
{
double slopeDeg = Rad2Deg(atan(slopePourcent / 100));
ASSERT(latDeg >= -90 && latDeg <= 90);
ASSERT(slopeDeg >= 0 && slopeDeg <= 90);
ASSERT(aspectDeg >= 0 && aspectDeg <= 360);
double latitude = Deg2Rad(latDeg);
double slope = Deg2Rad(slopeDeg);
double aspect = Deg2Rad(180 - aspectDeg);
SRI = cos(latitude)*cos(slope) + sin(latitude)*sin(slope)*cos(aspect);
}
return SRI;
//********************************
// _ASSERTE( slopePourcent >= 0);
// _ASSERTE(aspect >= 0 && aspect <= 360);
//
// //Sin et cos carré
// double cosLat² = Square(cos(lat*DEG2RAD));
// double sinLat² = Square(sin(lat*DEG2RAD));
//
//// double fPente = DEG_PER_RAD * asin( fPentePourcent / 100 );
// //slope in degree
// double slope = RAD2DEG*atan( slopePourcent/100 );
// ASSERT( slope == Rad2Deg(atan( slopePourcent/100 )) );
// ASSERT(slope>=0 && slope<=90 );
//
//
// int nPhi = ((aspect < 135) || (aspect >= 255))?1:-1;
//
// return slope*(cosLat²*nPhi + sinLat²*cos((aspect - 15)*DEG2RAD));
}
void ComputeSlopeAndAspect(double latDeg, double exposition, double& slopePourcent, double& aspect)
{
//double fCosLat2 = cos(Deg2Rad(lat)); fCosLat2 *= fCosLat2;
//double fSinLat2 = sin(Deg2Rad(lat)); fSinLat2 *= fSinLat2;
double slope = 0;
int nbRun = 0;
if (latDeg != 0)
{
double latitude = Deg2Rad(latDeg);
aspect = -1;
//double slope = 0;
double denominateur = 0;
do
{
slope = Rand(0.0, 89.0);
slope = Deg2Rad(slope);
//aspect = (float)Rand(0.0, 360.0);
//int nPhi = ((aspect < 135) || (aspect >= 255))?1:-1;
//_ASSERT(false); // a revoir avex la nouvelle exposition
//denominateur = (fCosLat2*nPhi + fSinLat2*cos(Deg2Rad(aspect - 15)));
denominateur = sin(latitude)*sin(slope);
if (denominateur != 0)
{
double tmp = (exposition - cos(latitude)*cos(slope)) / denominateur;
if (tmp >= -1 && tmp <= 1)
{
aspect = float(180 - Rad2Deg(acos(tmp)));
//slopePourcent = (float)tan( slope )*100;
//double test = GetExposition(latDeg, slopePourcent, aspect);
}
}
//else
//{
//aspect can be anything
//aspect = 0;
//}
//slope = exposition/denominateur;
nbRun++;
} while (nbRun < 500 && (denominateur == 0 || aspect < 0 || aspect>359));
if (nbRun == 500)
{
slope = 0;
aspect = 0;
}
}
else
{
ASSERT(exposition >= -1 && exposition <= 1);
slope = acos(exposition);
}
//fPentePourcent = (float)sin( fPente/DEG_PER_RAD )*100;
slopePourcent = (float)tan(slope) * 100;
_ASSERTE(slopePourcent >= 0);//&& fPentePourcent <= 100 );
_ASSERTE(nbRun == 500 || fabs(exposition - GetExposition(latDeg, slopePourcent, aspect)) < 0.001);
}
double GetDistance(double lat1, double lon1, double lat2, double lon2)
{
double angle = 0;
if (lat1 != lat2 || lon1 != lon2)
{
double P = (fabs(lon2 - lon1) <= 180) ? (lon2 - lon1) : (360.0 - fabs(lon2 - lon1));
double cosA = sin(lat1*DEG2RAD)*sin(lat2*DEG2RAD) + cos(lat1*DEG2RAD)*cos(lat2*DEG2RAD)*cos(P*DEG2RAD);
angle = acos(std::max(-1.0, std::min(1.0, cosA)));
}
return angle * 6371 * 1000;
}
bool IsValidSlopeWindow(float window[3][3], double noData)
{
int nbNoData = 0;
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
{
if (window[y][x] <= noData)
{
nbNoData++;
window[y][x] = window[1][1];
}
}
}
//We don't need the center cell to compute slope and aspect
//then if it's only the center cell that are missing we return true anyway
return window[1][1] > noData || nbNoData == 1;
}
void GetSlopeAndAspect(float window[3][3], double ewres, double nsres, double scale, double& slope, double& aspect)
{
//slope = 0;
//aspect = 0;
//if( !IsValidSlopeWindow(window) )
//return;
double dx = ((window[0][2] + window[1][2] + window[1][2] + window[2][2]) -
(window[0][0] + window[1][0] + window[1][0] + window[2][0])) / ewres;
double dy = ((window[0][0] + window[0][1] + window[0][1] + window[0][2]) -
(window[2][0] + window[2][1] + window[2][1] + window[2][2])) / nsres;
double key = (dx * dx + dy * dy);
slope = (float)(100 * (sqrt(key) / (8 * scale)));
aspect = (float)(atan2(dy, -dx) * RAD2DEG);
if (dx == 0 && dy == 0)
{
// lat area
aspect = 0;
}
else //transform from azimut angle to geographic angle
{
if (aspect > 90.0f)
aspect = 450.0f - aspect;
else
aspect = 90.0f - aspect;
}
if (aspect == 360.0)
aspect = 0.0f;
}
//**************************************************************
const double CMathEvaluation::EPSILON = 0.000001;
CMathEvaluation::CMathEvaluation(const char* strIn)
{
ASSERT(strIn != NULL);
string str(strIn);
size_t pos = str.find_first_not_of("!=<>");
ASSERT(pos >= 0);
m_op = GetOp(str.substr(0, pos));
m_value = ToValue<double>(str.substr(pos));
}
short CMathEvaluation::GetOp(const string& str)
{
short op = UNKNOWN;
if (str == "==")
op = EQUAL;
else if (str == "!=")
op = NOT_EQUAL;
else if (str == ">=")
op = GREATER_EQUAL;
else if (str == "<=")
op = LOWER_EQUAL;
else if (str == ">")
op = GREATER;
else if (str == "<")
op = LOWER;
return op;
}
bool CMathEvaluation::Evaluate(double value1, short op, double value2)
{
bool bRep = false;
switch (op)
{
case EQUAL: bRep = fabs(value1 - value2) < EPSILON; break;
case NOT_EQUAL: bRep = !Evaluate(value1, EQUAL, value2); break;
case GREATER_EQUAL: bRep = value1 >= value2; break;
case LOWER_EQUAL: bRep = value1 <= value2; break;
case GREATER: bRep = value1 > value2; break;
case LOWER: bRep = value1 < value2; break;
default: ASSERT(false);
}
return bRep;
}
//********************************************************************************************
void CBetaDistribution::SetTable(double alpha, double beta)
{
int i;
double tmp;
double sum_P = 0;
//Compute Beta cumulative probability distribution
m_XP[0].m_x = 0;
m_XP[0].m_p = 0;
for (i = 1; i <= 50; ++i)
{
tmp = (double)i / 50.;
m_XP[i].m_x = tmp;
if (i == 50) tmp = 0.995;
sum_P += pow(tmp, alpha - 1) * pow((1 - tmp), beta - 1);
m_XP[i].m_p = sum_P;
}
//Scale so P is [0,1]
for (i = 0; i <= 50; ++i)
{
m_XP[i].m_p /= sum_P;
}
}
double CBetaDistribution::XfromP(double p)const
{
_ASSERTE(p >= 0.0 && p <= 1.0);
double x = 0;
for (int i = 49; i >= 0; --i)
{
if (p > m_XP[i].m_p)
{
double slope = (m_XP[i + 1].m_x - m_XP[i].m_x) / (m_XP[i + 1].m_p - m_XP[i].m_p);
x = m_XP[i].m_x + (p - m_XP[i].m_p)* slope;
break;
}
}
ASSERT(!_isnan(x));
ASSERT(x >= 0);
return x;
}
double CSchoolfield::operator[](double T)const
{
const double R = 1.987;
double Tk = T + 273.15;
double a1 = m_p[PRHO25] * Tk / 298.15;
double a2 = exp(m_p[PHA] / R * (1 / 298.15 - 1 / Tk));
double b1 = exp(m_p[PHL] / R * (1 / m_p[PTL] - 1 / Tk));
double b2 = exp(m_p[PHH] / R * (1 / m_p[PTH] - 1 / Tk));
double r = (a1*a2) / (1 + b1 + b2);
ASSERT(r >= 0);
return r;
}
double CUnknown::operator[](double T)const
{
ASSERT(T >= -40 && T < 40);
double Fo = m_p[PA] + m_p[PB] * pow(fabs(T - m_p[PT0]), m_p[PX]);
return max(0.0, Fo);
}
/*unsigned int good_seed()
{
unsigned int random_seed, random_seed_a, random_seed_b;
std::ifstream file ("/dev/urandom", std::ios::binary);
if (file.is_open())
{
char * memblock;
int size = sizeof(int);
memblock = new char [size];
file.read (memblock, size);
file.close();
random_seed_a = *reinterpret_cast<int*>(memblock);
delete[] memblock;
}// end if
else
{
random_seed_a = 0;
}
random_seed_b = std::time(0);
random_seed = random_seed_a xor random_seed_b;
std::cout << "random_seed_a = " << random_seed_a << std::endl;
std::cout << "random_seed_b = " << random_seed_b << std::endl;
std::cout << " random_seed = " << random_seed << std::endl;
return random_seed;
} // end good_seed()
*/
void CRandomGenerator::Randomize(size_t seed)
{
if (seed == RANDOM_SEED)
{
static unsigned long ID = 1;
//seed = static_cast<unsigned long>(std::time(NULL)+ID*1000);
seed = static_cast<unsigned long>(__rdtsc() + ID * 1000);
ID++;
m_gen.seed((ULONG)seed);
}
else
{
m_gen.seed((ULONG)seed);
}
}
}//namespace WBSF | 27.407407 | 176 | 0.554741 | RNCan |
9ad6a8505f14e03c3def5a20acdd37af0be43ce6 | 2,092 | cpp | C++ | test/TestHelpers/ClangCompileHelper.cpp | ptensschi/CppUMockGen | d11f12297688f99863238b263f241b6e3ac66dfd | [
"BSD-3-Clause"
] | null | null | null | test/TestHelpers/ClangCompileHelper.cpp | ptensschi/CppUMockGen | d11f12297688f99863238b263f241b6e3ac66dfd | [
"BSD-3-Clause"
] | null | null | null | test/TestHelpers/ClangCompileHelper.cpp | ptensschi/CppUMockGen | d11f12297688f99863238b263f241b6e3ac66dfd | [
"BSD-3-Clause"
] | 1 | 2019-01-10T20:36:24.000Z | 2019-01-10T20:36:24.000Z | #include "ClangCompileHelper.hpp"
#include "ClangHelper.hpp"
#include <iostream>
bool ClangCompileHelper::CheckCompilation( const std::string &testedHeader, const std::string &testedSource )
{
#ifdef DISABLE_COMPILATION_CHECK
return true;
#else
CXIndex index = clang_createIndex( 0, 0 );
const char* clangOpts[] = { "-xc++", "-I" CPPUTEST_INCLUDE_DIR };
std::string compiledCode =
"#include <CppUTest/TestHarness.h>\n"
"#include <CppUTestExt/MockSupport.h>\n";
#ifdef INTERPRET_C
compiledCode += "extern \"C\" {";
#endif
compiledCode += testedHeader + "\n";
#ifdef INTERPRET_C
compiledCode += "}";
#endif
compiledCode += testedSource;
CXUnsavedFile unsavedFiles[] = { { "test_mock.cpp", compiledCode.c_str(), (unsigned long) compiledCode.length() } };
CXTranslationUnit tu = clang_parseTranslationUnit( index, "test_mock.cpp",
clangOpts, std::extent<decltype(clangOpts)>::value,
unsavedFiles, std::extent<decltype(unsavedFiles)>::value,
CXTranslationUnit_None );
if( tu == nullptr )
{
clang_disposeIndex( index );
throw std::runtime_error( "Error creating translation unit" );
}
unsigned int numDiags = clang_getNumDiagnostics(tu);
if( numDiags > 0 )
{
std::cerr << std::endl;
std::cerr << "---------------- Error compiling --------------" << std::endl;
std::cerr << compiledCode << std::endl;
std::cerr << "-----------------------------------------------" << std::endl;
for( unsigned int i = 0; i < numDiags; i++ )
{
CXDiagnostic diag = clang_getDiagnostic( tu, i );
std::cerr << clang_formatDiagnostic( diag, clang_defaultDiagnosticDisplayOptions() ) << std::endl;
clang_disposeDiagnostic( diag );
}
}
clang_disposeTranslationUnit( tu );
clang_disposeIndex( index );
return ( numDiags == 0 );
#endif
}
| 34.295082 | 121 | 0.5674 | ptensschi |
9adc96be6da2e72d5bbd72bc81c6703360f88afa | 2,076 | cpp | C++ | code/random/functions.cpp | adm244/mwsilver | d88ebb240095f0bd0adfe3cc983fa504d974ba83 | [
"Unlicense"
] | null | null | null | code/random/functions.cpp | adm244/mwsilver | d88ebb240095f0bd0adfe3cc983fa504d974ba83 | [
"Unlicense"
] | null | null | null | code/random/functions.cpp | adm244/mwsilver | d88ebb240095f0bd0adfe3cc983fa504d974ba83 | [
"Unlicense"
] | null | null | null | /*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
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 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.
*/
//IMPORTANT(adm244): SCRATCH VERSION JUST TO GET IT UP WORKING
#ifndef RANDOM_FUNCTIONS_CPP
#define RANDOM_FUNCTIONS_CPP
#include "random/randomlib.c"
internal int randomGenerated = 0;
internal uint8 randomCounters[MAX_BATCHES];
internal void RandomClearCounters()
{
randomGenerated = 0;
for( int i = 0; i < MAX_BATCHES; ++i ) {
randomCounters[i] = 0;
}
}
internal int GetNextBatchIndex(int batchesCount)
{
if( randomGenerated >= batchesCount ) {
RandomClearCounters();
}
int value;
for( ;; ) {
value = RandomInt(0, batchesCount - 1);
if( randomCounters[value] == 0 ) break;
}
++randomGenerated;
randomCounters[value] = 1;
return value;
}
internal void RandomGeneratorInitialize(int batchesCount)
{
int ticksPassed = GetTickCount();
int ij = ticksPassed % 31328;
int kj = ticksPassed % 30081;
RandomInitialize(ij, kj);
RandomClearCounters();
}
#endif
| 28.054054 | 71 | 0.753854 | adm244 |
9aea51745f3235fd439cd911bbe86c13eca10d38 | 12,965 | cpp | C++ | winmisc/shared/plugin.winmisc.cpp | ggcrunchy/solar2d-plugins | c3c9f41659ea64a1b04f992c3ca4b8549aa0dbe1 | [
"MIT"
] | 12 | 2020-05-04T08:49:04.000Z | 2021-12-30T09:35:17.000Z | winmisc/shared/plugin.winmisc.cpp | ggcrunchy/solar2d-plugins | c3c9f41659ea64a1b04f992c3ca4b8549aa0dbe1 | [
"MIT"
] | null | null | null | winmisc/shared/plugin.winmisc.cpp | ggcrunchy/solar2d-plugins | c3c9f41659ea64a1b04f992c3ca4b8549aa0dbe1 | [
"MIT"
] | 3 | 2021-02-19T18:39:02.000Z | 2022-03-09T17:14:57.000Z | /*
* 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.
*
* [ MIT license: http://www.opensource.org/licenses/mit-license.php ]
*/
#include "CoronaLua.h"
#include <windows.h>
#include <cstdlib>
#include <vector>
#define HWND_NAME "winmisc.window"
static HWND GetWindow (lua_State * L, int arg = 1)
{
return *(HWND *)luaL_checkudata(L, arg, HWND_NAME);
}
template<typename T>
int Box (lua_State * L, T item, const char * name)
{
if (item)
{
*static_cast<T *>(lua_newuserdata(L, sizeof(T))) = item; // ..., item
luaL_newmetatable(L, HWND_NAME);// ..., item, mt
lua_setmetatable(L, -2);// ..., item; item.metatable = mt
}
else lua_pushnil(L); // ..., nil
return 1;
}
static bool GetBytesFromBitmap (lua_State * L, HDC hdc, HBITMAP hBitmap)
{
BITMAPINFO info = {};
bool ok = false;
info.bmiHeader.biSize = sizeof(info.bmiHeader);
if (GetDIBits(hdc, hBitmap, 0, 0, nullptr, &info, DIB_RGB_COLORS))
{
// https://stackoverflow.com/a/3688682
std::vector<BYTE> bytes(info.bmiHeader.biSizeImage);
LONG abs_height = abs(info.bmiHeader.biHeight);
info.bmiHeader.biBitCount = 32;
info.bmiHeader.biCompression = BI_RGB;
info.bmiHeader.biHeight = -abs_height;
ok = GetDIBits(hdc, hBitmap, 0, abs_height, bytes.data(), &info, DIB_RGB_COLORS);
if (ok)
{
const BYTE * input = bytes.data();
LONG count = info.bmiHeader.biWidth * abs_height;
std::vector<BYTE> out(count * 3);
BYTE * output = out.data();
for (LONG i = 0; i < count; ++i)
{
output[0] = input[2];
output[1] = input[1];
output[2] = input[0];
output += 3;
input += 4;
}
lua_pushlstring(L, reinterpret_cast<char *>(out.data()), out.size()); // image
lua_pushinteger(L, info.bmiHeader.biWidth); // image, width
lua_pushinteger(L, abs_height); // image, width, height
}
}
ReleaseDC(NULL, hdc);
return ok;
}
static BOOL CALLBACK EnumWindowsProc (HWND window, LPARAM lparam)
{
lua_State * L = reinterpret_cast<lua_State *>(lparam);
lua_pushvalue(L, 1); // enumerator, enumerator
Box(L, window, HWND_NAME); // enumerator, enumerator, window
if (lua_pcall(L, 1, 1, 0) == 0) // enumerator, result? / err
{
lua_pushliteral(L, "done");// enumerator, result?, "done"
if (!lua_equal(L, 2, 3))
{
lua_pop(L, 2); // enumerator
return TRUE;
}
}
return FALSE;
}
CORONA_EXPORT int luaopen_plugin_winmisc (lua_State* L)
{
lua_newtable(L);// winmisc
luaL_Reg funcs[] = {
{
"CopyScreenToClipboard", [](lua_State * L)
{
// https://stackoverflow.com/a/28248531
int x = GetSystemMetrics(SM_XVIRTUALSCREEN);
int y = GetSystemMetrics(SM_YVIRTUALSCREEN);
int w = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int h = GetSystemMetrics(SM_CYVIRTUALSCREEN);
// copy screen to bitmap
HDC hScreen = GetDC(nullptr);
HDC hDC = CreateCompatibleDC(hScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h);
HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, x, y, SRCCOPY);
// save bitmap to clipboard
OpenClipboard(nullptr);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hBitmap);
CloseClipboard();
// clean up
SelectObject(hDC, old_obj);
DeleteDC(hDC);
ReleaseDC(nullptr, hScreen);
DeleteObject(hBitmap);
return 0;
}
}, {
"CopyWindowToClipboard", [](lua_State * L)
{
HWND window = GetWindow(L);
HDC hScreen = GetDC(window);
HDC hDC = CreateCompatibleDC(hScreen);
RECT rect;
GetWindowRect(window, &rect);
LONG w = rect.right - rect.left, h = rect.bottom - rect.top;
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h);
HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, rect.left, rect.top, SRCCOPY);
// save bitmap to clipboard
OpenClipboard(nullptr);
EmptyClipboard();
SetClipboardData(CF_BITMAP, hBitmap);
CloseClipboard();
// clean up
SelectObject(hDC, old_obj);
DeleteDC(hDC);
ReleaseDC(window, hScreen);
DeleteObject(hBitmap);
return 0;
}
}, {
"EnumerateDesktops", [](lua_State * L)
{
lua_settop(L, 1); // enumerator
luaL_argcheck(L, lua_isfunction(L, 1), 1, "Non-function desktop enumerator");
BOOL result = EnumDesktops(GetProcessWindowStation(), [](char * name, LPARAM state) {
lua_State * lstate = reinterpret_cast<lua_State *>(state);
lua_pushvalue(lstate, 1); // enumerator, enumerator
lua_pushstring(lstate, name); // enumerator, enumerator, name
if (lua_pcall(lstate, 1, 1, 0) == 0) // enumerator, result? / err
{
lua_pushliteral(lstate, "done");// enumerator, result?, "done"
if (!lua_equal(lstate, 2, 3))
{
lua_pop(lstate, 2); // enumerator
return TRUE;
}
}
return FALSE;
}, LONG_PTR(L));
lua_pushboolean(L, result); // enumerator[, result[, "done"]], ok
return 1;
}
}, {
"EnumerateDesktopWindows", [](lua_State * L)
{
lua_settop(L, 2); // name, enumerator
const char * name = luaL_checkstring(L, 1);
luaL_argcheck(L, lua_isfunction(L, 2), 2, "Non-function desktop window enumerator");
HDESK desktop = OpenDesktop(name, 0, FALSE, GENERIC_READ);
lua_remove(L, 1); // enumerator
BOOL result = !!desktop;
if (desktop)
{
result = EnumDesktopWindows(desktop, EnumWindowsProc, LONG_PTR(L));
CloseDesktop(desktop);
}
lua_pushboolean(L, result); // enumerator[, result[, "done"]], ok
return 1;
}
}, {
"EnumerateWindows", [](lua_State * L)
{
luaL_argcheck(L, lua_isfunction(L, 1), 1, "Non-function window enumerator");
BOOL result = EnumWindows(EnumWindowsProc, LONG_PTR(L));
lua_pushboolean(L, result); // enumerator[, result[, "done"]], ok
return 1;
}
}, {
"GetClipboardText", [](lua_State * L)
{
lua_settop(L, 0); // (empty)
BOOL ok = FALSE;
if (OpenClipboard(nullptr))
{
HANDLE hMem = GetClipboardData(CF_TEXT);
if (hMem)
{
void * data = GlobalLock(hMem);
if (data)
{
ok = TRUE;
lua_pushstring(L, (char *)data);// text
GlobalUnlock(hMem);
}
}
CloseClipboard();
}
lua_pushboolean(L, ok); // [text, ]ok
if (ok) lua_insert(L, -2); // ok, text
return lua_gettop(L);
}
}, {
"GetForegroundWindow", [](lua_State * L)
{
return Box(L, GetForegroundWindow(), HWND_NAME);
}
}, {
"GetImageDataFromClipboard", [](lua_State * L)
{
bool ok = false;
if (IsClipboardFormatAvailable(CF_BITMAP) && OpenClipboard(nullptr))
{
HDC hdc = GetDC(nullptr);
ok = GetBytesFromBitmap(L, hdc, (HBITMAP)GetClipboardData(CF_BITMAP));
CloseClipboard();
ReleaseDC(nullptr, hdc);
}
if (!ok) lua_pushboolean(L, 0); // false
return ok ? 3 : 1;
}
}, {
"GetImageDataFromScreen", [](lua_State * L)
{
int x = GetSystemMetrics(SM_XVIRTUALSCREEN);
int y = GetSystemMetrics(SM_YVIRTUALSCREEN);
int w = GetSystemMetrics(SM_CXVIRTUALSCREEN);
int h = GetSystemMetrics(SM_CYVIRTUALSCREEN);
// copy screen to bitmap
HDC hScreen = GetDC(nullptr);
HDC hDC = CreateCompatibleDC(hScreen);
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h);
HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, x, y, SRCCOPY);
bool ok = GetBytesFromBitmap(L, hDC, hBitmap);
// clean up
SelectObject(hDC, old_obj);
DeleteDC(hDC);
ReleaseDC(nullptr, hScreen);
DeleteObject(hBitmap);
if (!ok) lua_pushboolean(L, 0); // false
return ok ? 3 : 1;
}
}, {
"GetImageDataFromWindow", [](lua_State * L)
{
HWND window = GetWindow(L);
HDC hScreen = GetDC(window);
HDC hDC = CreateCompatibleDC(hScreen);
RECT rect;
GetWindowRect(window, &rect);
LONG w = rect.right - rect.left, h = rect.bottom - rect.top;
HBITMAP hBitmap = CreateCompatibleBitmap(hScreen, w, h);
HGDIOBJ old_obj = SelectObject(hDC, hBitmap);
BOOL bRet = BitBlt(hDC, 0, 0, w, h, hScreen, rect.left, rect.top, SRCCOPY);
bool ok = GetBytesFromBitmap(L, hDC, hBitmap);
// clean up
SelectObject(hDC, old_obj);
DeleteDC(hDC);
ReleaseDC(window, hScreen);
DeleteObject(hBitmap);
if (!ok) lua_pushboolean(L, 0); // false
return ok ? 3 : 1;
}
}, {
"GetWindowText", [](lua_State * L)
{
HWND window = GetWindow(L);
int len = GetWindowTextLength(window);
std::vector<char> str(len + 1);
GetWindowText(window, str.data(), len + 1);
lua_pushlstring(L, str.data(), size_t(len));// window, text
return 1;
}
}, {
"IsWindowVisible", [](lua_State * L)
{
lua_pushboolean(L, IsWindowVisible(GetWindow(L))); // window, is_visible
return 1;
}
}, {
"SetClipboardText", [](lua_State * L)
{
BOOL ok = FALSE;
if(OpenClipboard(nullptr))
{
if(EmptyClipboard())
{
HGLOBAL hMem = GlobalAlloc(GMEM_MOVEABLE, lua_objlen(L, 1) + 1);
memcpy(GlobalLock(hMem), lua_tostring(L, 1), lua_objlen(L, 1) + 1);
GlobalUnlock(hMem);
ok = SetClipboardData(CF_TEXT, hMem) != nullptr;
}
CloseClipboard();
}
lua_pushboolean(L, ok); // text, ok
return 1;
}
},
{ nullptr, nullptr }
};
luaL_register(L, nullptr, funcs);
return 1;
} | 30.650118 | 101 | 0.514925 | ggcrunchy |
9af2ffea551526586de0251519d1ae9fac9ae037 | 587 | cpp | C++ | String/MaximumOccurence.cpp | sanp9/DSA-Questions | f265075b83f66ec696576be3eaa5517ee387d5cf | [
"MIT"
] | null | null | null | String/MaximumOccurence.cpp | sanp9/DSA-Questions | f265075b83f66ec696576be3eaa5517ee387d5cf | [
"MIT"
] | null | null | null | String/MaximumOccurence.cpp | sanp9/DSA-Questions | f265075b83f66ec696576be3eaa5517ee387d5cf | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
void maxOccur(string str)
{
int freq[26] = {0};
char ans = 'a';
int maxF = 0;
for (int i = 0; i < str.length(); i++)
{
freq[str[i] - 'a']++;
} // for maintaining the count of occurrences of characters
for (int i = 0; i < 26; i++)
{
if (freq[i] > maxF)
{
maxF = freq[i];
ans = i + 'a';
}
}
cout << ans << endl;
cout << maxF << endl;
}
int main()
{
string str;
getline(cin, str);
maxOccur(str);
return 0;
}
| 15.447368 | 63 | 0.46678 | sanp9 |
9af73ce4c787f073abdfd54bc2461d8070e92fe4 | 5,009 | cpp | C++ | Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter17Exercise13Def.cpp | Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 9 | 2018-10-24T15:16:47.000Z | 2021-12-14T13:53:50.000Z | Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter17Exercise13Def.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | null | null | null | Visual Studio 2010/Projects/bjarneStroustrupC++PartIII/bjarneStroustrupC++PartIII/Chapter17Exercise13Def.cpp | ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup- | 6fd64801863e883508f15d16398744405f4f9e34 | [
"Unlicense"
] | 7 | 2018-10-29T15:30:37.000Z | 2021-01-18T15:15:09.000Z | /*
TITLE Linked list Chapter17Exercise13.cpp
"Bjarne Stroustrup "C++ Programming: Principles and Practice.""
COMMENT
Objcective: Modify Link to include struct God,
containing members of type string:
name, mythology, vehicle, weapon.
Write: print_all(), add_ordered() functions.
Input: -
Output: -
Author: Chris B. Kirov
Date: 07.12.2015
*/
// modifying member functions
/*
Member function: insert()
It inserts the new link
in before this object.
*/
Link* Link::insert (Link* n)
{
if (n == 0)
{
return this;
}
if (this == 0)
{
return n;
}
n->succ = this;
n->prev = prev;
if (prev)
{
prev->succ = n;
}
prev = n;
return n;
}
//------------------------------------------------------------------------
/*
Member function: add()
It adds new link after this object.
*/
Link* Link::add (Link* n)
{
if (n == 0 )
{
return this;
}
if (this == 0)
{
return n;
}
n->prev = this;
if (succ)
{
succ->prev = n;
}
n->succ = succ;
succ = n;
return n;
}
//------------------------------------------------------------------------
/*
Member function: add_ordered()
It inserts new link taking into
consideration the God's name of
the current last Link such that
the name of the last and the
new are in lexicographically
(increasing) order.
*/
Link* Link::add_ordered (Link* n)
{
if (n == 0)
{
return this;
}
// new list: first node
if (this == 0)
{
n->succ = 0;
n->prev = 0;
return n;
}
if (n->god < god)
{
Link* p = insert(n); // first element has changed
return p;
}
Link* p = this;
while (!(n->god < p->god)) // >= not defined for God
{
if (p->succ==0) // last element reached
{
p->add(n); // attach to end of list
return this; // first element has not changed
}
p = p->succ;
}
p->insert(n);
return this;
}
//------------------------------------------------------------------------
/*
Member function: erase()
It erases the current object
and connects its successor to
its predecessor; returns successor.
*/
Link* Link::erase (void)
{
if (this == 0)
{
return 0;
}
if (prev)
{
prev->succ = succ;
}
if (succ)
{
succ->prev = prev;
}
return succ;
}
//------------------------------------------------------------------------
/*
Member function: find()
It returns the first successor link containing
string name. Read and write permissions.
*/
Link* Link::find (const std::string& n)
{
Link* p = this;
while (p)
{
if (p->god.name == n)
{
return p;
}
p = p->succ;
}
return 0;
}
//------------------------------------------------------------------------
// non - modifying member functions
/*
Member function: find()
It returns the first successor link containing
string value. Read permission only.
*/
const Link* Link::find(const std::string &n) const
{
const Link* p = this;
while (p)
{
if (p->god.name == n)
{
return p;
}
p = p->succ;
}
return 0;
}
//------------------------------------------------------------------------
/*
Member function: advance()
It returns the link
found after n links, where
n could be either positive or
negative.
*/
Link* Link::advance (int n)
{
if (this == 0)
{
return 0;
}
Link* p = this;
if (n < 0)
{
while (n++)
{
if (prev == 0)
{
return 0;
}
p = prev;
}
}
if (n > 0)
{
while (n--)
{
if (succ == 0)
{
return 0;
}
p = succ;
}
}
return p;
}
//------------------------------------------------------------------------
// non - member functions
/*
Function: print_all_back_to_front();
It prints all nodes of the doubly linked
list starting from the last and advancing
to first node.
*/
void print_all_back_to_front(Link* n)
{
std::cout <<"{";
while (n)
{
std::cout << n->god;
if (n = n->next())
{
std::cout <<'\n';
}
}
std::cout <<"}";
}
//------------------------------------------------------------------------
/*
Function: print_all_front_to_back();
It prints all nodes of the doubly linked
list starting from the last and advancing
to first node.
*/
void print_all_front_to_back(Link* n)
{
std::cout <<"{";
while (n)
{
std::cout << n->god;
if (n = n->previous())
{
std::cout <<'\n';
}
}
std::cout <<"}";
}
//------------------------------------------------------------------------
/*
Function: order_list ();
It uses src link ptr to create a
lexicograhically ordered list:
dest link ptr, in terms of God's name.
*/
void order_list (Link* src, Link*& dest)
{
// traverse src from back to front
while (src)
{
// use src's God element to create a new Link as an element of an ordered List
dest = dest->add_ordered(new Link(God(src->god.name,
src->god.mythology,
src->god.vehicle,
src->god.weapon)));
src = src->next();
}
} | 15.555901 | 80 | 0.489918 | Ziezi |
9af9f58090a73a97ed73dde269039e1b91b34a4f | 253 | cpp | C++ | src/rick/RickState.cpp | ZZBGames/games | 8da707b0beb38aa4308dde1ce70ebe38fd82003a | [
"MIT"
] | null | null | null | src/rick/RickState.cpp | ZZBGames/games | 8da707b0beb38aa4308dde1ce70ebe38fd82003a | [
"MIT"
] | null | null | null | src/rick/RickState.cpp | ZZBGames/games | 8da707b0beb38aa4308dde1ce70ebe38fd82003a | [
"MIT"
] | null | null | null | //
// Created by mathbagu on 19/03/16.
//
#include <zzbgames/rick/RickState.hpp>
namespace zzbgames
{
namespace rick
{
RickState::RickState(RickStateStack& stateStack, RickContext& context)
: State(stateStack),
m_context(context)
{
}
}
} | 12.047619 | 70 | 0.699605 | ZZBGames |
9afaa845542f25886c2843e813a355e93dc14bad | 2,637 | hpp | C++ | libsynthpp/src/LSP/MIDI/Messages/BasicMessage.hpp | my04337/libsynthpp | 99584d0e568e6c92a5c298d4fdcde277fe7511f1 | [
"MIT"
] | 1 | 2018-01-31T14:02:32.000Z | 2018-01-31T14:02:32.000Z | libsynthpp/src/LSP/MIDI/Messages/BasicMessage.hpp | my04337/libsynthpp | 99584d0e568e6c92a5c298d4fdcde277fe7511f1 | [
"MIT"
] | 1 | 2018-02-21T02:33:47.000Z | 2018-02-21T02:36:23.000Z | libsynthpp/src/LSP/MIDI/Messages/BasicMessage.hpp | my04337/libsynthpp | 99584d0e568e6c92a5c298d4fdcde277fe7511f1 | [
"MIT"
] | 1 | 2018-02-20T05:30:52.000Z | 2018-02-20T05:30:52.000Z | #pragma once
#include <LSP/Base/Base.hpp>
#include <LSP/MIDI/Message.hpp>
namespace LSP::MIDI::Messages
{
/// ノートオン
class NoteOn
: public ChannelVoiceMessage
{
public:
NoteOn(uint8_t ch, uint8_t noteNo, uint8_t vel)
: mChannel(ch), mNoteNo(noteNo), mVelocity(vel)
{}
uint8_t channel()const noexcept override final { return mChannel; }
uint8_t noteNo()const noexcept { return mNoteNo; }
uint8_t velocity()const noexcept { return mVelocity; }
private:
uint8_t mChannel;
uint8_t mNoteNo;
uint8_t mVelocity;
};
/// ノートオフ
class NoteOff
: public ChannelVoiceMessage
{
public:
NoteOff(uint8_t ch, uint8_t noteNo, uint8_t vel)
: mChannel(ch), mNoteNo(noteNo), mVelocity(vel)
{}
uint8_t channel()const noexcept override final { return mChannel; }
uint8_t noteNo()const noexcept { return mNoteNo; }
private:
uint8_t mChannel;
uint8_t mNoteNo;
uint8_t mVelocity;
};
/// ポリフォニックキープレッシャー (アフタータッチ)
class PolyphonicKeyPressure
: public ChannelVoiceMessage
{
public:
PolyphonicKeyPressure(uint8_t ch, uint8_t noteNo, uint8_t value)
: mChannel(ch), mNoteNo(noteNo), mValue(value)
{}
uint8_t channel()const noexcept override final { return mChannel; }
private:
uint8_t mChannel;
uint8_t mNoteNo;
uint8_t mValue;
};
/// コントロールチェンジ & チャネルモードメッセージ
class ControlChange
: public ChannelVoiceMessage
{
public:
ControlChange(uint8_t ch, uint8_t ctrlNo, uint8_t value)
: mChannel(ch), mCtrlNo(ctrlNo), mValue(value)
{}
uint8_t channel()const noexcept override final { return mChannel; }
uint8_t ctrlNo()const noexcept { return mCtrlNo; }
uint8_t value()const noexcept { return mValue; }
private:
uint8_t mChannel;
uint8_t mCtrlNo;
uint8_t mValue;
};
/// プログラムチェンジ
class ProgramChange
: public ChannelVoiceMessage
{
public:
ProgramChange(uint8_t ch, uint8_t progNo)
: mChannel(ch), mProgNo(progNo)
{}
uint8_t channel()const noexcept override final { return mChannel; }
uint8_t progId()const noexcept { return mProgNo; }
private:
uint8_t mChannel;
uint8_t mProgNo;
};
/// チャネルプレッシャー (アフタータッチ)
class ChannelPressure
: public ChannelVoiceMessage
{
public:
ChannelPressure(uint8_t ch, uint8_t value)
: mChannel(ch), mValue(value)
{}
uint8_t channel()const noexcept override final { return mChannel; }
private:
uint8_t mChannel;
uint8_t mValue;
};
/// ピッチベンド
class PitchBend
: public ChannelVoiceMessage
{
public:
PitchBend(uint8_t ch, int16_t pitch)
: mChannel(ch), mPitch(pitch)
{}
uint8_t channel()const noexcept override final { return mChannel; }
int16_t pitch()const noexcept { return mPitch; }
private:
uint8_t mChannel;
int16_t mPitch; // -8192 <= x < +8191
};
} | 19.977273 | 69 | 0.740235 | my04337 |
9afc1a96924b965c5593c598045877e39440a6ed | 511 | cpp | C++ | 2021/day24/tests/TestClass.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | 3 | 2021-07-01T14:31:06.000Z | 2022-03-29T20:41:21.000Z | 2021/day24/tests/TestClass.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | null | null | null | 2021/day24/tests/TestClass.cpp | alexandru-andronache/adventofcode | ee41d82bae8b705818fda5bd43e9962bb0686fec | [
"Apache-2.0"
] | null | null | null | #include "TestClass.h"
#include "../test.h"
namespace aoc2021_day24 {
TEST_F(Tests2021Day24, part_1_test) {
ASSERT_EQ(part_1("../2021/day24/input_test.in"), 0);
}
TEST_F(Tests2021Day24, part_1_real_test) {
ASSERT_EQ(part_1("../2021/day24/input.in"), 0);
}
TEST_F(Tests2021Day24, part_2_test) {
ASSERT_EQ(part_2("../2021/day24/input_test.in"), 0);
}
TEST_F(Tests2021Day24, part_2_real_test) {
ASSERT_EQ(part_2("../2021/day24/input.in"), 0);
}
} | 25.55 | 60 | 0.632094 | alexandru-andronache |
9aff74edeb68c2441c3d1ca7b99dd3393f623d08 | 2,466 | hpp | C++ | libbio/include/bio/gpu/gpu_TransactionTypes.hpp | biosphere-switch/libbio | 7c892ff1e0f47e4612f3b66fdf043216764dfd1b | [
"MIT"
] | null | null | null | libbio/include/bio/gpu/gpu_TransactionTypes.hpp | biosphere-switch/libbio | 7c892ff1e0f47e4612f3b66fdf043216764dfd1b | [
"MIT"
] | null | null | null | libbio/include/bio/gpu/gpu_TransactionTypes.hpp | biosphere-switch/libbio | 7c892ff1e0f47e4612f3b66fdf043216764dfd1b | [
"MIT"
] | null | null | null |
#pragma once
#include <bio/gpu/gpu_Types.hpp>
namespace bio::gpu {
enum class ConnectionApi : i32 {
EGL = 1,
Cpu = 2,
Media = 3,
Camera = 4,
};
enum class DisconnectMode : u32 {
Api = 0,
AllLocal = 1,
};
struct QueueBufferOutput {
u32 width;
u32 height;
u32 transform_hint;
u32 pending_buffer_count;
};
struct Plane {
u32 width;
u32 height;
ColorFormat color_format;
Layout layout;
u32 pitch;
u32 map_handle_unused;
u32 offset;
Kind kind;
u32 block_height_log2;
DisplayScanFormat display_scan_format;
u32 second_field_offset;
u64 flags;
u64 size;
u32 unk[6];
};
static_assert(sizeof(Plane) == 0x58);
struct GraphicBufferHeader {
u32 magic;
u32 width;
u32 height;
u32 stride;
PixelFormat pixel_format;
GraphicsAllocatorUsage usage;
u32 pid;
u32 refcount;
u32 fd_count;
u32 buffer_size;
static constexpr u32 Magic = 0x47424652; // GBFR (Graphic Buffer)
};
// TODO: is the packed attribute really needed here?
struct __attribute__((packed)) GraphicBuffer {
GraphicBufferHeader header;
u32 null;
u32 map_id;
u32 zero;
u32 buffer_magic;
u32 pid;
u32 type;
GraphicsAllocatorUsage usage;
PixelFormat pixel_format;
PixelFormat external_pixel_format;
u32 stride;
u32 full_size;
u32 plane_count;
u32 zero_2;
Plane planes[3];
u64 unused;
static constexpr u32 Magic = 0xDAFFCAFF;
};
static_assert(sizeof(GraphicBuffer) == 0x16C);
struct Fence {
u32 id;
u32 value;
};
struct MultiFence {
u32 fence_count;
Fence fences[4];
};
struct Rect {
i32 left;
i32 top;
i32 right;
i32 bottom;
};
enum class Transform : u32 {
FlipH = 1,
FlipV = 2,
Rotate90 = 4,
Rotate180 = 3,
Rotate270 = 7,
};
struct QueueBufferInput {
i64 timestamp;
i32 is_auto_timestamp;
Rect crop;
i32 scaling_mode;
Transform transform;
u32 sticky_transform;
u32 unk;
u32 swap_interval;
MultiFence fence;
};
} | 20.213115 | 73 | 0.544201 | biosphere-switch |
b104357842a56d514edbcdeada4e43077f9c4043 | 433 | cpp | C++ | logsource.cpp | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | null | null | null | logsource.cpp | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | 2 | 2019-05-07T22:49:31.000Z | 2021-08-20T20:03:53.000Z | logsource.cpp | rdffg/bcaa_importer | f92e0b39673b5c557540154d4567c53a15adadcd | [
"Apache-2.0"
] | null | null | null | #include "logsource.h"
#include <QCoreApplication>
LogSource::LogSource(QObject *parent) : QObject(parent)
, m_logtext("")
{
}
void LogSource::addLogText(QString text) {
m_logtext += "\n" + text;
QCoreApplication::processEvents();
emit dataChanged();
}
void LogSource::clearLogText() {
m_logtext = "";
emit dataChanged();
}
QString LogSource::logtext() {
return m_logtext;
}
| 16.653846 | 56 | 0.628176 | rdffg |
623f6880c191cb8b07b9393f313a4d08c17c5afa | 1,876 | hpp | C++ | RL-master/Engine/UE3/PropertyFlags.hpp | jeremwhitten/RL | 15ff898afe82b6a07e076b8a3609c81a0942e6ca | [
"MIT"
] | 230 | 2018-01-26T07:20:25.000Z | 2022-03-26T14:57:00.000Z | Engine/UE3/PropertyFlags.hpp | ChairGraveyard/UnrealEngineSDKGenerator | 0589f640fa61c05316c1708e6c3b9ab3e13eb6aa | [
"MIT"
] | 1 | 2020-10-18T16:30:26.000Z | 2020-10-18T16:30:26.000Z | Engine/UE3/PropertyFlags.hpp | ChairGraveyard/UnrealEngineSDKGenerator | 0589f640fa61c05316c1708e6c3b9ab3e13eb6aa | [
"MIT"
] | 164 | 2018-01-15T09:11:46.000Z | 2022-03-08T11:57:12.000Z | #pragma once
#include <type_traits>
#include <string>
enum class UEPropertyFlags : uint64_t
{
Edit = 0x0000000000000001,
Const = 0x0000000000000002,
Input = 0x0000000000000004,
ExportObject = 0x0000000000000008,
OptionalParm = 0x0000000000000010,
Net = 0x0000000000000020,
EditFixedSize = 0x0000000000000040,
Parm = 0x0000000000000080,
OutParm = 0x0000000000000100,
SkipParm = 0x0000000000000200,
ReturnParm = 0x0000000000000400,
CoerceParm = 0x0000000000000800,
Native = 0x0000000000001000,
Transient = 0x0000000000002000,
Config = 0x0000000000004000,
Localized = 0x0000000000008000,
EditConst = 0x0000000000020000,
GlobalConfig = 0x0000000000040000,
Component = 0x0000000000080000,
AlwaysInit = 0x0000000000100000,
DuplicateTransient = 0x0000000000200000,
NeedCtorLink = 0x0000000000400000,
NoExport = 0x0000000000800000,
NoImport = 0x0000000001000000,
NoClear = 0x0000000002000000,
EditInline = 0x0000000004000000,
EditInlineUse = 0x0000000010000000,
Deprecated = 0x0000000020000000,
DataBinding = 0x0000000040000000,
SerializeText = 0x0000000080000000,
RepNotify = 0x0000000100000000,
Interp = 0x0000000200000000,
NonTransactional = 0x0000000400000000,
EditorOnly = 0x0000000800000000,
NotForConsole = 0x0000001000000000,
RepRetry = 0x0000002000000000,
PrivateWrite = 0x0000004000000000,
ProtectedWrite = 0x0000008000000000,
ArchetypeProperty = 0x0000010000000000,
EditHide = 0x0000020000000000,
EditTextBox = 0x0000040000000000,
CrossLevelPassive = 0x0000100000000000,
CrossLevelActive = 0x0000200000000000
};
inline bool operator&(UEPropertyFlags lhs, UEPropertyFlags rhs)
{
return (static_cast<std::underlying_type_t<UEPropertyFlags>>(lhs) & static_cast<std::underlying_type_t<UEPropertyFlags>>(rhs)) == static_cast<std::underlying_type_t<UEPropertyFlags>>(rhs);
}
std::string StringifyFlags(const UEPropertyFlags flags); | 32.344828 | 189 | 0.816631 | jeremwhitten |
62489fe7a0d3546aec6300f80ec138a763f427b7 | 2,775 | cpp | C++ | performerservice.cpp | audurara/verklegt1 | ca07845b9fc7129cb4c7ea4c3f1bad46899a4bcf | [
"MIT"
] | 1 | 2016-11-28T12:24:02.000Z | 2016-11-28T12:24:02.000Z | performerservice.cpp | audurara/verklegt1 | ca07845b9fc7129cb4c7ea4c3f1bad46899a4bcf | [
"MIT"
] | null | null | null | performerservice.cpp | audurara/verklegt1 | ca07845b9fc7129cb4c7ea4c3f1bad46899a4bcf | [
"MIT"
] | null | null | null | #include "performerservice.h"
#include "dataaccess.h"
#include <algorithm>
#include <iostream>
using namespace std;
struct PerformerComparison { //Struct sem ber saman nöfn
bool operator() (Performer i,Performer j) {
return (i.getName()<j.getName());
}
};
struct CompareYear{ //Fæðingarár borin saman
bool operator() (Performer i, Performer j) {
int value = atoi(i.getbYear().c_str());
int value2 = atoi(j.getbYear().c_str());
return (value < value2);
}
};
struct CompareGender{ //Kyn borin saman
bool operator() (Performer i, Performer j) {
return (i.getGender() > j.getGender());
}
};
struct CompareNationality{ //Þjóðerni borin saman
bool operator() (Performer i, Performer j) {
return (i.getNation() <j.getNation());
}
};
PerformerService::PerformerService() //Tómur smiður
{
}
vector<Performer> PerformerService::getPerformers() //Nær í gögn úr skrá og skilar þeim í vector
{
vector<Performer> getPerformers = _data.readData();
return getPerformers;
}
vector <Performer> PerformerService:: search(string name) //Leitar að ákveðnu nafni í listanum
{
vector<Performer> pf = getPerformers();
vector<Performer> newVector;
for(size_t i = 0; i < pf.size(); i++)
{
if(pf[i].getName() == name)
{
newVector.push_back(pf[i]);
}
}
return newVector;
}
vector<Performer> PerformerService::sortByName() { //Ber saman nöfn og raðar þeim í stafrófsröð
vector<Performer> pf = getPerformers();
PerformerComparison cmp;
sort(pf.begin(), pf.end(), cmp);
return pf;
}
vector <Performer> PerformerService::sortBybYear() //Ber saman ár og raðar þeim frá því lægsta til þess hæsta
{
vector <Performer> pf = getPerformers();
CompareYear cmp;
sort(pf.begin(), pf.end(), cmp);
return pf;
}
vector <Performer> PerformerService::sortByGender() //Ber saman kyn
{
vector <Performer> pf = getPerformers();
CompareGender cmp;
sort(pf.begin(), pf.end(), cmp);
return pf;
}
vector <Performer> PerformerService::sortByNationality() //Ber saman þjóðerni og raðar þeim eftir stafrófsröð
{
vector <Performer> pf = getPerformers();
CompareNationality cmp;
sort(pf.begin(), pf.end(), cmp);
return pf;
}
string PerformerService::addPerformer(string name, string gender, string birth, string death, string nation) //Bætir nýjum tölvunarfræðingi inn í skrána
{
string all = "," + name + "," + gender + "," + birth + "," + death + "," + nation;
_data.writeData(all);
return all;
}
string PerformerService::removeElement(string name) //Skilar til baka streng eftir að hafa eytt einu tilviki
{
_data.removeData(name);
return name;
}
| 25.458716 | 153 | 0.654054 | audurara |
6253a9e2743fc74e37b6814935199d1a09e23d38 | 2,008 | cc | C++ | mains/pool_identity_testing_main.cc | guilhermemtr/semistandard-tableaux | bdc25df3c091bb457055579455bb05d4d7f2f5b5 | [
"MIT"
] | null | null | null | mains/pool_identity_testing_main.cc | guilhermemtr/semistandard-tableaux | bdc25df3c091bb457055579455bb05d4d7f2f5b5 | [
"MIT"
] | null | null | null | mains/pool_identity_testing_main.cc | guilhermemtr/semistandard-tableaux | bdc25df3c091bb457055579455bb05d4d7f2f5b5 | [
"MIT"
] | null | null | null | #include <iostream>
#include <boost/program_options.hpp>
#include <cstdio>
#include "placid.hpp"
namespace po = boost::program_options;
namespace p = __placid;
int
main (int argc, char **argv)
{
p::free_monoid::element aaa;
p::tropical_elements::number bbb;
po::options_description desc ("Options");
desc.add_options () ("help,h", "Produces this help message.") //
("include,i",
po::value<std::vector<std::string>> (),
"Adds semistandard tableaux to the pool.") (
"test,t", po::value<std::string> (), "Sets the identity to be tested.");
po::positional_options_description p;
p.add ("include", -1);
po::variables_map vm;
po::store (
po::command_line_parser (argc, argv).options (desc).positional (p).run (),
vm);
po::notify (vm);
if (vm.count ("help"))
{
std::cout << desc << std::endl;
return 1;
}
p::pool<p::semistandard_tableaux::tableaux> pool;
std::vector<std::string> opts = vm["include"].as<std::vector<std::string>> ();
for (size_t i = 0; i < opts.size (); i++)
{
std::string in_fn = opts[i];
p::semistandard_tableaux::tableaux input;
try
{
input.read_file (in_fn);
pool.add (input);
} catch (std::string e)
{
std::cout << e << std::endl;
return 1;
}
}
if (vm.count ("test"))
{
std::string id_to_test = vm["test"].as<std::string> ();
try
{
pool.test_identity (id_to_test);
std::cout << "Identity holds." << std::endl;
} catch (std::unordered_map<std::string, p::semistandard_tableaux::tableaux>
counter_example)
{
std::cout << "Identity does not hold." << std::endl;
for (auto it : counter_example)
{
printf ("\n%s:\n", it.first.c_str ());
it.second.write (stdout, 2);
}
} catch (...)
{
printf ("Unknown error occurred.\n");
}
} else
{
std::cout << "No identity given" << std::endl;
return 1;
}
return 0;
}
| 22.561798 | 80 | 0.571713 | guilhermemtr |
625584b9c6553ba26611179070c2a817d20fa1f9 | 1,626 | cpp | C++ | leetcode/leetcode_1170_easy_compare_strings_by_frequency_of_the_smallest_character/main.v01.cpp | friskit-china/leetcode-cn-repo | 5f428e77f9d3f79da3e670a38b86d85bd58c81b2 | [
"MIT"
] | null | null | null | leetcode/leetcode_1170_easy_compare_strings_by_frequency_of_the_smallest_character/main.v01.cpp | friskit-china/leetcode-cn-repo | 5f428e77f9d3f79da3e670a38b86d85bd58c81b2 | [
"MIT"
] | null | null | null | leetcode/leetcode_1170_easy_compare_strings_by_frequency_of_the_smallest_character/main.v01.cpp | friskit-china/leetcode-cn-repo | 5f428e77f9d3f79da3e670a38b86d85bd58c81b2 | [
"MIT"
] | null | null | null | // https://leetcode-cn.com/problems/compare-strings-by-frequency-of-the-smallest-character/
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
// submit start
class Solution {
public:
vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {
vector<int> result;
int f_words[words.size()] = {0};
for (int i = 0; i < words.size(); ++i){
f_words[i] = f(words[i]);
}
for (auto it = queries.begin(); it != queries.end(); ++it){
int f_q = f(*it);
int counter = 0;
for (int i = 0; i < words.size(); ++i){
if (f_q < f_words[i]){
counter += 1;
}
}
result.push_back(counter);
}
return result;
}
int f(string s){
char min_word = 'z' + 1;
int min_counter = 0;
for (int i = 0; i < s.length(); ++i){
if (s[i] < min_word){
min_word = s[i];
min_counter = 1;
}else if(s[i] == min_word){
min_counter += 1;
}
}
return min_counter;
}
};
// submit end
int main(){
Solution sl;
// vector<string> queries = {"cbd"};
// vector<string> words = {"zaaaz"};
vector<string> queries = {"bbb", "cc"};
vector<string> words = {"a", "aa", "aaa", "aaaa"};
auto result = sl.numSmallerByFrequency(queries, words);
for (vector<int>::iterator it = result.begin(); it != result.end(); ++it){
cout<<*it<<" ";
}
cout<<endl;
return 0;
} | 26.225806 | 91 | 0.48893 | friskit-china |
625610649e940f4c7beef65f33bc9fcef38980d2 | 5,402 | cpp | C++ | ajaapps/crossplatform/demoapps/ntv2fieldburn/main.cpp | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | ajaapps/crossplatform/demoapps/ntv2fieldburn/main.cpp | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | ajaapps/crossplatform/demoapps/ntv2fieldburn/main.cpp | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | /* SPDX-License-Identifier: MIT */
/**
@file ntv2fieldburn/main.cpp
@brief Demonstration application to capture frames from the SDI input as two distinct fields
in separate, non-contiguous memory locations, "burn" a timecode window into each field,
and recombine the modified fields for SDI playout.
@copyright (C) 2013-2021 AJA Video Systems, Inc. All rights reserved.
**/
// Includes
#include "ajatypes.h"
#include "ajabase/common/options_popt.h"
#include "ntv2fieldburn.h"
#include "ajabase/system/systemtime.h"
#include <signal.h>
#include <iostream>
#include <iomanip>
using namespace std;
// Globals
static bool gGlobalQuit (false); ///< @brief Set this "true" to exit gracefully
static void SignalHandler (int inSignal)
{
(void) inSignal;
gGlobalQuit = true;
}
int main (int argc, const char ** argv)
{
char * pDeviceSpec (AJA_NULL); // Which device to use
char * pPixelFormat (AJA_NULL); // Pixel format spec
uint32_t inputNumber (1); // Which input to use (1-8, defaults to 1)
int noAudio (0); // Disable audio?
int noFieldMode (0); // Disable AutoCirculate Field Mode?
int doMultiChannel (0); // Set the board up for multi-channel/format
poptContext optionsContext; // Context for parsing command line arguments
AJADebug::Open();
// Command line option descriptions:
const struct poptOption userOptionsTable [] =
{
#if !defined(NTV2_DEPRECATE_16_0) // --board option is deprecated!
{"board", 'b', POPT_ARG_STRING, &pDeviceSpec, 0, "which device to use", "(deprecated)" },
#endif
{"device", 'd', POPT_ARG_STRING, &pDeviceSpec, 0, "which device to use", "index#, serial#, or model"},
{"input", 'i', POPT_ARG_INT, &inputNumber, 0, "which SDI input to use", "1-8"},
{"noaudio", 0, POPT_ARG_NONE, &noAudio, 0, "disables audio", AJA_NULL},
{"nofield", 0, POPT_ARG_NONE, &noFieldMode, 0, "disables field mode", AJA_NULL},
{"pixelFormat", 'p', POPT_ARG_STRING, &pPixelFormat, 0, "pixel format", "'?' or 'list' to list"},
{"multiChannel",'m', POPT_ARG_NONE, &doMultiChannel,0, "multiformat mode?", AJA_NULL},
POPT_AUTOHELP
POPT_TABLEEND
};
// Read command line arguments...
optionsContext = ::poptGetContext (AJA_NULL, argc, argv, userOptionsTable, 0);
::poptGetNextOpt (optionsContext);
optionsContext = ::poptFreeContext (optionsContext);
if (inputNumber > 8 || inputNumber < 1)
{cerr << "## ERROR: Input '" << inputNumber << "' not 1 thru 8" << endl; return 1;}
// Devices
const string legalDevices (CNTV2DemoCommon::GetDeviceStrings());
const string deviceSpec (pDeviceSpec ? pDeviceSpec : "0");
if (deviceSpec == "?" || deviceSpec == "list")
{cout << legalDevices << endl; return 0;}
if (!CNTV2DemoCommon::IsValidDevice(deviceSpec))
{cout << "## ERROR: No such device '" << deviceSpec << "'" << endl << legalDevices; return 1;}
// Pixel format
NTV2PixelFormat pixelFormat (NTV2_FBF_8BIT_YCBCR);
const string pixelFormatStr (pPixelFormat ? pPixelFormat : "1");
const string legalFBFs (CNTV2DemoCommon::GetPixelFormatStrings(PIXEL_FORMATS_ALL, deviceSpec));
if (pixelFormatStr == "?" || pixelFormatStr == "list")
{cout << CNTV2DemoCommon::GetPixelFormatStrings (PIXEL_FORMATS_ALL, deviceSpec) << endl; return 0;}
if (!pixelFormatStr.empty())
{
pixelFormat = CNTV2DemoCommon::GetPixelFormatFromString(pixelFormatStr);
if (!NTV2_IS_VALID_FRAME_BUFFER_FORMAT(pixelFormat))
{cerr << "## ERROR: Invalid '--pixelFormat' value '" << pixelFormatStr << "' -- expected values:" << endl << legalFBFs << endl; return 2;}
}
// Instantiate our NTV2FieldBurn object...
NTV2FieldBurn burner (deviceSpec, // Which device?
(noAudio ? false : true), // Include audio?
(noFieldMode ? false : true), // Field mode?
pixelFormat, // Frame buffer format
::GetNTV2InputSourceForIndex(inputNumber - 1), // Which input source?
doMultiChannel ? true : false); // Set the device up for multi-channel/format?
::signal (SIGINT, SignalHandler);
#if defined (AJAMac)
::signal (SIGHUP, SignalHandler);
::signal (SIGQUIT, SignalHandler);
#endif
const string hdg1 (" Capture Playout Capture Playout");
const string hdg2a(" Fields Fields Fields Buffer Buffer");
const string hdg2b(" Frames Frames Frames Buffer Buffer");
const string hdg3 ("Processed Dropped Dropped Level Level");
const string hdg2 (noFieldMode ? hdg2b : hdg2a);
// Initialize the NTV2FieldBurn instance...
if (AJA_FAILURE(burner.Init()))
{cerr << "## ERROR: Initialization failed" << endl; return 2;}
// Start the burner's capture and playout threads...
burner.Run ();
// Loop until someone tells us to stop...
cout << hdg1 << endl << hdg2 << endl << hdg3 << endl;
do
{
ULWord totalFrames(0), inputDrops(0), outputDrops(0), inputBufferLevel(0), outputBufferLevel(0);
burner.GetStatus (totalFrames, inputDrops, outputDrops, inputBufferLevel, outputBufferLevel);
cout << setw(9) << totalFrames << setw(9) << inputDrops << setw(9) << outputDrops << setw(9) << inputBufferLevel
<< setw(9) << outputBufferLevel << "\r" << flush;
AJATime::Sleep(500);
} while (!gGlobalQuit); // loop until signaled
cout << endl;
return 0;
} // main
| 41.236641 | 144 | 0.666235 | ibstewart |
6259cba42f6fc4ed7d503b6174f2f50ca56e30f2 | 5,700 | cpp | C++ | latte-dock/app/view/helpers/screenedgeghostwindow.cpp | VaughnValle/lush-pop | cdfe9d7b6a7ebb89ba036ab9a4f07d8db6817355 | [
"MIT"
] | 64 | 2020-07-08T18:49:29.000Z | 2022-03-23T22:58:49.000Z | latte-dock/app/view/helpers/screenedgeghostwindow.cpp | VaughnValle/kanji-pop | 0153059f0c62a8aeb809545c040225da5d249bb8 | [
"MIT"
] | 1 | 2021-04-02T04:39:45.000Z | 2021-09-25T11:53:18.000Z | latte-dock/app/view/helpers/screenedgeghostwindow.cpp | VaughnValle/kanji-pop | 0153059f0c62a8aeb809545c040225da5d249bb8 | [
"MIT"
] | 11 | 2020-12-04T18:19:11.000Z | 2022-01-10T08:50:08.000Z | /*
* Copyright 2018 Michail Vourlakos <mvourlakos@gmail.com>
*
* This file is part of Latte-Dock
*
* Latte-Dock is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* Latte-Dock 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 "screenedgeghostwindow.h"
// local
#include "../view.h"
// Qt
#include <QDebug>
#include <QSurfaceFormat>
#include <QQuickView>
#include <QTimer>
// KDE
#include <KWayland/Client/plasmashell.h>
#include <KWayland/Client/surface.h>
#include <KWindowSystem>
// X11
#include <NETWM>
namespace Latte {
namespace ViewPart {
ScreenEdgeGhostWindow::ScreenEdgeGhostWindow(Latte::View *view) :
SubWindow(view, QString("Screen Ghost Window"))
{
if (m_debugMode) {
m_showColor = QColor("purple");
m_hideColor = QColor("blue");
} else {
m_showColor = QColor(Qt::transparent);
m_hideColor = QColor(Qt::transparent);
m_showColor.setAlpha(0);
m_hideColor.setAlpha(1);
}
setColor(m_showColor);
//! this timer is used in order to avoid fast enter/exit signals during first
//! appearing after edge activation
m_delayedMouseTimer.setSingleShot(true);
m_delayedMouseTimer.setInterval(50);
connect(&m_delayedMouseTimer, &QTimer::timeout, this, [this]() {
if (m_delayedContainsMouse) {
setContainsMouse(true);
} else {
setContainsMouse(false);
}
});
updateGeometry();
hideWithMask();
}
ScreenEdgeGhostWindow::~ScreenEdgeGhostWindow()
{
}
QString ScreenEdgeGhostWindow::validTitlePrefix() const
{
return QString("#subghostedge#");
}
void ScreenEdgeGhostWindow::updateGeometry()
{
if (m_latteView->positioner()->slideOffset() != 0) {
return;
}
QRect newGeometry;
if (KWindowSystem::compositingActive()) {
m_thickness = 6;
} else {
m_thickness = 2;
}
int length{30};
int lengthDifference{0};
if (m_latteView->formFactor() == Plasma::Types::Horizontal) {
//! set minimum length to be 25% of screen width
length = qMax(m_latteView->screenGeometry().width()/4,qMin(m_latteView->absoluteGeometry().width(), m_latteView->screenGeometry().width() - 1));
lengthDifference = qMax(0,length - m_latteView->absoluteGeometry().width());
} else {
//! set minimum length to be 25% of screen height
length = qMax(m_latteView->screenGeometry().height()/4,qMin(m_latteView->absoluteGeometry().height(), m_latteView->screenGeometry().height() - 1));
lengthDifference = qMax(0,length - m_latteView->absoluteGeometry().height());
}
if (m_latteView->location() == Plasma::Types::BottomEdge) {
int xF = qMax(m_latteView->screenGeometry().left(), m_latteView->absoluteGeometry().left() - lengthDifference);
newGeometry.moveLeft(xF);
newGeometry.moveTop(m_latteView->screenGeometry().bottom() - m_thickness);
} else if (m_latteView->location() == Plasma::Types::TopEdge) {
int xF = qMax(m_latteView->screenGeometry().left(), m_latteView->absoluteGeometry().left() - lengthDifference);
newGeometry.moveLeft(xF);
newGeometry.moveTop(m_latteView->screenGeometry().top());
} else if (m_latteView->location() == Plasma::Types::LeftEdge) {
int yF = qMax(m_latteView->screenGeometry().top(), m_latteView->absoluteGeometry().top() - lengthDifference);
newGeometry.moveLeft(m_latteView->screenGeometry().left());
newGeometry.moveTop(yF);
} else if (m_latteView->location() == Plasma::Types::RightEdge) {
int yF = qMax(m_latteView->screenGeometry().top(), m_latteView->absoluteGeometry().top() - lengthDifference);
newGeometry.moveLeft(m_latteView->screenGeometry().right() - m_thickness);
newGeometry.moveTop(yF);
}
if (m_latteView->formFactor() == Plasma::Types::Horizontal) {
newGeometry.setWidth(length);
newGeometry.setHeight(m_thickness + 1);
} else {
newGeometry.setWidth(m_thickness + 1);
newGeometry.setHeight(length);
}
m_calculatedGeometry = newGeometry;
emit calculatedGeometryChanged();
}
bool ScreenEdgeGhostWindow::containsMouse() const
{
return m_containsMouse;
}
void ScreenEdgeGhostWindow::setContainsMouse(bool contains)
{
if (m_containsMouse == contains) {
return;
}
m_containsMouse = contains;
emit containsMouseChanged(contains);
}
bool ScreenEdgeGhostWindow::event(QEvent *e)
{
if (e->type() == QEvent::DragEnter || e->type() == QEvent::DragMove) {
if (!m_containsMouse) {
m_delayedContainsMouse = false;
m_delayedMouseTimer.stop();
setContainsMouse(true);
emit dragEntered();
}
} else if (e->type() == QEvent::Enter) {
m_delayedContainsMouse = true;
if (!m_delayedMouseTimer.isActive()) {
m_delayedMouseTimer.start();
}
} else if (e->type() == QEvent::Leave || e->type() == QEvent::DragLeave) {
m_delayedContainsMouse = false;
if (!m_delayedMouseTimer.isActive()) {
m_delayedMouseTimer.start();
}
}
return SubWindow::event(e);
}
}
}
| 31.318681 | 155 | 0.663509 | VaughnValle |
625beffe0f541f450e071f72a9482b6f8578d8e6 | 2,844 | hpp | C++ | include/elemental/blas-like/level1/Transpose.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/blas-like/level1/Transpose.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/blas-like/level1/Transpose.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef BLAS_TRAPEZOID_HPP
#define BLAS_TRAPEZOID_HPP
namespace elem {
template<typename T>
inline void
Transpose( const Matrix<T>& A, Matrix<T>& B, bool conjugate=false )
{
#ifndef RELEASE
CallStackEntry entry("Transpose");
#endif
const int m = A.Height();
const int n = A.Width();
if( B.Viewing() )
{
if( B.Height() != n || B.Width() != m )
{
std::ostringstream msg;
msg << "If Transpose'ing into a view, it must be the right size:\n"
<< " A ~ " << A.Height() << " x " << A.Width() << "\n"
<< " B ~ " << B.Height() << " x " << B.Width();
throw std::logic_error( msg.str().c_str() );
}
}
else
B.ResizeTo( n, m );
if( conjugate )
{
for( int j=0; j<n; ++j )
for( int i=0; i<m; ++i )
B.Set(j,i,Conj(A.Get(i,j)));
}
else
{
for( int j=0; j<n; ++j )
for( int i=0; i<m; ++i )
B.Set(j,i,A.Get(i,j));
}
}
template<typename T,Distribution U,Distribution V,
Distribution W,Distribution Z>
inline void
Transpose
( const DistMatrix<T,U,V>& A, DistMatrix<T,W,Z>& B, bool conjugate=false )
{
#ifndef RELEASE
CallStackEntry entry("Transpose");
#endif
if( B.Viewing() )
{
if( A.Height() != B.Width() || A.Width() != B.Height() )
{
std::ostringstream msg;
msg << "If Transpose'ing into a view, it must be the right size:\n"
<< " A ~ " << A.Height() << " x " << A.Width() << "\n"
<< " B ~ " << B.Height() << " x " << B.Width();
throw std::logic_error( msg.str().c_str() );
}
}
if( U == Z && V == W &&
A.ColAlignment() == B.RowAlignment() &&
A.RowAlignment() == B.ColAlignment() )
{
Transpose( A.LockedMatrix(), B.Matrix(), conjugate );
}
else
{
DistMatrix<T,Z,W> C( B.Grid() );
if( B.Viewing() || B.ConstrainedColAlignment() )
C.AlignRowsWith( B );
if( B.Viewing() || B.ConstrainedRowAlignment() )
C.AlignColsWith( B );
C = A;
if( !B.Viewing() )
{
if( !B.ConstrainedColAlignment() )
B.AlignColsWith( C );
if( !B.ConstrainedRowAlignment() )
B.AlignRowsWith( C );
B.ResizeTo( A.Width(), A.Height() );
}
Transpose( C.LockedMatrix(), B.Matrix(), conjugate );
}
}
} // namespace elem
#endif // ifndef BLAS_TRAPEZOID_HPP
| 27.61165 | 79 | 0.503165 | ahmadia |
625ef4959e4ed675f6b571aed964e6b44d9bd680 | 3,045 | cpp | C++ | src/pong_game/Ball.cpp | jjerome/Niski | 58bcc1303cdb6676c051d55e9d7a248dfea65cde | [
"MIT"
] | 1 | 2017-09-19T16:33:06.000Z | 2017-09-19T16:33:06.000Z | src/pong_game/Ball.cpp | jjerome/Niski | 58bcc1303cdb6676c051d55e9d7a248dfea65cde | [
"MIT"
] | null | null | null | src/pong_game/Ball.cpp | jjerome/Niski | 58bcc1303cdb6676c051d55e9d7a248dfea65cde | [
"MIT"
] | null | null | null | #include "pong_game/Ball.h"
#include "pong_game/Paddle.h"
#include "engine/ConVar.h"
#include "renderer/VertexBuffer2D.h"
#include "math/Math.h"
#include "utils/Log.h"
using namespace Niski::Pong_Game;
Niski::Engine::ConVar addPaddleVelocity("PongGame::Ball::AddPaddleVelocity", 0, "If enabled, when the ball collides with a paddle the y velocity of the paddle is added to the ball.");
Ball::Ball(PongWorld* world, const Niski::Math::Vector2D<float>& initialPosition, float radius) : Entity(world, "PongBall"), initialPosition_(initialPosition), radius_(radius)
{
setPosition(initialPosition);
}
Ball::~Ball(void)
{}
void Ball::render(Niski::Renderer::Renderer& renderer) const
{
//
// TODO: Kinda dangerous..
Niski::Renderer::VertexBuffer2D vBuffer;
const int16_t segments = 23;
vBuffer.setColor(Niski::Utils::Color(Niski::Utils::Color::white));
for(int16_t i = 0; i <= segments; ++i)
{
double t = (2 * Niski::Math::pi / segments) * i;
vBuffer.pushVertex(getPosition().x + (radius_ * cos(t)), getPosition().y - (radius_ * sin(t)));
}
vBuffer.setPrimitiveType(Niski::Renderer::VertexBuffer2D::lineList);
vBuffer.render(renderer);
vBuffer.flushVertices();
}
void Ball::reset(void)
{
setPosition(initialPosition_);
setVelocity(Niski::Math::Vector2D<float>(0.0f, 0.0f));
}
void Ball::onTouch(Entity* ent)
{
if(ent == nullptr)
{
Niski::Utils::bitch("Ball::OnTouch was called with a null ent.");
return;
}
Niski::Math::Vector2D<float> position(getPosition());
Niski::Math::Vector2D<float> newVelocity(getVelocity());
if(ent->getName() == "Paddle")
{
Paddle* paddle = static_cast<Paddle*>(ent);
Niski::Math::Vector2D<float> paddlePosition(paddle->getPosition());
Niski::Math::Rect2D paddleBounds(paddle->getBounds());
//
// "Push" the ball out of the paddle.
PongWorld* world = static_cast<PongWorld*>(getParent());
if(position.x < (world->getBounds().right / 2.0f))
{
if(position.x < paddleBounds.left + paddleBounds.right)
{
position.x = paddleBounds.left + paddleBounds.right + radius_;
}
}
else
{
if(position.x > paddleBounds.left)
{
position.x = paddleBounds.left - radius_;
}
}
newVelocity.x = -newVelocity.x;
if(addPaddleVelocity.getIntValue())
{
Niski::Math::Vector2D<float> paddleVelocity(paddle->getVelocity());
newVelocity.y += paddleVelocity.y;
}
}
else if(ent->getName() == "gameWorld")
{
PongWorld* world = static_cast<PongWorld*>(ent);
Niski::Math::Rect2D worldBounds(world->getBounds());
{
//
// This method is only called if we have hit the top or the bottom
// since the left and right are score material and thus handled by game rules
//
// Collision detection doesn't happen until it's in another rectangle.
// so we push it out.
if(position.y <= worldBounds.top)
{
position.y = worldBounds.top + radius_;
}
else
{
position.y = worldBounds.bottom - radius_;
}
newVelocity.y = -newVelocity.y;
}
}
setPosition(position);
setVelocity(newVelocity);
} | 25.588235 | 183 | 0.685714 | jjerome |
626695984253639e951f90b2e70651d7ca5877a2 | 14,973 | cc | C++ | libs/gather/test-gather.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | libs/gather/test-gather.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | libs/gather/test-gather.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | //==========================================================================
// ObTools::Gather: test-buffer.cc
//
// Test harness for gather buffer library
//
// Copyright (c) 2010 Paul Clark. All rights reserved
// This code comes with NO WARRANTY and is subject to licence agreement
//==========================================================================
#include "ot-gather.h"
#include <gtest/gtest.h>
namespace {
using namespace std;
using namespace ObTools;
TEST(GatherTest, TestSimpleAdd)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
const string expected(&data[0], strlen(data));
Gather::Segment& seg = buffer.add(reinterpret_cast<unsigned char *>(&data[0]),
strlen(data));
ASSERT_EQ(expected.size(), buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
ASSERT_EQ(data, string(reinterpret_cast<char *>(seg.data), seg.length));
}
TEST(GatherTest, TestInternalAdd)
{
Gather::Buffer buffer(0);
Gather::Segment& seg = buffer.add(16);
for (unsigned int i = 0; i < seg.length; ++i)
seg.data[i] = i;
ASSERT_EQ(16, buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
for (unsigned int i = 0; i < seg.length; ++i)
ASSERT_EQ(i, seg.data[i]) << "Where i = " << i;
}
TEST(GatherTest, TestSimpleInsert)
{
Gather::Buffer buffer(0);
uint32_t n = 0xDEADBEEF;
const uint32_t expected = n;
Gather::Segment &seg = buffer.insert(reinterpret_cast<Gather::data_t *>(&n),
sizeof(n));
ASSERT_EQ(sizeof(expected), buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
ASSERT_EQ(sizeof(expected), seg.length);
for (unsigned i = 0; i < sizeof(expected); ++i)
ASSERT_EQ((expected >> (i * 8)) & 0xff, seg.data[i]) << "Where i = " << i;
}
TEST(GatherTest, TestInsertBetween)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
const string expected_str(&data[0], strlen(data));
uint32_t n = 0x01234567;
const uint32_t expected_num(n);
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
buffer.insert(reinterpret_cast<Gather::data_t *>(&n), sizeof(n), 1);
const Gather::Segment *segments = buffer.get_segments();
ASSERT_EQ(expected_str.size() * 2 + sizeof(expected_num),
buffer.get_length());
ASSERT_LE(3, buffer.get_size());
ASSERT_EQ(3, buffer.get_count());
ASSERT_TRUE(segments);
const Gather::Segment &seg1 = segments[0];
ASSERT_EQ(expected_str.size(), seg1.length);
ASSERT_EQ(expected_str,
string(reinterpret_cast<char *>(seg1.data), seg1.length));
const Gather::Segment &seg2 = segments[1];
ASSERT_EQ(sizeof(expected_num), seg2.length);
for (unsigned i = 0; i < sizeof(expected_num); ++i)
ASSERT_EQ((expected_num >> (i * 8)) & 0xff, seg2.data[i])
<< "Where i = " << i;
const Gather::Segment &seg3 = segments[2];
ASSERT_EQ(expected_str.size(), seg3.length);
ASSERT_EQ(expected_str,
string(reinterpret_cast<char *>(seg3.data), seg3.length));
}
TEST(GatherTest, TestSimpleLimit)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
const unsigned int chop(8);
const string expected(&data[0], strlen(data) - chop);
Gather::Segment& seg = buffer.add(
reinterpret_cast<Gather::data_t *>(&data[0]),
strlen(data));
buffer.limit(buffer.get_length() - chop);
ASSERT_EQ(expected.size(), buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
ASSERT_EQ(expected, string(reinterpret_cast<char *>(seg.data), seg.length));
}
TEST(GatherTest, TestSimpleConsume)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
const unsigned int chop(7);
const string expected(&data[chop], strlen(data) - chop);
Gather::Segment& seg = buffer.add(
reinterpret_cast<Gather::data_t *>(&data[0]),
strlen(data));
buffer.consume(chop);
ASSERT_EQ(expected.size(), buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
ASSERT_EQ(expected, string(reinterpret_cast<char *>(seg.data), seg.length));
}
TEST(GatherTest, TestCopy)
{
Gather::Buffer buffer(0);
char one[] = "xHell";
char two[] = "o, wo";
char three[] = "rld!x";
const string expected = string(&one[1], strlen(one) - 1)
+ string(&two[0], strlen(two))
+ string(&three[0], strlen(three) - 1);
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
string actual;
actual.resize(expected.size());
unsigned int copied = buffer.copy(
reinterpret_cast<Gather::data_t *>(const_cast<char *>(actual.c_str())),
1, expected.size());
ASSERT_EQ(expected.size(), copied);
ASSERT_EQ(expected, actual);
}
TEST(GatherTest, TestAddFromBuffer)
{
Gather::Buffer buffer1(0);
char one[] = "xHell";
const string one_str(&one[0], strlen(one));
char two[] = "o, wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!x";
const string three_str(&three[0], strlen(three));
buffer1.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer1.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer1.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
Gather::Buffer buffer2(0);
char data[] = "Hello";
const string hello(&data[0], strlen(data));
buffer2.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
buffer2.add(buffer1, 6, 8);
const Gather::Segment *segments = buffer2.get_segments();
ASSERT_LE(3, buffer2.get_size());
ASSERT_EQ(3, buffer2.get_count());
ASSERT_TRUE(segments);
const Gather::Segment& segment1 = segments[0];
ASSERT_EQ(hello.size(), segment1.length);
ASSERT_EQ(hello,
string(reinterpret_cast<char *>(segment1.data), segment1.length));
const Gather::Segment& segment2 = segments[1];
ASSERT_EQ(two_str.substr(1).size(), segment2.length);
ASSERT_EQ(two_str.substr(1),
string(reinterpret_cast<char *>(segment2.data), segment2.length));
const Gather::Segment& segment3 = segments[2];
ASSERT_EQ(three_str.substr(0, 4).size(), segment3.length);
ASSERT_EQ(three_str.substr(0, 4),
string(reinterpret_cast<char *>(segment3.data), segment3.length));
}
TEST(GatherTest, TestAddBuffer)
{
Gather::Buffer buffer1(0);
char one[] = "Hello";
const string one_str(&one[0], strlen(one));
char two[] = ", wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!";
const string three_str(&three[0], strlen(three));
buffer1.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
Gather::Buffer buffer2(0);
Gather::Segment& segment = buffer2.add(strlen(two));
memcpy(segment.data, &two[0], segment.length);
buffer2.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
buffer1.add(buffer2);
const Gather::Segment *segments = buffer1.get_segments();
ASSERT_LE(3, buffer1.get_size());
ASSERT_EQ(3, buffer1.get_count());
ASSERT_TRUE(segments);
const Gather::Segment& segment1 = segments[0];
ASSERT_EQ(one_str.size(), segment1.length);
ASSERT_EQ(one_str,
string(reinterpret_cast<char *>(segment1.data), segment1.length));
const Gather::Segment& segment2 = segments[1];
ASSERT_EQ(two_str.size(), segment2.length);
ASSERT_EQ(two_str,
string(reinterpret_cast<char *>(segment2.data), segment2.length));
const Gather::Segment& segment3 = segments[2];
ASSERT_EQ(three_str.size(), segment3.length);
ASSERT_EQ(three_str,
string(reinterpret_cast<char *>(segment3.data), segment3.length));
}
TEST(GatherTest, TestIteratorLoop)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
const string one_str(&one[0], strlen(one));
char two[] = ", wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!";
const string three_str(&three[0], strlen(three));
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
const string expect = one_str + two_str + three_str;
string actual;
for (Gather::Buffer::iterator it = buffer.begin(); it != buffer.end(); ++it)
actual += reinterpret_cast<char&>(*it);
ASSERT_EQ(expect.size(), actual.size());
ASSERT_EQ(expect, actual);
}
TEST(GatherTest, TestIteratorAdd)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
const string one_str(&one[0], strlen(one));
char two[] = ", wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!";
const string three_str(&three[0], strlen(three));
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
const string expect = one_str + two_str + three_str;
Gather::Buffer::iterator it = buffer.begin();
it += 7;
ASSERT_EQ(expect[7], *it);
}
TEST(GatherTest, TestIteratorSub)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
const string one_str(&one[0], strlen(one));
char two[] = ", wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!";
const string three_str(&three[0], strlen(three));
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
const string expect = one_str + two_str + three_str;
Gather::Buffer::iterator it = buffer.end();
it -= 6;
ASSERT_EQ(expect[7], *it);
it -= 1;
ASSERT_EQ(expect[6], *it);
}
TEST(GatherTest, TestDump)
{
Gather::Buffer buffer(1);
ostringstream expect;
expect << "Buffer (4/4):" << endl
<< " 0" << endl
<< " 12" << endl
<< "0000: 656c6c6f 2c20776f 726c6421 | ello, world!" << endl
<< " 4" << endl
<< "0000: 67452301 | gE#." << endl
<< "* 8" << endl
<< "0000: 00010203 04050607 | ........" << endl
<< "Total length 24" << endl;
char data[] = "Hello, world!";
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
Gather::Segment& seg = buffer.add(16);
for (unsigned int i = 0; i < seg.length; ++i)
seg.data[i] = i;
uint32_t n = 0xDEADBEEF;
buffer.insert(reinterpret_cast<Gather::data_t *>(&n), sizeof(n));
uint32_t n2 = 0x01234567;
buffer.insert(reinterpret_cast<Gather::data_t *>(&n2), sizeof(n2), 2);
buffer.limit(buffer.get_length() - 8);
buffer.consume(5);
ostringstream actual;
buffer.dump(actual, true);
ASSERT_EQ(actual.str(), expect.str());
}
#if !defined(PLATFORM_WINDOWS)
TEST(GatherTest, TestFill)
{
Gather::Buffer buffer(1);
char data[] = "Hello, world!";
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
Gather::Segment& seg = buffer.add(16);
for (unsigned int i = 0; i < seg.length; ++i)
seg.data[i] = i;
uint32_t n = 0xDEADBEEF;
buffer.insert(reinterpret_cast<Gather::data_t *>(&n), sizeof(n));
uint32_t n2 = 0x01234567;
buffer.insert(reinterpret_cast<Gather::data_t *>(&n2), sizeof(n), 2);
buffer.limit(buffer.get_length() - 8);
buffer.consume(5);
struct iovec io[4];
buffer.fill(io, 4);
// Note: zero sized buffer is skipped
ASSERT_EQ(12, io[0].iov_len);
ASSERT_EQ(string("ello, world!"),
string(reinterpret_cast<char *>(io[0].iov_base), io[0].iov_len));
ASSERT_EQ(4, io[1].iov_len);
ASSERT_EQ(string("gE#\x01"),
string(reinterpret_cast<char *>(io[1].iov_base), io[1].iov_len));
ASSERT_EQ(8, io[2].iov_len);
ASSERT_EQ(string("\x00\x01\x02\x03\x04\x05\x06\x07", 8),
string(reinterpret_cast<char *>(io[2].iov_base), io[2].iov_len));
}
#endif
TEST(GatherTest, TestGetFlatDataSingleSegment)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
Gather::data_t buf[4];
Gather::data_t *p = buffer.get_flat_data(0, 4, buf);
ASSERT_NE(p, buf) << "Single segment get_flat_data used temporary buffer!\n";
ASSERT_EQ(string(reinterpret_cast<char *>(p), 4), "Hell");
}
TEST(GatherTest, TestGetFlatDataMultiSegment)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
char two[] = ", wo";
char three[] = "rld!";
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
Gather::data_t buf[7];
Gather::data_t *p = buffer.get_flat_data(3, 7, buf);
ASSERT_EQ(p, buf) << "Multi-segment get_flat_data didn't use temporary buffer!\n";
ASSERT_EQ(string(reinterpret_cast<char *>(p), 7), "lo, wor");
}
TEST(GatherTest, TestGetFlatDataOffEndFails)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
char two[] = ", wo";
char three[] = "rld!";
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
Gather::data_t buf[7];
Gather::data_t *p = buffer.get_flat_data(7, 7, buf);
ASSERT_FALSE(p) << "get_flat_data off the end didn't fail!\n";
}
TEST(GatherTest, TestReplaceSingleSegment)
{
Gather::Buffer buffer(0);
// Need to ensure it's owned data, not referenced
memcpy(buffer.add(13).data, "Hello, world!", 13);
buffer.replace(0, reinterpret_cast<const Gather::data_t *>("Salut"), 5);
Gather::data_t buf[13];
Gather::data_t *p = buffer.get_flat_data(0, 13, buf);
ASSERT_EQ(string(reinterpret_cast<char *>(p), 13), "Salut, world!");
}
TEST(GatherTest, TestReplaceMultiSegment)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
char two[] = ", wo";
char three[] = "rld!";
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
buffer.replace(4, reinterpret_cast<const Gather::data_t *>(" freezeth"), 9);
Gather::data_t buf[13];
Gather::data_t *p = buffer.get_flat_data(0, 13, buf);
ASSERT_EQ(string(reinterpret_cast<char *>(p), 13), "Hell freezeth");
}
} // anonymous namespace
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 32.980176 | 84 | 0.646631 | sandtreader |
6269092d278ad6e28176e79aea034cf363d74e23 | 151 | cc | C++ | src/foo/foo.cc | da2ce7/meson-sample-project | 225a2006d8ba207b044fd70a0ac7f4429a4fd27d | [
"MIT"
] | 86 | 2018-05-27T22:05:29.000Z | 2022-03-28T09:21:42.000Z | src/foo/foo.cc | seanwallawalla-forks/meson-sample-project | 0e09d1d1a08f9f19f7e7615e3ed21f548ac56b13 | [
"MIT"
] | 2 | 2019-08-14T09:06:29.000Z | 2019-08-16T14:20:01.000Z | src/foo/foo.cc | seanwallawalla-forks/meson-sample-project | 0e09d1d1a08f9f19f7e7615e3ed21f548ac56b13 | [
"MIT"
] | 24 | 2018-08-07T17:32:11.000Z | 2021-12-21T07:30:32.000Z | #include "foo/foo.h"
#include <config.h>
#include <iostream>
/*!
Description of implementation of foo
*/
int foo(int param) { return param + 1; }
| 16.777778 | 40 | 0.668874 | da2ce7 |
626b077564a109690a18d2404087d11dbef9bb0f | 2,319 | hpp | C++ | include/commands/Label.hpp | MrHands/Panini | 464999debf6ad6ee9f2184514ba719062f8375b5 | [
"MIT-0"
] | null | null | null | include/commands/Label.hpp | MrHands/Panini | 464999debf6ad6ee9f2184514ba719062f8375b5 | [
"MIT-0"
] | null | null | null | include/commands/Label.hpp | MrHands/Panini | 464999debf6ad6ee9f2184514ba719062f8375b5 | [
"MIT-0"
] | null | null | null | /*
MIT No Attribution
Copyright 2021-2022 Mr. Hands
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.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include "commands/CommandBase.hpp"
namespace panini
{
/*!
\brief Outputs a label statement.
A label is a name and a ":" chunk. The command pops the indentation
before writing the label and restores it afterwards.
Labels are useful when you don't want to modify the current
indentation level, e.g. when writing an access identifier for a class
or a switch..case statement.
Example:
\code{.cpp}
writer << Scope("class Vehicle", [](WriterBase& writer) {
writer << Label("public") << NextLine();
writer << "Vehicle(const std::string& maker);" << NextLine();
writer << Label("private") << NextLine();
writer << "std::string m_maker;" << NextLine();
}) << ";";
\endcode
Output:
\code{.cpp}
class Vehicle
{
public:
Vehicle(const std::string& maker);
private:
std::string m_maker;
};
\endcode
\sa Scope
*/
class Label
: public CommandBase
{
public:
/*!
Create a Label command with a `name` that is moved into the
instance.
*/
Label(std::string&& name)
: m_name(name)
{
}
/*!
Create a Label command with a `name` that is copied to the
instance.
*/
Label(const std::string& name)
: m_name(name)
{
}
virtual void Visit(WriterBase& writer) final
{
writer << IndentPop() << m_name << ":" << IndentPush();
}
private:
std::string m_name;
};
};
| 23.663265 | 77 | 0.688228 | MrHands |
626d8b588ed8c82861226897531f5254cedbada8 | 2,577 | cpp | C++ | TG/bookcodes/ch4/la4728.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | TG/bookcodes/ch4/la4728.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | TG/bookcodes/ch4/la4728.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // LA4728/UVa1453 Square
// Rujia Liu
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
struct Point {
int x, y;
Point(int x=0, int y=0):x(x),y(y) { }
};
typedef Point Vector;
Vector operator - (const Point& A, const Point& B) {
return Vector(A.x-B.x, A.y-B.y);
}
int Cross(const Vector& A, const Vector& B) {
return A.x*B.y - A.y*B.x;
}
int Dot(const Vector& A, const Vector& B) {
return A.x*B.x + A.y*B.y;
}
int Dist2(const Point& A, const Point& B) {
return (A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y);
}
bool operator < (const Point& p1, const Point& p2) {
return p1.x < p2.x || (p1.x == p2.x && p1.y < p2.y);
}
bool operator == (const Point& p1, const Point& p2) {
return p1.x == p2.x && p1.y == p2.y;
}
// 点集凸包
// 如果不希望在凸包的边上有输入点,把两个 <= 改成 <
// 注意:输入点集会被修改
vector<Point> ConvexHull(vector<Point>& p) {
// 预处理,删除重复点
sort(p.begin(), p.end());
p.erase(unique(p.begin(), p.end()), p.end());
int n = p.size();
int m = 0;
vector<Point> ch(n+1);
for(int i = 0; i < n; i++) {
while(m > 1 && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
ch[m++] = p[i];
}
int k = m;
for(int i = n-2; i >= 0; i--) {
while(m > k && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
ch[m++] = p[i];
}
if(n > 1) m--;
ch.resize(m);
return ch;
}
// 返回点集直径的平方
int diameter2(vector<Point>& points) {
vector<Point> p = ConvexHull(points);
int n = p.size();
if(n == 1) return 0;
if(n == 2) return Dist2(p[0], p[1]);
p.push_back(p[0]); // 免得取模
int ans = 0;
for(int u = 0, v = 1; u < n; u++) {
// 一条直线贴住边p[u]-p[u+1]
for(;;) {
// 当Area(p[u], p[u+1], p[v+1]) <= Area(p[u], p[u+1], p[v])时停止旋转
// 即Cross(p[u+1]-p[u], p[v+1]-p[u]) - Cross(p[u+1]-p[u], p[v]-p[u]) <= 0
// 根据Cross(A,B) - Cross(A,C) = Cross(A,B-C)
// 化简得Cross(p[u+1]-p[u], p[v+1]-p[v]) <= 0
int diff = Cross(p[u+1]-p[u], p[v+1]-p[v]);
if(diff <= 0) {
ans = max(ans, Dist2(p[u], p[v])); // u和v是对踵点
if(diff == 0) ans = max(ans, Dist2(p[u], p[v+1])); // diff == 0时u和v+1也是对踵点
break;
}
v = (v + 1) % n;
}
}
return ans;
}
int main() {
int T;
scanf("%d", &T);
while(T--) {
int n;
scanf("%d", &n);
vector<Point> points;
for(int i = 0; i < n; i++) {
int x, y, w;
scanf("%d%d%d", &x, &y, &w);
points.push_back(Point(x, y));
points.push_back(Point(x+w, y));
points.push_back(Point(x, y+w));
points.push_back(Point(x+w, y+w));
}
printf("%d\n", diameter2(points));
}
return 0;
}
| 23.216216 | 82 | 0.503298 | Anyrainel |
627067211edef4a9f95182e1b7a389c3569596cb | 5,872 | cpp | C++ | src/tests/possumwood/subnetwork_from_file.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | 1 | 2020-10-06T08:40:10.000Z | 2020-10-06T08:40:10.000Z | src/tests/possumwood/subnetwork_from_file.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | null | null | null | src/tests/possumwood/subnetwork_from_file.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | null | null | null | #include <actions/actions.h>
#include <actions/filesystem_mock.h>
#include <dependency_graph/graph.h>
#include <dependency_graph/metadata_register.h>
#include <dependency_graph/rtti.h>
#include <possumwood_sdk/app.h>
#include <boost/test/unit_test.hpp>
#include <dependency_graph/node_base.inl>
#include <dependency_graph/nodes.inl>
#include <dependency_graph/port.inl>
#include "common.h"
using namespace dependency_graph;
using possumwood::io::json;
namespace {
dependency_graph::NodeBase& findNode(dependency_graph::Network& net, const std::string& name) {
for(auto& n : net.nodes())
if(n.name() == name)
return n;
BOOST_REQUIRE(false && "Node not found, fail");
throw;
}
dependency_graph::NodeBase& findNode(const std::string& name) {
return findNode(possumwood::AppCore::instance().graph(), name);
}
json readJson(possumwood::IFilesystem& filesystem, const std::string& filename) {
json result;
auto stream = filesystem.read(possumwood::Filepath::fromString(filename));
(*stream) >> result;
return result;
}
} // namespace
BOOST_AUTO_TEST_CASE(network_from_file) {
auto filesystem = std::make_shared<possumwood::FilesystemMock>();
possumwood::App app(filesystem);
dependency_graph::State state;
// make sure the static handles are initialised
passThroughNode();
// three nodes, a connection, blind data
json subnetwork(
{{"nodes",
{{"input_0", {{"name", "this_is_an_input"}, {"type", "input"}}},
{"pass_through_0", {{"name", "pass_through"}, {"type", "pass_through"}}},
{"output_0", {{"name", "this_is_an_output"}, {"type", "output"}}}}},
{"connections",
{{{"in_node", "pass_through_0"}, {"in_port", "input"}, {"out_node", "input_0"}, {"out_port", "data"}},
{{"in_node", "output_0"}, {"in_port", "data"}, {"out_node", "pass_through_0"}, {"out_port", "output"}}}},
{"name", "network"},
{"type", "network"}});
subnetwork["ports"]["this_is_an_input"] = 8.0f;
(*filesystem->write(possumwood::Filepath::fromString("subnetwork_only.psw"))) << subnetwork;
BOOST_REQUIRE_NO_THROW(state = app.loadFile(possumwood::Filepath::fromString("subnetwork_only.psw")));
BOOST_REQUIRE(!state.errored());
// lets make sure this loads and saves correctly
BOOST_REQUIRE_NO_THROW(app.saveFile(possumwood::Filepath::fromString("subnetwork_only_too.psw"), false));
BOOST_CHECK_EQUAL(readJson(*filesystem, "subnetwork_only_too.psw"), subnetwork);
BOOST_REQUIRE_NO_THROW(app.loadFile(possumwood::Filepath::fromString("subnetwork_only_too.psw")));
/////////////
// attempt to serialize a simple setup with a subnetwork
{
json setup;
BOOST_REQUIRE_NO_THROW(setup = json({{"nodes",
{{"network_0",
{{"name", "network"},
{"type", "network"},
{"nodes", subnetwork["nodes"]},
{"connections", subnetwork["connections"]},
{"ports", {{"this_is_an_input", 0.0}}}}}}},
{"connections", std::vector<std::string>()},
{"name", "network"},
{"type", "network"}}));
(*filesystem->write(possumwood::Filepath::fromString("setup_with_subnetwork.psw"))) << setup;
BOOST_REQUIRE_NO_THROW(state = app.loadFile(possumwood::Filepath::fromString("setup_with_subnetwork.psw")));
BOOST_REQUIRE(!state.errored());
// lets make sure this loads and saves correctly
BOOST_REQUIRE_NO_THROW(app.saveFile(possumwood::Filepath::fromString("setup_with_subnetwork_too.psw"), false));
BOOST_CHECK_EQUAL(readJson(*filesystem, "setup_with_subnetwork_too.psw"), setup);
BOOST_REQUIRE_NO_THROW(app.loadFile(possumwood::Filepath::fromString("setup_with_subnetwork_too.psw")));
}
//////////////
// make a copy of that setup and try to set the source attribute - represents a network coming
// from another file
{
json setup;
BOOST_REQUIRE_NO_THROW(setup = json({{"nodes",
{{"network_0",
{{"name", "network"},
{"type", "network"},
{"source", "subnetwork_only.psw"},
{"ports", {{"this_is_an_input", 8.0}}}}}}},
{"connections", std::vector<std::string>()},
{"name", "network"},
{"type", "network"}}));
(*filesystem->write(possumwood::Filepath::fromString("setup_without_subnetwork.psw"))) << setup;
BOOST_REQUIRE_NO_THROW(state = app.loadFile(possumwood::Filepath::fromString("setup_without_subnetwork.psw")));
BOOST_REQUIRE(!state.errored());
// lets make sure this loads and saves correctly
BOOST_REQUIRE_NO_THROW(
app.saveFile(possumwood::Filepath::fromString("setup_without_subnetwork_too.psw"), false));
BOOST_CHECK_EQUAL(readJson(*filesystem, "setup_without_subnetwork_too.psw"), setup);
BOOST_REQUIRE_NO_THROW(app.loadFile(possumwood::Filepath::fromString("setup_without_subnetwork_too.psw")));
}
// check that we can set values on the network
auto& net = findNode("network").as<dependency_graph::Network>();
BOOST_CHECK_EQUAL(net.portCount(), 2u);
BOOST_CHECK_EQUAL(net.port(0).name(), "this_is_an_input");
BOOST_CHECK_EQUAL(net.port(0).get<float>(), 8.0f);
BOOST_CHECK_EQUAL(net.port(1).name(), "this_is_an_output");
BOOST_CHECK_EQUAL(net.port(1).get<float>(), 8.0f);
// test that the eval still works
BOOST_CHECK_NO_THROW(net.port(0).set(5.0f));
BOOST_CHECK_EQUAL(net.port(0).get<float>(), 5.0f);
BOOST_CHECK_EQUAL(net.port(1).get<float>(), 5.0f);
}
| 39.945578 | 113 | 0.626703 | LIUJUN-liujun |
6273a616ec80b4bf68bd6f7e18c4744366a5f8c8 | 5,425 | cpp | C++ | Game/OGRE/Tests/PlayPen/src/WindowEmbedding.cpp | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/OGRE/Tests/PlayPen/src/WindowEmbedding.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/OGRE/Tests/PlayPen/src/WindowEmbedding.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | 7 | 2021-08-31T14:34:23.000Z | 2022-01-19T08:25:58.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
/*
-----------------------------------------------------------------------------
Filename: WindowEmbedding.cpp
Description: Stuff your windows full of OGRE
-----------------------------------------------------------------------------
*/
#include "Ogre.h"
using namespace Ogre;
void setupResources(void)
{
// Load resource paths from config file
ConfigFile cf;
cf.load("resources.cfg");
// Go through all sections & settings in the file
ConfigFile::SectionIterator seci = cf.getSectionIterator();
String secName, typeName, archName;
while (seci.hasMoreElements())
{
secName = seci.peekNextKey();
ConfigFile::SettingsMultiMap *settings = seci.getNext();
ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i)
{
typeName = i->first;
archName = i->second;
ResourceGroupManager::getSingleton().addResourceLocation(
archName, typeName, secName);
}
}
}
//---------------------------------------------------------------------
// Windows Test
//---------------------------------------------------------------------
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#include "windows.h"
RenderWindow* renderWindow = 0;
bool winActive = false;
bool winSizing = false;
LRESULT CALLBACK TestWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if (uMsg == WM_CREATE)
{
return 0;
}
if (!renderWindow)
return DefWindowProc(hWnd, uMsg, wParam, lParam);
switch( uMsg )
{
case WM_ACTIVATE:
winActive = (LOWORD(wParam) != WA_INACTIVE);
break;
case WM_ENTERSIZEMOVE:
winSizing = true;
break;
case WM_EXITSIZEMOVE:
renderWindow->windowMovedOrResized();
renderWindow->update();
winSizing = false;
break;
case WM_MOVE:
case WM_SIZE:
if (!winSizing)
renderWindow->windowMovedOrResized();
break;
case WM_GETMINMAXINFO:
// Prevent the window from going smaller than some min size
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 100;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 100;
break;
case WM_CLOSE:
renderWindow->destroy(); // cleanup and call DestroyWindow
PostQuitMessage(0);
return 0;
case WM_PAINT:
if (!winSizing)
{
renderWindow->update();
return 0;
}
break;
}
return DefWindowProc( hWnd, uMsg, wParam, lParam );
}
INT WINAPI EmbeddedMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
{
try
{
// Create a new window
// Style & size
DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_OVERLAPPEDWINDOW;
// Register the window class
WNDCLASS wc = { 0, TestWndProc, 0, 0, hInst,
LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
(HBRUSH)GetStockObject(BLACK_BRUSH), 0, "TestWnd" };
RegisterClass(&wc);
HWND hwnd = CreateWindow("TestWnd", "Test embedding", dwStyle,
0, 0, 800, 600, 0, 0, hInst, 0);
Root root("", "");
root.loadPlugin("RenderSystem_GL");
//root.loadPlugin("RenderSystem_Direct3D9");
root.loadPlugin("Plugin_ParticleFX");
root.loadPlugin("Plugin_CgProgramManager");
// select first renderer & init with no window
root.setRenderSystem(*(root.getAvailableRenderers()->begin()));
root.initialise(false);
// create first window manually
NameValuePairList options;
options["externalWindowHandle"] =
StringConverter::toString((size_t)hwnd);
renderWindow = root.createRenderWindow("embedded", 800, 600, false, &options);
setupResources();
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
SceneManager *scene = root.createSceneManager(Ogre::ST_GENERIC, "default");
Camera *cam = scene->createCamera("cam");
Viewport* vp = renderWindow->addViewport(cam);
vp->setBackgroundColour(Ogre::ColourValue(0.5, 0.5, 0.7));
cam->setAutoAspectRatio(true);
cam->setPosition(0,0,300);
cam->setDirection(0,0,-1);
Entity* e = scene->createEntity("1", "ogrehead.mesh");
scene->getRootSceneNode()->createChildSceneNode()->attachObject(e);
Light* l = scene->createLight("l");
l->setPosition(300, 100, -100);
// message loop
MSG msg;
while(GetMessage(&msg, NULL, 0, 0 ) != 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
catch( Exception& e )
{
MessageBox( NULL, e.getFullDescription().c_str(),
"An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
}
return 0;
}
#endif
| 26.207729 | 87 | 0.655668 | hackerlank |
627492e773dce21dc549ac82c039f07e89be3fe7 | 1,690 | cc | C++ | tictoc/txc3.cc | deezombiedude612/masters-omnetpp | 949e5af7235114ca8de2ba9140c6422907bae50d | [
"MIT"
] | null | null | null | tictoc/txc3.cc | deezombiedude612/masters-omnetpp | 949e5af7235114ca8de2ba9140c6422907bae50d | [
"MIT"
] | null | null | null | tictoc/txc3.cc | deezombiedude612/masters-omnetpp | 949e5af7235114ca8de2ba9140c6422907bae50d | [
"MIT"
] | null | null | null | /*
* txc3.cc
*
* Created on: May 12, 2021
* Author: deezombiedude612
*/
#include <stdio.h>
#include <string.h>
#include <omnetpp.h>
using namespace omnetpp;
/**
* In this class we add a counter, and delete the message after ten exchanges.
*/
class Txc3 : public cSimpleModule {
private:
int counter; // Note the counter here
protected:
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
};
Define_Module(Txc3);
void Txc3::initialize() {
/**
* Initialize counter to ten. We'll decrement it every time and delete
* the message when it reaches zero.
*/
counter = 10;
/**
* The WATCH() statement below will let you examine the variable under
* Tkenv. After doing a few steps in the simulation, double-click either
* 'tic' or 'toc', select the Contents tab in the dialog that pops up,
* and you'll find 'counter' in the list.
*/
WATCH(counter);
if(strcmp("tic", getName()) == 0) {
EV << "Sending initial message\n";
cMessage *msg = new cMessage("tictocMsg");
send(msg, "out");
}
}
void Txc3::handleMessage(cMessage *msg) {
// Increment counter and check value.
counter--;
if(counter == 0) {
/**
* If counter is 0, delete message. If you run the model, you'll
* find that the simulation will stop at this point with the message
* "no more events".
*/
EV << getName() << "'s counter reached zero, deleting message\n";
delete msg;
} else {
EV << getName() << "'s counter is " << counter << ", sending back message\n";
send(msg, "out");
}
}
| 25.606061 | 85 | 0.606509 | deezombiedude612 |
6276f653074c7a3b38e2d082f15873a3e623b514 | 2,706 | hpp | C++ | navigation_layer/fovis/libfovis/libfovis/libfovis/stereo_calibration.hpp | kartavya2000/Anahita | 9afbf6c238658188df7d0d97b2fec3bd48028c03 | [
"BSD-3-Clause"
] | 5 | 2018-10-22T20:04:24.000Z | 2022-01-04T09:24:46.000Z | navigation_layer/fovis/libfovis/libfovis/libfovis/stereo_calibration.hpp | kartavya2000/Anahita | 9afbf6c238658188df7d0d97b2fec3bd48028c03 | [
"BSD-3-Clause"
] | 19 | 2018-10-03T12:14:35.000Z | 2019-07-07T09:33:14.000Z | navigation_layer/fovis/libfovis/libfovis/libfovis/stereo_calibration.hpp | kartavya2000/Anahita | 9afbf6c238658188df7d0d97b2fec3bd48028c03 | [
"BSD-3-Clause"
] | 15 | 2018-09-09T12:35:15.000Z | 2020-01-03T09:28:19.000Z | #ifndef __fovis_stereo_calibration_hpp__
#define __fovis_stereo_calibration_hpp__
#include <inttypes.h>
#include "camera_intrinsics.hpp"
#include "rectification.hpp"
namespace fovis
{
/**
* \ingroup DepthSources
* \brief Calibration data structure for stereo cameras.
*/
struct StereoCalibrationParameters
{
/**
* Translation vector: [ x, y, z ]
*/
double right_to_left_translation[3];
/**
* Rotation quaternion: [ w, x, y, z ]
*/
double right_to_left_rotation[4];
/**
* Intrinsics of the left camera.
*/
CameraIntrinsicsParameters left_parameters;
/**
* Intrinsics of the right camera.
*/
CameraIntrinsicsParameters right_parameters;
};
/**
* \ingroup DepthSources
* \brief Computes useful information from a StereoCalibrationParameters object
*/
class StereoCalibration
{
public:
StereoCalibration(const StereoCalibrationParameters& params);
~StereoCalibration();
/**
* Compute the 4x4 transformation matrix mapping [ u, v, disparity, 1 ]
* coordinates to [ x, y, z, w ] homogeneous coordinates in camera
* space.
*/
Eigen::Matrix4d getUvdToXyz() const {
double fx_inv = 1./_rectified_parameters.fx;
double base_inv = 1./getBaseline();
double cx = _rectified_parameters.cx;
double cy = _rectified_parameters.cy;
Eigen::Matrix4d result;
result <<
fx_inv , 0 , 0 , -cx * fx_inv ,
0 , fx_inv , 0 , -cy * fx_inv ,
0 , 0 , 0 , 1 ,
0 , 0 , fx_inv*base_inv , 0;
return result;
}
/**
* \return the width of the rectified camera.
*/
int getWidth() const {
return _rectified_parameters.width;
}
/**
* \return the height of the rectified camera.
*/
int getHeight() const {
return _rectified_parameters.height;
}
double getBaseline() const {
return -_parameters.right_to_left_translation[0];
}
const Rectification* getLeftRectification() const {
return _left_rectification;
}
const Rectification* getRightRectification() const {
return _right_rectification;
}
const CameraIntrinsicsParameters& getRectifiedParameters() const {
return _rectified_parameters;
}
/**
* \return a newly allocated copy of this calibration object.
*/
StereoCalibration* makeCopy() const;
private:
StereoCalibration() { }
void initialize();
StereoCalibrationParameters _parameters;
CameraIntrinsicsParameters _rectified_parameters;
Rectification* _left_rectification;
Rectification* _right_rectification;
};
}
#endif
| 23.530435 | 79 | 0.646711 | kartavya2000 |
62779338af81a8f087be2035267ce0bd8032074e | 1,283 | cxx | C++ | test/telea1.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 10 | 2018-03-26T07:41:44.000Z | 2021-11-06T08:33:24.000Z | test/telea1.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | null | null | null | test/telea1.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 1 | 2020-11-17T03:17:00.000Z | 2020-11-17T03:17:00.000Z | /* -*- C++ -*- */
/*************************************************************************
* Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch)
*
* For the licensing terms see the file COPYING
*
************************************************************************/
#include <stdio.h>
class A {
public:
int a;
};
class B : public A {
public:
int a;
};
void f(A x) {
printf("%d\n",x.a);
}
void test1() {
A a;
B b;
a.a = -12;
b.a = 1;
b.A::a = 2;
printf("%d %d %d\n", b.a , b.A::a , a.a);
a=b;
printf("%d %d %d\n", b.a , b.A::a , a.a);
f(a);
f(b);
A *pa = &a;
A *pb = &b;
pa->a = 123;
printf("%d %d %d\n", pb->a , pb->A::a , pa->a);
*pa = *pb;
printf("%d %d %d\n", pb->a , pb->A::a , pa->a);
}
void test2() {
A a[5];
B b[5];
int i;
for(i=0;i<5;i++) {
a[i].a = -12;
b[i].a = 1;
b[i].A::a = 2;
printf("%d %d %d\n", b[i].a , b[i].A::a , a[i].a);
a[i]=b[i];
printf("%d %d %d\n", b[i].a , b[i].A::a , a[i].a);
f(a[i]);
f(b[i]);
}
A *pa = a;
A *pb = b;
for(i=0;i<5;i++) {
pa[i].a = 123;
printf("%d %d %d\n", pb->a , pb[i].A::a , pa[i].a);
pa[i] = pb[i];
printf("%d %d %d\n", pb->a , pb[i].A::a , pa[i].a);
}
}
int main()
{
test1();
test2();
return 0;
}
| 16.881579 | 74 | 0.359314 | paulwratt |
62782608446126bae4ed17dfdebe4a4923d55144 | 240 | cpp | C++ | src/mwave/mwave_modules/src/mwave_modules/logic_component.cpp | mwaverecycling/ros2-packages | 6ae566d86dc5f724ee69255df3319f6692db6db5 | [
"MIT"
] | null | null | null | src/mwave/mwave_modules/src/mwave_modules/logic_component.cpp | mwaverecycling/ros2-packages | 6ae566d86dc5f724ee69255df3319f6692db6db5 | [
"MIT"
] | null | null | null | src/mwave/mwave_modules/src/mwave_modules/logic_component.cpp | mwaverecycling/ros2-packages | 6ae566d86dc5f724ee69255df3319f6692db6db5 | [
"MIT"
] | null | null | null | // TODO
#include "mwave_modules/logic_component.hpp"
namespace mwave_modules
{
LogicComponent::LogicComponent(const std::string & node_name, const std::string & namespace_)
: mwave_util::BroadcastNode(node_name, namespace_)
{
}
} | 20 | 94 | 0.754167 | mwaverecycling |
627a8d7ebd1e255e5da4c19be872be1eda90f71a | 11,297 | cpp | C++ | util.cpp | Cirras/eomap-classic | 7ba4f5208ce49aeacb17bc4ad016b278388485b8 | [
"Zlib"
] | 2 | 2020-11-02T08:23:11.000Z | 2020-11-03T18:14:51.000Z | util.cpp | Cirras/eomap-classic | 7ba4f5208ce49aeacb17bc4ad016b278388485b8 | [
"Zlib"
] | 4 | 2020-12-09T14:34:56.000Z | 2020-12-14T11:29:59.000Z | util.cpp | Cirras/eomap-classic | 7ba4f5208ce49aeacb17bc4ad016b278388485b8 | [
"Zlib"
] | 2 | 2020-12-09T12:40:10.000Z | 2020-12-14T20:52:10.000Z |
/* $Id: util.cpp 169 2009-10-23 20:17:53Z sausage $
* EOSERV is released under the zlib license.
* See LICENSE.txt for more info.
*/
#include "util.hpp"
#include <algorithm>
#include <ctime>
#include <limits>
#if defined(WIN32) || defined(WIN64)
#include <windows.h>
#endif // defined(WIN32) || defined(WIN64)
namespace util
{
variant::variant()
{
this->SetInt(0);
}
variant::variant(int i)
{
this->SetInt(i);
}
variant::variant(double d)
{
this->SetFloat(d);
}
variant::variant(const std::string &s)
{
this->SetString(s);
}
variant::variant(const char *p)
{
std::string s(p);
this->SetString(s);
}
variant::variant(bool b)
{
this->SetBool(b);
}
int variant::int_length(int x)
{
int count = 1;
int val = 10;
while (x >= val)
{
val *= 10;
++count;
}
return count;
}
int variant::GetInt()
{
if (this->cache_val[type_int])
{
return this->val_int;
}
this->cache_val[type_int] = true;
switch (this->type)
{
case type_float:
this->val_int = static_cast<int>(this->val_float);
break;
case type_string:
this->val_int = tdparse(this->val_string);
break;
case type_bool:
this->val_int = this->val_bool ? 0 : -1;
break;
default: ; // Shut the compiler up
}
return this->val_int;
}
double variant::GetFloat()
{
if (this->cache_val[type_float])
{
return this->val_float;
}
this->cache_val[type_float] = true;
switch (this->type)
{
case type_int:
this->val_float = static_cast<double>(this->val_int);
break;
case type_string:
this->val_float = tdparse(this->val_string);
break;
case type_bool:
this->val_float = this->val_bool ? 0.0 : 1.0;
break;
default: ; // Shut the compiler up
}
return this->val_float;
}
std::string variant::GetString()
{
if (this->cache_val[type_string])
{
return this->val_string;
}
this->cache_val[type_string] = true;
char buf[1024];
switch (this->type)
{
case type_int:
snprintf(buf, 1024, "%i", this->val_int);
this->val_string = buf;
break;
case type_float:
snprintf(buf, 1024, "%lf", this->val_float);
this->val_string = buf;
break;
case type_bool:
this->val_string = this->val_bool ? "yes" : "no";
break;
default: ; // Shut the compiler up
}
return this->val_string;
}
bool variant::GetBool()
{
if (this->cache_val[type_bool])
{
return this->val_bool;
}
this->cache_val[type_bool] = true;
int intval = 0;
std::string s = this->val_string;
switch (this->type)
{
case type_int:
this->val_bool = static_cast<bool>(this->val_int);
break;
case type_float:
this->val_bool = std::abs(this->val_float) != 0.0 && this->val_float == this->val_float;
break;
case type_string:
std::sscanf(this->val_string.c_str(), "%d", &intval);
util::lowercase(s);
this->val_bool = (s == "yes" || s == "true" || s == "enabled" || intval != 0);
break;
default: ; // Shut the compiler up
}
return this->val_bool;
}
void variant::SetType(variant::var_type type)
{
this->type = type;
for (std::size_t i = 0; i < sizeof(this->cache_val); ++i)
{
this->cache_val[i] = (static_cast<variant::var_type>(i) == type);
}
}
variant &variant::SetInt(int i)
{
this->val_int = i;
this->SetType(type_int);
return *this;
}
variant &variant::SetFloat(double d)
{
this->val_float = d;
this->SetType(type_float);
return *this;
}
variant &variant::SetString(const std::string &s)
{
this->val_string = s;
this->SetType(type_string);
return *this;
}
variant &variant::SetBool(bool b)
{
this->val_bool = b;
this->SetType(type_bool);
return *this;
}
variant &variant::operator =(int i)
{
return this->SetInt(i);
}
variant &variant::operator =(double d)
{
return this->SetFloat(d);
}
variant &variant::operator =(const std::string &s)
{
return this->SetString(s);
}
variant &variant::operator =(const char *p)
{
std::string s(p);
return this->SetString(s);
}
variant &variant::operator =(bool b)
{
return this->SetBool(b);
}
variant::operator int()
{
return this->GetInt();
}
variant::operator double()
{
return this->GetFloat();
}
variant::operator std::string()
{
return this->GetString();
}
variant::operator bool()
{
return this->GetBool();
}
std::string ltrim(const std::string &str)
{
std::size_t si = str.find_first_not_of(" \t\n\r");
if (si == std::string::npos)
{
si = 0;
}
else
{
--si;
}
++si;
return str.substr(si);
}
std::string rtrim(const std::string &str)
{
std::size_t ei = str.find_last_not_of(" \t\n\r");
if (ei == std::string::npos)
{
ei = str.length()-1;
}
++ei;
return str.substr(0, ei);
}
std::string trim(const std::string &str)
{
std::size_t si, ei;
bool notfound = false;
si = str.find_first_not_of(" \t\n\r");
if (si == std::string::npos)
{
si = 0;
notfound = true;
}
ei = str.find_last_not_of(" \t\n\r");
if (ei == std::string::npos)
{
if (notfound)
{
return "";
}
ei = str.length()-1;
}
++ei;
return str.substr(si, ei);
}
std::vector<std::string> explode(char delimiter, std::string str)
{
std::size_t lastpos = 0;
std::size_t pos = 0;
std::vector<std::string> pieces;
for (pos = str.find_first_of(delimiter); pos != std::string::npos; )
{
pieces.push_back(str.substr(lastpos, pos - lastpos));
lastpos = pos+1;
pos = str.find_first_of(delimiter, pos+1);
}
pieces.push_back(str.substr(lastpos));
return pieces;
}
std::vector<std::string> explode(std::string delimiter, std::string str)
{
std::size_t lastpos = 0;
std::size_t pos = 0;
std::vector<std::string> pieces;
if (delimiter.length() == 0)
{
return pieces;
}
if (delimiter.length() == 1)
{
return explode(delimiter[0], str);
}
for (pos = str.find(delimiter); pos != std::string::npos; )
{
pieces.push_back(str.substr(lastpos, pos - lastpos));
lastpos = pos + delimiter.length();
pos = str.find(delimiter, pos + delimiter.length());
}
pieces.push_back(str.substr(lastpos));
return pieces;
}
double tdparse(std::string timestr)
{
static char period_names[] = {'s', 'm', '%', 'k', 'h', 'd' };
static double period_mul[] = {1.0, 60.0, 100.0, 1000.0, 3600.0, 86400.0};
double ret = 0.0;
double val = 0.0;
bool decimal = false;
double decimalmulti = 0.1;
bool negate = false;
for (std::size_t i = 0; i < timestr.length(); ++i)
{
char c = timestr[i];
bool found = false;
if (c == '-')
{
negate = true;
continue;
}
if (c >= 'A' && c <= 'Z')
{
c -= 'A' - 'a';
}
for (std::size_t ii = 0; ii < sizeof(period_names)/sizeof(char); ++ii)
{
if (c == period_names[ii])
{
if (c == 'm' && timestr[i+1] == 's')
{
ret += val / 1000.0;
++i;
}
else if (c == '%')
{
ret += val / period_mul[ii];
}
else
{
ret += val * period_mul[ii];
}
found = true;
val = 0.0;
decimal = false;
decimalmulti = 0.1;
break;
}
}
if (!found)
{
if (c >= '0' && c <= '9')
{
if (!decimal)
{
val *= 10.0;
val += c - '0';
}
else
{
val += (c - '0') * decimalmulti;
decimalmulti /= 10.0;
}
}
else if (c == '.')
{
decimal = true;
decimalmulti = 0.1;
}
}
}
return (ret + val) * (negate ? -1.0 : 1.0);
}
int to_int(const std::string &subject)
{
return static_cast<int>(util::variant(subject));
}
double to_float(const std::string &subject)
{
return static_cast<double>(util::variant(subject));
}
std::string to_string(int subject)
{
return static_cast<std::string>(util::variant(subject));
}
std::string to_string(double subject)
{
return static_cast<std::string>(util::variant(subject));
}
void lowercase(std::string &subject)
{
std::transform(subject.begin(), subject.end(), subject.begin(), static_cast<int(*)(int)>(std::tolower));
}
void uppercase(std::string &subject)
{
std::transform(subject.begin(), subject.end(), subject.begin(), static_cast<int(*)(int)>(std::toupper));
}
void ucfirst(std::string &subject)
{
if (subject[0] > 'a' && subject[0] < 'z')
{
subject[0] += 'A' - 'a';
}
}
static void rand_init()
{
static bool init = false;
if (!init)
{
init = true;
std::srand(std::time(0));
}
}
static unsigned long long_rand()
{
#if RAND_MAX < 65535
return (std::rand() & 0xFF) << 24 | (std::rand() & 0xFF) << 16 | (std::rand() & 0xFF) << 8 | (std::rand() & 0xFF);
#else
#if RAND_MAX < 4294967295
return (std::rand() & 0xFFFF) << 16 | (std::rand() & 0xFFFF);
#else
return std::rand();
#endif
#endif
}
int rand(int min, int max)
{
rand_init();
rand(double(min), double(max));
return static_cast<int>(double(long_rand()) / (double(std::numeric_limits<unsigned long>::max()) + 1.0) * double(max - min + 1) + double(min));
}
double rand(double min, double max)
{
rand_init();
return double(long_rand()) / double(std::numeric_limits<unsigned long>::max()) * (max - min) + min;
}
double round(double subject)
{
return std::floor(subject + 0.5);
}
std::string timeago(double time, double current_time)
{
static bool init = false;
static std::vector<std::pair<int, std::string> > times;
if (!init)
{
init = true;
times.resize(5);
times.push_back(std::make_pair(1, "second"));
times.push_back(std::make_pair(60, "minute"));
times.push_back(std::make_pair(60*60, "hour"));
times.push_back(std::make_pair(24*60*60, "day"));
times.push_back(std::make_pair(7*24*60*60, "week"));
}
std::string ago;
double diff = current_time - time;
ago = ((diff >= 0) ? " ago" : " from now");
diff = std::abs(diff);
for (int i = times.size()-1; i >= 0; --i)
{
int x = int(diff / times[i].first);
diff -= x * times[i].first;
if (x > 0)
{
return util::to_string(x) + " " + times[i].second + ((x == 1) ? "" : "s") + ago;
}
}
return "now";
}
void sleep(double seconds)
{
#if defined(WIN32) || defined(WIN64)
Sleep(int(seconds * 1000.0));
#else // defined(WIN32) || defined(WIN64)
long sec = seconds;
long nsec = (seconds - double(sec)) * 1000000000.0;
timespec ts = {sec, nsec};
nanosleep(&ts, 0);
#endif // defined(WIN32) || defined(WIN64)
}
std::string DecodeEMFString(std::string chars)
{
reverse(chars.begin(), chars.end());
bool flippy = (chars.length() % 2) == 1;
for (std::size_t i = 0; i < chars.length(); ++i)
{
unsigned char c = chars[i];
if (flippy)
{
if (c >= 0x22 && c <= 0x4F)
c = (unsigned char)(0x71 - c);
else if (c >= 0x50 && c <= 0x7E)
c = (unsigned char)(0xCD - c);
}
else
{
if (c >= 0x22 && c <= 0x7E)
c = (unsigned char)(0x9F - c);
}
chars[i] = c;
flippy = !flippy;
}
return chars;
}
std::string EncodeEMFString(std::string chars)
{
bool flippy = (chars.length() % 2) == 1;
for (std::size_t i = 0; i < chars.length(); ++i)
{
unsigned char c = chars[i];
if (flippy)
{
if (c >= 0x22 && c <= 0x4F)
c = (unsigned char)(0x71 - c);
else if (c >= 0x50 && c <= 0x7E)
c = (unsigned char)(0xCD - c);
}
else
{
if (c >= 0x22 && c <= 0x7E)
c = (unsigned char)(0x9F - c);
}
chars[i] = c;
flippy = !flippy;
}
reverse(chars.begin(), chars.end());
return chars;
}
}
| 17.624025 | 144 | 0.589449 | Cirras |
627b5d30a69101c87233a69fde12f17eee36e414 | 180 | cpp | C++ | plasma_lambda/test2.cpp | plasma-effect/plasma_lambda | e2113076cd792e76237bd4f37869c6f39534d16f | [
"BSL-1.0"
] | null | null | null | plasma_lambda/test2.cpp | plasma-effect/plasma_lambda | e2113076cd792e76237bd4f37869c6f39534d16f | [
"BSL-1.0"
] | null | null | null | plasma_lambda/test2.cpp | plasma-effect/plasma_lambda | e2113076cd792e76237bd4f37869c6f39534d16f | [
"BSL-1.0"
] | null | null | null | #include"test.hpp"
#if TEST_CODE == 2
#include<iostream>
void test()
{
using namespace plasma::lambda;
auto func = _<1>();
std::cout << func(1, 2, 3) << std::endl;
}
#endif | 12 | 41 | 0.616667 | plasma-effect |
62833a86648c6b50eafb78f2dcb1f5c7c34d5803 | 278 | cpp | C++ | Challenges - Fundamentals/Print Series.cpp | helewrer3/CB_Launchpad | cda17f62a25e15cb914982d1cc24f7ba0e2f7a67 | [
"Unlicense"
] | 3 | 2019-10-04T13:24:16.000Z | 2020-01-22T05:07:02.000Z | Challenges - Fundamentals/Print Series.cpp | helewrer3/CB_Launchpad | cda17f62a25e15cb914982d1cc24f7ba0e2f7a67 | [
"Unlicense"
] | null | null | null | Challenges - Fundamentals/Print Series.cpp | helewrer3/CB_Launchpad | cda17f62a25e15cb914982d1cc24f7ba0e2f7a67 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
//Variables
int N1, N2, n = 1, val;
//Input
cin >> N1 >> N2;
// Process
while(n <= N1)
{
val = 3*n+2;
if(val%N2 != 0)
printf("%d\n", val);
else
N1++;
n++;
}
return 0;
} | 11.12 | 24 | 0.456835 | helewrer3 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.