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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3f71b7b2cd73f8dec8005e0dbe0616a2b6e7fcd1 | 3,960 | cpp | C++ | src/Client.cpp | texus/SpaceInvaders | aa43408e1579208cb6aed7a2af8ab29477447bd6 | [
"Zlib"
] | 1 | 2017-11-27T17:39:12.000Z | 2017-11-27T17:39:12.000Z | src/Client.cpp | texus/SpaceInvaders | aa43408e1579208cb6aed7a2af8ab29477447bd6 | [
"Zlib"
] | null | null | null | src/Client.cpp | texus/SpaceInvaders | aa43408e1579208cb6aed7a2af8ab29477447bd6 | [
"Zlib"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2013 Bruno Van de Velde (vdv_b@tgui.eu)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <SpaceInvaders/Client.hpp>
#include <SpaceInvaders/View/SFMLView.hpp>
namespace Game
{
////////////////////////////////////////////////////////////////////////////////////////////////////////
Client::Client()
{
loadNextLevel(Event{Event::Type::LevelComplete});
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
void Client::mainLoop()
{
sf::Clock clock;
// The main loop
while (m_running)
{
if (m_gameState == GameState::Playing)
m_controller->update(clock.restart());
else
clock.restart();
m_view->handleEvents();
m_view->draw();
sf::sleep(sf::milliseconds(1));
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
void Client::loadNextLevel(const Event&)
{
m_difficulty++;
m_view = std::unique_ptr<View::AbstractView>(new View::SFMLView{m_gameState, m_score});
m_controller = std::unique_ptr<Controller::Controller>(new Controller::Controller{m_view.get(), m_difficulty});
m_view->addObserver(std::bind(&Client::gameStateChanged, this, std::placeholders::_1), Event::Type::GameStateChanged);
// This function should be called again when the level is over
m_controller->addObserver(std::bind(&Client::loadNextLevel, this, std::placeholders::_1), Event::Type::LevelComplete);
// The program should quit when receiving the exit event
m_view->addObserver([this](const Event&){ m_running = false; }, Event::Type::ApplicationExit);
m_controller->addObserver(std::bind(&Client::gameOver, this, std::placeholders::_1), Event::Type::GameOver);
// Increase the score when an enemy gets killed
m_controller->addObserver([this](const Event& event){ m_score += event.score; }, Event::Type::ScoreChanged);
// Let the view know the current score
Event scoreEvent{Event::Type::ScoreChanged};
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
void Client::gameStateChanged(const Event& event)
{
m_gameState = event.gameState;
if (m_gameState == GameState::MainMenu)
m_score = 0;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
void Client::gameOver(const Event& event)
{
m_gameState = GameState::GameOver;
m_difficulty = 0;
loadNextLevel(event);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////
}
| 37.714286 | 126 | 0.507576 | texus |
3f73de2e36464439c9c6dd15f62f61d4c97c5569 | 3,710 | cpp | C++ | Connector/UserList.cpp | openlastchaos/lastchaos-source-server | 935b770fa857e67b705717d154b11b717741edeb | [
"Apache-2.0"
] | null | null | null | Connector/UserList.cpp | openlastchaos/lastchaos-source-server | 935b770fa857e67b705717d154b11b717741edeb | [
"Apache-2.0"
] | null | null | null | Connector/UserList.cpp | openlastchaos/lastchaos-source-server | 935b770fa857e67b705717d154b11b717741edeb | [
"Apache-2.0"
] | 1 | 2022-01-17T09:34:39.000Z | 2022-01-17T09:34:39.000Z | #include "stdhdrs.h"
#include "Server.h"
#include "User.h"
#include "UserList.h"
#include "Log.h"
#include "ProcConnMsg.h"
UserList::UserList(int max_channel_count)
{
init_(max_channel_count);
}
UserList::~UserList()
{
std::vector<channel_info*>::iterator it = vec_channel_info.begin();
std::vector<channel_info*>::iterator it_end = vec_channel_info.end();
for(; it != it_end; it++)
{
delete (*it);
}
}
int UserList::getUserCountInChannel( int channelNo )
{
return vec_channel_info[channelNo - 1]->user_count;
}
bool UserList::insert_( CUser* user )
{
if(findByUserIndex(user->m_index) != NULL)
return false;
login_user_info user_info;
user_info.user = user;
user_info.user_index = user->m_index;
user_info.user_name = user->m_name;
_map.insert(user_info);
vec_channel_info[user->m_subnum - 1]->user_count++;
GAMELOG << init("PLAYER_ADD", user->m_name)
<< vec_channel_info[user->m_subnum - 1]->user_count
<<end;
return true;
}
void UserList::delete_( CUser* user )
{
if( user == NULL )
return;
vec_channel_info[user->m_subnum - 1]->user_count--;
GAMELOG << init("PLAYER_DEL", user->m_name)
<< vec_channel_info[user->m_subnum - 1]->user_count
<<end;
_map.erase(user->m_index);
delete user;
return;
}
CUser* UserList::findByUserIndex( int user_index )
{
map_t::index<key_index>::type& use_tag = _map.get<key_index>();
map_t::index<key_index>::type::iterator it = use_tag.find(user_index);
const login_user_info& user_info = (*it);
if( it == use_tag.end() )
return NULL;
return user_info.user;
}
CUser* UserList::findByUserName( std::string user_name )
{
const map_t::index<key_name>::type& use_tag = _map.get<key_name>();
map_t::index<key_name>::type::iterator it = use_tag.find(user_name);
const login_user_info& user_info = (*it);
if( it == use_tag.end() )
return NULL;
return user_info.user;
}
int UserList::increasePlayerZoneCount( int channelNo, int zone_index )
{
if(channelNo > gserver.m_maxSubServer)
return -1;
if(zone_index > MAX_ZONES)
return -1;
return (vec_channel_info[channelNo - 1]->playersPerZone[zone_index])++;
}
int UserList::decreasePlayerZoneCount( int channelNo, int zone_index )
{
if(channelNo > gserver.m_maxSubServer)
return -1;
if(zone_index > MAX_ZONES)
return -1;
return (vec_channel_info[channelNo - 1]->playersPerZone[zone_index])--;
}
int UserList::getPlayerZoneCount( int channelNo, int zone_index )
{
if(channelNo > gserver.m_maxSubServer)
return -1;
if(zone_index > MAX_ZONES)
return -1;
return vec_channel_info[channelNo - 1]->playersPerZone[zone_index];
}
void UserList::setPlayerZoneCount( int channelNo, int zone_index, int count )
{
if(channelNo > gserver.m_maxSubServer)
return ;
if(zone_index > MAX_ZONES)
return ;
vec_channel_info[channelNo - 1]->playersPerZone[zone_index] = count;
}
void UserList::init_( int max_channel_count )
{
for(int i = 0; i < max_channel_count; i++)
{
channel_info* data = new channel_info();
this->vec_channel_info.push_back(data);
}
}
void UserList::logout_all( CDescriptor* d )
{
if(d == NULL)
return;
map_t::iterator it = _map.begin();
map_t::iterator it_end = _map.end();
login_user_info user_info;
for( ; it != it_end ; )
{
user_info = (*it);
if(user_info.user == NULL)
{
_map.erase(user_info.user_index);
it = _map.begin();
it_end = _map.end();
continue;
}
if(user_info.user->m_descserver == d)
{
CNetMsg::SP rmsg(new CNetMsg);
rmsg->Init(MSG_CONN_REQ);
RefMsg(rmsg) << (unsigned char)MSG_CONN_LOGOUT_REQ
<< user_info.user->m_name;
gserver.ProcessLogout(user_info.user);
it = _map.begin();
it_end = _map.end();
}
else
{
it++;
}
}
}
| 19.734043 | 77 | 0.695418 | openlastchaos |
3f76f281046daa25566549bc3fdeac6cfa191d54 | 4,962 | cpp | C++ | src/core/animation.cpp | cubic1271/leaps | 492cdcddfc0b3f63b657da94fc4a4303980dd07f | [
"Zlib",
"CC0-1.0",
"MIT"
] | null | null | null | src/core/animation.cpp | cubic1271/leaps | 492cdcddfc0b3f63b657da94fc4a4303980dd07f | [
"Zlib",
"CC0-1.0",
"MIT"
] | null | null | null | src/core/animation.cpp | cubic1271/leaps | 492cdcddfc0b3f63b657da94fc4a4303980dd07f | [
"Zlib",
"CC0-1.0",
"MIT"
] | null | null | null | #include <core/twilight.h>
#include <cmath>
#include <simple2d/simple2d.h>
#include "core/animation.h"
#include "core/resource.h"
#include "core/state.h"
static twilight::AnimationManager* _animation = nullptr;
int twilight::AnimatedSprite::load(S2D_Sprite* sprite, const uint32_t width, const uint32_t height, const bool loop) {
this->sprite = sprite;
this->width = width;
this->height = height;
this->should_loop = loop;
if(this->sprite) {
return twilight::TWILIGHT_OK;
}
return twilight::TWILIGHT_ERROR;
}
int twilight::AnimatedSprite::start() {
state = TWILIGHT_ANIM_RUNNING;
return twilight::TWILIGHT_OK;
}
int twilight::AnimatedSprite::stop() {
state = TWILIGHT_ANIM_STOP;
return twilight::TWILIGHT_OK;
}
int twilight::AnimatedSprite::reset() {
elapsed = 0.0;
return twilight::TWILIGHT_OK;
}
void twilight::AnimatedSprite::update(double dt) {
elapsed += (state == TWILIGHT_ANIM_RUNNING) ? dt : 0.0;
}
S2D_Sprite *twilight::AnimatedSprite::display() {
double sec_per_frame = 1.0 / double(fps);
auto frame = uint32_t(floor(elapsed / sec_per_frame));
if(frame * width >= sprite->img->width) {
if(should_loop) {
reset();
}
else {
state = TWILIGHT_ANIM_STOP;
}
return sprite;
}
S2D_ClipSprite(sprite, frame * width, 0, width, height);
return sprite;
}
void twilight::AnimatedText::update(double dt) {
timeElapsed += dt;
}
int twilight::AnimatedText::construct(AnimatedText* config) {
str = config->str;
font = config->font;
size = config->size;
locationStart = config->locationStart;
locationEnd = config->locationEnd;
colorStart = config->colorStart;
colorEnd = config->colorEnd;
timeElapsed = 0.0;
timeDuration = config->timeDuration;
ResourceManager* resource = ResourceManager::instance();
text = resource->getText(font, size);
if(nullptr == text) {
return twilight::TWILIGHT_ERROR;
}
S2D_SetText(text, str.c_str());
return twilight::TWILIGHT_OK;
}
void twilight::AnimatedText::render() {
WorldProjection* proj = WorldProjection::instance();
double frac = timeElapsed / timeDuration;
frac = frac > 1.0 ? 1.0 : frac;
ColorVec4 tColor = colorStart.mix(colorEnd, frac);
cv4_assign(text->color, tColor);
b2Vec2 tLocation = b2Vec2(locationStart.x * (1 - frac) + locationEnd.x * (frac),
locationStart.y * (1 - frac) + locationEnd.y * (frac));
tLocation = proj->worldToScreen(tLocation);
text->x = tLocation.x;
text->y = tLocation.y;
S2D_DrawText(text);
}
void twilight::AnimatedText::destroy() {
if(text) {
delete text;
}
}
twilight::AnimatedText twilight::AnimatedText::FadeTextDrift(std::string str, ColorVec4 color, b2Vec2 location, double duration, b2Vec2 speed, std::string font, int size) {
AnimatedText result;
result.str = str;
result.font = font;
result.size = size;
result.colorStart = color;
result.colorEnd = color;
result.colorEnd.a = 0.0;
result.locationStart = location;
result.locationEnd = b2Vec2(
location.x + (speed.x * duration),
location.y + (speed.y * duration)
);
result.timeDuration = duration;
return result;
}
void twilight::AnimationManager::update(double dt) {
for(auto entry : text) {
entry->update(dt);
}
auto iter = text.begin();
while(iter != text.end()) {
if((*iter)->expired()) {
text.erase(iter);
}
else {
++iter;
}
}
/*
text.erase(std::remove_if(
text.begin(),
text.end(),
[dt](AnimatedText* element) -> bool {
return element->expired();
}
));
*/
for(auto entry : sprite) {
entry->update(dt);
}
}
void twilight::AnimationManager::render() {
for(auto entry : text) {
entry->render();
}
WorldProjection* proj = WorldProjection::instance();
for(auto entry : sprite) {
S2D_Sprite* tSprite = entry->display();
b2Vec2 tLocation = entry->getLocation();
proj->worldToScreen(tLocation);
tSprite->x = tLocation.x;
tSprite->y = tLocation.y;
S2D_DrawSprite(tSprite);
}
}
void twilight::AnimationManager::addText(AnimatedText* aText) {
AnimatedText* nText = new AnimatedText;
nText->construct(aText);
text.push_back(nText);
}
void twilight::AnimationManager::addSprite(AnimatedSprite* aSprite) {
sprite.push_back(aSprite);
}
twilight::AnimationManager* twilight::AnimationManager::instance() {
if(!_animation) {
_animation = new AnimationManager;
}
return _animation;
}
| 27.414365 | 173 | 0.606207 | cubic1271 |
3f77d4632e2b98ac958a05d26dfadff941a35116 | 5,167 | cpp | C++ | main.cpp | nmalysheva/SSATAN-X | 1a7dcf1b8d3addf2b228109418e8a5a4ad161aae | [
"MIT"
] | null | null | null | main.cpp | nmalysheva/SSATAN-X | 1a7dcf1b8d3addf2b228109418e8a5a4ad161aae | [
"MIT"
] | null | null | null | main.cpp | nmalysheva/SSATAN-X | 1a7dcf1b8d3addf2b228109418e8a5a4ad161aae | [
"MIT"
] | null | null | null | #include <iostream>
#include <chrono>
#include <fstream>
#include <string>
#include "contact_network/ContactNetwork.h"
#include "algorithms/SSA.h"
#include "algorithms/SSATANX.h"
#include "utilities/types.h"
#include "utilities/Settings.h"
void saveInitialStates(nlohmann::ordered_json &output, const ContactNetwork &contNetwork, const Settings& settings)
{
output["initial_states"][Specie::S]["S"] = contNetwork.countByState(Specie::S);
output["initial_states"][Specie::I]["I"] = contNetwork.countByState(Specie::I);
output["initial_states"][Specie::D]["D"] = contNetwork.countByState(Specie::D);
output["start_edges"] = contNetwork.countEdges();
output["rate_of_make_a_new_contact"] = {settings.getNewConactRateParameters().a, settings.getNewConactRateParameters().b};
output["rate_of_loose_a_contact"] = {settings.getLooseConactRateParameters().a, settings.getLooseConactRateParameters().b};
//output["birth_rate"] = settings.getBirthRate();
output["diagnosis_rate"] = settings.getDiagnosisRate();
output["transmission_rate"] = settings.getTransmissionRate();
}
void saveOutput(nlohmann::ordered_json &output, const ContactNetwork &contNetwork, const NetworkStorage &nwStorage)
{
output["final_states"][Specie::S]["S"] = contNetwork.countByState(Specie::S);
output["final_states"][Specie::I]["I"] = contNetwork.countByState(Specie::I);
output["final_states"][Specie::D]["D"] = contNetwork.countByState(Specie::D);
size_t i = 0;
for (const auto &item : nwStorage)
{
size_t j = 0;
output["networkStates"][i]["time"] = item.first;
for (const auto &spcs : item.second)
{
output["networkStates"][i]["nw_states"][j]["id"] = spcs.id;
output["networkStates"][i]["nw_states"][j]["state"] = spcs.sp.getState();
output["networkStates"][i]["nw_states"][j]["rate_of_make_a_new_contact"] = spcs.sp.getNewContactRate();
output["networkStates"][i]["nw_states"][j]["rate_of_loose_a_contact"] = spcs.sp.getLooseContactRate();
output["networkStates"][i]["nw_states"][j]["death_rate"] = spcs.sp.getDeathRate();
output["networkStates"][i]["nw_states"][j]["diagnosis_rate"] = spcs.sp.getDiagnosisRate();
output["networkStates"][i]["nw_states"][j]["neighbors"] = spcs.contacts;
j ++;
}
i++;
}
}
void executeSSA(const Settings& settings)
{
ContactNetwork contNetwork(settings);
nlohmann::ordered_json output;
saveInitialStates(output, contNetwork, settings);
NetworkStorage nwStorage;
nwStorage.reserve(1e6 + 1);
auto start_time = std::chrono::high_resolution_clock::now();
auto const filename = std::chrono::system_clock::now().time_since_epoch().count();
SSA().execute(0, settings.getSimulationTime(), contNetwork, nwStorage);
auto end_time = std::chrono::high_resolution_clock::now();
auto time = end_time - start_time;
output["duration_in_milliseconds"] = std::chrono::duration <double, std::milli> (time).count();
saveOutput(output, contNetwork, nwStorage);
std::string fileName = "SSA_" + std::to_string(filename) + ".txt";
std::ofstream newFile;
newFile.open(fileName);
newFile << output << std::endl;
newFile.close();
}
void executeSSATANX(const Settings& settings)
{
ContactNetwork contNetwork(settings);
nlohmann::ordered_json output;
saveInitialStates(output, contNetwork, settings);
NetworkStorage nwStorage;
nwStorage.reserve(1e6 + 1);
size_t nRejections = 0;
size_t nAcceptance = 0;
size_t nThin = 0;
auto start_time = std::chrono::high_resolution_clock::now();
auto const filename = std::chrono::system_clock::now().time_since_epoch().count();
SSATANX().execute(0, settings.getSimulationTime(), contNetwork, nwStorage,nRejections, nAcceptance, nThin);
auto end_time = std::chrono::high_resolution_clock::now();
auto time = end_time - start_time;
std::string fileName = "SSX_" + std::to_string(filename) + ".txt";
output["duration_in_milliseconds"] = std::chrono::duration <double, std::milli> (time).count();
output["accepted"] = nAcceptance;
output["rejected"] = nRejections;
output["thined"] = nThin;
saveOutput(output, contNetwork, nwStorage);
std::ofstream newFile;
newFile.open(fileName);
newFile << output << std::endl;
newFile.close();
}
void viralDynamics(int argc, char* argv[])
{
std::string mode = std::string(argv[2]);
//size_t simulationNumber = std::stoi(argv[3]);
std::string fileName = std::string(argv[1]);
Settings settings;
settings.parseSettings(fileName);
if (mode=="-SSA")
{
executeSSA(settings);
}
else if (mode=="-SSX")
{
executeSSATANX(settings);
}
else
{
std::string msg = "Invalid algorthm specified";
throw std::domain_error(msg);
}
}
int main(int argc, char* argv[])
{
if (argc != 3)
{
std::string msg = "Invalid parameters";
throw std::domain_error(msg);
}
else
{
viralDynamics(argc, argv);
}
return 0;
}
| 33.551948 | 127 | 0.666151 | nmalysheva |
3f7fac708aa99c149751d95398167c92a44ffe3e | 2,999 | hh | C++ | mimosa/flat/flat.hh | abique/mimosa | 42c0041b570b55a24c606a7da79c70c9933c07d4 | [
"MIT"
] | 24 | 2015-01-19T16:38:24.000Z | 2022-01-15T01:25:30.000Z | mimosa/flat/flat.hh | abique/mimosa | 42c0041b570b55a24c606a7da79c70c9933c07d4 | [
"MIT"
] | 2 | 2017-01-07T10:47:06.000Z | 2018-01-16T07:19:57.000Z | mimosa/flat/flat.hh | abique/mimosa | 42c0041b570b55a24c606a7da79c70c9933c07d4 | [
"MIT"
] | 7 | 2015-01-19T16:38:31.000Z | 2020-12-12T19:10:30.000Z | #pragma once
# include <sys/types.h>
# include <sys/stat.h>
# include <fcntl.h>
# include <unistd.h>
# include <string>
# include <cstdint>
# include <cassert>
namespace mimosa
{
namespace flat
{
/**
* @class Flat
*
* This class is an helper to manage memory mapped.
* It is usefull when dealing with custom data structures mapped from
* the disk or on memory.
*
* @warning Flat rely on mremap() for brk() sbrk() and reserve(), so
* pointers obtained from base(), ptr() and ptr0() are valid until a
* mremap operation happened.
*/
class Flat
{
public:
/**
* This creates a flat memory mapping
*
* @param path the path to the file to be mapped, if path is empty
* then we will map RAM.
* @param oflags the open flags, see man 2 open
* @param mode the open mode, see
*/
Flat(const std::string & path, int oflags, mode_t mode);
~Flat();
/**
* checks that the flat mapping succeed
*/
inline bool ok() const { return base_; }
/**
* @return the used size
*/
inline size_t size() const { return size_; }
/**
* @return the mapped size
*/
inline size_t mappedSize() const { return mapped_size_; }
/**
* convient helper to know the base pointer of the memory mapping
*/
inline void * base() const { return base_; }
/**
* Ensure that we have at least size mapped
*/
bool reserve(size_t size);
/**
* increased the used size by @param increment
* @return true on success, and false otherwise, see errno.
*/
inline bool brk(ssize_t increment) { return sbrk(increment) != (void*)-1; }
/**
* increased the used size by @param increment
* @return the previous flat break pointer on success, (void*)-1 on error
*/
void * sbrk(ssize_t increment);
/**
* converts an address relative to the beginning of the flat memory
* mapping to a pointer
*/
inline void * ptr(size_t addr) const { return addr + base_; }
/**
* like ptr() but return nullptr if addr is 0
*/
inline void * ptr0(size_t addr) const { return addr > 0 ? addr + base_ : nullptr; }
/**
* converts a pointer to an address relative to the beginning of
* the flat memory mapping
*/
inline size_t addr(void * ptr) const {
assert(ptr >= base_ && base_ + size_ <= ptr);
return static_cast<uint8_t*> (ptr) - base_;
}
/**
* helper to round up size to PAGE_SIZE
*/
static inline size_t ceil(size_t size) {
if (size % PAGE_SIZE)
return size + PAGE_SIZE - size % PAGE_SIZE;
return size;
}
private:
static const long PAGE_SIZE;
int fd_;
uint8_t * base_;
size_t size_;
size_t mapped_size_;
};
}
}
| 25.415254 | 89 | 0.565522 | abique |
3f82f51b08b2c21cc6b39615b7e285c9426f84bc | 1,315 | cpp | C++ | rt/core/point.cpp | DasNaCl/old-university-projects | af1c82afec4805ea672e0c353369035b394cb69d | [
"Apache-2.0"
] | null | null | null | rt/core/point.cpp | DasNaCl/old-university-projects | af1c82afec4805ea672e0c353369035b394cb69d | [
"Apache-2.0"
] | null | null | null | rt/core/point.cpp | DasNaCl/old-university-projects | af1c82afec4805ea672e0c353369035b394cb69d | [
"Apache-2.0"
] | null | null | null | #include <core/assert.h>
#include <core/float4.h>
#include <core/point.h>
#include <core/scalar.h>
#include <core/vector.h>
#include <algorithm>
#include <cmath>
namespace rt
{
Point::Point(const Float4& f4)
: x()
, y()
, z()
{
//assert(std::fabs(f4[3] - 1.f) < rt::epsilon);
if(f4[3] == 0)
{
x = f4[0];
y = f4[1];
z = f4[2];
}
else
{
x = f4[0] / f4[3];
y = f4[1] / f4[3];
z = f4[2] / f4[3];
}
}
Vector Point::operator-(const Point& b) const
{
return Vector(x - b.x, y - b.y, z - b.z);
}
bool Point::operator==(const Point& b) const
{
return std::fabs(x - b.x) < rt::epsilon && std::fabs(y - b.y) < rt::epsilon &&
std::fabs(z - b.z) < rt::epsilon;
}
bool Point::operator!=(const Point& b) const
{
return std::fabs(x - b.x) > rt::epsilon || std::fabs(y - b.y) > rt::epsilon ||
std::fabs(z - b.z) > rt::epsilon;
}
Point operator*(float scalar, const Point& b)
{
return Point(scalar * b.x, scalar * b.y, scalar * b.z);
}
Point operator*(const Point& a, float scalar)
{
return scalar * a;
}
Point min(const Point& a, const Point& b)
{
return Point(std::min(a.x, b.x), std::min(a.y, b.y), std::min(a.z, b.z));
}
Point max(const Point& a, const Point& b)
{
return Point(std::max(a.x, b.x), std::max(a.y, b.y), std::max(a.z, b.z));
}
}
| 18.785714 | 80 | 0.556654 | DasNaCl |
3f8385305d24e1f06891371c6aa908593e6be346 | 400 | hpp | C++ | include/Container.hpp | syoch/wiiu-libgu | 6744c46c9522c1a6def23aa613e8b759c50064c4 | [
"MIT"
] | 1 | 2021-02-26T15:49:54.000Z | 2021-02-26T15:49:54.000Z | include/Container.hpp | syoch/wiiu-libgui | 6744c46c9522c1a6def23aa613e8b759c50064c4 | [
"MIT"
] | null | null | null | include/Container.hpp | syoch/wiiu-libgui | 6744c46c9522c1a6def23aa613e8b759c50064c4 | [
"MIT"
] | null | null | null | #pragma once
#ifndef LIBGUI_CONTAINER
#define LIBGUI_CONTAINER
#include <vector>
#include "ContainerBase.hpp"
namespace GUI
{
class Container : public virtual ContainerBase, public virtual WidgetBase
{
public:
Container(ContainerBase &super, int x, int y, int w, int h);
void _draw() override;
void hide() override;
void show() override;
};
}
#endif | 20 | 77 | 0.67 | syoch |
3f8fc89bab828b99b641295c68067cb9f1f58cec | 1,850 | cpp | C++ | matrix_formula/main.cpp | nkhatsko/tasks | a22cf0325cd2c563d39b247e12d910da9fa4f938 | [
"MIT"
] | null | null | null | matrix_formula/main.cpp | nkhatsko/tasks | a22cf0325cd2c563d39b247e12d910da9fa4f938 | [
"MIT"
] | null | null | null | matrix_formula/main.cpp | nkhatsko/tasks | a22cf0325cd2c563d39b247e12d910da9fa4f938 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
std::vector<int> get_vector(std::string print, char separator, char end) {
std::cout << print;
std::string str;
std::vector<int> vector;
while ((std::getline(std::cin, str, separator) && str.back() != end)) {
vector.push_back(std::atoi(str.c_str()));
};
return (vector);
};
std::vector<std::vector<int>> get_matrix(std::vector<int> vector) {
std::vector<std::vector<int>> matrix;
for (int n = 0; n < vector.size() - 1; n++) {
matrix.push_back({});
for (auto el : vector) {
matrix.back().push_back(pow(el, n));
};
};
return (matrix);
};
void print(const std::vector<std::vector<int>> &matrix) {
for (int i = 0; i < matrix.size(); i++) {
std::cout << "| ";
for (int n = 0; n < matrix[i].size(); n++) {
std::vector<int> line;
for (int t = 0; t < matrix.size(); t++) {
line.push_back(matrix[t][n]);
};
int max = std::to_string(
line[
std::distance(
line.begin(),
std::max_element(
line.begin(),
line.end()))
]
).size();
std::cout << matrix[i][n];
int el_len = std::to_string(matrix[i][n]).size();
while (el_len <= max) {
std::cout << ' ';
el_len++;
};
};
std::cout << '|' << '\n';
};
};
int main() {
std::cout << "│ x1:1^(n-1) x1:2^(n-1) x1:3^(n-1) ... x1:n^(n-1) │" << '\n';
std::cout << "│ · │" << '\n';
std::cout << "│ · │" << '\n';
std::cout << "│ · │" << '\n';
std::cout << "│ xm:1^(n-1) xm:2^(n-1) xm:3^(n-1) ... xm:n^(n-1) │" << '\n';
std::cout << '\n';
while (true) {
auto vector = get_vector("enter vector: ", ' ', ';');
auto matrix = get_matrix(vector);
print(matrix);
std::cout << '\n';
};
return (0);
};
| 21.511628 | 76 | 0.475135 | nkhatsko |
3f92f360b98a412392412917d7ed6b0c3c0171ab | 3,475 | cpp | C++ | Enemy.cpp | FroxCode/Portfolio-MOSH | 76748ccc1e1ec05cc0803ca0819c4ad6be99cab9 | [
"MIT"
] | null | null | null | Enemy.cpp | FroxCode/Portfolio-MOSH | 76748ccc1e1ec05cc0803ca0819c4ad6be99cab9 | [
"MIT"
] | null | null | null | Enemy.cpp | FroxCode/Portfolio-MOSH | 76748ccc1e1ec05cc0803ca0819c4ad6be99cab9 | [
"MIT"
] | null | null | null | //Created by Cmag, Dsin
#include "Enemy.h"
Enemy::Enemy(){}
Enemy::~Enemy(){}
Enemy::Enemy(string const &texture, string const &deathSnd, vector<shared_ptr<Vector2f>> nodes) :
animatedSprite(sf::seconds(0.2f), true, false)
{
startPoint = Vector2f(nodes.at(0)->x -96, nodes.at(0)->y); //set the start node
endPoint = *nodes.at(0); //set the first end point
m_nodeIndex = 0;//what node the enemy is on
animatedSprite.setOrigin(32, 32); //set origin of sprite
m_position = startPoint; //set the start position
bounds = IntRect(Vector2i(m_position), Vector2i(64, 64));
for (int i = 0; i < nodes.size(); i++)
{
m_nodes.push_back(Vector2f(nodes.at(i)->x,nodes.at(i)->y)); //read in the path for the enemy to walk
}
if (!m_texture.loadFromFile(texture))
{
std::string s("Error loading texture");
throw std::exception(s.c_str());
}
deathSound.reCreate(deathSnd, 60); //set sound for dying
walkingAnimation.setSpriteSheet(m_texture); //Frames for animating
walkingAnimation.addFrame(sf::IntRect(0, 0, 64, 64));
walkingAnimation.addFrame(sf::IntRect(64, 0, 64, 64));
walkingAnimation.addFrame(sf::IntRect(128, 0, 64, 64));
walkingAnimation.addFrame(sf::IntRect(192, 0, 64, 64));
currentAnimation = &walkingAnimation;
distance = sqrt(((endPoint.x - startPoint.x) * (endPoint.x - startPoint.x)) + ((endPoint.y - startPoint.y) * (endPoint.y - startPoint.y))); //get distance to first point
direction = Vector2f((endPoint.x - startPoint.x) / distance, (endPoint.y - startPoint.y) / distance);//get direction vector to first point
}
void Enemy::animate()
{
animatedSprite.setPosition(sf::Vector2f(m_position.x, m_position.y));
m_time = m_clock.restart();
animatedSprite.play(*currentAnimation); //plays animation of the guy walking
animatedSprite.move(Vector2f(1, 0) * m_time.asSeconds());
animatedSprite.update(m_time);
}
void Enemy::render(RenderWindow &window)
{
if (m_isAlive)
{
animate();
window.draw(animatedSprite);
}
}
void Enemy::update()
{
switch (state)
{
case Enemy::Idle:
break;
case Enemy::Walking:
if (slowed)
{ //if he's slowed, start a timer
slowTimer++;
if (slowTimer >= 180)
{ //when the timer hits 3 seconds, speed him back up
slowed = false;
m_velocity *= 2;
slowTimer = 0;
}
}
if (health <= 0)
{ //dead
state = Death;
deathSound.playSingle();
}
if ( std::abs(m_position.x - endPoint.x) < 2 && std::abs(m_position.y - endPoint.y) < 2)
{ //if the enemy hits the endpoint
m_nodeIndex++; //increase the node index
if (m_nodeIndex >= m_nodes.size())
{
state = State::Attacking; //attack if at the end node
break;
}
//reset pathing
startPoint = endPoint;
endPoint = m_nodes.at(m_nodeIndex);
m_position = startPoint;
distance = sqrt(((endPoint.x - startPoint.x) * (endPoint.x - startPoint.x)) + ((endPoint.y - startPoint.y) * (endPoint.y - startPoint.y)));
direction = Vector2f((endPoint.x - startPoint.x) / distance, (endPoint.y - startPoint.y) / distance);
}
else
{
m_position.x += direction.x * m_velocity * FPS; //move towards target node
m_position.y += direction.y * m_velocity * FPS;
}
break;
case Enemy::Attacking:
break;
case Enemy::Death:
m_isAlive = false;
m_position = Vector2f(-100, -100);
break;
default:
break;
}
bounds = IntRect(Vector2i(m_position.x - 32, m_position.y - 32), Vector2i(64, 64)); //set bound rectangle
}
void Enemy::slow()
{
slowed = true;
m_velocity /= 2;
}
| 29.449153 | 170 | 0.673669 | FroxCode |
3f93a1cf5f60f2ea6daaa230d0f4f64a31c9b33f | 14,727 | hpp | C++ | task-movement/Koala/graph/view.hpp | miloszc/task-movement | 26b40595b590b0fcc3c226fbe8576faa3b5c1244 | [
"MIT"
] | null | null | null | task-movement/Koala/graph/view.hpp | miloszc/task-movement | 26b40595b590b0fcc3c226fbe8576faa3b5c1244 | [
"MIT"
] | 19 | 2019-02-15T09:04:22.000Z | 2020-06-23T21:42:29.000Z | task-movement/Koala/graph/view.hpp | miloszc/task-movement | 26b40595b590b0fcc3c226fbe8576faa3b5c1244 | [
"MIT"
] | 1 | 2019-05-04T16:12:25.000Z | 2019-05-04T16:12:25.000Z | // Subgraph
template< class Graph, class VChooser, class EChooser >
Subgraph< Graph,VChooser,EChooser >::Subgraph( const Graph &g, std::pair< VChooser,EChooser > chs,
std::pair< bool,bool > fr):
SubgraphBase(), vchoose( chs.first ), echoose( chs.second ), counters( fr )
{
SubgraphBase::link( &g );
}
template< class Graph, class VChooser, class EChooser >
Subgraph< Graph,VChooser,EChooser >::Subgraph( std::pair< VChooser,EChooser > chs,
std::pair< bool,bool > fr):
SubgraphBase(), vchoose( chs.first ), echoose( chs.second ), counters( fr )
{}
template< class Graph, class VChooser, class EChooser >
void Subgraph< Graph,VChooser,EChooser >::setChoose( const std::pair< VChooser,EChooser > &chs )
{
vchoose = chs.first;
echoose = chs.second;
counters.reset(true,true);
}
template< class Graph, class VChooser, class EChooser >
bool Subgraph< Graph,VChooser,EChooser >::good( PVertex vert, bool deep ) const
{
if (!vert) return true;
if (deep) return up().good( vert,true ) && vchoose( vert,up() );
else return vchoose( vert,up() );
// return vchoose( vert,up() ) && (!deep || up().good( vert,true ));
}
template< class Graph, class VChooser, class EChooser >
bool Subgraph< Graph,VChooser,EChooser >::good( PEdge edge, bool deep ) const
{
if (!edge) return true;
std::pair< PVertex,PVertex > ends = edge->getEnds();
if (deep) return up().good( edge,true ) && vchoose( ends.first,up() ) && vchoose( ends.second,up() ) && echoose( edge,up() );
else return vchoose( ends.first,up() ) && vchoose( ends.second,up() ) && echoose( edge,up() );
// return vchoose( ends.first,up() ) && vchoose( ends.second,up() )
// && echoose( edge,up() ) && (!deep || up().good( edge,true ));
}
template< class Graph, class VChooser, class EChooser > typename Subgraph< Graph,VChooser,EChooser >::PVertex
Subgraph< Graph,VChooser,EChooser >::getVertNext( PVertex v ) const
{
do
v = up().getVertNext( v );
while (v && !vchoose( v,up() ));
return v;
}
template< class Graph, class VChooser, class EChooser > typename Subgraph< Graph,VChooser,EChooser >::PVertex
Subgraph< Graph,VChooser,EChooser >::getVertPrev( PVertex v ) const
{
do
v = up().getVertPrev( v );
while (v && !vchoose( v,up() ));
return v;
}
template< class Graph, class VChooser, class EChooser > typename Subgraph< Graph,VChooser,EChooser >::PEdge
Subgraph< Graph,VChooser,EChooser >::getEdgeNext( PEdge e, EdgeDirection mask ) const
{
do
e = up().getEdgeNext( e,mask );
while (e && !(vchoose( up().getEdgeEnd1( e ),up() )
&& vchoose( up().getEdgeEnd2( e ),up() ) && echoose( e,up() )));
return e;
}
template< class Graph, class VChooser, class EChooser > typename Subgraph< Graph,VChooser,EChooser >::PEdge
Subgraph< Graph,VChooser,EChooser >::getEdgeNext( PVertex vert, PEdge e, EdgeDirection mask ) const
{
do
e = up().getEdgeNext( vert,e,mask );
while (e && !(vchoose( e->getEnd(vert),up() ) && echoose( e,up() )));
return e;
}
template< class Graph, class VChooser, class EChooser > typename Subgraph< Graph,VChooser,EChooser >::PEdge
Subgraph< Graph,VChooser,EChooser >::getEdgePrev( typename Subgraph< Graph,VChooser,EChooser >::PEdge e,
EdgeDirection mask ) const
{
do
e = up().getEdgePrev( e,mask );
while (e && !(vchoose( up().getEdgeEnd1(e),up() )
&& vchoose( up().getEdgeEnd2(e),up() ) && echoose( e,up() )));
return e;
}
template< class Graph, class VChooser, class EChooser >
int Subgraph< Graph,VChooser,EChooser >::getVertNo( ) const
{
const typename Subgraph< Graph,VChooser,EChooser >::RootGrType *res = getRootPtr();
koalaAssert( res,GraphExc );
bool b;
if (isBoolChooser(vchoose,b))
if (b) return up().getVertNo();
else return 0;
else if (counters.freezev && counters.vcount!=-1) return counters.vcount;
else return counters.vcount=this->getVerts( blackHole );
}
template< class Graph, class VChooser, class EChooser >
int Subgraph< Graph,VChooser,EChooser >::getEdgeNo( EdgeDirection mask ) const
{
const typename Subgraph< Graph,VChooser,EChooser >::RootGrType *res = getRootPtr();
koalaAssert( res,GraphExc );
bool bv,be;
EdgeType amask;
if (isBoolChooser(vchoose,bv) && isBoolChooser(echoose,be))
{ if (!bv || !be) return 0;
return up().getEdgeNo(mask);
}
if (isBoolChooser(vchoose,bv) && isEdgeTypeChooser(echoose,amask))
{ if (!bv) return 0;
return up().getEdgeNo(mask&amask);
}
if (!(counters.freezee && counters.eloopcount!=-1))
{
counters.eloopcount=counters.eundircount=counters.edircount=0;
PEdge edge = this->getEdgeNext((PEdge)0,EdAll);
while (edge) {
switch (this->getEdgeType( edge ))
{
case Loop: counters.eloopcount++; break;
case Undirected: counters.eundircount++; break;
case Directed: counters.edircount++; break;
default : assert(0);
}
edge = this->getEdgeNext(edge,EdAll);
}
}
return ((mask & EdLoop) ? counters.eloopcount : 0 )
+((mask & EdUndir) ? counters.eundircount : 0)
+((mask & (EdDirIn|EdDirOut)) ? counters.edircount : 0);
}
template< class Graph, class VChooser, class EChooser > typename Subgraph< Graph,VChooser,EChooser >::PEdge
Subgraph< Graph,VChooser,EChooser >::getEdgePrev( PVertex vert, PEdge e, EdgeDirection mask ) const
{
do
e = up().getEdgePrev( vert,e,mask );
while (e && !(vchoose( e->getEnd(vert),up() ) && echoose( e,up() )));
return e;
}
template< class Graph, class VChooser, class EChooser >
int Subgraph< Graph,VChooser,EChooser >::getEdgeNo( PVertex vert, EdgeDirection mask ) const
{
bool bv,be;
EdgeType amask;
if (isBoolChooser(vchoose,bv) && isBoolChooser(echoose,be))
{ if (!bv || !be) return 0;
return up().getEdgeNo(vert,mask);
}
if (isBoolChooser(vchoose,bv) && isEdgeTypeChooser(echoose,amask))
{ if (!bv) return 0;
return up().getEdgeNo(vert,mask&amask);
}
return this->getEdges( blackHole,vert,mask );
}
template< class Graph, class VChooser, class EChooser > typename Subgraph< Graph,VChooser,EChooser >::PEdge
Subgraph< Graph,VChooser,EChooser >::getEdgeNext( PVertex vert1, PVertex vert2, PEdge e, EdgeDirection mask ) const
{
do
e = up().getEdgeNext( vert1,vert2,e,mask );
while (e && !(
echoose( e,up() )));
return e;
}
template< class Graph, class VChooser, class EChooser > typename Subgraph< Graph,VChooser,EChooser >::PEdge
Subgraph< Graph,VChooser,EChooser >::getEdgePrev( PVertex vert1, PVertex vert2, PEdge e, EdgeDirection mask ) const
{
do
e = up().getEdgePrev( vert1,vert2,e,mask );
while (e && !(
echoose( e,up() )));
return e;
}
template< class Graph, class VChooser, class EChooser >
int Subgraph< Graph,VChooser,EChooser >::getEdgeNo( PVertex vert1, PVertex vert2, EdgeDirection mask ) const
{
bool bv,be;
EdgeType amask;
if (isBoolChooser(vchoose,bv) && isBoolChooser(echoose,be))
{ if (!bv || !be) return 0;
return up().getEdgeNo(vert1,vert2,mask);
}
if (isBoolChooser(vchoose,bv) && isEdgeTypeChooser(echoose,amask))
{ if (!bv) return 0;
return up().getEdgeNo(vert1,vert2,mask&amask);
}
return this->getEdges( blackHole,vert1,vert2,mask );
}
template< class Graph, class VChooser, class EChooser >
Subgraph< Graph,VChooser,EChooser > makeSubgraph( const Graph &g, const std::pair< VChooser,EChooser > &chs,
std::pair< bool,bool > fr )
{
return Subgraph< Graph,VChooser,EChooser >( g,chs,fr );
}
template< class Graph, class VChooser, class EChooser >
const typename Subgraph< Graph,VChooser,EChooser >::RootGrType &Subgraph< Graph,VChooser,EChooser >::root() const
{
const typename Subgraph< Graph,VChooser,EChooser >::RootGrType *res = getRootPtr();
koalaAssert( res,GraphExc );
return *res;
}
template< class Graph, class VChooser, class EChooser >
const typename Subgraph< Graph,VChooser,EChooser >::ParentGrType &Subgraph< Graph,VChooser,EChooser >::up() const
{
const typename Subgraph< Graph,VChooser,EChooser >::ParentGrType *res = getParentPtr();
koalaAssert( res,GraphExc );
return *res;
}
template< class Graph, class VChooser, class EChooser >
bool Subgraph< Graph,VChooser,EChooser >::isEdgeTypeChooser( const EdgeTypeChooser &x, Koala::EdgeDirection &val )
{
val = x.mask;
return true;
}
template< class Graph, class VChooser, class EChooser >
bool Subgraph< Graph,VChooser,EChooser >::isBoolChooser( const BoolChooser &x, bool &val )
{
val = x.val;
return true;
}
// UndirView
template< class Graph > const typename UndirView< Graph >::ParentGrType &UndirView< Graph >::up() const
{
const typename UndirView< Graph >::ParentGrType *res = getParentPtr();
koalaAssert( res,GraphExc );
return *res;
}
template< class Graph > const typename UndirView< Graph >::RootGrType &UndirView< Graph >::root() const
{
const typename UndirView< Graph >::RootGrType *res = getRootPtr();
koalaAssert( res,GraphExc );
return *res;
}
template< class Graph > EdgeDirection UndirView< Graph >::getEdgeDir( PEdge edge, PVertex v ) const
{
EdgeDirection dir = up().getEdgeDir( edge,v );
return (dir == EdNone || dir == EdLoop) ? dir : EdUndir;
}
// RevView
template< class Graph > const typename RevView< Graph >::ParentGrType &RevView< Graph >::up() const
{
const typename RevView< Graph >::ParentGrType *res = getParentPtr();
koalaAssert( res,GraphExc );
return *res;
}
template< class Graph > const typename RevView< Graph >::RootGrType &RevView< Graph >::root() const
{
const RevView< Graph >::RootGrType *res = getRootPtr();
koalaAssert( res,GraphExc );
return *res;
}
template< class Graph > std::pair< typename RevView< Graph >::PVertex,typename RevView< Graph >::PVertex >
RevView< Graph >::getEdgeEnds( PEdge edge ) const
{
std::pair< typename RevView< Graph >::PVertex,typename RevView< Graph >::PVertex > res = up().getEdgeEnds( edge );
switch (up().getEdgeType( edge ))
{
case EdNone:
case Loop:
case Undirected: return res;
default: return std::make_pair( res.second,res.first );
}
}
template< class Graph > typename RevView< Graph >::PVertex RevView< Graph >::getEdgeEnd1( PEdge edge ) const
{
std::pair< typename RevView< Graph >::PVertex,typename RevView< Graph >::PVertex > res = up().getEdgeEnds( edge );
switch (up().getEdgeType( edge ))
{
case EdNone:
case Loop:
case Undirected: return res.first;
default: return res.second;
}
}
template< class Graph > typename RevView< Graph >::PVertex RevView< Graph >::getEdgeEnd2( PEdge edge ) const
{
std::pair< typename RevView< Graph >::PVertex,typename RevView< Graph >::PVertex > res = up().getEdgeEnds( edge );
switch (up().getEdgeType( edge ))
{
case EdNone:
case Loop:
case Undirected : return res.second;
default: return res.first;
}
}
template< class Graph > EdgeDirection RevView< Graph >::getEdgeDir( PEdge edge, PVertex v ) const
{
EdgeDirection dir = up().getEdgeDir( edge,v );
switch (dir)
{
case EdDirIn: return EdDirOut;
case EdDirOut: return EdDirIn;
default: return dir;
}
}
template< class Graph > EdgeDirection RevView< Graph >::transl( EdgeDirection mask )
{
EdgeDirection dirmask = mask & Directed;
switch (dirmask)
{
case Directed:
case 0: break;
case EdDirIn:
dirmask = EdDirOut;
break;
case EdDirOut:
dirmask = EdDirIn;
break;
}
return (mask & (~Directed)) | dirmask;
}
template< class Graph > EdgeDirection RevView< Graph >::nextDir( EdgeDirection dir )
{
switch (dir)
{
case EdLoop: return EdUndir;
case EdUndir: return EdDirOut;
case EdDirOut: return EdDirIn;
}
return EdNone;
}
template< class Graph > EdgeDirection RevView< Graph >::prevDir( EdgeDirection dir )
{ switch (dir)
{
case EdDirIn: return EdDirOut;
case EdDirOut: return EdUndir;
case EdUndir: return EdLoop;
}
return EdNone;
}
template< class Graph > typename RevView< Graph >::PEdge
RevView< Graph >::getNext( typename RevView< Graph >::PVertex vert, typename RevView< Graph >::PEdge edge,
EdgeDirection direct ) const
{
koalaAssert(vert,GraphExcNullVert);
koalaAssert(!(edge && !this->isEdgeEnd( edge,vert )),GraphExcWrongConn);
if (!direct) return NULL;
EdgeDirection type = up().getEdgeDir( edge,vert );
EdgeDirection nexttype = (type == EdNone) ? EdLoop : nextDir(type);
PEdge res;
if (edge && (type & direct)) res = up().getEdgeNext(vert,edge,type);
else res = 0;
if (res) return res;
switch (nexttype)
{
case EdLoop:
if (direct & EdLoop) res = up().getEdgeNext(vert,(PEdge)0,EdLoop);
if (res) return res;
case EdUndir:
if (direct & EdUndir) res = up().getEdgeNext(vert,(PEdge)0,EdUndir);
if (res) return res;
case EdDirOut:
if (direct & EdDirOut) res = up().getEdgeNext(vert,(PEdge)0,EdDirOut);
if (res) return res;
case EdDirIn:
if (direct & EdDirIn) res = up().getEdgeNext(vert,(PEdge)0,EdDirIn);
}
return res;
}
template< class Graph > typename RevView< Graph >::PEdge
RevView< Graph >::getPrev( typename RevView< Graph >::PVertex vert, typename RevView< Graph >::PEdge edge,
EdgeDirection direct ) const
{
koalaAssert( vert,GraphExcNullVert );
koalaAssert( !(edge && !this->isEdgeEnd( edge,vert )),GraphExcWrongConn );
if (!direct) return NULL;
EdgeDirection type = up().getEdgeDir( edge,vert );
EdgeDirection nexttype = (type == EdNone) ? EdDirIn : prevDir(type);
PEdge res;
if (edge && (type & direct)) res = up().getEdgePrev( vert,edge,type );
else res = 0;
if (res) return res;
switch (nexttype)
{
case EdDirIn:
if (direct & EdDirIn) res = up().getEdgePrev( vert,(PEdge)0,EdDirIn );
if (res) return res;
case EdDirOut:
if (direct & EdDirOut) res = up().getEdgePrev( vert,(PEdge)0,EdDirOut );
if (res) return res;
case EdUndir:
if (direct & EdUndir) res = up().getEdgePrev( vert,(PEdge)0,EdUndir );
if (res) return res;
case EdLoop:
if (direct & EdLoop) res = up().getEdgePrev( vert,(PEdge)0,EdLoop );
if (res) return res;
}
return res;
}
template< class Graph > typename RevView< Graph >::PEdge
RevView< Graph >::getPrev( typename RevView< Graph >::PVertex vert1, typename RevView< Graph >::PVertex vert2,
typename RevView< Graph >::PEdge edge, EdgeDirection direct ) const
{
do
edge = getPrev( vert1,edge,direct );
while (edge && up().getEdgeEnd( edge,vert1 ) != vert2);
return edge;
}
template< class Graph > typename RevView< Graph >::PEdge
RevView< Graph >::getNext( typename RevView< Graph >::PVertex vert1, typename RevView< Graph >::PVertex vert2,
typename RevView< Graph >::PEdge edge, EdgeDirection direct ) const
{
do
edge = getNext( vert1,edge,direct );
while (edge && up().getEdgeEnd( edge,vert1 ) != vert2);
return edge;
}
| 32.654102 | 126 | 0.679908 | miloszc |
3fa35c464ee1c8739ef7654c5254fe9d652152e7 | 1,898 | hpp | C++ | src/Context.hpp | jparimaa/vk-start | 78d02373765614b21fdaff6756dc37eb3dc98dbd | [
"MIT"
] | null | null | null | src/Context.hpp | jparimaa/vk-start | 78d02373765614b21fdaff6756dc37eb3dc98dbd | [
"MIT"
] | null | null | null | src/Context.hpp | jparimaa/vk-start | 78d02373765614b21fdaff6756dc37eb3dc98dbd | [
"MIT"
] | null | null | null | #pragma once
#include "VulkanUtils.hpp"
#define GLFW_INCLUDE_VULKAN
#include <GLFW/glfw3.h>
#include <vector>
class Context final
{
public:
struct KeyEvent
{
int key;
int action;
};
Context();
~Context();
GLFWwindow* getGlfwWindow() const;
VkPhysicalDevice getPhysicalDevice() const;
VkDevice getDevice() const;
VkInstance getInstance() const;
const std::vector<VkImage>& getSwapchainImages() const;
VkQueue getGraphicsQueue() const;
VkCommandPool getGraphicsCommandPool() const;
VkSurfaceKHR getSurface() const;
bool update();
std::vector<KeyEvent> getKeyEvents();
glm::dvec2 getCursorPosition();
uint32_t acquireNextSwapchainImage();
void submitCommandBuffers(const std::vector<VkCommandBuffer>& commandBuffers);
private:
void initGLFW();
void createInstance();
void createWindow();
void handleKey(GLFWwindow* /*window*/, int key, int /*scancode*/, int action, int /*mods*/);
void enumeratePhysicalDevice();
void createDevice();
void createSwapchain();
void createCommandPools();
void createSemaphores();
void createFences();
VkInstance m_instance;
VkDebugUtilsMessengerEXT m_debugMessenger;
GLFWwindow* m_window;
bool m_shouldQuit = false;
std::vector<KeyEvent> m_keyEvents;
glm::dvec2 m_cursorPosition;
VkSurfaceKHR m_surface;
VkPhysicalDevice m_physicalDevice;
VkPhysicalDeviceProperties m_physicalDeviceProperties;
VkDevice m_device;
VkQueue m_graphicsQueue;
VkQueue m_computeQueue;
VkQueue m_presentQueue;
VkSwapchainKHR m_swapchain;
std::vector<VkImage> m_swapchainImages;
VkCommandPool m_graphicsCommandPool;
VkCommandPool m_computeCommandPool;
VkSemaphore m_imageAvailable;
VkSemaphore m_renderFinished;
std::vector<VkFence> m_inFlightFences;
uint32_t m_imageIndex;
};
| 27.507246 | 96 | 0.722339 | jparimaa |
3fa3aaef3a583494000c8abf974bc5d413d34426 | 13,906 | cc | C++ | src/components/application_manager/test/commands/hmi/simple_requests_to_hmi_test.cc | APipko/sdl_core | 7f7fcbb998fb17f2954fd103349af67ea9b71a3f | [
"BSD-3-Clause"
] | 2 | 2016-09-21T12:36:17.000Z | 2017-11-03T07:58:33.000Z | src/components/application_manager/test/commands/hmi/simple_requests_to_hmi_test.cc | APipko/sdl_core | 7f7fcbb998fb17f2954fd103349af67ea9b71a3f | [
"BSD-3-Clause"
] | 64 | 2016-04-21T10:30:58.000Z | 2020-01-30T11:17:36.000Z | src/components/application_manager/test/commands/hmi/simple_requests_to_hmi_test.cc | APipko/sdl_core | 7f7fcbb998fb17f2954fd103349af67ea9b71a3f | [
"BSD-3-Clause"
] | 12 | 2015-09-14T08:17:55.000Z | 2018-06-29T10:16:59.000Z | /*
* Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Copyright (c) 2017 Xevo Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the copyright holders nor the names of their contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "gtest/gtest.h"
#include "utils/shared_ptr.h"
#include "smart_objects/smart_object.h"
#include "application_manager/smart_object_keys.h"
#include "application_manager/commands/commands_test.h"
#include "application_manager/commands/command_request_test.h"
#include "application_manager/commands/command.h"
#include "application_manager/commands/hmi/allow_app_request.h"
#include "application_manager/commands/hmi/allow_all_apps_request.h"
#include "application_manager/commands/hmi/basic_communication_system_request.h"
#include "application_manager/commands/hmi/button_get_capabilities_request.h"
#include "application_manager/commands/hmi/navi_alert_maneuver_request.h"
#include "application_manager/commands/hmi/navi_audio_stop_stream_request.h"
#include "application_manager/commands/hmi/navi_get_way_points_request.h"
#include "application_manager/commands/hmi/navi_is_ready_request.h"
#include "application_manager/commands/hmi/navi_send_location_request.h"
#include "application_manager/commands/hmi/navi_show_constant_tbt_request.h"
#include "application_manager/commands/hmi/navi_stop_stream_request.h"
#include "application_manager/commands/hmi/navi_subscribe_way_points_request.h"
#include "application_manager/commands/hmi/navi_unsubscribe_way_points_request.h"
#include "application_manager/commands/hmi/navi_update_turn_list_request.h"
#include "application_manager/commands/hmi/sdl_activate_app_response.h"
#include "application_manager/commands/hmi/sdl_get_list_of_permissions_response.h"
#include "application_manager/commands/hmi/sdl_get_status_update_response.h"
#include "application_manager/commands/hmi/ui_scrollable_message_request.h"
#include "application_manager/commands/hmi/ui_set_app_icon_request.h"
#include "application_manager/commands/hmi/ui_set_display_layout_request.h"
#include "application_manager/commands/hmi/ui_set_global_properties_request.h"
#include "application_manager/commands/hmi/request_to_hmi.h"
#include "application_manager/commands/hmi/vi_get_vehicle_type_request.h"
#include "application_manager/commands/hmi/vi_is_ready_request.h"
#include "application_manager/commands/hmi/vi_read_did_request.h"
#include "application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h"
#include "application_manager/commands/hmi/dial_number_request.h"
#include "application_manager/commands/hmi/tts_is_ready_request.h"
#include "application_manager/commands/hmi/tts_set_global_properties_request.h"
#include "application_manager/commands/hmi/tts_speak_request.h"
#include "application_manager/commands/hmi/tts_stop_speaking_request.h"
#include "application_manager/commands/hmi/tts_get_supported_languages_request.h"
#include "application_manager/commands/hmi/tts_change_registration_request.h"
#include "application_manager/commands/hmi/tts_get_capabilities_request.h"
#include "application_manager/commands/hmi/tts_get_language_request.h"
#include "application_manager/commands/hmi/close_popup_request.h"
#include "application_manager/commands/hmi/ui_add_command_request.h"
#include "application_manager/commands/hmi/ui_add_submenu_request.h"
#include "application_manager/commands/hmi/ui_alert_request.h"
#include "application_manager/commands/hmi/ui_change_registration_request.h"
#include "application_manager/commands/hmi/ui_delete_command_request.h"
#include "application_manager/commands/hmi/ui_delete_submenu_request.h"
#include "application_manager/commands/hmi/ui_end_audio_pass_thru_request.h"
#include "application_manager/commands/hmi/ui_get_capabilities_request.h"
#include "application_manager/commands/hmi/ui_get_language_request.h"
#include "application_manager/commands/hmi/ui_get_supported_languages_request.h"
#include "application_manager/commands/hmi/ui_is_ready_request.h"
#include "application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h"
#include "application_manager/commands/hmi/ui_perform_interaction_request.h"
#include "application_manager/commands/hmi/vi_diagnostic_message_request.h"
#include "application_manager/commands/hmi/vi_get_dtcs_request.h"
#include "application_manager/commands/hmi/vi_get_vehicle_data_request.h"
#include "application_manager/commands/hmi/ui_set_media_clock_timer_request.h"
#include "application_manager/commands/hmi/ui_show_request.h"
#include "application_manager/commands/hmi/ui_slider_request.h"
#include "application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h"
#include "application_manager/commands/hmi/vr_add_command_request.h"
#include "application_manager/commands/hmi/vr_change_registration_request.h"
#include "application_manager/commands/hmi/vr_delete_command_request.h"
#include "application_manager/commands/hmi/vr_get_capabilities_request.h"
#include "application_manager/commands/hmi/vr_get_supported_languages_request.h"
#include "application_manager/commands/hmi/vr_get_language_request.h"
#include "application_manager/commands/hmi/vr_is_ready_request.h"
#include "application_manager/commands/hmi/vr_perform_interaction_request.h"
#include "application_manager/commands/hmi/allow_all_apps_request.h"
#include "application_manager/commands/hmi/basic_communication_system_request.h"
#include "application_manager/commands/hmi/button_get_capabilities_request.h"
#include "application_manager/commands/hmi/allow_app_request.h"
#include "application_manager/commands/hmi/navi_send_location_request.h"
#include "application_manager/commands/hmi/navi_unsubscribe_way_points_request.h"
#include "application_manager/commands/hmi/navi_update_turn_list_request.h"
#include "application_manager/commands/hmi/navi_show_constant_tbt_request.h"
#include "application_manager/commands/hmi/navi_stop_stream_request.h"
#include "application_manager/commands/hmi/navi_subscribe_way_points_request.h"
#include "application_manager/commands/hmi/sdl_policy_update.h"
#include "application_manager/commands/hmi/ui_set_icon_request.h"
#include "application_manager/commands/hmi/dial_number_request.h"
#include "application_manager/commands/hmi/ui_send_haptic_data_request.h"
#include "application_manager/test/include/application_manager/mock_event_dispatcher.h"
namespace test {
namespace components {
namespace commands_test {
namespace hmi_commands_test {
namespace simple_requests_to_hmi_test {
using ::testing::_;
using ::testing::Types;
using ::testing::NotNull;
using ::utils::SharedPtr;
namespace am_commands = application_manager::commands;
using am_commands::MessageSharedPtr;
using event_engine_test::MockEventDispatcher;
class RequestToHMITest : public CommandsTest<CommandsTestMocks::kIsNice> {};
TEST_F(RequestToHMITest, BasicMethodsOverloads_SUCCESS) {
SharedPtr<am_commands::RequestToHMI> command(
CreateCommand<am_commands::RequestToHMI>());
// Current implementation always return `true`
EXPECT_TRUE(command->Init());
EXPECT_NO_THROW(command->Run());
EXPECT_TRUE(command->CleanUp());
}
TEST_F(RequestToHMITest, SendRequest_SUCCESS) {
SharedPtr<am_commands::RequestToHMI> command(
CreateCommand<am_commands::RequestToHMI>());
EXPECT_CALL(app_mngr_, SendMessageToHMI(NotNull()));
command->SendRequest();
}
template <typename Command>
class RequestToHMICommandsTest
: public CommandsTest<CommandsTestMocks::kIsNice> {
public:
typedef Command CommandType;
};
template <typename Command>
class RequestToHMICommandsTest2 : public RequestToHMICommandsTest<Command> {};
template <typename Command>
class RequestToHMICommandsTest3
: public CommandRequestTest<CommandsTestMocks::kIsNice> {
public:
typedef Command CommandType;
};
typedef Types<am_commands::VIGetVehicleTypeRequest,
am_commands::VIReadDIDRequest,
am_commands::VISubscribeVehicleDataRequest,
am_commands::hmi::DialNumberRequest,
am_commands::ClosePopupRequest,
am_commands::TTSSetGlobalPropertiesRequest,
am_commands::TTSSpeakRequest,
am_commands::TTSStopSpeakingRequest,
am_commands::TTSGetSupportedLanguagesRequest,
am_commands::UIAddCommandRequest,
am_commands::UIAddSubmenuRequest,
am_commands::UIAlertRequest,
am_commands::UIChangeRegistrationRequest,
am_commands::UIDeleteCommandRequest,
am_commands::UIDeleteSubmenuRequest,
am_commands::UIEndAudioPassThruRequest,
am_commands::UIGetCapabilitiesRequest,
am_commands::UIGetLanguageRequest,
am_commands::UIGetSupportedLanguagesRequest,
am_commands::UIPerformAudioPassThruRequest,
am_commands::UIPerformInteractionRequest,
am_commands::VIDiagnosticMessageRequest,
am_commands::VIGetDTCsRequest,
am_commands::VIGetVehicleDataRequest,
am_commands::UISetMediaClockTimerRequest,
am_commands::UIShowRequest,
am_commands::VIUnsubscribeVehicleDataRequest,
am_commands::VRAddCommandRequest,
am_commands::VRChangeRegistrationRequest,
am_commands::VRDeleteCommandRequest,
am_commands::UISliderRequest,
am_commands::TTSChangeRegistrationRequest,
am_commands::TTSGetCapabilitiesRequest,
am_commands::TTSGetLanguageRequest,
am_commands::AllowAllAppsRequest,
am_commands::BasicCommunicationSystemRequest,
am_commands::ButtonGetCapabilitiesRequest,
am_commands::NaviSendLocationRequest,
am_commands::NaviUnSubscribeWayPointsRequest,
am_commands::NaviUpdateTurnListRequest,
am_commands::NaviShowConstantTBTRequest,
am_commands::NaviStopStreamRequest,
am_commands::NaviSubscribeWayPointsRequest,
am_commands::NaviAlertManeuverRequest,
am_commands::AudioStopStreamRequest,
am_commands::NaviGetWayPointsRequest,
am_commands::UISetGlobalPropertiesRequest,
am_commands::UISendHapticDataRequest> RequestCommandsList;
typedef Types<am_commands::UIScrollableMessageRequest,
am_commands::VRGetCapabilitiesRequest,
am_commands::UISetAppIconRequest,
am_commands::UiSetDisplayLayoutRequest,
am_commands::VRGetSupportedLanguagesRequest,
am_commands::VRGetLanguageRequest,
am_commands::VRPerformInteractionRequest,
am_commands::AllowAppRequest,
// TODO (OKozlov). Need to clarify why UT fails
// for UISetIconRequest
// am_commands::UISetIconRequest,
#if defined(PROPRIETARY_MODE) || defined(EXTERNAL_PROPRIETARY_MODE)
am_commands::SDLPolicyUpdate,
#endif
am_commands::hmi::DialNumberRequest> RequestCommandsList2;
typedef Types<am_commands::VIIsReadyRequest,
am_commands::TTSIsReadyRequest,
am_commands::UIIsReadyRequest,
am_commands::NaviIsReadyRequest,
am_commands::VRIsReadyRequest> RequestCommandsList3;
TYPED_TEST_CASE(RequestToHMICommandsTest, RequestCommandsList);
TYPED_TEST_CASE(RequestToHMICommandsTest2, RequestCommandsList2);
TYPED_TEST_CASE(RequestToHMICommandsTest3, RequestCommandsList3);
TYPED_TEST(RequestToHMICommandsTest, Run_SendMessageToHMI_SUCCESS) {
typedef typename TestFixture::CommandType CommandType;
SharedPtr<CommandType> command = this->template CreateCommand<CommandType>();
EXPECT_CALL(this->app_mngr_, SendMessageToHMI(NotNull()));
command->Run();
}
TYPED_TEST(RequestToHMICommandsTest2, Run_SendMessageToHMI_SUCCESS) {
typedef typename TestFixture::CommandType CommandType;
SharedPtr<CommandType> command = this->template CreateCommand<CommandType>();
EXPECT_CALL(this->app_mngr_, SendMessageToHMI(NotNull()));
command->Run();
}
TYPED_TEST(RequestToHMICommandsTest3, Run_SendMessageToHMI_SUCCESS) {
typedef typename TestFixture::CommandType CommandType;
SharedPtr<CommandType> command = this->template CreateCommand<CommandType>();
EXPECT_CALL(this->app_mngr_, SendMessageToHMI(NotNull()));
command->Run();
}
} // namespace simple_requests_to_hmi_test
} // namespace hmi_commands_test
} // namespace commands_test
} // namespace components
} // namespace test
| 48.622378 | 87 | 0.795987 | APipko |
3fa587992b30560de5af9c1b0ad54d606bb4fff3 | 1,434 | hpp | C++ | src/cxx/ctul/cfg/collections.hpp | c0de4un/cxx-thread-util | 3b7f85e32370cfeb699d7a7d3c8bf08ca99acbe5 | [
"MIT"
] | 1 | 2020-01-30T15:13:37.000Z | 2020-01-30T15:13:37.000Z | src/cxx/ctul/cfg/collections.hpp | c0de4un/cxx-thread-util | 3b7f85e32370cfeb699d7a7d3c8bf08ca99acbe5 | [
"MIT"
] | null | null | null | src/cxx/ctul/cfg/collections.hpp | c0de4un/cxx-thread-util | 3b7f85e32370cfeb699d7a7d3c8bf08ca99acbe5 | [
"MIT"
] | null | null | null | /**
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
**/
#ifndef CTUL_CFG_COLLECTIONS_HPP
#define CTUL_CFG_COLLECTIONS_HPP
// -----------------------------------------------------------
// ===========================================================
// INCLUDES
// ===========================================================
// Include C++ map
#include <map>
// Include C++ vector
#include <vector>
// Include C++ deque
#include <deque>
// ===========================================================
// FORWARD-DECLARATIONS
// ===========================================================
// ===========================================================
// TYPES
// ===========================================================
template <typename K, typename V>
using map_t = std::map<K, V>;
template <typename T>
using vec_t = std::vector<T>;
template <typename T>
using deque_t = std::deque<T>;
// -----------------------------------------------------------
#endif // !CTUL_CFG_COLLECTIONS_HPP | 29.875 | 80 | 0.477685 | c0de4un |
3fa59f47cb5e9f19ab64685b31997165b029dd9e | 4,133 | cpp | C++ | irohad/torii/processor/impl/query_processor_impl.cpp | steephengeorge/iroha | 9e0e19035308c6ebaf706f709c5b7b3ac46e708b | [
"Apache-2.0"
] | null | null | null | irohad/torii/processor/impl/query_processor_impl.cpp | steephengeorge/iroha | 9e0e19035308c6ebaf706f709c5b7b3ac46e708b | [
"Apache-2.0"
] | null | null | null | irohad/torii/processor/impl/query_processor_impl.cpp | steephengeorge/iroha | 9e0e19035308c6ebaf706f709c5b7b3ac46e708b | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. 2017 All Rights Reserved.
* http://soramitsu.co.jp
*
* 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 "torii/processor/query_processor_impl.hpp"
#include "backend/protobuf/from_old_model.hpp"
#include "backend/protobuf/query_responses/proto_query_response.hpp"
namespace iroha {
namespace torii {
/**
* Checks if public keys are subset of given signaturies
* @param signatures user signatories, an iterable collection
* @param public_keys vector of public keys
* @return true if user has needed signatories, false instead
*/
bool signaturesSubset(
const shared_model::interface::SignatureSetType &signatures,
const std::vector<shared_model::crypto::PublicKey> &public_keys) {
// TODO 09/10/17 Lebedev: simplify the subset verification IR-510
// #goodfirstissue
// TODO 30/04/2018 x3medima17: remove code duplication in query_processor
// IR-1192 and stateful_validator
std::unordered_set<std::string> txPubkeys;
for (auto sign : signatures) {
txPubkeys.insert(sign->publicKey().toString());
}
return std::all_of(public_keys.begin(),
public_keys.end(),
[&txPubkeys](const auto &public_key) {
return txPubkeys.find(public_key.toString())
!= txPubkeys.end();
});
}
/**
* Builds QueryResponse that contains StatefulError
* @param hash - original query hash
* @return QueryRepsonse
*/
std::shared_ptr<shared_model::interface::QueryResponse> buildStatefulError(
const shared_model::interface::types::HashType &hash) {
return clone(
shared_model::proto::TemplateQueryResponseBuilder<>()
.queryHash(hash)
.errorQueryResponse<
shared_model::interface::StatefulFailedErrorResponse>()
.build());
}
QueryProcessorImpl::QueryProcessorImpl(
std::shared_ptr<ametsuchi::Storage> storage)
: storage_(storage) {}
bool QueryProcessorImpl::checkSignatories(
const shared_model::interface::Query &qry) {
const auto &sig = *qry.signatures().begin();
const auto &wsv_query = storage_->getWsvQuery();
auto qpf =
model::QueryProcessingFactory(wsv_query, storage_->getBlockQuery());
auto signatories = wsv_query->getSignatories(qry.creatorAccountId());
if (not signatories) {
return false;
}
bool result = signaturesSubset({sig}, *signatories);
return result;
}
void QueryProcessorImpl::queryHandle(
std::shared_ptr<shared_model::interface::Query> qry) {
if (not checkSignatories(*qry)) {
auto response = buildStatefulError(qry->hash());
subject_.get_subscriber().on_next(response);
return;
}
const auto &wsv_query = storage_->getWsvQuery();
auto qpf =
model::QueryProcessingFactory(wsv_query, storage_->getBlockQuery());
auto qpf_response = qpf.execute(*qry);
auto qry_resp =
std::static_pointer_cast<shared_model::proto::QueryResponse>(
qpf_response);
subject_.get_subscriber().on_next(
std::make_shared<shared_model::proto::QueryResponse>(
qry_resp->getTransport()));
}
rxcpp::observable<std::shared_ptr<shared_model::interface::QueryResponse>>
QueryProcessorImpl::queryNotifier() {
return subject_.get_observable();
}
} // namespace torii
} // namespace iroha
| 37.572727 | 79 | 0.654246 | steephengeorge |
3fa920a8e140455c19e4f17f78f268b7b2551546 | 467 | cpp | C++ | Arrays and Strings/1.3 URLify.cpp | AbrMa/Interview-Prep | 692bfd5a3bd85238b717ecd277dd739191d5fef2 | [
"MIT"
] | null | null | null | Arrays and Strings/1.3 URLify.cpp | AbrMa/Interview-Prep | 692bfd5a3bd85238b717ecd277dd739191d5fef2 | [
"MIT"
] | null | null | null | Arrays and Strings/1.3 URLify.cpp | AbrMa/Interview-Prep | 692bfd5a3bd85238b717ecd277dd739191d5fef2 | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
using namespace std;
string URLify (string& str, int& n) {
int copy = n - 1, write = str.size() - 1;
while (copy >= 0) {
if (str[copy] == ' ') {
str[write - 2] = '%';
str[write - 1] = '2';
str[write] = '0';
write -= 3;
}
else {
str[write] = str[copy];
write--;
}
copy--;
}
return str;
}
int main() {
int n = 13;
string str = "Mr John Smith ";
cout << URLify(str, n) << endl;
return 0;
}
| 15.566667 | 42 | 0.513919 | AbrMa |
3fa9f33b0594dda6cb807432272c3b9ebd27c924 | 600 | cpp | C++ | src/SingleHtmlElement.cpp | liferili/HTML-Formatter | 3ebf2a9814c8e077f98e2ef6d8135292d6387a76 | [
"MIT"
] | null | null | null | src/SingleHtmlElement.cpp | liferili/HTML-Formatter | 3ebf2a9814c8e077f98e2ef6d8135292d6387a76 | [
"MIT"
] | null | null | null | src/SingleHtmlElement.cpp | liferili/HTML-Formatter | 3ebf2a9814c8e077f98e2ef6d8135292d6387a76 | [
"MIT"
] | null | null | null | //
// Created by Liferov Ilia (liferili) on 6/5/16.
//
#include "SingleHtmlElement.h"
using namespace std;
SingleHtmlElement::SingleHtmlElement(string name, bool block, set <string> &attributes) :HtmlElement(name, block, attributes){}
bool SingleHtmlElement::isBlock() const {return this->block;}
bool SingleHtmlElement::checkChild(const string &child)const {return false;}
bool SingleHtmlElement::checkAttribute(const string &attribute)const {
auto it=this->attributes.find(attribute);
return !(it == this->attributes.end());
}
bool SingleHtmlElement::isPaired()const {return false;}
| 28.571429 | 127 | 0.753333 | liferili |
3fab57890f3dd25784e7ecd305afb55dce7bf8b0 | 985 | cpp | C++ | CADYDIST.cpp | Akki5/spoj-solutions | 9169830415eb4f888ba0300eb47a423166b8d938 | [
"MIT"
] | 1 | 2019-05-23T20:03:40.000Z | 2019-05-23T20:03:40.000Z | CADYDIST.cpp | Akki5/spoj-solutions | 9169830415eb4f888ba0300eb47a423166b8d938 | [
"MIT"
] | null | null | null | CADYDIST.cpp | Akki5/spoj-solutions | 9169830415eb4f888ba0300eb47a423166b8d938 | [
"MIT"
] | 1 | 2021-08-28T16:48:42.000Z | 2021-08-28T16:48:42.000Z | #include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
void quickSort(long long arr[], int left, int right)
{
int i = left, j = right;
long long tmp;
long long pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
}
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
int main()
{
int n;
scanf("%d",&n);
long long int ans;
while(n!=0)
{
long long int *C=new long long int[n];
long long int *P=new long long int[n];
for(int i=0;i<n;i++)
scanf("%lld",&C[i]);
for(int i=0;i<n;i++)
scanf("%lld",&P[i]);
quickSort(C,0,n-1);
quickSort(P,0,n-1);
ans=0;
for(int i=0;i<n;i++)
ans+=C[i]*P[n-i-1];
printf("%lld\n",ans);
scanf("%d",&n);
}
}
| 18.240741 | 52 | 0.474112 | Akki5 |
3fabce870ca5fde9e03a4a59cd6d1a27ef0a5a9e | 1,826 | hpp | C++ | deprecated/TESTS/tensorIdxImporterTests.hpp | lubatang/uTensor | aedbc9bb5dc2e7532b744a9c6fe713c1d22bdb0b | [
"Apache-2.0"
] | 1 | 2018-05-01T19:13:52.000Z | 2018-05-01T19:13:52.000Z | deprecated/TESTS/tensorIdxImporterTests.hpp | lubatang/uTensor | aedbc9bb5dc2e7532b744a9c6fe713c1d22bdb0b | [
"Apache-2.0"
] | 1 | 2018-04-18T16:00:04.000Z | 2018-04-18T16:00:04.000Z | deprecated/TESTS/tensorIdxImporterTests.hpp | lubatang/uTensor | aedbc9bb5dc2e7532b744a9c6fe713c1d22bdb0b | [
"Apache-2.0"
] | null | null | null | #ifndef UTENSOR_IDX_IMPORTER_TESTS
#define UTENSOR_IDX_IMPORTER_TESTS
#include "tensorIdxImporter.hpp"
#include "test.hpp"
class idxImporterTest : public Test {
public:
void ntoh32Test(void) {
testStart("ntoh32 test");
uint32_t input = 63;
timer_start();
uint32_t result = ntoh32(input);
timer_stop();
passed(result == 1056964608);
}
void ucharTest(void) {
testStart("uchar import test");
TensorIdxImporter t_import;
timer_start();
Tensor* t =
t_import.ubyte_import("/fs/testData/idxImport/uint8_4d_power2.idx");
timer_stop();
double result = sum<unsigned char>(t);
passed(result == 4518);
delete t;
}
void shortTest(void) {
testStart("short import test");
TensorIdxImporter t_import;
timer_start();
Tensor* t =
t_import.short_import("/fs/testData/idxImport/int16_4d_power2.idx");
timer_stop();
double result = sum<short>(t);
passed(result == 270250);
delete t;
}
void intTest(void) {
testStart("int import test");
TensorIdxImporter t_import;
timer_start();
Tensor* t =
t_import.int_import("/fs/testData/idxImport/int32_4d_power2.idx");
timer_stop();
double result = sum<int>(t);
passed(result == 7158278745);
delete t;
}
void floatTest(void) {
testStart("float import test");
TensorIdxImporter t_import;
timer_start();
Tensor* t =
t_import.float_import("/fs/testData/idxImport/float_4d_power2.idx");
timer_stop();
double result = sum<float>(t);
DEBUG("***floating point test yielded: %.8e\r\n", (float)result);
passed((float)result == -1.0f);
delete t;
}
void runAll(void) {
ntoh32Test();
ucharTest();
shortTest();
intTest();
floatTest();
}
};
#endif // UTENSOR_IDX_IMPORTER_TESTS
| 23.113924 | 76 | 0.648959 | lubatang |
3fae16b8625fda8ecb93c718fdbf8a8a58cf32d5 | 1,847 | cpp | C++ | src/api/optimizers/nativeoptimizer.cpp | DavidPerezSanchez/GOS | 8621f319f2fa174af89771db861c93fbb6a2a684 | [
"Apache-2.0"
] | 5 | 2020-12-29T07:56:09.000Z | 2022-01-04T03:11:34.000Z | src/api/optimizers/nativeoptimizer.cpp | DavidPerezSanchez/GOS | 8621f319f2fa174af89771db861c93fbb6a2a684 | [
"Apache-2.0"
] | 4 | 2020-04-15T06:41:56.000Z | 2020-04-21T07:34:13.000Z | src/api/optimizers/nativeoptimizer.cpp | roger21gm/CSP2SAT | 8621f319f2fa174af89771db861c93fbb6a2a684 | [
"Apache-2.0"
] | 2 | 2021-01-07T18:15:26.000Z | 2022-03-07T11:54:08.000Z | #include "nativeoptimizer.h"
#include <iostream>
NativeOptimizer::NativeOptimizer() : Optimizer(){
}
int NativeOptimizer::minimize(Encoder * e, int lb, int ub, bool useAssumptions, bool narrowBounds){
if(beforeNativeOptimizationCall)
beforeNativeOptimizationCall(lb, ub);
bool issat = e->optimize(lb,ub);
if(afterNativeOptimizationCall)
afterNativeOptimizationCall(lb, ub,e);
if(issat){
int obj = e->getObjective();
if(obj==INT_MIN){
smtapierrors::fatalError(
"The encoding must implement getObjective() to retrieve optimal solutions from native optimization"
,SOLVING_ERROR
);
}
if(onNewBoundsProved) onNewBoundsProved(obj,obj);
if(onSATSolutionFound) onSATSolutionFound(lb,ub,obj);
if(onProvedOptimum) onProvedOptimum(obj);
return obj;
}
else{
if(onUNSATBoundsDetermined) onUNSATBoundsDetermined(lb,ub);
if(onProvedUNSAT) onProvedUNSAT();
return INT_MIN;
}
}
int NativeOptimizer::maximize(Encoder * e, int lb, int ub, bool useAssumptions, bool narrowBounds){
if(beforeNativeOptimizationCall)
beforeNativeOptimizationCall(lb, ub);
bool issat = e->optimize(lb,ub);
if(afterNativeOptimizationCall)
afterNativeOptimizationCall(lb, ub,e);
if(issat){
int obj = e->getObjective();
if(obj==INT_MIN){
smtapierrors::fatalError(
"The encoding must implement getObjective() to retrieve optimal solutions from native optimization"
,SOLVING_ERROR
);
}
if(onNewBoundsProved) onNewBoundsProved(obj,obj);
if(onSATSolutionFound) onSATSolutionFound(lb,ub,obj);
if(onProvedOptimum) onProvedOptimum(obj);
return obj;
}
else{
if(onUNSATBoundsDetermined) onUNSATBoundsDetermined(lb,ub);
if(onProvedUNSAT) onProvedUNSAT();
return INT_MIN;
}
}
NativeOptimizer::~NativeOptimizer() {
}
| 24.959459 | 104 | 0.716297 | DavidPerezSanchez |
3fb27d1c757eba88294d4f9fb02eccb670014165 | 6,155 | cpp | C++ | Sources/Core/cpp/SemanticAnalyzer/SMExAnaphora.cpp | elzin/SentimentAnalysisService | 41fba2ef49746473535196e89a5e49250439fd83 | [
"MIT"
] | 2 | 2021-07-07T19:39:11.000Z | 2021-12-02T15:54:15.000Z | Sources/Core/cpp/SemanticAnalyzer/SMExAnaphora.cpp | elzin/SentimentAnalysisService | 41fba2ef49746473535196e89a5e49250439fd83 | [
"MIT"
] | null | null | null | Sources/Core/cpp/SemanticAnalyzer/SMExAnaphora.cpp | elzin/SentimentAnalysisService | 41fba2ef49746473535196e89a5e49250439fd83 | [
"MIT"
] | 1 | 2021-12-01T17:48:20.000Z | 2021-12-01T17:48:20.000Z | #include "StdAfx.h"
#include ".\smexanaphora.h"
namespace SS
{
namespace Semantic
{
namespace AnalysisExperts
{
namespace IndexationExperts
{
CSMExAnaphora::CSMExAnaphora(void)
{
m_sDescription=_T(__FUNCTION__);
m_AnalyseLanguage=SS::Core::Types::ealUndefined;
}
CSMExAnaphora::~CSMExAnaphora(void)
{
}
bool CSMExAnaphora::AnalizeSentence()
{
SS_TRY
{
UINT uiWordCountInSentence=0;
wstring sz_Word;//
TBoxUnits l_units;
do{
uiWordCountInSentence++;
l_units.clear();
sz_Word = m_pCurrentUnit->GetWord();
/*if (uiWordCountInSentence<=5)
{*/
if(m_pCurrentUnit->HasChilds())
{
CollectListOfNameAgents(l_units);
ReplaceProNoun(uiWordCountInSentence,m_pCurrentUnit,l_units);
}
else
{
if ( IsNameAgent())
{
sz_Word = m_pCurrentUnit->GetWord();
ReplaceProNoun(uiWordCountInSentence,m_pCurrentUnit, l_units);
}
}
/*} else break;*/
}while(GetNextUnit());
return true;
}
SS_CATCH(L"")
}
bool CSMExAnaphora::Init(IText * pIText)
{
SS_TRY
{
if (!CSMExpert::Init(pIText)) return false;
}
SS_CATCH(L"")
return true;
}
void CSMExAnaphora::ReplaceProNoun(UINT & uiWordCount, IUnit * poInfo, TBoxUnits l_units)
{
SS_TRY
{
UINT uiSentence=0;
UINT uiWordCountIn=0;
wstring sz_Word;
IUnit * pUnit;
list<IUnit*>::iterator it;
do
{
uiSentence++;
//uiWordCount=0;
if(!GetFirstUnit())
continue;
do
{
uiWordCountIn++;
if (uiWordCountIn<=uiWordCount)
continue;
sz_Word = m_pCurrentUnit->GetWord();
if (IsNameAgent())
{
pUnit = m_pCurrentUnit;
if (GetPrevUnit())
{
uiWordCount = uiWordCountIn-1;
return;
}else
{
ReplaceProNoun(uiWordCountIn,pUnit,l_units);
return;
}
}
sz_Word=m_pCurrentUnit->GetWord();
if (IsAimWord(sz_Word.c_str()) && IsValidGender(poInfo))
{
CopyUnit(poInfo, false);
if(l_units.empty() == false)
{
for(it=l_units.begin(); it!=l_units.end(); it++)
{
CopyUnit(*it, true);
}
}
}
}while(GetNextUnit());
uiWordCount=0;
uiWordCountIn=0;
}while (uiSentence<3 && GetNextSentence() );
uiWordCount = uiWordCountIn;
return;
}
SS_CATCH(L"")
}
bool CSMExAnaphora::IsAimWord(const TCHAR * sWord)
{
SS_TRY
{
wstring sz_Word(sWord);
m_StringService.LowerSz((TCHAR*)sz_Word.c_str());
set<wstring>::iterator i=m_AimWords.find(sz_Word.c_str());
return (i!=m_AimWords.end());
}
SS_CATCH(L"")
}
void CSMExAnaphora::CollectListOfNameAgents(TBoxUnits & l_units)
{
SS_TRY
{
IUnit * pUnit;
pUnit = m_pCurrentUnit->GetLeftChildUnit();
do{
if (IsSemanticName(pUnit))
{
l_units.push_back(pUnit);
}
}while(pUnit = pUnit->GetRightUnit());
return;
}
SS_CATCH(L"")
}
bool CSMExAnaphora::IsSemanticName(IUnit * pUnit)
{
SS_TRY
{
SS::Core::Features::CSemanticFeature oSemanticFeature;
oSemanticFeature.Undefine();
CollectSemanticFeature(oSemanticFeature,pUnit);
if(oSemanticFeature.m_SemanticType.IsContain(Values::TSemanticType.smtPerson))
return true;
return false;
}
SS_CATCH(L"");
}
void CSMExAnaphora::CopyUnit(IUnit * pUnit, bool bMorphoOnly)
{
SS_TRY
{
if(!pUnit) return;
//unsigned int iIndex;
IFeature * pFeature, *pF2;
int iMorphoInfo=0, iPartOfSpeech=0;
list<IFeature*> l_Features;
list<IFeature*>::iterator it;
UINT uiDicNumber;
IIndex * pIndex;
IIndex * pIndex2;
//if(!bMorphoOnly)
//{
//m_pCurrentUnit->ClearUnit();
//m_pCurrentUnit->ClearIndexList();
//}
pIndex=pUnit->GetFirstIndex();
if (pIndex)
{
do
{
//iIndex = pIndex->GetDictionaryIndex()->GetFirst();
//uiDicNumber = pIndex->GetDictionaryIndex()->GetDictionaryNumber()/*iIndex>>24*/;
//uiDicNumber = iIndex->GetDictionaryNumber();
uiDicNumber = pIndex->GetDictionaryIndex()->GetFirst().GetDictionaryNumber();
if(bMorphoOnly && ((uiDicNumber) == SS::Dictionary::DATA_TYPE::NAMES::ednSemantic||
(uiDicNumber) == SS::Dictionary::DATA_TYPE::NAMES::ednSyntax))
continue;
pFeature = pIndex->GetFirstFeature();
if(!pFeature)
{
continue;
}
do
{
m_pIAMCMorpho->EnCode(uiDicNumber,pFeature->GetMorphoInfo(),pFeature->GetPartOfSpeech(),&m_MorphoFeature);
if ( m_MorphoFeature.m_PartOfSpeechTypes.Equal(Values::PartOfSpeechTypes.postNoun) || m_MorphoFeature.m_PartOfSpeechTypes.Equal(Values::PartOfSpeechTypes.postPronoun) )
{
m_pIAMCMorpho->Code(uiDicNumber,&m_MorphoFeature,&iMorphoInfo,&iPartOfSpeech);
if (iMorphoInfo>=0 && iPartOfSpeech>=0)
{
pF2=m_pIBlackBoxFactory->CreateFeature();
//pF2->SetIndexSynonymsClass(pFeature->GetIndexSynonymsClass());
pF2->SetMorphoIndex(pFeature->GetMorphoIndex());
pF2->SetMorphoInfo(iMorphoInfo);
pF2->SetPartOfSpeech(iPartOfSpeech);
l_Features.push_back(pF2);
}
}
}while((pFeature=pIndex->GetNextFeature()));
if (!l_Features.empty())
{
pIndex2 = m_pIBlackBoxFactory ->CreateIndex();
pIndex2->GetDictionaryIndex()->AppendIndex(pIndex->GetDictionaryIndex()->GetFirst());
pIndex2->SetIndexationFlag(true);
m_pCurrentUnit->AddIndex(pIndex2);
for(it=l_Features.begin(); it!=l_Features.end();it++)
{
pIndex2->AddFeature(*it);
}
l_Features.clear();
}
}while(pIndex=pUnit->GetNextIndex());
}
}
SS_CATCH(L"")
}
bool CSMExAnaphora::IsValidGender(IUnit * pAgent)
{
SS_TRY
{
if(!pAgent) return false;
SS::Core::Features::CMorphoFeature oMorphoFeature,oMorphoFeature2;
CollectMorphoFeature(oMorphoFeature,pAgent);
CollectMorphoFeature(oMorphoFeature2);
if(oMorphoFeature.m_GenderType.IsContain(Values::GenderType.gtFemale) &&
oMorphoFeature2.m_GenderType.IsContain(Values::GenderType.gtFemale))
return true;
else if(oMorphoFeature.m_GenderType.IsContain(Values::GenderType.gtMasculine) &&
oMorphoFeature2.m_GenderType.IsContain(Values::GenderType.gtMasculine))
return true;
else return false;
}
SS_CATCH(L"")
}
//////////////////////////////////////////////////////////////////////////
}
}
}
} | 21.826241 | 173 | 0.664988 | elzin |
3fb9734b54fec3560c2c51f0eb10fb4a3115c03b | 623 | cpp | C++ | Porblems/anton_and_danik.cpp | ashish-ad/CPP-STL-Practice-and-Cp | ca8a112096ad96ed1abccddc9e99b1ead5cf522b | [
"Unlicense"
] | null | null | null | Porblems/anton_and_danik.cpp | ashish-ad/CPP-STL-Practice-and-Cp | ca8a112096ad96ed1abccddc9e99b1ead5cf522b | [
"Unlicense"
] | null | null | null | Porblems/anton_and_danik.cpp | ashish-ad/CPP-STL-Practice-and-Cp | ca8a112096ad96ed1abccddc9e99b1ead5cf522b | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main(){
long int n ;
string s;
cin>>n>>s;
char arr[n];
for (int i=0;i<n;i++){
arr[i]=s[i];
}
int anton=0,danik=0;
for (char i : arr){
//cout<<i<<" ";
if(i=='A'){
anton+=1;
}
else {
danik+=1;
}
}
//cout<<endl<<anton<<endl<<danik<<endl;
if (anton>danik){
cout<<"Anton"<<endl;
}
else if (danik>anton){
cout<<"Danik"<<endl;
}
else if(danik==anton)
{
cout<<"Friendship"<<endl;
}
return 0;
} | 16.837838 | 43 | 0.41252 | ashish-ad |
3fbcd59b7846eddd1194c42f3fa8a38a3e8fd0c2 | 2,432 | hpp | C++ | NavalFreightCompany.hpp | danilaferents/Vessels | 06d5f3d08d1f059e53946a06240c69bd4b5e9c7f | [
"Apache-2.0"
] | null | null | null | NavalFreightCompany.hpp | danilaferents/Vessels | 06d5f3d08d1f059e53946a06240c69bd4b5e9c7f | [
"Apache-2.0"
] | null | null | null | NavalFreightCompany.hpp | danilaferents/Vessels | 06d5f3d08d1f059e53946a06240c69bd4b5e9c7f | [
"Apache-2.0"
] | null | null | null | #pragma once
#ifndef NavalFreightCompany_hpp
#define NavalFreightCompany_hpp
#include "main.hpp"
#include "Destination.hpp"
#include "Vessels.hpp"
#include "PassengerVessel.hpp"
#include "CargoVessel.hpp"
using namespace cargovessel;
using namespace passengervessel;
namespace navalfreightcompany
{
class NavalFreightCompany
{
private:
// имеющиеся корабли
std::list<Vessel*> ships;
// место где порт расположен
Destination* location;
public:
NavalFreightCompany()
{
location=nullptr;
}
~NavalFreightCompany()
{
for (auto i=ships.begin();i!=ships.end();i++)
{
if (*i) delete (*i);
}
if (location) delete location;
}
// добавление корабля
void add(Vessel* v, Destination* d);
void add(Vessel* v);
// удаление корабля
void remove(Vessel* v);
void remove(int id);
// списать весь хлам - когда-либо ремонтировавшиеся суда
void draft();
// напечатать статистику: сколько пассажирских, сколько грузовых, из них когда-либо ломавшихся
void printStats() const;
// внести запись о ремонте корабля по id
void markRepaired(int id, std::string* date_repaired);
// внести запись о повреждении корабля по id
void markDamaged(int id, std::string* date_damaged);
// поменять пункт назначения корабля
void changeDestination(int id, Destination* dest);
// напечатать сколько кораблей идут в пункт назначения X
void printHeadingTo(std::string s) const;
// Печать всех данных о компании
bool AreThereShips() const;
int HowManyShips() const;
int HowManyRepairedShips() const;
void SetLocation(Destination *location)
{
this->location=location;
}
friend std::ostream& operator<<(std::ostream& os, const NavalFreightCompany& v)
{
for(auto i=v.ships.begin();i!=v.ships.end();i++)
{
os<<(**i)<<std::endl;
}
return os;
}
};
}
#endif /* NavalFreightCompany_hpp */
| 34.253521 | 106 | 0.541118 | danilaferents |
3fc0088a75ac48b065a0010718549bed0335cc51 | 905 | hpp | C++ | source/mpl/mpl_flatten.hpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | 16 | 2015-12-04T18:17:03.000Z | 2020-09-11T08:40:32.000Z | source/mpl/mpl_flatten.hpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | 12 | 2017-07-12T02:04:05.000Z | 2018-07-07T01:17:12.000Z | source/mpl/mpl_flatten.hpp | dlin172/Plange | 4b36a1225b2263bc8d38a6d1cc9b50c3d4b58e04 | [
"BSD-3-Clause"
] | 5 | 2016-11-11T11:47:47.000Z | 2020-02-06T02:07:30.000Z | #ifndef INCLUDING_MPL_FLATTEN_HPP
#define INCLUDING_MPL_FLATTEN_HPP
#include "mpl_list.hpp"
namespace mpl {
namespace detail::flatten {
template<typename TAccumulator, typename TList>
struct impl {};
template<typename TList, template<typename...> typename UContainer>
struct impl<TList, UContainer<>> {
using result = TList;
};
template<template<typename...> typename TContainer, typename... Ts, template<typename...> typename UContainer, template<typename...> typename VContainer, typename... Vs, typename... Us>
struct impl<TContainer<Ts...>, UContainer<VContainer<Vs...>, Us...>> {
using result = typename impl<TContainer<Ts..., Vs...>, list<Us...>>::result;
};
}
template<typename TList>
using flatten = typename detail::flatten::impl<list<>, TList>::result;
}
#define INCLUDED_MPL_FLATTEN_HPP
#elif !defined(INCLUDED_MPL_FLATTEN_HPP)
# error circular inclusion
#endif | 30.166667 | 187 | 0.730387 | dlin172 |
3fc6dba9f72442725e296de264539c08b8001cc9 | 2,333 | cpp | C++ | source/msynth/msynth/ui/processor/MIIRControl.cpp | MRoc/MSynth | 3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829 | [
"MIT"
] | 1 | 2022-01-30T07:40:31.000Z | 2022-01-30T07:40:31.000Z | source/msynth/msynth/ui/processor/MIIRControl.cpp | MRoc/MSynth | 3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829 | [
"MIT"
] | null | null | null | source/msynth/msynth/ui/processor/MIIRControl.cpp | MRoc/MSynth | 3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829 | [
"MIT"
] | null | null | null | /**
* (C)2000-2003 MRoc
*/
#include "MIIRControl.h"
#define ID_LFO_CONTROL 3080
#define ID_ENV_CONTROL 3081
MPoint MIIRControl::COMBO_POINTS[] = {
MPoint( 15, 70 ),
MPoint( 15, 88 ),
MPoint( 15, 106 ) };
MIIRControl::MIIRControl() :
MAbstractDescriptorView(),
ivPtLfoControl( 0 ),
ivPtEnvControl( 0 ),
ivLabelName( 0 )
{
for( unsigned int i=0;i<8;i++ )
ivPtFloatGuis[ i ] = 0;
for( i=0;i<3;i++ )
ivPtCombo[ i ] = 0;
setSize( MSize( 418, 135 ) );
}
MIIRControl::~MIIRControl()
{
}
void MIIRControl::setDescriptor( IDescriptor* pDescriptor )
{
ASSERT( ivPtDescriptor == 0 );
ASSERT( pDescriptor != 0 );
MAbstractDescriptorView::setDescriptor( pDescriptor );
ivLabelName = new MLabel( ivPtDescriptor->getShortName(), MColorMap::FG_COLOR2, MColorMap::BK_COLOR2 );
ivLabelName->setRect( MRect( 1, 1, getWidth() - 2, 10 ) );
addChild( ivLabelName );
unsigned int start = MIIR::CUTOFF;
unsigned int stop = MIIR::RESONANCE + 1;
for( unsigned int i=start;i<stop;i++ )
{
int index = i - start;
MFloatControl* ptControl = (MFloatControl*) ((MIIR*)ivPtDescriptor)->getControl( i );
ivPtFloatGuis[ index ] = new MFloatGui( ptControl, ivBkColor );
addChild( ivPtFloatGuis[ index ] );
}
for( i=0;i<3;i++ )
{
ivPtCombo[i] = new MComboGui( (MDiscreteComboControl*)((MIIR*)ivPtDescriptor)->getControl( i ), ivBkColor );
ivPtCombo[i]->setRect(
MRect(
COMBO_POINTS[ i ].getX(),
COMBO_POINTS[ i ].getY(),
100,
20 ) );
addChild( ivPtCombo[ i ] );
}
int xx = 20;
for( i=0;i<2;i++ )
{
ivPtFloatGuis[ i ]->setPoint( MPoint( xx, 18 ) );
xx += ivPtFloatGuis[ i ]->getWidth() + 5;
}
ivPtEnvControl = new MControlSubView(
((MIIR*)ivPtDescriptor)->getEnvelope(),
getBkColor() );
ivPtEnvControl->setPoint( MPoint( 130, 15 ) );
addChild( ivPtEnvControl );
ivPtLfoControl = new MControlSubView( ((MIIR*)ivPtDescriptor)->getLfo(), getBkColor() );
ivPtLfoControl->setPoint( MPoint( 130, 75 ) );
addChild( ivPtLfoControl );
}
void MIIRControl::paint( IGraphics* ptGraphics, const MRect &rect )
{
ptGraphics->fillRect( rect, ivBkColor );
ptGraphics->drawRect( rect, MColorMap::FG_COLOR3 );
}
MAbstractDescriptorView* MIIRControl::createInstance()
{
return new MIIRControl();
} | 25.086022 | 111 | 0.645092 | MRoc |
3fc790a4fd9ba523b1216e41f5a10ed871f83289 | 3,537 | cc | C++ | test/ustc_dbms_test.cc | zonghuaxiansheng/DSMgr | 91de5694c0b9cd6e49aa937fb04b488d005b25be | [
"Apache-2.0"
] | 1 | 2022-01-06T12:25:49.000Z | 2022-01-06T12:25:49.000Z | test/ustc_dbms_test.cc | zonghuaxiansheng/DSMgr | 91de5694c0b9cd6e49aa937fb04b488d005b25be | [
"Apache-2.0"
] | null | null | null | test/ustc_dbms_test.cc | zonghuaxiansheng/DSMgr | 91de5694c0b9cd6e49aa937fb04b488d005b25be | [
"Apache-2.0"
] | null | null | null | #include "buffer_manager.h"
// #include "data_storage_manager.h"
#include <ctime>
#include <iostream>
enum OPS_E {R, W};
struct OPS {
OPS_E ops_e_;
int page_id_;
};
bool RunBMgrTraceTest(ustc_dbms::BMgr& bmgr,
std::string& trace_path,
bool is_run) {
std::fstream trace;
trace.open(trace_path, std::ios::in);
if (!trace.is_open()) {
std::cerr << "Test: " << __FUNC__
<< " Read trace file failed !"
<< std::endl;
return false;
}
std::vector<OPS> ops_vec;
int ops_i;
char buf;
while (!trace.eof()) {
OPS ops;
trace >> ops_i >> buf >> ops.page_id_;
ops.ops_e_ = (OPS_E)ops_i;
ops_vec.push_back(ops);
}
trace.close();
int max_page_id = 0;
for (auto ops : ops_vec) {
// std::cout << "* Op: " << ops.ops_e_
// << " Page id: " << ops.page_id_ << std::endl;
if (ops.page_id_ > max_page_id) {
max_page_id = ops.page_id_;
}
}
if (!is_run) {
max_page_id ++;
std::cout << "Test: " << __FUNC__
<< " Max page id is " << max_page_id << std::endl;
// Initial BMgr
std::cout << "Test: " << __FUNC__
<< " Build db file ..." << std::endl;
bmgr.InitBMgrTest(max_page_id);
std::cout << "Test: " << __FUNC__
<< " Build done ..." << std::endl;
} else {
std::cout << "Test: " << __FUNC__
<< " Trace test start ..."
<< std::endl;
// Run test
for (auto ops : ops_vec) {
switch (ops.ops_e_) {
case R :
bmgr.FixPage(ops.page_id_, 0);
bmgr.UnfixPage(ops.page_id_);
break;
case W :
bmgr.WritePage(ops.page_id_);
break;
default :
std::cout << "WTF ?" << std::endl;
break;
}
}
bmgr.WriteDirtys();
std::cout << "Test: " << __FUNC__
<< " Trace test done ..."
<< std::endl;
bmgr.PrintIO();
bmgr.PrintCnt();
}
return true;
}
int main(void) {
int buffer_size = 1024*16;
int bucket_size = 32;
bool is_build = false;
std::string db_path("out/data.dbf");
std::string trace_path("data/data-5w-50w-zipf.txt");
// std::string trace_path("data/db-data-gen.txt");
std::cout << "***********************USTC DBMS TEST***********************" << std::endl;
ustc_dbms::BMgr bmgr(buffer_size,
bucket_size,
db_path,
is_build);
clock_t start_t, end_t;
start_t = clock();
// Run BMgr trace test
RunBMgrTraceTest(bmgr, trace_path, ~is_build);
end_t = clock();
double proc_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;
std::cout <<"Test: " << __FUNC__
<< std::endl << std::endl
<< "* Time Details: <time>: " << proc_t << "(s)"
<< std::endl << std::endl;
// bmgr.InitBMgrTest(1000);
// for (int i = 1; i < 100; i ++) {
// bmgr.FixPage(i, 0);
// }
// bmgr.WritePage(20);
// bmgr.WritePage(30);
// bmgr.SetDirty(10);
// bmgr.SetDirty(20);
// bmgr.PrintFrame(10);
// bmgr.SetClean(10);
// bmgr.PrintFrame(10);
// bmgr.WriteDirtys();
// bmgr.PrintIO();
// auto [page_id, frame_id] = bmgr.FixNewPage();
// std::cout << "Test: " << __FUNC__
// << " FixNewPage return with page_id[" << page_id
// << "] frame_id[" << frame_id << "]"
// << std::endl;
// std::cout << "***********************USTC DBMS TEST***********************" << std::endl;
return 0;
}
| 27.418605 | 94 | 0.502969 | zonghuaxiansheng |
3fce84655661d91fc4d422e299ec28385ed777eb | 1,083 | hpp | C++ | 2021/day8/src/lib.hpp | falseth/AdventOfCode | 7d37e6b42be2e90660fbf322fbd1dad780793740 | [
"MIT"
] | null | null | null | 2021/day8/src/lib.hpp | falseth/AdventOfCode | 7d37e6b42be2e90660fbf322fbd1dad780793740 | [
"MIT"
] | null | null | null | 2021/day8/src/lib.hpp | falseth/AdventOfCode | 7d37e6b42be2e90660fbf322fbd1dad780793740 | [
"MIT"
] | null | null | null | #ifndef LIB_HPP
#define LIB_HPP
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>
#include <vector>
#include <cmath>
#include <iterator>
#include "EasyBMP.h"
using namespace std;
vector<string> parse(string input, string delimiter);
template<class T> ostream& operator<<(ostream& lhs, vector<T>& rhs);
template<class T> vector<T> operator-(vector<T>& lhs, vector<T>& rhs);
string operator-(string& lhs, string& rhs);
void draw(BMP& image, int i, int j, int r = 255, int g = 0, int b = 0, int a = 255);
void drawDisplay(char num, BMP& image, int i, int j, int r = 255, int g = 0, int b = 0, int a = 255);
vector<bool> highlightSegments(char num);
class Displays {
public:
vector<string> patterns;
vector<string> outputs;
int basicDigitsCount; // How many 1, 4, 7 and 8 appears.
string output;
string one, four, seven, eight;
string zero, two, three, five, six, nine;
vector<string> twoThreeFive, zeroSixNine;
char a, b, c, d, e, f, g;
Displays(string entry);
string decode();
void toConsole();
};
#endif
| 25.785714 | 101 | 0.674054 | falseth |
3fd4a37fdcd71323b2ee4978ea85b0131551a5db | 307 | cpp | C++ | Source/Catastrophe/Gameplay/QTE_Bob/QteBobWidget.cpp | Enderderder/CatastropheGame | 251888d384ae59966788cce7bbbc98c3c0be7433 | [
"MIT"
] | null | null | null | Source/Catastrophe/Gameplay/QTE_Bob/QteBobWidget.cpp | Enderderder/CatastropheGame | 251888d384ae59966788cce7bbbc98c3c0be7433 | [
"MIT"
] | null | null | null | Source/Catastrophe/Gameplay/QTE_Bob/QteBobWidget.cpp | Enderderder/CatastropheGame | 251888d384ae59966788cce7bbbc98c3c0be7433 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "QteBobWidget.h"
UQteBobWidget::UQteBobWidget(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{}
void UQteBobWidget::InitializeQteWidget_Implementation()
{
/// Let blueprint do the thing
}
| 21.928571 | 78 | 0.794788 | Enderderder |
3fdf102762937105990c560a0e3af2a87d6b233c | 1,053 | hpp | C++ | include/sparse/common/utility.hpp | BorysekOndrej/sparse-not-forked | f4010d6bcd46b00261b4296d8010a7a0eb3d471f | [
"MIT"
] | 1 | 2021-04-27T16:11:16.000Z | 2021-04-27T16:11:16.000Z | include/sparse/common/utility.hpp | BorysekOndrej/sparse-not-forked | f4010d6bcd46b00261b4296d8010a7a0eb3d471f | [
"MIT"
] | 17 | 2021-03-14T09:17:32.000Z | 2021-05-23T16:10:00.000Z | include/sparse/common/utility.hpp | BorysekOndrej/sparse-not-forked | f4010d6bcd46b00261b4296d8010a7a0eb3d471f | [
"MIT"
] | 1 | 2021-05-20T15:13:05.000Z | 2021-05-20T15:13:05.000Z | #pragma once
#include <filesystem>
#include <nlohmann/json.hpp>
#include <sparse/common/types.hpp>
#include <string>
#include <unordered_map>
namespace sparse::common
{
std::string load_file_into_string(const std::filesystem::path& filename);
/**
* @brief Removes whitespace characters from both ends of given string
* @param sw_ string view
* @return trimmed string view
*/
std::string_view trim_line(std::string_view sw_);
/**
* @brief Removes whitespace characters from both ends of a given string
* @param sw_ string
* @return trimmed string view
*/
std::string trim_line(std::string sw_);
/**
* @brief to_json
* @param j json
* @param versions versions object
*/
void to_json(nlohmann::json& j, const versions_t& versions);
/**
* @brief to_json
* @param j json
* @param revision revision object
*/
void to_json(nlohmann::json& j, const revision_t& revision);
/**
* @brief to_json
* @param j json
* @param section section object
*/
void to_json(nlohmann::json& j, const section_t& section);
} // namespace sparse::common
| 21.489796 | 73 | 0.719848 | BorysekOndrej |
3fdf7f168d3b5e5bb4109bae633e1c61d14b00c9 | 40,687 | hpp | C++ | core/src/cogs/collections/btree.hpp | cogmine/cogs | ef1c369a36a4f811704e0ced0493c3a6f8eca821 | [
"MIT"
] | 5 | 2019-02-08T15:59:14.000Z | 2022-01-22T19:12:33.000Z | core/src/cogs/collections/btree.hpp | cogmine/cogs | ef1c369a36a4f811704e0ced0493c3a6f8eca821 | [
"MIT"
] | 1 | 2019-12-03T03:11:34.000Z | 2019-12-03T03:11:34.000Z | core/src/cogs/collections/btree.hpp | cogmine/cogs | ef1c369a36a4f811704e0ced0493c3a6f8eca821 | [
"MIT"
] | null | null | null | //
// Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC
//
// Status: Good
#ifndef COGS_HEADER_COLLECTION_BTREE
#define COGS_HEADER_COLLECTION_BTREE
#include "cogs/collections/tlink.hpp"
#include "cogs/mem/ptr.hpp"
namespace cogs {
/// @brief Tree traversal order
enum class btree_traversal
{
/// @brief In-order binary tree traversal
inorder,// = 0x01,
/// @brief Pre-order binary tree traversal
preorder,// = 0x02,
/// @brief Post-order binary tree traversal
postorder,// = 0x03,
/// @brief Reverse in-order binary tree traversal
reverse_inorder,// = 0x04,
/// @brief Reverse pre-order binary tree traversal
reverse_preorder,// = 0x05,
/// @brief Reverse post-order binary tree traversal
reverse_postorder,// = 0x06
};
/// @ingroup BinaryTrees
/// @brief A base class for intrusive binary trees.
template <class derived_node_t = tlink_t<void, ptr>, template <typename> class ref_type = ptr>
class btree
{
public:
/// @brief Alias to this type.
typedef btree<derived_node_t, ref_type> this_t;
/// @brief Alias to the node type.
typedef derived_node_t node_t;
/// @brief The node reference type
typedef ref_type<node_t> ref_t;
private:
ref_t m_root;
ref_t m_leftmost;
ref_t m_rightmost;
const ref_t get_sidebottom(bool right, const ref_t& cur) const
{
ref_t n = cur;
ref_t child;
typename ref_t::locked_t lockedRef;
for (;;)
{
lockedRef = n;
for (;;)
{
child = lockedRef->get_child_link(right);
if (!child)
break;
n = child;
lockedRef = n;
}
child = lockedRef->get_child_link(!right);
if (!child)
break;
n = child;
}
return n;
}
ref_t get_next_preorder_or_prev_postorder(bool preorder, const ref_t& cur) const
{
typename ref_t::locked_t curLocked = cur;
bool postorder = !preorder;
ref_t n = curLocked->get_child_link(postorder);
if (!n)
{
n = curLocked->get_child_link(preorder);
if (!n)
{
n = cur;
ref_t parent = curLocked->get_parent_link();
typename ref_t::locked_t parentResolved;
while (!!parent)
{
parentResolved = parent;
if (parentResolved->get_child_link(postorder) == n)
{
const ref_t& parentChild = parentResolved->get_child_link(preorder);
if (!!parentChild)
return parentChild;
}
n = parent;
parent = parentResolved->get_parent_link();
}
ref_t emptyRef;
return emptyRef;
}
}
return n;
}
ref_t get_prev_preorder_or_next_postorder(bool preorder, const ref_t& cur) const
{
typename ref_t::locked_t curLocked = cur;
const ref_t& parent = curLocked->get_parent_link();
if (!!parent)
{
typename ref_t::locked_t parentResolved = parent;
const ref_t& parentChild = parentResolved->get_child_link(!preorder);
if ((!!parentChild) && (cur == parentResolved->get_child_link(preorder)))
return get_sidebottom(preorder, parentChild);
}
return parent;
}
ref_t get_inorder(bool next, const ref_t& cur) const
{
typename ref_t::locked_t lockedRef = cur;
const ref_t& child = lockedRef->get_child_link(next);
if (!!child)
{
if (next)
return get_leftmost(child);
return get_rightmost(child);
}
ref_t parent;
ref_t n = cur;
for (;;)
{
parent = lockedRef->get_parent_link();
if (!parent)
break;
lockedRef = parent;
if (n != lockedRef->get_child_link(next))
break;
n = parent;
}
return parent;
}
public:
btree() { }
btree(this_t&& t)
{
m_root = std::move(t.m_root);
m_leftmost = std::move(t.m_leftmost);
m_rightmost = std::move(t.m_rightmost);
}
this_t& operator=(this_t&& t)
{
m_root = std::move(t.m_root);
m_leftmost = std::move(t.m_leftmost);
m_rightmost = std::move(t.m_rightmost);
return *this;
}
/// @{
/// @brief Gets a reference to the root node
/// @return A reference to the root node
ref_t& get_root() { return m_root; }
/// @brief Gets a const reference to the root node
/// @return A const reference to the root node
const ref_t& get_root() const { return m_root; }
/// @}
/// @{
/// @brief Gets a reference to the leftmost (first) node
/// @return A reference to the leftmost (first) node
ref_t& get_leftmost() { return m_leftmost; }
/// @brief Gets a const reference to the leftmost (first) node
/// @return A const reference to the leftmost (first) node
const ref_t& get_leftmost() const { return m_leftmost; }
/// @brief Gets a reference to the leftmost node below a specified parent node
/// @param cur Parent node to scan left from
/// @return A reference to the leftmost node below a specified parent node
const ref_t get_leftmost(const ref_t& cur) const
{
ref_t n = cur;
typename ref_t::locked_t lockedRef;
for (;;)
{
lockedRef = n;
const ref_t& n_child = lockedRef->get_left_link();
if (!n_child)
break;
n = n_child;
}
return n;
}
/// @}
/// @{
/// @brief Gets a reference to the rightmost (last) node
/// @return A reference to the rightmost (last) node
ref_t& get_rightmost(){ return m_rightmost; }
/// @brief Gets a const reference to the rightmost (last) node
/// @return A const reference to the rightmost (last) node
const ref_t& get_rightmost() const { return m_rightmost; }
/// @brief Gets a reference to the leftmost node below a specified parent node
/// @param cur Parent node to scan right from
/// @return A reference to the leftmost node below a specified parent node
const ref_t get_rightmost(const ref_t& cur) const
{
ref_t n = cur;
typename ref_t::locked_t lockedRef;
for (;;)
{
lockedRef = n;
const ref_t& n_child = lockedRef->get_right_link();
if (!n_child)
break;
n = n_child;
}
return n;
}
/// @}
/// @{
/// @brief Sets the root node
/// @param r Value to set root node to
void set_root(const ref_t& r) { m_root = r; }
/// @}
/// @{
/// @brief Sets the leftmost (first) node
/// @param f Value to set leftmost (first) node to
void set_leftmost(const ref_t& f) { m_leftmost = f; }
/// @}
/// @{
/// @brief Sets the rightmost (last) node
/// @param l Value to set rightmost (last) node to
void set_rightmost(const ref_t& l) { m_rightmost = l; }
/// @}
/// @{
/// @brief Clears the root, leftmost and rightmost values maintained by the btree. Does not delete any elements.
void clear()
{
m_root.release();
m_leftmost.release();
m_rightmost.release();
}
/// @}
/// @{
/// @brief Tests if the tree is empty
/// @return True if the tree is empty
bool is_empty() const { return !m_root; }
/// @}
/// @{
/// @brief Swaps the contents of this tree with another.
/// @param wth The tree to swap with.
void swap(this_t& wth)
{
cogs::swap(m_root, wth.m_root);
cogs::swap(m_rightmost, wth.m_rightmost);
cogs::swap(m_leftmost, wth.m_leftmost);
}
/// @}
/// @{
/// @brief Get the first in-order node
/// @return The first in-order node
const ref_t& get_first_inorder() const { return m_leftmost; }
/// @}
/// @{
/// @brief Get the first post-order node
/// @return The first post-order node
const ref_t get_first_postorder() const { return (!m_leftmost) ? m_leftmost : get_sidebottom(false, m_leftmost); }
/// @}
/// @{
/// @brief Get the first pre-order node
/// @return The first pre-order node
const ref_t& get_first_preorder() const { return m_root; }
/// @}
/// @{
/// @brief Get the last in-order node
/// @return The last in-order node
const ref_t& get_last_inorder() const { return m_rightmost; }
/// @}
/// @{
/// @brief Get the last post-order node
/// @return The last post-order node
const ref_t& get_last_postorder() const { return m_root; }
/// @}
/// @{
/// @brief Get the last pre-order node
/// @return The last pre-order node
const ref_t get_last_preorder() const { return !m_rightmost ? m_rightmost : get_sidebottom(true, m_rightmost); }
/// @}
/// @{
/// @brief Get the first node, based on a constant traversal order
/// @tparam order The traversal order
/// @return The first node, based on the specified traversal order.
template <btree_traversal order>
const ref_t get_first()
{
if (order == btree_traversal::inorder)
return get_first_inorder();
else if (order == btree_traversal::preorder)
return get_first_preorder();
else if (order == btree_traversal::postorder)
return get_first_postorder();
else if (order == btree_traversal::reverse_inorder)
return get_last_inorder();
else if (order == btree_traversal::reverse_preorder)
return get_last_preorder();
else if (order == btree_traversal::reverse_postorder)
return get_last_postorder();
}
/// @}
/// @{
/// @brief Get the last node, based on a constant traversal order
/// @tparam order The traversal order
/// @return The last node, based on the specified traversal order.
template <btree_traversal order>
const ref_t get_last()
{
if (order == btree_traversal::inorder)
return get_last_inorder();
else if (order == btree_traversal::preorder)
return get_last_preorder();
else if (order == btree_traversal::postorder)
return get_last_postorder();
else if (order == btree_traversal::reverse_inorder)
return get_first_inorder();
else if (order == btree_traversal::reverse_preorder)
return get_first_preorder();
else if (order == btree_traversal::reverse_postorder)
return get_first_postorder();
}
/// @}
/// @{
/// @brief Get the next in-order node
/// @param cur The node to get the next in-order node from
/// @return The next in-order node
ref_t get_next_inorder(const ref_t& cur) const { return get_inorder(true, cur); }
/// @}
/// @{
/// @brief Get the previous in-order node
/// @param cur The node to get the previous in-order node from
/// @return The previous in-order node
ref_t get_prev_inorder(const ref_t& cur) const { return get_inorder(false, cur); }
/// @}
/// @{
/// @brief Get the next pre-order node
/// @param cur The node to get the next pre-order node from
/// @return The next pre-order node
ref_t get_next_preorder(const ref_t& cur) const { return get_next_preorder_or_prev_postorder(true, cur); }
/// @}
/// @{
/// @brief Get the previous pre-order node
/// @param cur The node to get the previous pre-order node from
/// @return The previous pre-order node
ref_t get_prev_preorder(const ref_t& cur) const { return get_prev_preorder_or_next_postorder(true, cur); }
/// @}
/// @{
/// @brief Get the next post-order node
/// @param cur The node to get the next post-order node from
/// @return The next post-order node
ref_t get_next_postorder(const ref_t& cur) const { return get_prev_preorder_or_next_postorder(false, cur); }
/// @}
/// @{
/// @brief Get the previous post-order node
/// @param cur The node to get the previous post-order node from
/// @return The previous post-order node
ref_t get_prev_postorder(const ref_t& cur) const { return get_next_preorder_or_prev_postorder(false, cur); }
/// @}
/// @{
/// @brief Get the next node, based on a constant traversal order
/// @tparam order The traversal order
/// @param cur The node to get the next node from
/// @return The next node, based on the specified traversal order.
template <btree_traversal order>
ref_t get_next(const ref_t& cur) const
{
if (order == btree_traversal::inorder)
return get_next_inorder(cur);
else if (order == btree_traversal::preorder)
return get_next_preorder(cur);
else if (order == btree_traversal::postorder)
return get_next_postorder(cur);
else if (order == btree_traversal::reverse_inorder)
return get_prev_inorder(cur);
else if (order == btree_traversal::reverse_preorder)
return get_prev_preorder(cur);
else if (order == btree_traversal::reverse_postorder)
return get_prev_postorder(cur);
}
/// @}
/// @{
/// @brief Get the previous node, based on a constant traversal order
/// @tparam order The traversal order
/// @param cur The node to get the previous node from
/// @return The previous node, based on the specified traversal order.
template <btree_traversal order>
ref_t get_prev(const ref_t& cur) const
{
if (order == btree_traversal::inorder)
return get_prev_inorder(cur);
else if (order == btree_traversal::preorder)
return get_prev_preorder(cur);
else if (order == btree_traversal::postorder)
return get_prev_postorder(cur);
else if (order == btree_traversal::reverse_inorder)
return get_next_inorder(cur);
else if (order == btree_traversal::reverse_preorder)
return get_next_preorder(cur);
else if (order == btree_traversal::reverse_postorder)
return get_next_postorder(cur);
}
/// @}
};
/// @brief Sorted binary tree insert mode
enum class sorted_btree_insert_mode
{
/// @brief Allow multiple equal keys
multi,// = 0,
/// @brief Enforce unique keys, abort if already exists
unique,// = 1,
/// @brief Enforce unique keys, replace if already exists
replace// = 2
};
/// @ingroup BinaryTrees
/// @brief A base class for sorted intrusive binary trees.
///
/// derived_node_t must be derived from tlink_t<>, and include the equivalent of the following member function:
/// @code{.cpp}
/// const key_t& get_key() const;
/// @endcode
/// @tparam key_t The key type to contain
/// @tparam derived_node_t A class derived from tlink_t.
/// @tparam comparator_t A static comparator class used to compare keys. Default: default_comparator
/// @tparam ref_type Reference type to use for links. Default: ptr
template <typename key_t, typename derived_node_t, class comparator_t, template <typename> class ref_type = ptr>
class sorted_btree : protected btree<derived_node_t, ref_type>
{
public:
typedef key_t key_type;
/// @brief Alias to this type.
typedef sorted_btree<key_t, derived_node_t, comparator_t, ref_type> this_t;
/// @brief Alias to the node type.
typedef derived_node_t node_t;
/// @brief The node reference type
typedef ref_type<node_t> ref_t;
private:
typedef btree<derived_node_t, ref_type> base_t;
sorted_btree(const this_t&) = delete;
this_t& operator=(const this_t&) = delete;
const ref_t get_rightmost() const { return base_t::get_rightmost(); }
const ref_t get_leftmost() const { return base_t::get_leftmost(); }
const ref_t get_rightmost(const ref_t& cur) const { return base_t::get_rightmost(cur); }
const ref_t get_leftmost(const ref_t& cur) const { return base_t::get_leftmost(cur); }
void set_leftmost(const ref_t& f) { base_t::set_leftmost(f); }
void set_rightmost(const ref_t& l) { base_t::set_rightmost(l); }
template <bool rightSideLarger>
bool balance_remove_inner(const ref_t& nIn, ref_t& swappedWith, ref_t& liftedChild)
{
bool result = false;
ref_t emptyRef;
ref_t n = nIn;
typename ref_t::locked_t lockedRef = n;
bool wasRightNode = false;
ref_t* localRoot = &liftedChild;
swappedWith.release();
ref_t leftChild = lockedRef->get_left_link(); // Might be null
ref_t rightChild = lockedRef->get_right_link(); // Might be null
ref_t parent = lockedRef->get_parent_link(); // Might be null
typename ref_t::locked_t lockedParent;
if (!!parent)
{
lockedParent = parent;
wasRightNode = (lockedParent->get_right_link() == n);
}
int mode = (!!leftChild ? 1 : 0) + (!!rightChild ? 2 : 0);
switch (mode)
{
case 0: // neither right nor left nodes are present
{
liftedChild.release();
if (get_leftmost() == n)
set_leftmost(parent);
if (get_rightmost() == n)
set_rightmost(parent);
if (!!parent)
result = wasRightNode;
}
break;
case 1: // left node is present
{
result = wasRightNode;
liftedChild = leftChild; // leftChild moves up to take its place
typename ref_t::locked_t lockedChild = leftChild;
lockedChild->set_parent_link(parent);
if (get_rightmost() == n)
set_rightmost(get_rightmost(leftChild));
}
break;
case 2: // right node is present
{
result = wasRightNode;
liftedChild = rightChild; // rightChild moves up to take its place
typename ref_t::locked_t lockedChild = rightChild;
lockedChild->set_parent_link(parent);
if (get_leftmost() == n)
set_leftmost(get_leftmost(rightChild));
}
break;
case 3: // both are present.
{
const ref_t& child = rightSideLarger ? rightChild : leftChild;
const ref_t& otherChild = rightSideLarger ? leftChild : rightChild;
localRoot = &swappedWith;
if (rightSideLarger) // Find node to swap with it.
swappedWith = get_leftmost(child);
else
swappedWith = get_rightmost(child);
typename ref_t::locked_t lockedSwappedWith = swappedWith;
liftedChild = lockedSwappedWith->get_child_link(rightSideLarger);
// Simultaneously swap 2 nodes, remove one, and lift its 1 child (if any)
typename ref_t::locked_t lockedOtherChild = otherChild;
lockedOtherChild->set_parent_link(swappedWith);
lockedSwappedWith->set_child_link(!rightSideLarger, otherChild);
if (swappedWith == child) // In case swapping with a child node
{
lockedRef->set_parent_link(swappedWith);
result = rightSideLarger;
}
else
{
ref_t swappedWithParent = lockedSwappedWith->get_parent_link();
lockedRef->set_parent_link(swappedWithParent); // just for the purpose of reporting back. Not actually in the list anymore.
if (!!liftedChild)
{
typename ref_t::locked_t lockedLiftedChild = liftedChild;
lockedLiftedChild->set_parent_link(swappedWithParent);
}
typename ref_t::locked_t lockedSwappedWithParent = swappedWithParent;
result = (lockedSwappedWithParent->get_right_link() == swappedWith);
lockedSwappedWithParent->set_child_link(!rightSideLarger, liftedChild);
typename ref_t::locked_t lockedChild = child;
lockedChild->set_parent_link(swappedWith);
lockedSwappedWith->set_child_link(rightSideLarger, child);
}
lockedSwappedWith->set_parent_link(parent);
}
break;
};
if (n == get_root())
set_root(*localRoot);
else
lockedParent->set_child_link(wasRightNode, *localRoot);
return result;
}
protected:
sorted_btree()
{ }
sorted_btree(this_t&& t)
: base_t(std::move(t))
{ }
this_t& operator=(this_t&& t)
{
base_t::operator=(std::move(t));
return *this;
}
/// @{
/// @brief Get the root node
const ref_t& get_root() const { return base_t::get_root(); }
/// @}
/// @{
/// @brief Sets the root node
/// @param r Value to set root node to
void set_root(const ref_t& r) { base_t::set_root(r); }
/// @}
/// @{
/// @brief Inserts a node into the sorted_btree.
/// @param n The node to insert.
/// @param insertMode The mode of the insert operation
/// @param hint If set, must be the result of a prior call to one of the 'last_equal' or
/// 'nearest_greater' find() functions passed the value being inserted. This is useful
/// if additional work is needed before insert, only if an existing match is or is not found.
/// @return A reference to an equal node in the case of collision, or an empty node if no collision.
ref_t insert(const ref_t& n, sorted_btree_insert_mode insertMode, const ref_t& hint = ref_t())
{
ref_t emptyRef;
typename ref_t::locked_t lockedRef = n;
lockedRef->set_left_link(emptyRef);
lockedRef->set_right_link(emptyRef);
// If empty
bool hasRoot = !!get_root();
if (!hasRoot)
{
lockedRef->set_parent_link(emptyRef);
set_root(n);
set_leftmost(n);
set_rightmost(n);
return emptyRef;
}
const key_t& key = lockedRef->get_key();
// Prepend optimization
typename ref_t::locked_t lockedCompareTo = get_rightmost();
const key_t& rightmostKey = lockedCompareTo->get_key();
bool isNotLess = !comparator_t::is_less_than(key, rightmostKey);
if (isNotLess)
{
bool isEqual = !comparator_t::is_less_than(rightmostKey, key);
if (isEqual)
{
if (insertMode == sorted_btree_insert_mode::unique)
return get_rightmost();
if (insertMode == sorted_btree_insert_mode::replace)
{
ref_t& parentNode = lockedCompareTo->get_parent_link();
lockedRef->set_parent_link(parentNode);
//Last won't have a right node, but may have a left node
ref_t& leftNode = lockedCompareTo->get_left_link();
if (!!leftNode)
{
typename ref_t::locked_t lockedLeftNode = leftNode;
lockedLeftNode->set_parent_link(n);
}
lockedRef->set_left_link(leftNode);
if (!!parentNode)
{
typename ref_t::locked_t lockedParentNode = parentNode;
lockedParentNode->set_child_link(true, n);
}
else // if (get_rightmost() == get_root())
set_root(n);
return get_rightmost();
}
}
lockedRef->set_parent_link(get_rightmost());
lockedCompareTo->set_right_link(n);
ref_t result = isEqual ? get_rightmost() : emptyRef;
set_rightmost(n);
return result;
}
// Append optimization
lockedCompareTo = get_leftmost();
const key_t& leftmostKey = lockedCompareTo->get_key();
bool isLess = comparator_t::is_less_than(key, leftmostKey);
if (isLess)
{
lockedRef->set_parent_link(get_leftmost());
lockedCompareTo->set_left_link(n);
set_leftmost(n);
return emptyRef;
}
// If hint is present, we know it's a valid parent node for the node being inserted.
ref_t compareTo = !hint ? get_root() : hint;
bool wasLess = false;
ref_t parent;
for (;;)
{
lockedCompareTo = compareTo;
const key_t& cmpKey = lockedCompareTo->get_key();
isLess = comparator_t::is_less_than(key, cmpKey);
// Check for an equal node. If so, we're done.
if ((insertMode != sorted_btree_insert_mode::multi) && !isLess && !comparator_t::is_less_than(cmpKey, key))
{
if (insertMode == sorted_btree_insert_mode::replace)
{
lockedRef->set_parent_link(lockedCompareTo->get_parent_link());
ref_t& rightNode = lockedCompareTo->get_right_link();
if (!!rightNode)
{
typename ref_t::locked_t lockedRightNode = rightNode;
lockedRightNode->set_parent_link(n);
}
lockedRef->set_right_link(rightNode);
ref_t& leftNode = lockedCompareTo->get_left_link();
if (!!leftNode)
{
typename ref_t::locked_t lockedLeftNode = leftNode;
lockedLeftNode->set_parent_link(n);
}
lockedRef->set_left_link(leftNode);
if (!!parent)
{
typename ref_t::locked_t lockedParent = parent;
lockedParent->set_child_link(!wasLess, n);
}
else // if (compareTo == get_root())
set_root(n);
}
return compareTo;
}
wasLess = isLess;
parent = compareTo;
compareTo = lockedCompareTo->get_child_link(!isLess);
if (!compareTo)
{
lockedRef->set_parent_link(parent);
if (isLess)
lockedCompareTo->set_left_link(n);
else
lockedCompareTo->set_right_link(n);
break;
}
}
return emptyRef;
}
/// @}
/// @{
/// @brief Rotate a node to the right.
///
/// The node will be pushed down and to the right. Its left child, if any, takes it place.
/// @param n The node to rotate to the right.
/// @param updateParent If false, the parent (or the root node) are not updated to reflect the rotation.
void rotate_right(const ref_t& n, bool updateParent = true)
{
typename ref_t::locked_t lockedRef = n;
ref_t child = lockedRef->get_left_link();
typename ref_t::locked_t lockedParent = n;
typename ref_t::locked_t lockedChild = child;
ref_t childChild = lockedChild->get_right_link();
ref_t oldParentParent = lockedParent->get_parent_link();
lockedChild->set_parent_link(oldParentParent);
lockedChild->set_right_link(n);
if (updateParent)
{
if (n == get_root())
set_root(child);
else
{
typename ref_t::locked_t lockedParentParent = oldParentParent;
lockedParentParent->set_child_link((lockedParentParent->get_right_link() == n), child);
}
}
lockedParent->set_parent_link(child);
lockedParent->set_left_link(childChild);
if (!!childChild)
childChild->set_parent_link(n);
}
/// @}
/// @{
/// @brief Rotate a node to the left.
///
/// The node will be pushed down and to the left. Its right child, if any, takes it place.
/// @param n The node to rotate to the left.
/// @param updateParent If false, the parent (or the root node) are not updated to reflect the rotation.
void rotate_left(const ref_t& n, bool updateParent = true)
{
typename ref_t::locked_t lockedRef = n;
ref_t child = lockedRef->get_right_link();
typename ref_t::locked_t lockedParent = n;
typename ref_t::locked_t lockedChild = child;
ref_t childChild = lockedChild->get_left_link();
ref_t oldParentParent = lockedParent->get_parent_link();
lockedChild->set_parent_link(oldParentParent);
lockedChild->set_left_link(n);
if (updateParent)
{
if (n == get_root())
set_root(child);
else
{
typename ref_t::locked_t lockedParentParent = oldParentParent;
lockedParentParent->set_child_link((lockedParentParent->get_right_link() == n), child);
}
}
lockedParent->set_parent_link(child);
lockedParent->set_right_link(childChild);
if (!!childChild)
childChild->set_parent_link(n);
}
/// @}
/// @{
/// @brief Remove a node, and begin the process of rebalancing the tree.
///
/// Removing a node with only 1 child, the operation is fairly simple; Move the child up into its place.
/// Removing a node with 2 children is only slightly more complicated. As a rule for sorted binary trees, any
/// node with 2 children has a next (and previous) in-order node that has 0 or 1 children (i.e. in-order next
/// may only have a right link, and in-order prev may only have a left link). The removing and in-order
/// adjacent nodes can simply be swapped. The node to be removed then has 0 or 1 child, and can be easily removed.
///
/// In order to update balancing information (red/black or avl), we need to return the node swapped with, and
/// the single child node swapped into place after removal. The caller needs to handle the following scenarios:
///
/// - If swappedWith is null, and liftedChild is null, the removed node had no children.
/// The removed node will retain a link to its original parent, which the caller may need for repaint.
///
/// - If swappedWith is null, and liftedChild is not null, the removed node had 1 child, which was moved into its place.
/// The removed node will retain a link to its original parent, which the caller may need for repaint.
///
/// - If swappedWith is not null, and liftedChild is null, the removed node had 2 children, and was swapped with
/// a node with 0 children. The removed node will retain a pointer to parent of the node it was swapped with,
/// which the caller may need for repainting.
///
/// - If swappedWith is not null, and liftedChild is not null, the removed node had 2 children, and was swapped with
/// a node with 1 child. The removed node will retain a pointer to the parent of the node it was swapped with.
///
/// @returns True if the removed node (after swapped) was its parent's right node.
bool balance_remove(const ref_t& n, ref_t& swappedWith, ref_t& liftedChild, bool rightSideLarger)
{
if (rightSideLarger)
return balance_remove_inner<true>(n, swappedWith, liftedChild);
return balance_remove_inner<false>(n, swappedWith, liftedChild);
}
/// @}
/// @{
/// @brief Swaps the contents of this tree with another.
/// @param srcDst The tree to swap with.
void swap(this_t& wth) { base_t::swap(wth); }
/// @}
public:
/// @{
/// @brief Tests if the tree is empty
/// @return True if the tree is empty
bool is_empty() const { return base_t::is_empty(); }
/// @}
/// @{
/// @brief Clears the root, leftmost and rightmost values maintained by the tree. Does not delete any elements.
void clear() { base_t::clear(); }
/// @}
/// @{
/// @brief Get the first in-order node
/// @return The first in-order node
const ref_t& get_first() const { return base_t::get_first_inorder(); }
/// @}
/// @{
/// @brief Get the last in-order node
/// @return The last in-order node
const ref_t& get_last() const { return base_t::get_last_inorder(); }
/// @}
/// @{
/// @brief Get the next in-order node
/// @param cur The node to get the next in-order node from
/// @return The next in-order node
ref_t get_next(const ref_t& cur) const { return base_t::get_next_inorder(cur); }
/// @}
/// @{
/// @brief Get the previous in-order node
/// @param cur The node to get the previous in-order node from
/// @return The previous in-order node
ref_t get_prev(const ref_t& cur) const { return base_t::get_prev_inorder(cur); }
/// @}
/// @{
/// @brief Get the first post-order node
/// @return The first post-order node
const ref_t get_first_postorder() const { return base_t::get_first_postorder(); }
/// @}
/// @{
/// @brief Get the last post-order node
/// @return The last post-order node
const ref_t& get_last_postorder() const { return base_t::get_last_postorder(); }
/// @}
/// @{
/// @brief Get the next post-order node
/// @param cur The node to get the next post-order node from
/// @return The next post-order node
ref_t get_next_postorder(const ref_t& cur) const { return base_t::get_next_postorder(cur); }
/// @}
/// @{
/// @brief Get the previous post-order node
/// @param cur The node to get the previous post-order node from
/// @return The previous post-order node
ref_t get_prev_postorder(const ref_t& cur) const { return base_t::get_prev_postorder(cur); }
/// @}
/// @{
/// @brief Find any node matching the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_any_equal(const key_t& criteria) const
{
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(criteria, key))
n = lockedRef->get_left_link();
else if (comparator_t::is_less_than(key, criteria))
n = lockedRef->get_right_link();
else
break;
}
return n;
}
/// @}
/// @{
/// @brief Find the first in-order node matching the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_first_equal(const key_t& criteria) const
{
ref_t lastFound;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(key, criteria))
n = lockedRef->get_right_link();
else if (comparator_t::is_less_than(criteria, key))
n = lockedRef->get_left_link();
else
{
lastFound = n;
// Once we've found an equal node, and go left, all nodes
// are either smaller or equal to criteria. No need to check
// if criteria is less than key.
n = lockedRef->get_left_link();
while (!!n)
{
lockedRef = n;
if (comparator_t::is_less_than(lockedRef->get_key(), criteria))
n = lockedRef->get_right_link();
else // they are equal
{
lastFound = n;
n = lockedRef->get_left_link();
}
}
break;
}
}
return lastFound;
}
/// @}
/// @{
/// @brief Find the last in-order node matching the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_last_equal(const key_t& criteria) const
{
ref_t lastFound;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(criteria, key))
n = lockedRef->get_left_link();
else if (comparator_t::is_less_than(key, criteria))
n = lockedRef->get_right_link();
else
{
lastFound = n;
// Once we've found an equal node, and go right, all nodes
// are either greater or equal to criteria. No need to check
// if key is less than criteria.
n = lockedRef->get_right_link();
while (!!n)
{
lockedRef = n;
if (comparator_t::is_less_than(criteria, lockedRef->get_key()))
n = lockedRef->get_left_link();
else // they are equal
{
lastFound = n;
n = lockedRef->get_right_link();
}
}
break;
}
}
return lastFound;
}
/// @}
/// @{
/// @brief Find the nearest node less than the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_nearest_less_than(const key_t& criteria) const
{
ref_t lastFound;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(key, criteria))
{
lastFound = n;
n = lockedRef->get_right_link();
}
else if (comparator_t::is_less_than(criteria, key))
n = lockedRef->get_left_link();
else
{
// Once we've found an equal node, and go left, all nodes
// are either smaller or equal to criteria. No need to check
// if criteria is less than key.
n = lockedRef->get_left_link();
while (!!n)
{
lockedRef = n;
if (comparator_t::is_less_than(lockedRef->get_key(), criteria))
{
lastFound = n;
n = lockedRef->get_right_link();
}
else // they are equal
n = lockedRef->get_left_link();
}
break;
}
}
return lastFound;
}
/// @}
/// @{
/// @brief Find the nearest node greater than the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_nearest_greater_than(const key_t& criteria) const
{
ref_t lastFound;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(criteria, key))
{
lastFound = n;
n = lockedRef->get_left_link();
}
else if (comparator_t::is_less_than(key, criteria))
n = lockedRef->get_right_link();
else
{
// Once we've found an equal node, and go right, all nodes
// are either greater or equal to criteria. No need to check
// if key is less than criteria.
n = lockedRef->get_right_link();
while (!!n)
{
lockedRef = n;
if (comparator_t::is_less_than(criteria, lockedRef->get_key()))
{
lastFound = n;
n = lockedRef->get_left_link();
}
else // they are equal
n = lockedRef->get_right_link();
}
break;
}
}
return lastFound;
}
/// @}
/// @{
/// @brief Find any node matching, or the nearest node less than the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_any_equal_or_nearest_less_than(const key_t& criteria) const
{
ref_t lastFound;
ref_t lastLesser;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(key, criteria))
{
lastLesser = n; // lesser
n = lockedRef->get_right_link();
}
else if (comparator_t::is_less_than(criteria, key))
n = lockedRef->get_left_link();
else
{
lastFound = n; // equal
break;
}
}
return lastFound;
}
/// @}
/// @{
/// @brief Find any node matching, or the nearest node greater than the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_any_equal_or_nearest_greater_than(const key_t& criteria) const
{
ref_t lastFound;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(criteria, key))
{
lastFound = n; // greater
n = lockedRef->get_left_link();
}
else if (comparator_t::is_less_than(key, criteria))
n = lockedRef->get_right_link();
else
{
lastFound = n; // equal
break;
}
}
return lastFound;
}
/// @}
/// @{
/// @brief Find the first in-order node matching, or the nearest node less than the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_first_equal_or_nearest_less_than(const key_t& criteria) const
{
ref_t lastFound;
ref_t lastLesser;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(key, criteria))
{
lastLesser = n; // lesser
n = lockedRef->get_right_link();
}
else if (comparator_t::is_less_than(criteria, key))
n = lockedRef->get_left_link();
else
{
lastFound = n; // equal
// Once we've found an equal node, and go left, all nodes
// are either smaller or equal to criteria. No need to check
// if criteria is less than key.
n = lockedRef->get_left_link();
while (!!n)
{
lockedRef = n;
if (comparator_t::is_less_than(lockedRef->get_key(), criteria))
n = lockedRef->get_right_link();
else
{
lastFound = n; // equal
n = lockedRef->get_left_link();
}
}
break;
}
}
return lastFound;
}
/// @}
/// @{
/// @brief Find the first in-order node matching, or the nearest node greater than the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_first_equal_or_nearest_greater_than(const key_t& criteria) const
{
ref_t lastFound;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(criteria, key))
{
lastFound = n; // greater
n = lockedRef->get_left_link();
}
else if (comparator_t::is_less_than(key, criteria))
n = lockedRef->get_right_link();
else
{
lastFound = n; // equal
// Once we've found an equal node, and go left, all nodes
// are either lesser or equal to criteria. No need to check
// if criteria is less than key.
n = lockedRef->get_left_link();
while (!!n)
{
lockedRef = n;
if (comparator_t::is_less_than(lockedRef->get_key(), criteria))
n = lockedRef->get_right_link();
else // they are equal
{
lastFound = n; // equal
n = lockedRef->get_left_link();
}
}
break;
}
}
return lastFound;
}
/// @}
/// @{
/// @brief Find the last in-order node matching, or the nearest node less than the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_last_equal_or_nearest_less_than(const key_t& criteria) const
{
ref_t lastFound;
ref_t lastLesser;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(key, criteria))
{
lastLesser = n; // lesser
n = lockedRef->get_right_link();
}
else if (comparator_t::is_less_than(criteria, key))
n = lockedRef->get_left_link();
else
{
lastFound = n; // equal
// Once we've found an equal node, and go right, all nodes
// are either greater or equal to criteria. No need to check
// if key is less than criteria.
n = lockedRef->get_right_link();
while (!!n)
{
lockedRef = n;
if (comparator_t::is_less_than(criteria, lockedRef->get_key()))
n = lockedRef->get_left_link();
else // they are equal
{
lastFound = n; // equal
n = lockedRef->get_right_link();
}
}
break;
}
}
return lastFound;
}
/// @}
/// @{
/// @brief Find the last in-order node matching, or the nearest node greater than the criteria value
/// @param criteria The value to match
/// @return The node found, or empty if not found.
ref_t find_last_equal_or_nearest_greater_than(const key_t& criteria) const
{
ref_t lastFound;
ref_t n = get_root();
typename ref_t::locked_t lockedRef;
while (!!n)
{
lockedRef = n;
const key_t& key = lockedRef->get_key();
if (comparator_t::is_less_than(criteria, key))
{
lastFound = n; // greater
n = lockedRef->get_left_link();
}
else if (comparator_t::is_less_than(key, criteria))
n = lockedRef->get_right_link();
else
{
lastFound = n; // equal
// Once we've found an equal node, and go right, all nodes
// are either greater or equal to criteria. No need to check
// if key is less than criteria.
n = lockedRef->get_right_link();
while (!!n)
{
lockedRef = n;
if (comparator_t::is_less_than(criteria, lockedRef->get_key()))
n = lockedRef->get_left_link();
else // they are equal
{
lastFound = n; // equal
n = lockedRef->get_right_link();
}
}
break;
}
}
return lastFound;
}
/// @}
};
}
#endif
| 28.876508 | 128 | 0.674147 | cogmine |
3fe273369053c8b68929caac458fbcd4abe95670 | 3,659 | cpp | C++ | utility/detail/iface.linux.cpp | ExploreWilder/libutility | b3600d5bc77211c567674032ad1a7c65ff56cc1b | [
"BSD-2-Clause"
] | 2 | 2018-08-26T07:34:38.000Z | 2019-02-25T07:27:57.000Z | utility/detail/iface.linux.cpp | ExploreWilder/libutility | b3600d5bc77211c567674032ad1a7c65ff56cc1b | [
"BSD-2-Clause"
] | 1 | 2021-02-22T17:23:02.000Z | 2021-04-08T15:18:57.000Z | utility/detail/iface.linux.cpp | ExploreWilder/libutility | b3600d5bc77211c567674032ad1a7c65ff56cc1b | [
"BSD-2-Clause"
] | 3 | 2019-09-25T05:22:06.000Z | 2022-03-29T09:18:42.000Z | /**
* Copyright (c) 2017 Melown Technologies SE
*
* 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.
*/
#include <sys/types.h>
#include <ifaddrs.h>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <system_error>
#include "iface.hpp"
namespace utility { namespace detail {
namespace ip = boost::asio::ip;
namespace {
template <typename Endpoint, typename Protocol>
Endpoint
endpointForIface(const Protocol &protocol
, const std::string &iface
, unsigned short portNum)
{
int family;
switch (protocol.family()) {
case PF_INET: family = AF_INET; break;
case PF_INET6: family = AF_INET6; break;
default:
throw std::runtime_error("Unsupported protocol family.");
}
struct ::ifaddrs *ifa;
if (-1 == ::getifaddrs(&ifa)) {
std::system_error e(errno, std::system_category(), "getifaddrs");
throw e;
}
std::shared_ptr<struct ::ifaddrs> guard(ifa, [](struct ::ifaddrs *ifa) {
freeifaddrs(ifa);
});
for (; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_name != iface) { continue; }
if (ifa->ifa_addr->sa_family == family) {
break;
}
}
if (!ifa) {
throw std::runtime_error("Interface <" + iface + "> not found.");
}
switch (protocol.family()) {
case PF_INET:
return { ip::address_v4
(ntohl(reinterpret_cast<struct sockaddr_in*>
(ifa->ifa_addr)->sin_addr.s_addr))
, portNum };
case PF_INET6: {
auto s6(reinterpret_cast<struct sockaddr_in6*>(ifa->ifa_addr));
ip::address_v6::bytes_type a;
for (int i = 0; i < 16; ++i) { a[i] = s6->sin6_addr.s6_addr[i]; }
return { ip::address_v6(a, s6->sin6_scope_id), portNum };
} }
throw std::runtime_error("Unsupported protocol family.");
}
} // namespace
ip::tcp::endpoint
tcpEndpointForIface(const ip::tcp &protocol
, const std::string &iface
, unsigned short portNum)
{
return endpointForIface<ip::tcp::endpoint>(protocol, iface, portNum);
}
ip::udp::endpoint
udpEndpointForIface(const ip::udp &protocol
, const std::string &iface
, unsigned short portNum)
{
return endpointForIface<ip::udp::endpoint>(protocol, iface, portNum);
}
} } // namespace utility::detail
| 31.817391 | 78 | 0.656737 | ExploreWilder |
3fe470ec03d8756e24f91db108cfe5d668492844 | 1,102 | hpp | C++ | include/containers/pop_front.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 44 | 2020-10-03T21:37:52.000Z | 2022-03-26T10:08:46.000Z | include/containers/pop_front.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | 1 | 2021-01-01T23:22:39.000Z | 2021-01-01T23:22:39.000Z | include/containers/pop_front.hpp | davidstone/bounded-integer | d4f9a88a12174ca8382af60b00c5affd19aa8632 | [
"BSL-1.0"
] | null | null | null | // Copyright David Stone 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <containers/algorithms/erase.hpp>
#include <containers/begin_end.hpp>
#include <containers/front_back.hpp>
#include <containers/constant_time_erasable.hpp>
#include <containers/is_range.hpp>
#include <bounded/detail/construct_destroy.hpp>
#include <bounded/integer.hpp>
namespace containers {
namespace detail {
template<typename Container>
concept member_pop_frontable = requires (Container & container) { container.pop_front(); };
template<typename Container>
concept pop_frontable = member_pop_frontable<Container> or constant_time_erasable<Container>;
} // namespace detail
template<detail::pop_frontable Container>
constexpr auto pop_front(Container & c) -> void {
if constexpr (detail::member_pop_frontable<Container>) {
c.pop_front();
} else {
static_assert(constant_time_erasable<Container>);
containers::erase(c, containers::begin(c));
}
}
} // namespace containers
| 28.25641 | 93 | 0.778584 | davidstone |
3fe6dd0aff22cee668181ae38d3261139a86c049 | 5,299 | cc | C++ | abel/chrono/civil_time.cc | Conun/abel | 485ef38c917c0df3750242cc38966a2bcb163588 | [
"BSD-3-Clause"
] | null | null | null | abel/chrono/civil_time.cc | Conun/abel | 485ef38c917c0df3750242cc38966a2bcb163588 | [
"BSD-3-Clause"
] | null | null | null | abel/chrono/civil_time.cc | Conun/abel | 485ef38c917c0df3750242cc38966a2bcb163588 | [
"BSD-3-Clause"
] | null | null | null | //
#include <abel/chrono/civil_time.h>
#include <cstdlib>
#include <string>
#include <abel/strings/str_cat.h>
#include <abel/chrono/time.h>
namespace abel {
namespace {
// Since a civil time has a larger year range than abel::abel_time (64-bit years vs
// 64-bit seconds, respectively) we normalize years to roughly +/- 400 years
// around the year 2400, which will produce an equivalent year in a range that
// abel::abel_time can handle.
ABEL_FORCE_INLINE chrono_year_t NormalizeYear(chrono_year_t year) {
return 2400 + year % 400;
}
// Formats the given chrono_second according to the given format.
std::string FormatYearAnd(string_view fmt, chrono_second cs) {
const chrono_second ncs(NormalizeYear(cs.year()), cs.month(), cs.day(),
cs.hour(), cs.minute(), cs.second());
const time_zone utc = utc_time_zone();
// TODO(abel-team): Avoid conversion of fmt std::string.
return string_cat(cs.year(),
format_time(std::string(fmt), from_chrono(ncs, utc), utc));
}
template <typename CivilT>
bool ParseYearAnd(string_view fmt, string_view s, CivilT* c) {
// Civil times support a larger year range than abel::abel_time, so we need to
// parse the year separately, normalize it, then use abel::parse_time on the
// normalized std::string.
const std::string ss = std::string(s); // TODO(abel-team): Avoid conversion.
const char* const np = ss.c_str();
char* endp;
errno = 0;
const chrono_year_t y =
std::strtoll(np, &endp, 10); // NOLINT(runtime/deprecated_fn)
if (endp == np || errno == ERANGE) return false;
const std::string norm = string_cat(NormalizeYear(y), endp);
const time_zone utc = utc_time_zone();
abel_time t;
if (parse_time(string_cat("%Y", fmt), norm, utc, &t, nullptr)) {
const auto cs = to_chrono_second(t, utc);
*c = CivilT(y, cs.month(), cs.day(), cs.hour(), cs.minute(), cs.second());
return true;
}
return false;
}
// Tries to parse the type as a CivilT1, but then assigns the result to the
// argument of type CivilT2.
template <typename CivilT1, typename CivilT2>
bool ParseAs(string_view s, CivilT2* c) {
CivilT1 t1;
if (parse_chrono_time(s, &t1)) {
*c = CivilT2(t1);
return true;
}
return false;
}
template <typename CivilT>
bool ParseLenient(string_view s, CivilT* c) {
// A fastpath for when the given std::string data parses exactly into the given
// type T (e.g., s="YYYY-MM-DD" and CivilT=chrono_day).
if (parse_chrono_time(s, c)) return true;
// Try parsing as each of the 6 types, trying the most common types first
// (based on csearch results).
if (ParseAs<chrono_day>(s, c)) return true;
if (ParseAs<chrono_second>(s, c)) return true;
if (ParseAs<chrono_hour>(s, c)) return true;
if (ParseAs<chrono_month>(s, c)) return true;
if (ParseAs<chrono_minute>(s, c)) return true;
if (ParseAs<chrono_year>(s, c)) return true;
return false;
}
} // namespace
std::string format_chrono_time(chrono_second c) {
return FormatYearAnd("-%m-%dT%H:%M:%S", c);
}
std::string format_chrono_time(chrono_minute c) {
return FormatYearAnd("-%m-%dT%H:%M", c);
}
std::string format_chrono_time(chrono_hour c) {
return FormatYearAnd("-%m-%dT%H", c);
}
std::string format_chrono_time(chrono_day c) { return FormatYearAnd("-%m-%d", c); }
std::string format_chrono_time(chrono_month c) { return FormatYearAnd("-%m", c); }
std::string format_chrono_time(chrono_year c) { return FormatYearAnd("", c); }
bool parse_chrono_time(string_view s, chrono_second* c) {
return ParseYearAnd("-%m-%dT%H:%M:%S", s, c);
}
bool parse_chrono_time(string_view s, chrono_minute* c) {
return ParseYearAnd("-%m-%dT%H:%M", s, c);
}
bool parse_chrono_time(string_view s, chrono_hour* c) {
return ParseYearAnd("-%m-%dT%H", s, c);
}
bool parse_chrono_time(string_view s, chrono_day* c) {
return ParseYearAnd("-%m-%d", s, c);
}
bool parse_chrono_time(string_view s, chrono_month* c) {
return ParseYearAnd("-%m", s, c);
}
bool parse_chrono_time(string_view s, chrono_year* c) {
return ParseYearAnd("", s, c);
}
bool ParseLenientCivilTime(string_view s, chrono_second* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, chrono_minute* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, chrono_hour* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, chrono_day* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, chrono_month* c) {
return ParseLenient(s, c);
}
bool ParseLenientCivilTime(string_view s, chrono_year* c) {
return ParseLenient(s, c);
}
namespace chrono_internal {
std::ostream& operator<<(std::ostream& os, chrono_year y) {
return os << format_chrono_time(y);
}
std::ostream& operator<<(std::ostream& os, chrono_month m) {
return os << format_chrono_time(m);
}
std::ostream& operator<<(std::ostream& os, chrono_day d) {
return os << format_chrono_time(d);
}
std::ostream& operator<<(std::ostream& os, chrono_hour h) {
return os << format_chrono_time(h);
}
std::ostream& operator<<(std::ostream& os, chrono_minute m) {
return os << format_chrono_time(m);
}
std::ostream& operator<<(std::ostream& os, chrono_second s) {
return os << format_chrono_time(s);
}
} // namespace chrono_internal
} // namespace abel
| 32.509202 | 83 | 0.699 | Conun |
3fe9116e9ceb73ca2a0810d417e7837052d2dd1c | 2,219 | hpp | C++ | externals/browser/externals/browser/externals/libhttp/http/request.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 1 | 2021-09-02T08:42:59.000Z | 2021-09-02T08:42:59.000Z | externals/browser/externals/browser/externals/libhttp/http/request.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | null | null | null | externals/browser/externals/browser/externals/libhttp/http/request.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | null | null | null | /**
* Copyright (c) 2017 Melown Technologies SE
*
* 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.
*/
#ifndef http_request_hpp_included_
#define http_request_hpp_included_
#include <string>
#include <vector>
namespace http {
struct Header {
std::string name;
std::string value;
typedef std::vector<Header> list;
Header() {}
Header(const std::string &name, const std::string &value)
: name(name), value(value) {}
};
struct Request {
/** Uri as received from client
*/
std::string uri;
/** Cleaned-up path from uri
*/
std::string path;
/** Query string from uri
*/
std::string query;
Header::list headers;
bool hasHeader(const std::string &name) const;
const std::string* getHeader(const std::string &name) const;
};
inline bool Request::hasHeader(const std::string &name) const
{
return getHeader(name);
}
} // namespace http
#endif // http_request_hpp_included_
| 30.39726 | 78 | 0.722397 | HanochZhu |
3feadb764dcbf2e7f025966e13fdc60bf3e7ee7f | 31,178 | cpp | C++ | src/db/dbITerm.cpp | mgwoo/OpenDB | 8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4 | [
"BSD-3-Clause"
] | 1 | 2021-03-04T02:35:47.000Z | 2021-03-04T02:35:47.000Z | src/db/dbITerm.cpp | mgwoo/OpenDB | 8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4 | [
"BSD-3-Clause"
] | null | null | null | src/db/dbITerm.cpp | mgwoo/OpenDB | 8bf8df500dc525f2abfa16a8f5ac2cb67c09b6f4 | [
"BSD-3-Clause"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// BSD 3-Clause License
//
// Copyright (c) 2019, Nefelus Inc
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "dbITerm.h"
#include "dbDatabase.h"
#include "dbHier.h"
#include "dbBTerm.h"
#include "dbChip.h"
#include "dbInst.h"
#include "dbTmg.h"
#include "dbInstHdr.h"
#include "dbNet.h"
#include "dbLib.h"
#include "dbMaster.h"
#include "dbMTerm.h"
#include "dbBlock.h"
#include "dbBlockCallBackObj.h"
#include "dbTable.h"
#include "dbArrayTable.h"
#include "dbTable.hpp"
#include "dbShape.h"
#include "dbJournal.h"
#include "dbTmgJournal.h"
#include "db.h"
#include "dbDiff.hpp"
#include "logger.h"
#ifdef _WIN32
#define MINFLOAT -1.0e+20
#define MAXFLOAT 1.0e+20
#endif
namespace odb {
#ifdef FULL_ECO
#define FLAGS(iterm) (*((uint *) &iterm->_flags))
#endif
template class dbTable<_dbITerm>;
bool _dbITerm::operator==( const _dbITerm & rhs ) const
{
if( _flags._mterm_idx != rhs._flags._mterm_idx )
return false;
if( _flags._spef != rhs._flags._spef )
return false;
if( _flags._special != rhs._flags._special )
return false;
if( _flags._connected != rhs._flags._connected )
return false;
if( _ext_id != rhs._ext_id )
return false;
if( _net != rhs._net )
return false;
if( _inst != rhs._inst )
return false;
if( _tmg != rhs._tmg )
return false;
if( _next_net_iterm != rhs._next_net_iterm )
return false;
if( _prev_net_iterm != rhs._prev_net_iterm )
return false;
return true;
}
bool _dbITerm::operator<( const _dbITerm & rhs ) const
{
_dbBlock * lhs_blk = (_dbBlock *) getOwner();
_dbBlock * rhs_blk = (_dbBlock *) rhs.getOwner();
_dbInst * lhs_inst = lhs_blk->_inst_tbl->getPtr(_inst);
_dbInst * rhs_inst = rhs_blk->_inst_tbl->getPtr(rhs._inst);
int r = strcmp( lhs_inst->_name, rhs_inst->_name );
if ( r < 0 )
return true;
if ( r > 0 )
return false;
_dbMTerm * lhs_mterm = getMTerm();
_dbMTerm * rhs_mterm = rhs.getMTerm();
return strcmp( lhs_mterm->_name, rhs_mterm->_name ) < 0;
}
void _dbITerm::differences( dbDiff & diff, const char * field, const _dbITerm & rhs ) const
{
if ( ! diff.deepDiff() )
{
DIFF_BEGIN
DIFF_FIELD( _net);
DIFF_FIELD( _inst);
DIFF_FIELD( _tmg);
DIFF_FIELD( _flags._mterm_idx);
DIFF_FIELD( _flags._spef);
DIFF_FIELD( _flags._special);
DIFF_FIELD( _flags._connected);
DIFF_FIELD( _ext_id);
DIFF_FIELD( _next_net_iterm);
DIFF_FIELD( _prev_net_iterm);
DIFF_END
}
else
{
_dbBlock * lhs_blk = (_dbBlock *) getOwner();
_dbBlock * rhs_blk = (_dbBlock *) rhs.getOwner();
_dbInst * lhs_inst = lhs_blk->_inst_tbl->getPtr(_inst);
_dbInst * rhs_inst = rhs_blk->_inst_tbl->getPtr(rhs._inst);
_dbMTerm * lhs_mterm = getMTerm();
_dbMTerm * rhs_mterm = rhs.getMTerm();
assert( strcmp( lhs_inst->_name, rhs_inst->_name ) == 0 );
assert( strcmp( lhs_mterm->_name, rhs_mterm->_name ) == 0 );
diff.begin_object("<> %s (_dbITerm)\n", lhs_mterm->_name );
if ( (_net != 0) && (rhs._net != 0) )
{
_dbNet * lhs_net = lhs_blk->_net_tbl->getPtr(_net);
_dbNet * rhs_net = rhs_blk->_net_tbl->getPtr(rhs._net);
diff.diff( "_net", lhs_net->_name, rhs_net->_name );
}
else if ( _net != 0 )
{
_dbNet * lhs_net = lhs_blk->_net_tbl->getPtr(_net);
diff.out( dbDiff::LEFT, "_net", lhs_net->_name );
}
else if ( rhs._net != 0 )
{
_dbNet * rhs_net = rhs_blk->_net_tbl->getPtr(rhs._net);
diff.out( dbDiff::RIGHT, "_net", rhs_net->_name );
}
DIFF_OBJECT( _tmg, lhs_blk->_tmg_tbl, rhs_blk->_tmg_tbl );
DIFF_FIELD( _flags._spef);
DIFF_FIELD( _flags._special);
DIFF_FIELD( _flags._connected);
DIFF_FIELD( _ext_id);
diff.end_object();
}
}
void _dbITerm::out( dbDiff & diff, char side, const char * field ) const
{
if ( ! diff.deepDiff() )
{
DIFF_OUT_BEGIN
DIFF_OUT_FIELD( _net);
DIFF_OUT_FIELD( _inst);
DIFF_OUT_FIELD( _tmg);
DIFF_OUT_FIELD( _flags._mterm_idx);
DIFF_OUT_FIELD( _flags._spef);
DIFF_OUT_FIELD( _flags._special);
DIFF_OUT_FIELD( _flags._connected);
DIFF_OUT_FIELD( _ext_id);
DIFF_OUT_FIELD( _next_net_iterm);
DIFF_OUT_FIELD( _prev_net_iterm);
DIFF_END
}
else
{
_dbMTerm * mterm = getMTerm();
diff.begin_object("%c %s (_dbITerm)\n", side, mterm->_name );
_dbBlock * blk = (_dbBlock *) getOwner();
if ( _net != 0 )
{
_dbNet * net = blk->_net_tbl->getPtr(_net);
diff.out( side, "_net", net->_name );
}
DIFF_OUT_OBJECT( _tmg, blk->_tmg_tbl );
DIFF_OUT_FIELD( _flags._spef);
DIFF_OUT_FIELD( _flags._special);
DIFF_OUT_FIELD( _flags._connected);
DIFF_OUT_FIELD( _ext_id);
diff.end_object();
}
}
_dbMTerm *
_dbITerm::getMTerm() const
{
_dbBlock * block = (_dbBlock *) getOwner();
_dbInst * inst = block->_inst_tbl->getPtr(_inst);
_dbInstHdr * inst_hdr = block->_inst_hdr_tbl->getPtr(inst->_inst_hdr);
_dbDatabase * db = getDatabase();
_dbLib * lib = db->_lib_tbl->getPtr(inst_hdr->_lib);
_dbMaster * master = lib->_master_tbl->getPtr(inst_hdr->_master);
dbId<_dbMTerm> mterm = inst_hdr->_mterms[_flags._mterm_idx];
return master->_mterm_tbl->getPtr(mterm);
}
_dbInst *
_dbITerm::getInst() const
{
_dbBlock * block = (_dbBlock *) getOwner();
_dbInst * inst = block->_inst_tbl->getPtr(_inst);
return inst;
}
////////////////////////////////////////////////////////////////////
//
// dbITerm - Methods
//
////////////////////////////////////////////////////////////////////
dbInst *
dbITerm::getInst()
{
_dbITerm * iterm = (_dbITerm *) this;
_dbBlock * block = (_dbBlock *) getOwner();
_dbInst * inst = block->_inst_tbl->getPtr(iterm->_inst);
return (dbInst *) inst;
}
dbNet *
dbITerm::getNet()
{
_dbITerm * iterm = (_dbITerm *) this;
_dbBlock * block = (_dbBlock *) getOwner();
if ( iterm->_net == 0 )
return NULL;
_dbNet * net = block->_net_tbl->getPtr(iterm->_net);
return (dbNet *) net;
}
dbMTerm *
dbITerm::getMTerm()
{
_dbITerm * iterm = (_dbITerm *) this;
_dbBlock * block = (_dbBlock *) getOwner();
_dbInst * inst = block->_inst_tbl->getPtr(iterm->_inst);
_dbInstHdr * inst_hdr = block->_inst_hdr_tbl->getPtr(inst->_inst_hdr);
_dbDatabase * db = getDatabase();
_dbLib * lib = db->_lib_tbl->getPtr(inst_hdr->_lib);
_dbMaster * master = lib->_master_tbl->getPtr(inst_hdr->_master);
dbId<_dbMTerm> mterm = inst_hdr->_mterms[iterm->_flags._mterm_idx];
return (dbMTerm *) master->_mterm_tbl->getPtr(mterm);
}
dbBTerm *
dbITerm::getBTerm()
{
_dbITerm * iterm = (_dbITerm *) this;
_dbBlock * block = (_dbBlock *) getOwner();
_dbInst * inst = block->_inst_tbl->getPtr(iterm->_inst);
if ( inst->_hierarchy == 0 )
return NULL;
_dbHier * hier = block->_hier_tbl->getPtr(inst->_hierarchy);
_dbChip * chip = (_dbChip *) block->getOwner();
_dbBlock * child = chip->_block_tbl->getPtr( hier->_child_block );
dbId<_dbBTerm> bterm = hier->_child_bterms[iterm->_flags._mterm_idx];
return (dbBTerm *) child->_bterm_tbl->getPtr(bterm);
}
void dbITerm::initTiming()
{
_dbITerm * iterm = (_dbITerm *) this;
_dbBlock * block = (_dbBlock *) getOwner();
((dbBlock*)block)->initTmbTbl(); // ex: "Tmg tmg" after "db read"
if ( iterm->_tmg == 0 )
iterm->_tmg = block->_tmg_tbl->createArray();
uint scns = (uint)block->_number_of_scenarios;
for (uint ks = 0; ks <= scns; ks++) {
_dbTmg * tmg_min = block->_tmg_tbl->getPtr(iterm->_tmg + TMG_MIN + ks*2);
_dbTmg * tmg_max = block->_tmg_tbl->getPtr(iterm->_tmg + TMG_MAX + ks*2);
// payam: changes MAX/MIN_INT to MAX/MINFLOAT
tmg_min->_slew_rise = FLT_MAX;
tmg_min->_slew_fall = FLT_MAX;
tmg_min->_slack_rise = FLT_MAX;
tmg_min->_slack_fall = FLT_MAX;
///tmg_min->_scenario._slew_rise = 0;
///tmg_min->_scenario._slew_fall = 0;
///tmg_min->_scenario._slack_rise = 0;
///tmg_min->_scenario._slack_fall = 0;
tmg_max->_slew_rise = FLT_MIN;
tmg_max->_slew_fall = FLT_MIN;
tmg_max->_slack_rise = FLT_MAX;
tmg_max->_slack_fall = FLT_MAX;
///tmg_max->_scenario._slew_rise = 0;
///tmg_max->_scenario._slew_fall = 0;
///tmg_max->_scenario._slack_rise = 0;
///tmg_max->_scenario._slack_fall = 0;
}
}
bool dbITerm::getWorstSlack(float wns[2], float tns[2], uint scenario[2])
{
_dbITerm * iterm = (_dbITerm *) this;
_dbBlock * block = (_dbBlock *) getOwner();
if ( iterm->_tmg == 0 )
return false;
//_dbTmg * tmg_min = block->_tmg_tbl->getPtr(iterm->_tmg);
//_dbTmg * tmg_max = block->_tmg_tbl->getPtr(iterm->_tmg+1U);
//bool worstTerm= tmg_min->updateSlacks(wns, tns, scenario, TMG_MIN);
//worstTerm= tmg_max->updateSlacks(wns, tns, scenario, TMG_MAX) || worstTerm;
uint scns = (uint)block->_number_of_scenarios;
_dbTmg * tmg_min;
_dbTmg * tmg_max;
bool worstTermMin = false;
bool worstTermMax = false;
for (uint ks = 1; ks <= scns; ks++) {
tmg_min = block->_tmg_tbl->getPtr(iterm->_tmg + TMG_MIN + ks*2);
tmg_max = block->_tmg_tbl->getPtr(iterm->_tmg + TMG_MAX + ks*2);
if (tmg_min->updateSlacks(wns, tns, TMG_MIN)) {
scenario[TMG_MIN] = ks;
worstTermMin = true;
}
if (tmg_max->updateSlacks(wns, tns, TMG_MAX)) {
scenario[TMG_MAX] = ks;
worstTermMax = true;
}
}
if (worstTermMin)
tns[TMG_MIN] += wns[TMG_MIN];
if (worstTermMax)
tns[TMG_MAX] += wns[TMG_MAX];
return (worstTermMin || worstTermMax);
}
// payam: return type from int to float
float dbITerm::getSlewRise( dbTimingMode mode )
{
uint scenario = 0;
return getSlewRise( mode, scenario );
}
float dbITerm::getSlewRise( dbTimingMode mode, uint scenario )
{
_dbITerm * iterm = (_dbITerm *) this;
if ( iterm->_tmg == 0 )
initTiming();
_dbBlock * block = (_dbBlock *) getOwner();
float slew = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + scenario*2)->_slew_rise;
if(isDebug("TMG_DB", "L")) {
const char* iname= getInst()->getConstName();
const char* mname= getMTerm()->getConstName();
debug("TMG_DB","L","#%d SlewRise[%d]-[S%d]: %g %s/%s\n",
getId(), mode, scenario, slew, iname, mname);
}
return slew;
}
// payam: return type from int to float
float dbITerm::getSlewFall( dbTimingMode mode )
{
uint scenario = 0;
return getSlewFall( mode, scenario );
}
float dbITerm::getSlewFall( dbTimingMode mode, uint scenario )
{
_dbITerm * iterm = (_dbITerm *) this;
if ( iterm->_tmg == 0 )
initTiming();
_dbBlock * block = (_dbBlock *) getOwner();
float slew = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + scenario*2)->_slew_fall;
if(isDebug("TMG_DB", "L")) {
const char* iname= getInst()->getConstName();
const char* mname= getMTerm()->getConstName();
debug("TMG_DB","L","#%d SlewFall[%d]-[S%d]: %g %s/%s\n",
getId(), mode, scenario, slew, iname, mname);
}
return slew;
}
// payam: return type from int to float
float dbITerm::getSlackRise( dbTimingMode mode )
{
uint scenario = 0;
return getSlackRise( mode, scenario );
}
float dbITerm::getSlackRise( dbTimingMode mode, uint scenario )
{
_dbITerm * iterm = (_dbITerm *) this;
if ( iterm->_tmg == 0 )
initTiming();
_dbBlock * block = (_dbBlock *) getOwner();
float slack = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + scenario*2)->_slack_rise;
if(isDebug("TMG_DB", "I")) {
const char* iname= getInst()->getConstName();
const char* mname= getMTerm()->getConstName();
debug("TMG_DB","I","#%d SlackRise[%d]-[S%d]: %g %s/%s\n",
getId(), mode, scenario, slack, iname, mname);
_dbBlock * block = (_dbBlock *) getOwner();
uint scns = (uint)block->_number_of_scenarios;
for (uint ii= 0; ii<=scns; ii++) {
float v = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + ii*2)->_slack_rise;
debug("TMG_DB","I","\t%d %g\n", ii, v);
}
}
return slack;
}
// payam: return type from int to float
float dbITerm::getSlackFall( dbTimingMode mode )
{
uint scenario = 0;
return getSlackFall( mode, scenario );
}
float dbITerm::getSlackFall( dbTimingMode mode, uint scenario )
{
_dbITerm * iterm = (_dbITerm *) this;
if ( iterm->_tmg == 0 )
initTiming();
_dbBlock * block = (_dbBlock *) getOwner();
float slack = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + scenario*2)->_slack_fall;
if(isDebug("TMG_DB", "I")) {
const char* iname= getInst()->getConstName();
const char* mname= getMTerm()->getConstName();
debug("TMG_DB","I","#%d SlackFall[%d]-[S%d]: %g %s/%s\n",
getId(), mode, scenario, slack, iname, mname);
_dbBlock * block = (_dbBlock *) getOwner();
uint scns = (uint)block->_number_of_scenarios;
for (uint ii= 0; ii<=scns; ii++) {
float v = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + ii*2)->_slack_fall;
debug("TMG_DB","I","\t%d %g\n", ii, v);
}
}
return slack;
}
// payam: type from int to float
void dbITerm::setSlewRise( dbTimingMode mode, float value, uint scenario )
{
_dbITerm * iterm = (_dbITerm *) this;
if ( iterm->_tmg == 0 )
initTiming();
_dbBlock * block = (_dbBlock *) getOwner();
block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + scenario*2)->_slew_rise = value;
if (scenario == 0)
return;
float wslew = value;
float nslew;
// dimitri_fix uint ws = scenario;
for (uint ks = 1; ks <= (uint)block->_number_of_scenarios && ks != scenario; ks++) {
nslew = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + ks*2)->_slew_rise;
if ((mode == TMG_MIN && nslew < wslew) || (mode == TMG_MAX && nslew > wslew)) {
wslew = nslew;
// dimitri_fix ws = ks;
}
}
block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode)->_slew_rise = wslew;
}
// payam: type from int to float
void dbITerm::setSlewFall( dbTimingMode mode, float value, uint scenario )
{
_dbITerm * iterm = (_dbITerm *) this;
if ( iterm->_tmg == 0 )
initTiming();
_dbBlock * block = (_dbBlock *) getOwner();
block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + scenario*2)->_slew_fall = value;
if (scenario == 0)
return;
float wslew = value;
float nslew;
// dimitri_fix uint ws = scenario;
for (uint ks = 1; ks <= (uint)block->_number_of_scenarios && ks != scenario; ks++) {
nslew = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + ks*2)->_slew_fall;
if ((mode == TMG_MIN && nslew < wslew) || (mode == TMG_MAX && nslew > wslew)) {
wslew = nslew;
// dimitri_fix ws = ks;
}
}
block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode)->_slew_fall = wslew;
}
void dbITerm::setSlackRise( dbTimingMode mode, float value, uint scenario )
{
_dbITerm * iterm = (_dbITerm *) this;
if ( iterm->_tmg == 0 )
initTiming();
_dbBlock * block = (_dbBlock *) getOwner();
block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + scenario*2)->_slack_rise = value;
if (scenario == 0)
return;
float wslack = value;
float nslack;
// dimitri_fix uint ws = scenario;
for (uint ks = 1; ks <= (uint)block->_number_of_scenarios && ks != scenario; ks++) {
nslack = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + ks*2)->_slack_rise;
if (nslack < wslack) {
wslack = nslack;
// dimitri_fix ws = ks;
}
}
block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode)->_slack_rise = wslack;
uint ii= (uint) mode;
if ((block->_flags._active_pins>0) && (value<0.0) ) {
block->_WNS[ii]= MIN(block->_WNS[ii], value);
block->_TNS[ii] += value;
}
}
// payam: type from int to float
void dbITerm::setSlackFall( dbTimingMode mode, float value, uint scenario )
{
_dbITerm * iterm = (_dbITerm *) this;
if ( iterm->_tmg == 0 )
initTiming();
_dbBlock * block = (_dbBlock *) getOwner();
block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + scenario*2)->_slack_fall = value;
if (scenario == 0)
return;
float wslack = value;
float nslack;
// dimitri_fix uint ws = scenario;
for (uint ks = 1; ks <= (uint)block->_number_of_scenarios && ks != scenario; ks++) {
nslack = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode + ks*2)->_slack_fall;
if (nslack < wslack) {
wslack = nslack;
// dimitri_fix ws = ks;
}
}
block->_tmg_tbl->getPtr(iterm->_tmg + (uint) mode)->_slack_fall = wslack;
uint ii= (uint) mode;
if ((block->_flags._active_pins>0) && (value<0.0) ) {
block->_WNS[ii]= MIN(block->_WNS[ii], value);
block->_TNS[ii] += value;
}
}
//void dbITerm::ecoTiming()
//{
// _dbITerm * iterm = (_dbITerm *) this;
// _dbBlock * block = (_dbBlock *) getOwner();
//
// if ( iterm->_tmg == 0 )
// initTiming();
//
// if ( block->_tmg_journal )
// {
// _dbTmg * min_tmg = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) TMG_MIN);
// _dbTmg * max_tmg = block->_tmg_tbl->getPtr(iterm->_tmg + (uint) TMG_MAX);
// block->_tmg_journal->beginAction( dbTmgJournal::UPDATE_ITERM_TMG );
// block->_tmg_journal->pushParam( iterm->getId() );
// block->_tmg_journal->pushParam( min_tmg->_slew_rise );
// block->_tmg_journal->pushParam( max_tmg->_slew_rise );
// block->_tmg_journal->pushParam( min_tmg->_slew_fall );
// block->_tmg_journal->pushParam( max_tmg->_slew_fall );
// block->_tmg_journal->pushParam( min_tmg->_slack_rise );
// block->_tmg_journal->pushParam( max_tmg->_slack_rise );
// block->_tmg_journal->pushParam( min_tmg->_slack_fall );
// block->_tmg_journal->pushParam( max_tmg->_slack_fall );
// block->_tmg_journal->endAction();
// }
//}
dbBlock *
dbITerm::getBlock()
{
return (dbBlock *) getOwner();
}
void dbITerm::setClocked(bool v)
{
_dbITerm * iterm = (_dbITerm *) this;
iterm->_flags._clocked = v;
}
bool dbITerm::isClocked()
{
bool masterFlag= getMTerm()->getSigType()==dbSigType::CLOCK ? true : false;
_dbITerm * iterm = (_dbITerm *) this;
return iterm->_flags._clocked>0 || masterFlag ? true : false;
}
void dbITerm::setMark(uint v)
{
_dbITerm * iterm = (_dbITerm *) this;
iterm->_flags._mark = v;
}
bool dbITerm::isSetMark()
{
_dbITerm * iterm = (_dbITerm *) this;
return iterm->_flags._mark>0 ? true : false;
}
bool dbITerm::isSpecial()
{
_dbITerm * iterm = (_dbITerm *) this;
return iterm->_flags._special == 1;
}
void dbITerm::setSpecial()
{
_dbITerm * iterm = (_dbITerm *) this;
//_dbBlock * block = (_dbBlock *) getOwner();
// dimitri_fix: need to FIX on FULL_ECO uint prev_flags = FLAGS(iterm);
#ifdef FULL_ECO
uint prev_flags = FLAGS(iterm);
#endif
iterm->_flags._special = 1;
#ifdef FULL_ECO
if ( block->_journal )
{
debug("DB_ECO","A","ECO: Iterm %d, setSpecial\n",getId());
block->_journal->updateField( this, _dbNet::FLAGS, prev_flags, FLAGS(iterm) );
}
#endif
}
void dbITerm::clearSpecial()
{
_dbITerm * iterm = (_dbITerm *) this;
//_dbBlock * block = (_dbBlock *) getOwner();
// dimitri_fix: need to FIX on FULL_ECO //uint prev_flags = FLAGS(iterm);
#ifdef FULL_ECO
uint prev_flags = FLAGS(iterm);
#endif
iterm->_flags._special = 0;
#ifdef FULL_ECO
if ( block->_journal )
{
debug("DB_ECO","A","ECO: Iterm %d, clearSpecial\n",getId());
block->_journal->updateField( this, _dbNet::FLAGS, prev_flags, FLAGS(iterm) );
}
#endif
}
void dbITerm::setSpef(uint v)
{
_dbITerm * iterm = (_dbITerm *) this;
//_dbBlock * block = (_dbBlock *) getOwner();
// dimitri_fix: need to FIX on FULL_ECO //uint prev_flags = FLAGS(iterm);
#ifdef FULL_ECO
uint prev_flags = FLAGS(iterm);
#endif
iterm->_flags._spef= v;
#ifdef FULL_ECO
if ( block->_journal )
{
debug("DB_ECO","A","ECO: Iterm %d, setSpef\n",getId());
block->_journal->updateField( this, _dbNet::FLAGS, prev_flags, FLAGS(iterm) );
}
#endif
}
// added TmgTmpD, which says whether a term is an new pin or not - payam
void dbITerm::setTmgTmpD(bool v)
{
_dbITerm * iterm = (_dbITerm *) this;
iterm->_flags._tmgTmpD = v;
}
bool dbITerm::isSetTmgTmpD()
{
_dbITerm * iterm = (_dbITerm *) this;
return (iterm->_flags._tmgTmpD==1) ? true : false;
}
// added TmgTmpC, which says whether a term is an endpoint or not - payam
void dbITerm::setTmgTmpC(bool v)
{
_dbITerm * iterm = (_dbITerm *) this;
iterm->_flags._tmgTmpC = v;
}
bool dbITerm::isSetTmgTmpC()
{
_dbITerm * iterm = (_dbITerm *) this;
return (iterm->_flags._tmgTmpC==1) ? true : false;
}
void dbITerm::setTmgTmpB(bool v)
{
_dbITerm * iterm = (_dbITerm *) this;
iterm->_flags._tmgTmpB = v;
}
bool dbITerm::isSetTmgTmpB()
{
_dbITerm * iterm = (_dbITerm *) this;
return (iterm->_flags._tmgTmpB==1) ? true : false;
}
void dbITerm::setTmgTmpA(bool v)
{
_dbITerm * iterm = (_dbITerm *) this;
iterm->_flags._tmgTmpA = v;
}
bool dbITerm::isSetTmgTmpA()
{
_dbITerm * iterm = (_dbITerm *) this;
return (iterm->_flags._tmgTmpA==1) ? true : false;
}
bool dbITerm::isSpef()
{
_dbITerm * iterm = (_dbITerm *) this;
return (iterm->_flags._spef>0) ? true : false;
}
void dbITerm::setExtId(uint v)
{
_dbITerm * iterm = (_dbITerm *) this;
iterm->_ext_id= v;
}
uint dbITerm::getExtId()
{
_dbITerm * iterm = (_dbITerm *) this;
return iterm->_ext_id;
}
bool dbITerm::isConnected()
{
_dbITerm * iterm = (_dbITerm *) this;
return iterm->_flags._connected == 1;
}
void dbITerm::setConnected()
{
_dbITerm * iterm = (_dbITerm *) this;
// dimitri_fix: need to FIX on FULL_ECO uint prev_flags = FLAGS(iterm);
#ifdef FULL_ECO
_dbBlock * block = (_dbBlock *) getOwner();
uint prev_flags = FLAGS(iterm);
#endif
iterm->_flags._connected = 1;
#ifdef FULL_ECO
if ( block->_journal )
{
debug("DB_ECO","A","ECO: Iterm %d, setConnected\n",getId());
block->_journal->updateField( this, _dbNet::FLAGS, prev_flags, FLAGS(iterm) );
}
#endif
}
void dbITerm::clearConnected()
{
_dbITerm * iterm = (_dbITerm *) this;
// uint prev_flags = FLAGS(iterm);
#ifdef FULL_ECO
_dbBlock * block = (_dbBlock *) getOwner();
uint prev_flags = FLAGS(iterm);
#endif
iterm->_flags._connected = 0;
#ifdef FULL_ECO
if ( block->_journal )
{
debug("DB_ECO","A","ECO: Iterm %d, clearConnected\n",getId());
block->_journal->updateField( this, _dbNet::FLAGS, prev_flags, FLAGS(iterm) );
}
#endif
}
dbITerm *
dbITerm::connect( dbInst * inst_, dbNet * net_, dbMTerm * mterm_ )
{
_dbInst * inst = (_dbInst *) inst_;
//_dbNet * net = (_dbNet *) net_;
_dbMTerm * mterm = (_dbMTerm *) mterm_;
_dbBlock * block = (_dbBlock *) inst->getOwner();
_dbITerm * iterm = block->_iterm_tbl->getPtr( inst->_iterms[mterm->_order_id] );
connect( (dbITerm *) iterm, net_);
return (dbITerm *) iterm;
}
void
dbITerm::connect( dbITerm * iterm_, dbNet * net_ )
{
_dbITerm * iterm = (_dbITerm *) iterm_;
_dbNet * net = (_dbNet *) net_;
_dbBlock * block = (_dbBlock *) iterm->getOwner();
if ( iterm->_net != 0 )
disconnect(iterm_);
if ( block->_journal )
{
debug("DB_ECO","A","ECO: connect Iterm %d to net %d\n",iterm_->getId(),net_->getId());
block->_journal->beginAction( dbJournal::CONNECT_OBJECT );
block->_journal->pushParam( dbITermObj );
block->_journal->pushParam( iterm_->getId() );
block->_journal->pushParam( net_->getId() );
block->_journal->endAction();
}
iterm->_net = net->getOID();
if ( net->_iterms != 0 )
{
_dbITerm * tail = block->_iterm_tbl->getPtr( net->_iterms );
iterm->_next_net_iterm = net->_iterms;
iterm->_prev_net_iterm = 0;
tail->_prev_net_iterm = iterm->getOID();
} else {
iterm->_next_net_iterm = 0;
iterm->_prev_net_iterm = 0;
}
net->_iterms = iterm->getOID();
std::list<dbBlockCallBackObj *>::iterator cbitr;
for (cbitr = block->_callbacks.begin(); cbitr != block->_callbacks.end(); ++cbitr)
(**cbitr)().inDbITermConnect(iterm_); // client ECO optimization - payam
}
void
dbITerm::disconnect( dbITerm * iterm_ )
{
_dbITerm * iterm = (_dbITerm *) iterm_;
if ( iterm->_net == 0 )
return;
_dbBlock * block = (_dbBlock *) iterm->getOwner();
_dbNet * net = block->_net_tbl->getPtr(iterm->_net);
if ( block->_journal )
{
debug("DB_ECO","A","ECO: disconnect Iterm %d\n",iterm_->getId());
block->_journal->beginAction( dbJournal::DISCONNECT_OBJECT );
block->_journal->pushParam( dbITermObj );
block->_journal->pushParam( iterm_->getId() );
block->_journal->endAction();
}
std::list<dbBlockCallBackObj *>::iterator cbitr;
for (cbitr = block->_callbacks.begin(); cbitr != block->_callbacks.end(); ++cbitr)
(**cbitr)().inDbITermDisconnect(iterm_);
uint id = iterm->getOID();
if ( net->_iterms == id )
{
net->_iterms = iterm->_next_net_iterm;
if ( net->_iterms != 0 )
{
_dbITerm * t = block->_iterm_tbl->getPtr( net->_iterms );
t->_prev_net_iterm = 0;
}
}
else
{
if ( iterm->_next_net_iterm != 0 )
{
_dbITerm * next = block->_iterm_tbl->getPtr( iterm->_next_net_iterm );
next->_prev_net_iterm = iterm->_prev_net_iterm;
}
if ( iterm->_prev_net_iterm != 0 )
{
_dbITerm * prev = block->_iterm_tbl->getPtr( iterm->_prev_net_iterm );
prev->_next_net_iterm = iterm->_next_net_iterm;
}
}
iterm->_net = 0;
if ( iterm->_tmg )
iterm_->initTiming();
}
dbSet<dbITerm>::iterator dbITerm::disconnect( dbSet<dbITerm>::iterator & itr )
{
dbITerm * it = *itr;
dbSet<dbITerm>::iterator next = ++itr;
disconnect(it);
return next;
}
dbSigType dbITerm::getSigType()
{
_dbMTerm * mterm = (_dbMTerm *) getMTerm();
return dbSigType( mterm->_flags._sig_type );
}
dbIoType dbITerm::getIoType()
{
_dbMTerm * mterm = (_dbMTerm *) getMTerm();
return dbIoType( mterm->_flags._io_type );
}
bool dbITerm::isOutputSignal(bool io)
{
_dbMTerm * mterm = (_dbMTerm *) getMTerm();
dbSigType sType= dbSigType( mterm->_flags._sig_type );
dbIoType ioType= dbIoType( mterm->_flags._io_type );
if ((sType == dbSigType::GROUND)|| (sType == dbSigType::POWER))
return false;
if (ioType==dbIoType::OUTPUT)
return true;
if (io && (ioType==dbIoType::INOUT))
return true;
return false;
}
bool dbITerm::isInputSignal(bool io)
{
_dbMTerm * mterm = (_dbMTerm *) getMTerm();
dbSigType sType= dbSigType( mterm->_flags._sig_type );
dbIoType ioType= dbIoType( mterm->_flags._io_type );
if ((sType == dbSigType::GROUND)|| (sType == dbSigType::POWER))
return false;
if (ioType==dbIoType::INPUT)
return true;
if (io && (ioType==dbIoType::INOUT))
return true;
return false;
}
dbITerm *
dbITerm::getITerm( dbBlock * block_, uint dbid )
{
_dbBlock * block = (_dbBlock *) block_;
return (dbITerm *) block->_iterm_tbl->getPtr(dbid);
}
bool
dbITerm::getAvgXY( int *x, int *y)
{
dbMTerm *mterm = getMTerm();
int nn = 0;
double xx=0.0, yy=0.0;
int px,py;
dbInst *inst = getInst();
inst->getOrigin(px,py);
adsPoint origin = adsPoint(px,py);
dbOrientType orient = inst->getOrient();
dbTransform transform( orient, origin );
dbSet<dbMPin> mpins = mterm->getMPins();
dbSet<dbMPin>::iterator mpin_itr;
for (mpin_itr = mpins.begin(); mpin_itr != mpins.end(); mpin_itr++) {
dbMPin *mpin = *mpin_itr;
dbSet<dbBox> boxes = mpin->getGeometry();
dbSet<dbBox>::iterator box_itr;
for (box_itr = boxes.begin(); box_itr != boxes.end(); box_itr++) {
dbBox * box = *box_itr; adsRect rect;
box->getBox( rect );
transform.apply( rect );
xx += rect.xMin()+rect.xMax();
yy += rect.yMin()+rect.yMax();
nn += 2;
}
}
if (!nn) {
warning(0, "Can not find physical location of iterm %s/%s\n",
getInst()->getConstName(), getMTerm()->getConstName()); return false;
}
xx /= nn;
yy /= nn;
*x = int(xx);
*y = int(yy);
return true;
}
void dbITerm::print(FILE *fp, const char *trail)
{
if (fp==NULL)
{
notice(0, "%d %s %s %s%s", getId(), getMTerm()->getConstName(),
getMTerm()->getMaster()->getConstName(),getInst()->getConstName(), trail);
}
else {
fprintf(fp, "%d %s %s %s%s", getId(), getMTerm()->getConstName(),
getMTerm()->getMaster()->getConstName(),getInst()->getConstName(), trail);
}
}
} // namespace
| 29.778415 | 95 | 0.6095 | mgwoo |
6847601bfd862fb484ee2369be0adf8d6a92b3c9 | 2,798 | hpp | C++ | include/codegen/include/OVR/OpenVR/IVRSpatialAnchors.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/OVR/OpenVR/IVRSpatialAnchors.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/OVR/OpenVR/IVRSpatialAnchors.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:04 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: System.ValueType
#include "System/ValueType.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: OVR::OpenVR
namespace OVR::OpenVR {
}
// Completed forward declares
// Type namespace: OVR.OpenVR
namespace OVR::OpenVR {
// Autogenerated type: OVR.OpenVR.IVRSpatialAnchors
struct IVRSpatialAnchors : public System::ValueType {
public:
// Nested type: OVR::OpenVR::IVRSpatialAnchors::_CreateSpatialAnchorFromDescriptor
class _CreateSpatialAnchorFromDescriptor;
// Nested type: OVR::OpenVR::IVRSpatialAnchors::_CreateSpatialAnchorFromPose
class _CreateSpatialAnchorFromPose;
// Nested type: OVR::OpenVR::IVRSpatialAnchors::_GetSpatialAnchorPose
class _GetSpatialAnchorPose;
// Nested type: OVR::OpenVR::IVRSpatialAnchors::_GetSpatialAnchorDescriptor
class _GetSpatialAnchorDescriptor;
// OVR.OpenVR.IVRSpatialAnchors/_CreateSpatialAnchorFromDescriptor CreateSpatialAnchorFromDescriptor
// Offset: 0x0
OVR::OpenVR::IVRSpatialAnchors::_CreateSpatialAnchorFromDescriptor* CreateSpatialAnchorFromDescriptor;
// OVR.OpenVR.IVRSpatialAnchors/_CreateSpatialAnchorFromPose CreateSpatialAnchorFromPose
// Offset: 0x8
OVR::OpenVR::IVRSpatialAnchors::_CreateSpatialAnchorFromPose* CreateSpatialAnchorFromPose;
// OVR.OpenVR.IVRSpatialAnchors/_GetSpatialAnchorPose GetSpatialAnchorPose
// Offset: 0x10
OVR::OpenVR::IVRSpatialAnchors::_GetSpatialAnchorPose* GetSpatialAnchorPose;
// OVR.OpenVR.IVRSpatialAnchors/_GetSpatialAnchorDescriptor GetSpatialAnchorDescriptor
// Offset: 0x18
OVR::OpenVR::IVRSpatialAnchors::_GetSpatialAnchorDescriptor* GetSpatialAnchorDescriptor;
// Creating value type constructor for type: IVRSpatialAnchors
IVRSpatialAnchors(OVR::OpenVR::IVRSpatialAnchors::_CreateSpatialAnchorFromDescriptor* CreateSpatialAnchorFromDescriptor_ = {}, OVR::OpenVR::IVRSpatialAnchors::_CreateSpatialAnchorFromPose* CreateSpatialAnchorFromPose_ = {}, OVR::OpenVR::IVRSpatialAnchors::_GetSpatialAnchorPose* GetSpatialAnchorPose_ = {}, OVR::OpenVR::IVRSpatialAnchors::_GetSpatialAnchorDescriptor* GetSpatialAnchorDescriptor_ = {}) : CreateSpatialAnchorFromDescriptor{CreateSpatialAnchorFromDescriptor_}, CreateSpatialAnchorFromPose{CreateSpatialAnchorFromPose_}, GetSpatialAnchorPose{GetSpatialAnchorPose_}, GetSpatialAnchorDescriptor{GetSpatialAnchorDescriptor_} {}
}; // OVR.OpenVR.IVRSpatialAnchors
}
DEFINE_IL2CPP_ARG_TYPE(OVR::OpenVR::IVRSpatialAnchors, "OVR.OpenVR", "IVRSpatialAnchors");
#pragma pack(pop)
| 59.531915 | 641 | 0.78985 | Futuremappermydud |
684b10100037d7d9894576302539127df413e867 | 1,361 | cpp | C++ | src/pockets/Profiling.cpp | pourpluie/Pockets-team | cbae274cdabf2896ab7ecf113bccfbd005916ea7 | [
"BSD-2-Clause"
] | null | null | null | src/pockets/Profiling.cpp | pourpluie/Pockets-team | cbae274cdabf2896ab7ecf113bccfbd005916ea7 | [
"BSD-2-Clause"
] | null | null | null | src/pockets/Profiling.cpp | pourpluie/Pockets-team | cbae274cdabf2896ab7ecf113bccfbd005916ea7 | [
"BSD-2-Clause"
] | null | null | null |
#include "Profiling.h"
using namespace pockets;
OpenGLTimer::OpenGLTimer():
mId( 0 ),
mWaiting( false ),
mValue( 0 )
{}
//! initialize OpenGL state of timer
void OpenGLTimer::setup()
{
glGenQueries( 1, &mId );
}
OpenGLTimer::~OpenGLTimer()
{
glDeleteQueries( 1, &mId );
}
//! mark the beginning of the OpenGL commands you want to time
void OpenGLTimer::begin()
{
if( !mWaiting )
{ glBeginQuery( GL_TIME_ELAPSED, mId ); }
}
//! mark the end of the OpenGL commands you want to time
void OpenGLTimer::end()
{
if( !mWaiting )
{
glEndQuery( GL_TIME_ELAPSED );
mWaiting = true;
}
}
// returns true if OpenGL query result is ready
bool OpenGLTimer::available()
{
int a = 0;
glGetQueryObjectiv( mId, GL_QUERY_RESULT_AVAILABLE, &a );
return a == GL_TRUE;
}
//! returns the latest valid timing information in milliseconds
//! updates with new data if available
double OpenGLTimer::getMilliseconds()
{
if( available() )
{
glGetQueryObjectui64v( mId, GL_QUERY_RESULT, &mValue );
mWaiting = false;
}
return mValue * 1.0e-6;
}
//! blocks until OpenGL timing information is ready and returns milliseconds
double OpenGLTimer::getMillisecondsBlocking()
{
bool ready = false;
while( !ready )
{ ready = available(); }
mWaiting = false;
glGetQueryObjectui64v( mId, GL_QUERY_RESULT, &mValue );
return mValue * 1.0e-6;
}
| 20.621212 | 76 | 0.693608 | pourpluie |
684b80fc84d6a66e8c216428d76247423586c351 | 1,466 | cpp | C++ | Algorithms/SubSetSum.cpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | 1 | 2022-03-25T10:20:25.000Z | 2022-03-25T10:20:25.000Z | Algorithms/SubSetSum.cpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | null | null | null | Algorithms/SubSetSum.cpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | null | null | null | #include <iostream>
#include <vector>
#include <deque>
#include <set>
#include <stdio.h>
#include <unordered_map>
#include <limits>
using namespace std;
int count = 0;
vector<vector<int> > SubsetSumsHelper;
void SubsbetSum(vector<vector<int> > &SubsetSumsHelper, const vector<int> &input, const int index_t, const int sum_t)
{
SubsetSumsHelper[0][0] = 1;
for(auto index = 1; index < index_t; index++){
for(auto sum = 0; sum <= sum_t; sum++){
SubsetSumsHelper[index][0] = 1;
if(sum <= input[index - 1]){
SubsetSumsHelper[index][sum] = SubsetSumsHelper[index - 1][sum];
}
else if(sum > input[index - 1])
{
SubsetSumsHelper[index][sum] = SubsetSumsHelper[index - 1][sum] || SubsetSumsHelper[index - 1][sum - input[index]];
}
}
}
}
void FillPreFill(vector<vector<int> > &SubsetSumsHelper, const size_t rows, const size_t cols)
{
vector<int> temp;
for(auto i = 0; i < rows; i++){
for(auto j = 0; j < cols + 1; j++){
temp.emplace_back(0);
}
SubsetSumsHelper.emplace_back(temp);
temp.erase(temp.begin(), temp.end());
}
}
void printMatrix(vector<vector<int> > &arrays)
{
for(const auto& array : arrays){
for(const auto& item : array){
printf("%3d", item);
}
cout << "\n";
}
}
int main(void)
{
vector<int> input = {2, 4, 6, 10};
FillPreFill(SubsetSumsHelper, 4, 16);
SubsbetSum(SubsetSumsHelper, input, 4, 16);
printMatrix(SubsetSumsHelper);
return 0;
} | 25.719298 | 120 | 0.632333 | hendry19901990 |
6852b00b1f8dbf2060bba66c9f2254c860d21f8b | 17,444 | cpp | C++ | libace/model/BasicType.cpp | xguerin/ace | ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b | [
"MIT"
] | 5 | 2016-06-14T17:56:47.000Z | 2022-02-10T19:54:25.000Z | libace/model/BasicType.cpp | xguerin/ace | ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b | [
"MIT"
] | 42 | 2016-06-21T20:48:22.000Z | 2021-03-23T15:20:51.000Z | libace/model/BasicType.cpp | xguerin/ace | ad6e1bc4cb4f10d6cf5b782f623ec0eef13e000b | [
"MIT"
] | 1 | 2016-10-02T02:58:49.000Z | 2016-10-02T02:58:49.000Z | /**
* Copyright (c) 2016 Xavier R. Guerin
*
* 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 <ace/model/BasicType.h>
#include <ace/model/Dependency.h>
#include <ace/model/Errors.h>
#include <ace/model/Model.h>
#include <ace/engine/Master.h>
#include <ace/tree/Checker.h>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
namespace ace { namespace model {
BasicType::BasicType(const Kind k, std::string const& a)
: m_declName()
, m_kind(k)
, m_arityMap(a)
, m_mayInherit(false)
, m_doc()
, m_attributes()
{
m_attributes.setParent(this);
m_attributes.define<KindAttributeType>("kind", false);
m_attributes.define<ArityAttributeType>("arity", false);
m_attributes.define<DocAttributeType>("doc", false);
m_attributes.define<DeprecatedAttributeType>("deprecated", true);
m_attributes.define<HookAttributeType>("hook", true);
m_attributes.define<InheritAttributeType>("inherit", true);
m_attributes.exclude("hook", "either");
m_attributes.exclude("hook", "map");
m_attributes.exclude("hook", "range");
m_attributes.exclude("hook", "size");
m_attributes.exclude("inherit", "hook");
}
BasicType::BasicType(BasicType const& o)
: Object(o)
, Instance(o)
, Coach(o)
, Generator(o)
, m_declName(o.m_declName)
, m_kind(o.m_kind)
, m_arityMap(o.m_arityMap)
, m_mayInherit(o.m_mayInherit)
, m_doc(o.m_doc)
, m_attributes(o.m_attributes)
{
m_attributes.setParent(this);
}
bool
BasicType::checkModel(tree::Value const& t) const
{
tree::Checker chk(path(), t);
tree::Checker::Schema schm = m_attributes.schema();
if (not chk.validate(schm)) {
return false;
}
if (not m_attributes.checkModel(t)) {
return false;
}
if (static_cast<tree::Primitive const&>(t["doc"])
.value<std::string>()
.empty()) {
ERROR(ERR_EMPTY_DOC);
return false;
}
Arity arity;
std::string value =
static_cast<tree::Primitive const&>(t["arity"]).value<std::string>();
Arity::parse(value, arity);
if (m_arityMap.find_first_of(arity.marker()) == std::string::npos) {
ERROR(ERR_INVALID_ARITY_FOR_TYPE(value, m_kind));
return false;
}
value = static_cast<tree::Primitive const&>(t["kind"]).value<std::string>();
if (kindOf(value) == Kind::Undefined) {
ERROR(ERR_TYPE_NOT_KNOWN(value));
return false;
} else if (kindOf(value) != m_kind) {
ERROR(ERR_UNEXPECTED_TYPE(value));
return false;
}
return true;
}
void
BasicType::loadModel(tree::Value const& t)
{
m_attributes.loadModel(t);
m_doc = static_cast<DocAttributeType const&>(*m_attributes["doc"]).head();
Attribute::Ref ar = m_attributes["arity"];
if (m_attributes.has("inherit")) {
ar = m_attributes["inherit"];
m_mayInherit = static_cast<InheritAttributeType const&>(*ar).head();
}
}
bool
BasicType::flattenModel()
{
if (not m_attributes.flattenModel()) {
return false;
}
return true;
}
bool
BasicType::validateModel()
{
if (not m_attributes.validateModel()) {
return false;
}
return true;
}
void
BasicType::display(Coach::Branch const& br) const
{
br.print(std::cout) << arity() << " " << m_name << " ";
std::cout << "(" << toString(m_kind) << ")";
std::cout << std::endl;
}
bool
BasicType::explain(tree::Path const& p,
tree::Path::const_iterator const& i) const
{
Coach::explain(p, i);
if (i != p.end()) {
return false;
}
std::cout << std::left;
for (auto& a : m_attributes) {
std::cout << std::setw(13) << a->name() << ": ";
a->print(std::cout, 15);
}
std::cout << std::right;
return true;
}
bool
BasicType::hasPrivateNamespaceDefinition() const
{
return false;
}
void
BasicType::doPrivateNamespaceDefinition(std::string const& ns, std::ostream& o,
int l) const
{}
bool
BasicType::hasTypeDeclaration() const
{
return false;
}
void
BasicType::doTypeDeclaration(std::ostream& o, int l) const
{}
void
BasicType::doTypeDefinition(std::ostream& o, int l) const
{
if (multiple()) {
indent(o, l) << "std::vector<" + typeName() + "> m_" + m_declName << ";";
o << std::endl;
} else {
indent(o, l) << typeName() << " m_" << m_declName << ";" << std::endl;
if (optional()) {
indent(o, l) << "bool m_has_" << m_declName << ";" << std::endl;
}
}
}
void
BasicType::doBuildDefinition(std::string const& e, std::ostream& o, int l) const
{
doBuildDefinition("m_has_" + m_declName, "m_" + m_declName, e, o, l);
if (isDeprecated()) {
indent(o, l) << "if (not m_" << m_declName << ".empty()) {" << std::endl;
indent(o, l + 2) << "std::cerr << \"<ACE> DEPRECATED(" << path()
<< "): \";";
o << std::endl;
indent(o, l + 2) << "std::cerr << \"" << deprecatedMessage() << "\";"
<< std::endl;
indent(o, l + 2) << "std::cerr << std::endl;" << std::endl;
indent(o, l) << "}" << std::endl;
}
}
void
BasicType::doBuildDefinition(std::string const& s, std::string const& v,
std::string const& e, std::ostream& o, int l) const
{
indent(o, l);
if (optional() and not multiple()) {
o << s << " = ";
}
o << "ace::tree::utils::parsePrimitive<" << typeName() << ">(r, " << e << ", "
<< v << ");";
o << std::endl;
}
void
BasicType::doSerializerDefinition(std::string const& c, std::string const& n,
std::ostream& o, int l) const
{
doSerializerDefinition(c, n, "m_" + m_declName, false, o, l);
}
void
BasicType::doSerializerDefinition(std::string const& c, std::string const& n,
std::string const& v, const bool b,
std::ostream& o, int l) const
{
if (not multiple()) {
int offset = 0;
if (optional() and not b) {
offset = 2;
indent(o, l) << "if (m_has_" << m_declName << ") {" << std::endl;
}
indent(o, l + offset);
o << c << "->put(ace::tree::Primitive::build(" << n << ", " << v << "));";
o << std::endl;
if (optional() and not b) {
indent(o, l) << "}" << std::endl;
}
} else {
indent(o, l);
o << "if (not " << v << ".empty()) {" << std::endl;
auto tmpArray = tempName();
indent(o, l + 2);
o << "auto " << tmpArray << " = ace::tree::Array::build(" << n << ");";
o << std::endl;
auto tmpIndex = tempName();
indent(o, l + 2);
o << "for (auto const & " << tmpIndex << " : " << v << ") {" << std::endl;
indent(o, l + 4);
o << tmpArray << "->push_back(ace::tree::Primitive::build(\"\", ";
if (m_kind == Kind::Boolean) {
o << "static_cast<bool>(";
}
o << tmpIndex;
if (m_kind == Kind::Boolean) {
o << ")";
}
o << "));";
o << std::endl;
indent(o, l + 2);
o << "}" << std::endl;
indent(o, l + 2);
o << "o->put(" << tmpArray << ");" << std::endl;
indent(o, l);
o << "}" << std::endl;
}
}
void
BasicType::doCheckerInterface(std::ostream& o, int l) const
{
indent(o, l) << "virtual bool has_" << m_declName << "() const = 0;"
<< std::endl;
}
void
BasicType::doCheckerDeclaration(std::ostream& o, int l) const
{
indent(o, l) << "bool has_" << m_declName << "() const;" << std::endl;
}
void
BasicType::doCheckerDefinition(std::ostream& o, int l) const
{
const Model* m = static_cast<const Model*>(owner());
std::string const& h = m->normalizedName();
indent(o, l) << "bool " << h << "::has_" << m_declName << "() const {"
<< std::endl;
if (multiple()) {
indent(o, l + 2) << "return not m_" << m_declName << ".empty();"
<< std::endl;
} else {
indent(o, l + 2) << "return m_has_" << m_declName << ";" << std::endl;
}
indent(o, l) << "}" << std::endl;
}
void
BasicType::doGetterInterface(std::ostream& o, int l) const
{
std::string tn = decorateType(typeName());
indent(o, l) << "virtual " << tn << " const & " << m_declName
<< "() const = 0;" << std::endl;
}
void
BasicType::doGetterDeclaration(std::ostream& o, int l) const
{
std::string tn = decorateType(typeName());
indent(o, l) << tn << " const & " << m_declName << "() const;" << std::endl;
}
void
BasicType::doGetterDefinition(std::ostream& o, int l) const
{
const Model* m = static_cast<const Model*>(owner());
std::string const& h = m->normalizedName();
std::string tn = decorateType(typeName());
indent(o, l) << tn << " const & " << h << "::" << m_declName << "() const {"
<< std::endl;
if (optional()) {
if (multiple()) {
indent(o, l + 2) << "if (m_" << m_declName << ".empty()) ";
} else {
indent(o, l + 2) << "if (not m_has_" << m_declName << ") ";
}
o << "ace::tree::utils::illegalValueAccess(__PRETTY_FUNCTION__);"
<< std::endl;
}
indent(o, l + 2) << "return m_" << m_declName << ";" << std::endl;
indent(o, l) << "}" << std::endl;
}
bool
BasicType::merge(BasicType const& b)
{
return m_attributes.merge(b.m_attributes);
}
bool
BasicType::override(BasicType const& b)
{
return m_attributes.override(b.m_attributes);
}
void
BasicType::promoteArity(tree::Path const& p,
tree::Path::const_iterator const& i)
{
if (i == p.end() and arity().promote()) {
MASTER.pushPromoted(path());
}
}
void
BasicType::disable(tree::Path const& p, tree::Path::const_iterator const& i)
{
if (optional()) {
arity().disable();
}
}
bool
BasicType::isObject() const
{
return false;
}
bool
BasicType::isEnumerated() const
{
return false;
}
bool
BasicType::isRanged() const
{
return false;
}
bool
BasicType::isMapped() const
{
return false;
}
bool
BasicType::checkValueConstraint(std::list<tree::Value::Ref> const& v) const
{
ERROR(ERR_CANNOT_CONSTRAIN);
return false;
}
bool
BasicType::checkRangeConstraint(std::string const& v) const
{
ERROR(ERR_CANNOT_CONSTRAIN);
return false;
}
bool
BasicType::constrainByValue(std::list<tree::Value::Ref> const& v)
{
ERROR(ERR_CANNOT_CONSTRAIN);
return false;
}
bool
BasicType::constrainByRange(std::string const& v)
{
ERROR(ERR_CANNOT_CONSTRAIN);
return false;
}
BasicType::Kind
BasicType::kindOf(std::string const& s)
{
const std::map<std::string, ace::model::BasicType::Kind> stringToKind = {
{ "boolean", ace::model::BasicType::Kind::Boolean },
{ "class", ace::model::BasicType::Kind::Class },
{ "cpuid", ace::model::BasicType::Kind::CPUID },
{ "enum", ace::model::BasicType::Kind::Enum },
{ "file", ace::model::BasicType::Kind::File },
{ "float", ace::model::BasicType::Kind::Float },
{ "integer", ace::model::BasicType::Kind::Integer },
{ "ipv4", ace::model::BasicType::Kind::IPv4 },
{ "mac", ace::model::BasicType::Kind::MAC },
{ "plugin", ace::model::BasicType::Kind::Plugin },
{ "select", ace::model::BasicType::Kind::Selector },
{ "string", ace::model::BasicType::Kind::String },
{ "uri", ace::model::BasicType::Kind::URI },
};
if (stringToKind.find(s) == stringToKind.end()) {
return Kind::Undefined;
}
return stringToKind.at(s);
}
std::string
BasicType::toString(const Kind k)
{
const std::map<ace::model::BasicType::Kind, std::string> kindToString = {
{ ace::model::BasicType::Kind::Boolean, "boolean" },
{ ace::model::BasicType::Kind::CPUID, "cpuid" },
{ ace::model::BasicType::Kind::Class, "class" },
{ ace::model::BasicType::Kind::Enum, "enum" },
{ ace::model::BasicType::Kind::File, "file" },
{ ace::model::BasicType::Kind::Float, "float" },
{ ace::model::BasicType::Kind::Integer, "integer" },
{ ace::model::BasicType::Kind::IPv4, "ipv4" },
{ ace::model::BasicType::Kind::MAC, "mac" },
{ ace::model::BasicType::Kind::Plugin, "plugin" },
{ ace::model::BasicType::Kind::Selector, "select" },
{ ace::model::BasicType::Kind::String, "string" },
{ ace::model::BasicType::Kind::URI, "uri" },
};
if (kindToString.find(k) == kindToString.end()) {
return "undefined";
}
return kindToString.at(k);
}
void
BasicType::foreach (tree::Object const& r, Callback const& op) const
{
tree::Value const& v = r.get(m_name);
switch (v.type()) {
case tree::Value::Type::Object:
case tree::Value::Type::Boolean:
case tree::Value::Type::Float:
case tree::Value::Type::Integer:
case tree::Value::Type::String:
op(v);
break;
case tree::Value::Type::Array:
for (auto& e : static_cast<tree::Array const&>(v)) {
op(*e);
}
break;
default:
break;
}
}
void
BasicType::setName(std::string const& s)
{
Object::setName(s);
m_declName = common::String::normalize(s);
}
bool
BasicType::checkInstance(tree::Object const& r, tree::Value const& v) const
{
if (v.type() == tree::Value::Type::Undefined) {
return false;
}
if (not multiple() and v.type() == tree::Value::Type::Array) {
ERROR(ERR_WRONG_ARITY_COUNT);
return false;
}
/**
* Validate the attributes once to make sure that bounds are respected
*/
return m_attributes.checkInstance(r, v);
}
void
BasicType::expandInstance(tree::Object& r, tree::Value& v)
{
return m_attributes.expandInstance(r, v);
}
bool
BasicType::flattenInstance(tree::Object& r, tree::Value& v)
{
return m_attributes.flattenInstance(r, v);
}
bool
BasicType::resolveInstance(tree::Object const& r, tree::Value const& v) const
{
/**
* Validate the attributes twice to make sure that dynamic constraints are
* respected
*/
return m_attributes.resolveInstance(r, v);
}
void
BasicType::collectModelFileDependencies(std::set<std::string>& d) const
{}
void
BasicType::collectInterfaceIncludes(std::set<std::string>& i) const
{
i.insert("<vector>");
}
void
BasicType::collectImplementationIncludes(std::set<std::string>& i) const
{
i.insert("<cstdlib>");
i.insert("<vector>");
}
bool
BasicType::injectDefault(tree::Object const& r, tree::Value& v) const
{
return false;
}
std::string
BasicType::decorateType(std::string const& n) const
{
if (multiple()) {
return "std::vector<" + n + ">";
}
return n;
}
bool
BasicType::disabled() const
{
return arity() == Arity::Kind::Disabled;
}
bool
BasicType::optional() const
{
return arity() == Arity::Kind::UpToOne or arity() == Arity::Kind::Any;
}
bool
BasicType::required() const
{
return arity() == Arity::Kind::One or arity() == Arity::Kind::AtLeastOne;
}
bool
BasicType::multiple() const
{
return arity() == Arity::Kind::AtLeastOne or arity() == Arity::Kind::Any;
}
bool
BasicType::has(tree::Path const& p, tree::Path::const_iterator const& i) const
{
return i == p.end();
}
void
BasicType::get(tree::Path const& p, tree::Path::const_iterator const& i,
std::list<BasicType::Ref>& r) const
{}
bool
BasicType::operator<=(BasicType const& o) const
{
return m_kind == o.m_kind and arity() <= o.arity();
}
bool
BasicType::operator>(BasicType const& o) const
{
return m_kind != o.m_kind or not(arity() <= o.arity());
}
std::string const&
BasicType::declName() const
{
return m_declName;
}
BasicType::Kind
BasicType::kind() const
{
return m_kind;
}
Arity&
BasicType::arity()
{
return static_cast<ArityAttributeType&>(*m_attributes["arity"]).value();
}
Arity const&
BasicType::arity() const
{
return static_cast<ArityAttributeType const&>(*m_attributes["arity"]).value();
}
bool
BasicType::mayInherit() const
{
return m_mayInherit;
}
bool
BasicType::hasHook() const
{
return m_attributes.has("hook");
}
Hook const&
BasicType::hook() const
{
return static_cast<HookAttributeType const&>(*m_attributes["hook"]).hook();
}
bool
BasicType::hasDependencies() const
{
return m_attributes.has("deps");
}
BasicType::DepsAttributeType::Dependencies const&
BasicType::dependencies() const
{
return std::static_pointer_cast<DepsAttributeType>(m_attributes["deps"])
->values();
}
bool
BasicType::isDeprecated() const
{
return m_attributes.has("deprecated");
}
std::string const&
BasicType::deprecatedMessage() const
{
auto const& ar = *m_attributes["deprecated"];
return static_cast<DeprecatedAttributeType const&>(ar).head();
}
std::ostream&
operator<<(std::ostream& o, BasicType const& k)
{
o << "[" << k.arity() << "] ";
o << std::setw(9) << BasicType::toString(k.m_kind);
o << " " << k.m_doc;
return o;
}
std::ostream&
operator<<(std::ostream& o, const BasicType::Kind k)
{
o << BasicType::toString(k);
return o;
}
}}
| 24.569014 | 80 | 0.619984 | xguerin |
68613319ae7fddc8555bb650a590ddf0ee0ecf7f | 73 | cpp | C++ | sources/source.cpp | Lasar1k/LAB_03_SharedPtr | e07b4ae86dc1ae6bacff8844348eb6138c8af83f | [
"MIT"
] | null | null | null | sources/source.cpp | Lasar1k/LAB_03_SharedPtr | e07b4ae86dc1ae6bacff8844348eb6138c8af83f | [
"MIT"
] | null | null | null | sources/source.cpp | Lasar1k/LAB_03_SharedPtr | e07b4ae86dc1ae6bacff8844348eb6138c8af83f | [
"MIT"
] | null | null | null | // Copyright 2021 Lasar1k <alf.ivan2002@gmail.com>
#include <header.hpp>
| 24.333333 | 50 | 0.753425 | Lasar1k |
68664f21c3e11b8200f975b1caa8ab5f98f1f2c1 | 1,571 | cc | C++ | core/src/EnablePluginFromThis.cc | scpeters-test/ign-plugin | 94482af3e9b2cc1cbb7c2dbeb2c7846f8283f0f6 | [
"Apache-2.0"
] | 10 | 2020-04-15T16:59:32.000Z | 2022-03-18T20:36:17.000Z | core/src/EnablePluginFromThis.cc | scpeters-test/ign-plugin | 94482af3e9b2cc1cbb7c2dbeb2c7846f8283f0f6 | [
"Apache-2.0"
] | 47 | 2020-05-04T15:07:18.000Z | 2022-03-18T20:53:54.000Z | core/src/EnablePluginFromThis.cc | scpeters-test/ign-plugin | 94482af3e9b2cc1cbb7c2dbeb2c7846f8283f0f6 | [
"Apache-2.0"
] | 11 | 2020-05-05T22:04:44.000Z | 2022-03-18T13:59:46.000Z | /*
* Copyright (C) 2018 Open Source Robotics Foundation
*
* 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 <ignition/plugin/EnablePluginFromThis.hh>
#include <ignition/plugin/WeakPluginPtr.hh>
namespace ignition
{
namespace plugin
{
class EnablePluginFromThis::Implementation
{
public: WeakPluginPtr weak;
};
EnablePluginFromThis::EnablePluginFromThis()
: pimpl(new Implementation())
{
// Do nothing
}
PluginPtr EnablePluginFromThis::PluginFromThis()
{
return this->pimpl->weak.Lock();
}
ConstPluginPtr EnablePluginFromThis::PluginFromThis() const
{
return this->pimpl->weak.Lock();
}
EnablePluginFromThis::~EnablePluginFromThis()
{
// Do nothing
}
std::shared_ptr<void>
EnablePluginFromThis::PluginInstancePtrFromThis() const
{
return this->pimpl->weak.Lock()->PrivateGetInstancePtr();
}
void EnablePluginFromThis::PrivateSetPluginFromThis(const PluginPtr &_ptr)
{
this->pimpl->weak = _ptr;
}
}
}
| 24.936508 | 78 | 0.691916 | scpeters-test |
687302306554ccd5dd517a01b6a6b7bf7defe867 | 3,358 | hpp | C++ | libiop/protocols/encoded/lincheck/holographic_lincheck_aux.hpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/protocols/encoded/lincheck/holographic_lincheck_aux.hpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | libiop/protocols/encoded/lincheck/holographic_lincheck_aux.hpp | alexander-zw/libiop | a2ed2ec2f3e85f29b6035951553b02cb737c817a | [
"MIT"
] | null | null | null | /**@file
*****************************************************************************
virtual oracles for holographic lincheck
*****************************************************************************
* @author This file is part of libiop (see AUTHORS)
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef LIBIOP_PROTOCOLS_ENCODED_LINCHECK_HOLOGRAPHIC_LINCHECK_AUX_HPP_
#define LIBIOP_PROTOCOLS_ENCODED_LINCHECK_HOLOGRAPHIC_LINCHECK_AUX_HPP_
#include <cstring>
#include <cstddef>
#include <map>
#include <memory>
#include <vector>
#include "libiop/algebra/polynomials/lagrange_polynomial.hpp"
#include "libiop/algebra/polynomials/bivariate_lagrange_polynomial.hpp"
#include "libiop/algebra/lagrange.hpp"
#include "libiop/iop/iop.hpp"
#include "libiop/protocols/encoded/lincheck/common.hpp"
namespace libiop {
template<typename FieldT>
class holographic_multi_lincheck_virtual_oracle : public virtual_oracle<FieldT> {
protected:
const field_subset<FieldT> codeword_domain_;
const field_subset<FieldT> summation_domain_;
const std::size_t input_variable_dim_;
const std::vector<std::shared_ptr<sparse_matrix<FieldT> >> matrices_;
std::vector<FieldT> r_Mz_;
lagrange_polynomial<FieldT> p_alpha_prime_;
public:
holographic_multi_lincheck_virtual_oracle(
const field_subset<FieldT> &codeword_domain,
const field_subset<FieldT> &summation_domain,
const std::size_t input_variable_dim,
const std::vector<std::shared_ptr<sparse_matrix<FieldT> >> &matrices);
// TODO: Make this take in p_alpha
void set_challenge(const FieldT &alpha, const std::vector<FieldT> r_Mz);
FieldT eval_at_out_of_domain_point(const std::vector<FieldT> &constituent_oracle_evaluations) const;
virtual std::shared_ptr<std::vector<FieldT>> evaluated_contents(
const std::vector<std::shared_ptr<std::vector<FieldT>>> &constituent_oracle_evaluations) const;
virtual FieldT evaluation_at_point(
const std::size_t evaluation_position,
const FieldT evaluation_point,
const std::vector<FieldT> &constituent_oracle_evaluations) const;
};
template<typename FieldT>
class single_matrix_denominator : public virtual_oracle<FieldT> {
protected:
const field_subset<FieldT> codeword_domain_;
const field_subset<FieldT> summation_domain_;
const std::size_t input_variable_dim_;
FieldT row_query_point_;
FieldT column_query_point_;
public:
single_matrix_denominator(
const field_subset<FieldT> &codeword_domain,
const field_subset<FieldT> &summation_domain,
const std::size_t input_variable_dim);
void set_challenge(const FieldT &row_query_point,
const FieldT &column_query_point);
virtual std::shared_ptr<std::vector<FieldT>> evaluated_contents(
const std::vector<std::shared_ptr<std::vector<FieldT>>> &constituent_oracle_evaluations) const;
virtual FieldT evaluation_at_point(
const std::size_t evaluation_position,
const FieldT evaluation_point,
const std::vector<FieldT> &constituent_oracle_evaluations) const;
};
} // libiop
#include "libiop/protocols/encoded/lincheck/holographic_lincheck_aux.tcc"
#endif // LIBIOP_PROTOCOLS_ENCODED_LINCHECK_HOLOGRAPHIC_LINCHECK_AUX_HPP_
| 38.597701 | 104 | 0.715307 | alexander-zw |
6878b9cb8aab5ce5e4ae89cff4b488f8e95f4418 | 704 | cpp | C++ | solved/0-b/blind-escape/gen.cpp | abuasifkhan/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-09-30T19:18:04.000Z | 2021-06-26T21:11:30.000Z | solved/0-b/blind-escape/gen.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | null | null | null | solved/0-b/blind-escape/gen.cpp | sbmaruf/pc-code | 77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90 | [
"Unlicense"
] | 13 | 2015-01-04T09:49:54.000Z | 2021-06-03T13:18:44.000Z | #include <cstdio>
#include <cstdlib>
#include <ctime>
#define MAXT 200
#define MAXM 12
#define MAXN 12
void test_case()
{
int M = rand() % (MAXM - 5) + 6;
int N = rand() % (MAXN - 5) + 6;
printf("%d %d\n", M, N);
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
char c = '.';
if (rand() % 2 != 0)
c = '#';
if (i == 0 || j == 0 || i == M - 1 || j == N - 1)
if (rand() % 4 != 0)
c = '#';
putchar(c);
}
putchar('\n');
}
}
int main()
{
srand(time(NULL));
int T = MAXT;
printf("%d\n", T);
while (T--) test_case();
return 0;
}
| 17.170732 | 61 | 0.369318 | abuasifkhan |
687c6c3cfe93274ccace579761ac7c8416b3de0a | 3,127 | cpp | C++ | cynosdb/src/v20190107/model/AccountParam.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | cynosdb/src/v20190107/model/AccountParam.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | cynosdb/src/v20190107/model/AccountParam.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/cynosdb/v20190107/model/AccountParam.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cynosdb::V20190107::Model;
using namespace std;
AccountParam::AccountParam() :
m_paramNameHasBeenSet(false),
m_paramValueHasBeenSet(false)
{
}
CoreInternalOutcome AccountParam::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ParamName") && !value["ParamName"].IsNull())
{
if (!value["ParamName"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AccountParam.ParamName` IsString=false incorrectly").SetRequestId(requestId));
}
m_paramName = string(value["ParamName"].GetString());
m_paramNameHasBeenSet = true;
}
if (value.HasMember("ParamValue") && !value["ParamValue"].IsNull())
{
if (!value["ParamValue"].IsString())
{
return CoreInternalOutcome(Core::Error("response `AccountParam.ParamValue` IsString=false incorrectly").SetRequestId(requestId));
}
m_paramValue = string(value["ParamValue"].GetString());
m_paramValueHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void AccountParam::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_paramNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ParamName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_paramName.c_str(), allocator).Move(), allocator);
}
if (m_paramValueHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ParamValue";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_paramValue.c_str(), allocator).Move(), allocator);
}
}
string AccountParam::GetParamName() const
{
return m_paramName;
}
void AccountParam::SetParamName(const string& _paramName)
{
m_paramName = _paramName;
m_paramNameHasBeenSet = true;
}
bool AccountParam::ParamNameHasBeenSet() const
{
return m_paramNameHasBeenSet;
}
string AccountParam::GetParamValue() const
{
return m_paramValue;
}
void AccountParam::SetParamValue(const string& _paramValue)
{
m_paramValue = _paramValue;
m_paramValueHasBeenSet = true;
}
bool AccountParam::ParamValueHasBeenSet() const
{
return m_paramValueHasBeenSet;
}
| 27.919643 | 141 | 0.70323 | suluner |
68841e24e938e5f6292b471e54f773ed3dac408c | 3,129 | cpp | C++ | lib/Globe/GlobeTest.cpp | andyrobinson/ard-nav | 8162b2c9b882393ffd44e42d3f0816d7b1090760 | [
"MIT"
] | null | null | null | lib/Globe/GlobeTest.cpp | andyrobinson/ard-nav | 8162b2c9b882393ffd44e42d3f0816d7b1090760 | [
"MIT"
] | null | null | null | lib/Globe/GlobeTest.cpp | andyrobinson/ard-nav | 8162b2c9b882393ffd44e42d3f0816d7b1090760 | [
"MIT"
] | null | null | null | #include "Globe.h"
#include "gtest/gtest.h"
#include "math.h"
namespace {
Globe globe;
position London = {51.5073509,-0.12775823,0.0};
position Manchester = {53.479324,-2.2484851,0.0};
position Chorlton = {53.4407973,-2.272291,0.0};
position PlattFields = {53.44580, -2.22515,0.0};
position NewYork = {40.7127837, -74.0059413,0.0};
position Moscow = {55.755826, 37.6173,0.0};
position Sydney = {-33.8674869, 151.2069902,0.0};
position Capetown = {-33.9248685, 18.4240553,0.0};
position Santiago = {-33.4691199,-70.641997,0.0};
class GlobeTest : public ::testing::Test {
protected:
GlobeTest() {
//sail = Sail(stub_servo);
// You can do set-up work for each test here.
}
~GlobeTest() override {
// You can do clean-up work that doesn't throw exceptions here.
}
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
void SetUp() override {
// Code here will be called immediately after the constructor (right
// before each test).
}
void TearDown() override {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test suite for Foo.
double percentage_diff(double x, double y) {
double diff = (100.0 * (x-y))/x;
return fabs(diff);
}
};
TEST_F(GlobeTest, should_calculate_distance_to_within_one_tenth_percent) {
ASSERT_LT(percentage_diff(4565.0,globe.distance_between(&Manchester,&Chorlton)),0.1);
ASSERT_LT(percentage_diff(262100.0,globe.distance_between(&Manchester,&London)),0.1);
ASSERT_LT(percentage_diff(5570000.0,globe.distance_between(&London,&NewYork)),0.1);
ASSERT_LT(percentage_diff(2543000.0,globe.distance_between(&Manchester,&Moscow)),0.1);
ASSERT_LT(percentage_diff(11010000.0,globe.distance_between(&Sydney,&Capetown)),0.1);
ASSERT_LT(percentage_diff(12560000.0,globe.distance_between(&Capetown,&NewYork)),0.1);
ASSERT_LT(percentage_diff(11680000.0,globe.distance_between(&Santiago,&Chorlton)),0.1);
}
TEST_F(GlobeTest, should_calculate_bearing_between_points) {
EXPECT_EQ(200,globe.bearing(&Manchester,&Chorlton));
EXPECT_EQ(146,globe.bearing(&Manchester,&London));
EXPECT_EQ(288,globe.bearing(&London,&NewYork));
EXPECT_EQ(64,globe.bearing(&London,&Moscow));
EXPECT_EQ(357,globe.bearing(&Santiago,&NewYork));
EXPECT_EQ(80,globe.bearing(&Chorlton,&PlattFields));
EXPECT_EQ(260,globe.bearing(&PlattFields,&Chorlton));
}
TEST_F(GlobeTest, should_calculate_new_position_from_bearing_and_distance) {
position chorlton = globe.new_position(&Manchester,200,4565);
position new_york = globe.new_position(&London,288,5570000);
ASSERT_LT(percentage_diff(chorlton.latitude, Chorlton.latitude),1);
ASSERT_LT(percentage_diff(chorlton.longitude, Chorlton.longitude),1);
ASSERT_LT(percentage_diff(new_york.longitude, NewYork.longitude),1);
ASSERT_LT(percentage_diff(new_york.latitude, NewYork.latitude),1);
}
} //namespace
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 35.965517 | 89 | 0.737616 | andyrobinson |
68874461e5eca8dab1305093130c71286798eda3 | 6,678 | cpp | C++ | src/serialport.cpp | cybercrafts/roomba-driver | 9e338db5ef6d02a23e042c88953d921db5f353a3 | [
"MIT"
] | null | null | null | src/serialport.cpp | cybercrafts/roomba-driver | 9e338db5ef6d02a23e042c88953d921db5f353a3 | [
"MIT"
] | null | null | null | src/serialport.cpp | cybercrafts/roomba-driver | 9e338db5ef6d02a23e042c88953d921db5f353a3 | [
"MIT"
] | null | null | null | #include "serialport.h"
#include <iostream>
#include <vector>
#include <cctype>
#include <sstream>
#include <strings.h>
using namespace std;
unique_ptr<SerialPort> SerialPort::NewInstance(
const std::string& usb_port
){
// Try to open the file
int fd = open(usb_port.c_str(), O_RDWR | O_NOCTTY);
if (fd == -1){
perror("USB Open: Unable to open ");
return nullptr;
}
#if 0
// PULSE the BRC pin which is connected to the RTS
int RTS_flag = TIOCM_RTS;
// Set - HIGH
ioctl(fd, TIOCMBIS, &RTS_flag);
// Reset - LOW
ioctl(fd, TIOCMBIC, &RTS_flag);
this_thread::sleep_for(chrono::milliseconds(1000));
// Set - HIGH
ioctl(fd, TIOCMBIS, &RTS_flag);
#endif
if (!SerialPort::ConfigureSerial(fd)){
cout << "Error configuring serial port\n";
return nullptr;
}
#if 0
// Read the response from the port
int bytes_available = 0;
int retry_count = 5;
vector<uint8_t> rx_buffer;
while(retry_count){
ioctl(fd, FIONREAD, &bytes_available);
if (bytes_available){
rx_buffer.resize(bytes_available);
auto n = read(fd, &rx_buffer[0], bytes_available);
//cout << "Bytes available: " << bytes_available << " Read: " << n << endl;
cout << ToString(rx_buffer) << endl;
}
this_thread::sleep_for(chrono::milliseconds(25));
bytes_available = 0;
retry_count--;
}
#endif
// Create the new object
auto new_instance = new SerialPort(fd);
return unique_ptr<SerialPort>(new_instance);
}
SerialPort::SerialPort(int fd)
: m_fd(fd){
}
SerialPort::~SerialPort(){
close(m_fd);
}
bool SerialPort::ConfigureSerial(int fd){
// Good serial port programming resources
// Theory: https://www.cmrr.umn.edu/~strupp/serial.html#CONTENTS
// Example:
//
struct termios tty_settings{0};
if (tcgetattr(fd, &tty_settings) != 0){
perror("USB port settings cannot be changed ");
return false;
}
cout << "Initial Serial Port settings\n";
cout << "Input Speed: " << tty_settings.c_ispeed << endl;
cout << "Output Speed: " << tty_settings.c_ospeed << endl;
cfsetspeed(&tty_settings, B115200);
// Parity - None
tty_settings.c_cflag &= ~PARENB;
tty_settings.c_iflag |= IGNPAR ;
// Stop bits 1
tty_settings.c_cflag &= ~CSTOPB;
// Data bits 8 (first clear the CSIZE mask)
tty_settings.c_iflag &= ~ISTRIP ; // Clear the ISTRIP flag.
tty_settings.c_cflag &= ~CSIZE;;
tty_settings.c_cflag |= CS8;
tcflush(fd, TCIOFLUSH);
// Flow control H/W None
tty_settings.c_cflag &= ~CRTSCTS;
// Software Flow control None
tty_settings.c_iflag &= ~(IXON | IXOFF);
// Enable Rx and no modem control
tty_settings.c_cflag |= CREAD | CLOCAL;
// Ignore Break conditions on input.
tty_settings.c_iflag = IGNBRK;
tty_settings.c_oflag = 0;
// Clear the cannonical mode by clearing this
tty_settings.c_lflag = 0;
// No Output Processing i.e., we need raw
tty_settings.c_oflag &= ~OPOST;
// tty_settings.c_oflag &= ~ONLCR;
// Just use the default for the following
//tty_settings.c_cc[VTIME] = 0; /* inter-character timer unused */
//tty_settings.c_cc[VMIN] = 50; /* non-blocking read */
if (tcsetattr(fd, TCSANOW, &tty_settings) != 0) {
perror("Error from tcsetattr: ");
return false;
}
return true;
}
//------------------------------------------------------------------------------
// read
//------------------------------------------------------------------------------
bool
SerialPort::read(
vector<uint8_t>& rx_buffer,
int timeout_in_ms){
int rx_buffer_size = 0;
int bytes_available = 0;
int offset = 0;
int const WAIT_TIME_IN_MS = 20;
auto start_time = std::chrono::high_resolution_clock::now();
int retry_count = 0;
std::lock_guard<std::mutex> guard(m_lock);
while(true){
ioctl(m_fd, FIONREAD, &bytes_available);
if (bytes_available){
//cout << "Bytes available: " << bytes_available << "\n";
rx_buffer_size += bytes_available;
rx_buffer.resize(rx_buffer_size);
auto n = ::read(m_fd, &rx_buffer[offset], bytes_available);
//cout << "Bytes expected: " << rx_buffer.size() << " Read: " << n << endl;
if (n != bytes_available){
perror("Error reading response. ");
return false;
}
offset += bytes_available;
//cout << "Bytes read: " << n << "\n";
bytes_available = 0;
// Temp: Output this
//cout << "READ\n";
//cout << ToString(rx_buffer) << endl;
}
auto end_time = std::chrono::high_resolution_clock::now();
auto elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(
end_time - start_time).count();
if (timeout_in_ms){
if (elapsed >= timeout_in_ms){
//cout << endl << "Timeout: " << elapsed << endl;
return false;
}
}
else {
//cout << endl;
return true;
}
//cout << "Bytes expected: " << rx_buffer.size() << " available: " << bytes_available << endl;
retry_count++;
if (retry_count % 10 == 0) {
//cout << "." << flush;
}
std::this_thread::sleep_for(std::chrono::milliseconds(WAIT_TIME_IN_MS));
}
return false;
}
//------------------------------------------------------------------------------
// write
//------------------------------------------------------------------------------
bool
SerialPort::write(uint8_t* tx_data, int size){
int bytes_written = 0;
std::lock_guard<std::mutex> guard(m_lock);
if (::write(m_fd, tx_data, size) != size){
perror("Error sending command: ");
return false;
}
return true;
}
//------------------------------------------------------------------------------
// ToString
//------------------------------------------------------------------------------
string
SerialPort::ToString(const vector<uint8_t>& data){
ostringstream output;
for ( auto i = 0; i < data.size(); i++){
if (isprint(data[i])){
output << data[i];
}
else if (isspace(data[i])){
output << data[i];
}
else {
int int_value = (int) data[i];
//output << "0x" << hex << (int) data[i];
output << int_value << endl;
}
}
return output.str();
}
| 28.177215 | 102 | 0.532794 | cybercrafts |
688c15037e040bb417a5aa5352a321f096272d9e | 764 | hh | C++ | src/Titon/Route/LocaleRoute.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 206 | 2015-01-02T20:01:12.000Z | 2021-04-15T09:49:56.000Z | src/Titon/Route/LocaleRoute.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 44 | 2015-01-02T06:03:43.000Z | 2017-11-20T18:29:06.000Z | src/Titon/Route/LocaleRoute.hh | titon/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 27 | 2015-01-03T05:51:29.000Z | 2022-02-21T13:50:40.000Z | <?hh // strict
/**
* @copyright 2010-2015, The Titon Project
* @license http://opensource.org/licenses/bsd-license.php
* @link http://titon.io
*/
namespace Titon\Route;
/**
* Prepends all routes with a locale matching pattern.
*
* @package Titon\Route
*/
class LocaleRoute extends Route {
/**
* Prepend the locale to the front of the route before compilation.
*
* @return string
*/
public function compile(): string {
if ($this->isCompiled()) {
return $this->compiled;
}
if (mb_substr($this->getPath(), 0, 9) !== '/<locale>') {
$this->prepend('/<locale>');
}
$this->addPattern('locale', self::LOCALE);
return parent::compile();
}
}
| 20.648649 | 71 | 0.561518 | ciklon-z |
688d9a496417492681949db5e849cb662e3bc65c | 48,277 | hpp | C++ | Samples/Win7Samples/dataaccess/oledb_conformance/include/ctable.hpp | windows-development/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 8 | 2017-04-30T17:38:27.000Z | 2021-11-29T00:59:03.000Z | Samples/Win7Samples/dataaccess/oledb_conformance/include/ctable.hpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | null | null | null | Samples/Win7Samples/dataaccess/oledb_conformance/include/ctable.hpp | TomeSq/Windows-classic-samples | 96f883e4c900948e39660ec14a200a5164a3c7b7 | [
"MIT"
] | 2 | 2020-08-11T13:21:49.000Z | 2021-09-01T10:41:51.000Z | //--------------------------------------------------------------------
// Microsoft OLE DB Test
//
// Copyright 1995-2000 Microsoft Corporation.
//
// @doc
//
// @module CTable Header Module | This module contains header information for CTable
//
// @normal (C) Copyright 1995-1998 Microsoft Corporation. All Rights Reserved.
//
// @comm
// Special Notes...: (OPTIONAL NOTES FOR SPECIAL CIRCUMSTANCES)
//
// <nl><nl>
// Revision History:<nl>
//
// [00] MM-DD-YY EMAIL_NAME ACTION PERFORMED... <nl>
// [01] 10-05-95 Microsoft Created <nl>
// [02] 12-01-96 Microsoft Updated for release <nl>
//
// @head3 CTable Elements|
//
// @subindex CTable|
//
//---------------------------------------------------------------------------
#ifndef _CTable_HPP_
#define _CTable_HPP_
//-----------------------------------------------------------------------------
// @comm #pragma warning (disable: 4251) - This warning is generated by having
// CLists as member variables in a class that is exposed through
// a dll interface. This is simply a warning. The CList member variables
// are not exposed even if they are public data members. There have to be Get/Set
// functions that handle these member variables.
//
//-----------------------------------------------------------------------------
#pragma warning (disable :4251)
/////////////////////////////////////////////////////////////////////
// Includes
//
/////////////////////////////////////////////////////////////////////
#include "CCol.hpp"
#include "CTree.hpp"
#include "List.h"
#define READ_DBPROP_COL_AUTOINCREMENT 1
#define READ_DBPROP_COL_DEFAULT 2
#define READ_DBPROP_COL_FIXEDLENGTH 4
#define READ_DBPROP_COL_NULLABLE 8
#define READ_DBPROP_COL_UNIQUE 16
#define READ_COL_CLSID 32
const ULONG COL_NOT_COND = 0x1;
const ULONG COL_COND_NULL = 0x2;
const ULONG COL_COND_DEFAULT = 0x4;
const ULONG COL_COND_UNIQUE = 0x8;
const ULONG COL_COND_UPDATEABLE = 0x10;
const ULONG COL_COND_AUTOINC = 0x20;
const ULONG COL_COND_NOTNULL = COL_COND_NULL | COL_NOT_COND;
const ULONG COL_COND_NOTDEFAULT = COL_COND_DEFAULT | COL_NOT_COND;
const ULONG COL_COND_NOTUNIQUE = COL_COND_UNIQUE | COL_NOT_COND;
const ULONG COL_COND_NOTUPDATEABLE = COL_COND_UPDATEABLE | COL_NOT_COND;
const ULONG COL_COND_NOTAUTOINC = COL_COND_AUTOINC | COL_NOT_COND;
//--------------------------------------------------------------------
// @class A class used to generate internation strings based on the code
// page.
class CLocaleInfo
{
public:
//Convstructors
CLocaleInfo(LCID lcid);
virtual ~CLocaleInfo();
//String Creation Methods
virtual BOOL MakeUnicodeIntlString(WCHAR* pwsz, INT len);
virtual BOOL MakeUnicodeIntlData(WCHAR* pwsz, INT len);
virtual BOOL MakeAnsiIntlString(CHAR* psz, INT len);
virtual WCHAR MakeUnicodeChar();
virtual void MakeAnsiChar(CHAR* pcLead, CHAR* pcTrail);
virtual WCHAR* MakeUnicodeInt(int val);
//Localized Convervsion Methods
virtual HRESULT LocalizeString(WCHAR* pwszString, BSTR* pbstrLocalizedString);
virtual HRESULT LocalizeVariant(VARIANT* pVariant, VARIANT* pVarLocalized);
//Interface
virtual BOOL SetAnsiSeed(INT val);
virtual BOOL SetUnicodeSeed(INT val);
protected:
LCID m_lcid;
WCHAR* m_wszUnicodeChars;
UCHAR* m_szAnsiChars;
INT m_cchUnicode;
INT m_cchAnsi;
INT m_seedUnicode;
INT m_seedAnsi;
INT m_nCharMaxWidth;
WCHAR* m_wszSurrogateChars;
};
//-----------------------------------------------------------------------------
// @class CTable | The class is responsible for creating, manipulating,
// and deleting tables. The columns of the tables are actually CCol objects.
//
// <nl><nl>
// Caveat 1: Important pointers<nl>
// The constructor has to have the DataSource Object and Session Object
// passed to it or the class will not work. However, the IMalloc
// pointer is created inside the constructor so the class can
// manage its own memory. This IMalloc pointer is passed down
// to the CCol class's constructor, so the CCol and CTable objects
// are meant to be used together. <nl>
//
// <nl>
// Caveat 2: SQL Statments<nl>
// The BuildCommand/Execute commands and Select command have similar
// functionality. But for insert/update/delete, the ExecuteCommand
// cannot be used. The CreateSQLStmt/BuildCommand/ExecuteCommand
// functions should be reviewed before use. Each has several uses.<nl>
//
// <nl>
// Caveat 3: The following functions are not implemented currently: <nl>
// DoesIndexExist()<nl>
// SetExistingTable()<nl>
// SetFromIColumnsInfoGetColumnInfo()<nl>
// SetFromColumnsRowset()<nl>
// SetTableColumnInfo()<nl>
//
// <nl>
// Caveat 4:Array numbers<nl>
// CCol objects are actually stored in the CTable in the MFC class of
// CList,which is 0 based. <nl>
// Columns in the base table are 1 based unless there is a bookmark.
// Then the bookmark is the 0th element.<nl>
// Rows in the base table and CTable object are 1 based.<nl>
//
//-----------------------------------------------------------------------------
class CTable : public CSchema
{
// @access Private
private:
// @cmember Name of view over this table. <nl>
WCHAR * m_pwszViewName;
// @cmember Structure containing table name, used for ITableDefinition. <nl>
DBID m_TableID;
// IDBInfo (used Literals)
ULONG m_cLiteralInfo;
DBLITERALINFO* m_rgLiteralInfo;
WCHAR* m_pwszLiteralInfoBuffer;
// @cmember Name of index on this table. <nl>
WCHAR * m_pwszIndexName;
// @cmember Test case module name. <nl>
WCHAR * m_pwszModuleName;
// @cmember Total number of rows in CTable object. <nl>
DBCOUNTITEM m_ulRows;
// @cmember Next row to insert, used in Insert ONLY. <nl>
DBCOUNTITEM m_ulNextRow;
// @cmember Indicates what SQL Support the Provider has.
LONG_PTR m_lSQLSupport;
// @cmember DataSource interface
IDBInitialize* m_pIDBInitialize;
// @cmember Session interfaces
IOpenRowset* m_pIOpenRowset;
IDBCreateCommand* m_pIDBCreateCommand;
// @cmember Error object used to verify OLE DB calls. <nl>
CError * m_pError;
// @cmember Outer Unknown (controlling unknown) for use with ITableDefinition::CreateTable <nl>
IUnknown* m_pUnkOuter;
// @cmember REFIID in ITableDefinition::CreateTable <nl>
IID* m_riid;
// @cmember Pointer to DBID returned by ITableDefinition::CreateTable <nl>
DBID** m_ppTableID;
// @cmember Pointer to the rowset interface returned when creating a table <nl>
IUnknown** m_ppRowset;
// @cmember Array of property sets used for ITableDefinition::CreateTable <nl>
DBPROPSET *m_rgPropertySets;
// @cmember Number of elements in the array of properties <nl>
ULONG m_cPropertySets;
// @cmember Array of column descriptors used for ITableDefinition::CreateTable <nl>
DBCOLUMNDESC* m_rgColumnDesc;
// @cmember Number of elements in the array of column descriptors <nl>
DBORDINAL m_cColumnDesc;
// @cmember Whether to use a NULL Table ID in ITableDefinition::CreateTable <nl>
BOOL m_fInputTableID;
// @cmember Whether to build a list of column desc for ITableDefinition::CreateTable <nl>
BOOL m_fBuildColumnDesc;
// tell what props and supl info are available on col
// @cmember Column Has Default Value
BOOL m_fHasAuto;
// @cmember Column Has Default Value
BOOL m_fHasUnique;
// @cmember Column Has Default Value
BOOL m_fHasCLSID;
// @cmember Column Has Default Value
BOOL m_fHasDefault;
// @cmember Flag for available column properties (which properties of the column were got)
ULONG m_fColProps;
// @cmember Flag if the Provider is ReadOnly
ULONG m_fProviderReadOnly;
// @cmember ULONG for the Identifier Case
ULONG_PTR m_ulIdentifierCase;
// @cmember Cached PROVIDER_TYPES schema info
CSchema * m_pSchemaCache;
// @access Public
public:
// @cmember Command object to use in this class. <nl>
ICommand * m_pICommand;
// migrate to use this function instead of using public member m_pICommand
virtual inline ICommand * get_ICommandPTR(void) { return m_pICommand; };
virtual inline void set_ICommandPTR( ICommand *pICommand) { m_pICommand = pICommand; };
// @cmember Constructor. There is only one. <nl>
CTable(
IUnknown * pSessionIUnknown, // [IN] CreateCommand pointer from client
WCHAR * pwszModuleName=NULL, // [IN] Table name, optional (Default=NULL)
ENULL eNull=USENULLS // [IN] Should nulls be used (Default=USENULLS)
);
// @cmember Destructor. Gets rid of any memory. <nl>
virtual ~CTable(void);
// @cmember Builds an array used by ITableDefinition::CreateTable, <nl>
// based on column info. <nl>
HRESULT BuildColumnDescs(DBCOLUMNDESC** prgColumnDescs);
// @cmember Builds a DBCOLUMNDESC stru used by ITableDefinition::CreateTable, <nl>
// and ITableDefinition::AddColumn based on column info. <nl>
HRESULT BuildColumnDesc(DBCOLUMNDESC *pColumnDesc, CCol& CurCol);
// @cmember PrintTable. Prints CCol Info in debug window ONLY. <nl>
void PrintCColInfo();
// @cmember Reset the pointer to IDBCreateCommand inside CTable. <nl>
// This function should only be called within the same Data Source object. <nl>
// The intention of this method is for CTransaction class so that when <nl>
// ExecuteCommand is called, a new pIDBCreateCommand is used for the new <nl>
// transacion. <nl>
HRESULT ResetCreateCommand(
IDBCreateCommand *pIDBCreateCommand // [IN] IDBCreateCommand pointer
);
// @cmember Returns if Non null columns can be created on the database.
BOOL IsNonNullColumnsAllowed();
// @cmember Returns the SQLSupport of a Provider.
void ProviderSQLSupport();
// @cmember Creates table of all types found in Data Source #1. Default behavior <nl>
// creates a table with an autogenerated table name. The table has no rows. The <nl>
// index is on the first column. <nl>
HRESULT CreateTable(
DBCOUNTITEM ulRowCount, // [IN] Number of rows to generate, 1 based
DBORDINAL ulIndex=1, // [IN] Column that has index, 1 based (Default=1)
WCHAR * pwszTableName=NULL, // [IN] TableName,if NULL will be created internally (Default=NULL)
EVALUE eValue=PRIMARY, // [IN] Initial or second value of data to insert (Default=PRIMARY)
BOOL fFirstUpdateable=FALSE // [IN] TRUE means first column will not be autoinc (Default=FALSE)
);
// @cmember Creates table based on list of provider types #2. Default behavior <nl>
// creates a table with an autogenerated table name. The table has no rows. The <nl>
// index is on the first column. <nl>
// Please note that the private library will NOT <nl>
// arrange your columns. The order you pass them in is the order the table will <nl>
// be created. If any column you pass in can't be created or the index can't <nl>
// be created on the column specified, the table creation will fail. <nl>
HRESULT CreateTable(
CList <DBTYPE,DBTYPE>& rDBTypesList, // [IN] Types of columns
DBCOUNTITEM ulRowCount, // [IN] Number of rows to generate, 1 based
DBORDINAL ulIndex=1, // [IN] Column that has index (Default=1)
WCHAR * pwszTableName=NULL, // [IN] TableName,if NULL will be created internally (Default=NULL)
EVALUE eValue=PRIMARY, // [IN] Initial or second value of data to insert (Default=PRIMARY)
BOOL fFirstUpdateable=FALSE // [IN] TRUE means first column will not be autoinc (Default=FALSE)
);
// @cmember Creates table based on list of native types #3.Default behavior <nl>
// creates a table with an autogenerated table name. The table has no rows. The <nl>
// index is on the first column. <nl>
// Please note that the private library will NOT <nl>
// arrange your columns. The order you pass them in is the order the table will <nl>
// be created. If any column you pass in can't be created or the index can't <nl>
// be created on the column specified, the table creation will fail. <nl>
HRESULT CreateTable(
CList <WCHAR * ,WCHAR *>& rNativeTypesList, // [IN] Types of columns
DBCOUNTITEM ulRowCount, // [IN] Number of rows to generate
DBORDINAL ulIndex=1, // [IN] Column that has index (Default=1)
WCHAR * pwszTableName=NULL, // [IN] TableName,if NULL will be created internally (Default=NULL)
EVALUE eValue=PRIMARY, // [IN] Initial or second value of data (Default=PRIMARY)
BOOL fFirstUpdateable=FALSE // [IN] TRUE means first column will not be autoinc (Default=FALSE)
);
// @cmember Creates Index on Table. Default behavior creates unique index <nl>
// on column 1. <nl>
// "create [unique] index index_name on table_name (column_name)" , uses <nl>
// column ordinal number (m_ColNum). Index name is same as table name. Index <nl>
// is unique if EINDEXTYPE is UNIQUE, else not unique. <nl>
HRESULT CreateIndex(
DBORDINAL ulColNum=1, // [IN] Column number,first column should be numeric (Default=1)
EINDEXTYPE eIndexType=UNIQUE, // [IN] Constraint type (Default=UNIQUE)
LPWSTR pwszIndexName=NULL // [IN] Index name to use, default NULL will use table name.
);
// @cmember Creates Index on Table. Default behavior creates unique index
// Used to create an index on one or more columns
HRESULT CTable::CreateIndex(
DBORDINAL* rgulOrdinals, // [IN] Array of ordinals
DBORDINAL cOrdinals, // [IN] Count of ordinals
EINDEXTYPE eIndexType=UNIQUE, // [IN] Type of index (Default = UNIQUE)
LPWSTR pwszIndexName=NULL // [IN] Index name to use, default NULL will use table name.
);
// @cmember Builds a select statement on table, executes if requested.
// This function is an alternative to BuildComand and ExecuteCommand.
// It would be used when you know which singular row you want returned.
HRESULT Select(
IUnknown* pIUnkOuter, // [IN] Aggregate
DBCOUNTITEM ulRowNumber, // [IN] Row number to select
REFIID riid, // [IN] Type of interface user wants back
ULONG cPropSets, // [IN] Count of property sets.
DBPROPSET* rgPropSets, // [IN] Array of DBPROPSET structures.
DBROWCOUNT* pcRowsAffected, // [OUT] Pointer to memory in which to return the count
// of rows affected by a command that updates, deletes,
// or inserts rows.
IUnknown ** ppIUnknown, // [OUT] Interface pointer user wants back (Default=NULL)
ICommand ** ppICommand=NULL // [IN/OUT] If ppICommand == NULL, this function uses
// its own command object and then frees it, caller does nothing.
// <nl>
// If *ppICommand is not null, this value is used as the
// ICommand interface for all command operations in this function.
// Caller maintains responsiblity to release this interface.
// <nl>
// If *ppICommand is null, this function creates a new command object
// and places the ICommand interface to this object in *ppICommand.
// Caller assumes responsibility to release this interface.
);
// @cmember Inserts a row into the table. If commands are supported,
// it builds insert SQL statement and executes if requested.
// If commands are not supported, IRowsetNewRow is used to insert data,
// but only if fExecute = TRUE.
// Default behavior is to insert the next row.<nl>
// Inserts 1 row into the table. If ulRowNumber == 0 then ulRowNumber
// == m_ulNextRow. Rownumbers start at 0 in the private library, regardless
// of how they are treated in the Data Source.
// ppwszInsert should look like "Insert into table (col1,...) values (x, ...)".
// Client must IMalloc->Free(pwszInsert) if not passed as NULL.
// If pwszSelect == NULL, client doesn't want statement returned.
HRESULT Insert(
DBCOUNTITEM ulRowNumber=0, // [IN] Row number to insert (Default = Next row)
EVALUE eValue=PRIMARY, // [IN] Initial or second value of data (Default=PRIMARY)
BOOL fExecute=TRUE, // [IN] True indicates execute statement (Default=TRUE)
WCHAR ** pwszInsert=NULL,// [OUT] SQL statement generated. NULL is returned in commands aren't supported (Default=NULL)
BOOL fNULL=FALSE, // [IN] TRUE indicates that NULL values will be inserted whenever possible
DBCOUNTITEM cRowsToInsert = 1
);
// @cmember Inserts using IRowsetChange::InsertRow <nl>
HRESULT Insert(
EVALUE eValue, // [IN] Initial or second value of data
DBCOUNTITEM ulRowNumber, // [IN] Row number to insert
DBCOUNTITEM cRowsToInsert = 1 // [IN] number of rows to insert
);
// @cmember Inserts a row into the table using commands with a literal insert statements.
// the values specified by user.
HRESULT InsertWithUserLiterals(
DBORDINAL cCols, // [IN] number of values to insert
DBORDINAL *pulColOrdinals, // [IN] array of column ordinals
WCHAR **pwszLiterals // [IN] values to insert
);
// @cmember Inserts a row into the table with parameters. This function will only
// work when commands are supported. it builds the sql statements and executes if
// requested.
// pwszInsert should look like "Insert into table (col1, ...) values (?, ...);
HRESULT InsertWithParams(
DBCOUNTITEM ulRowNumber=0, // [IN] Row number to insert (Default = Next row)
EVALUE eValue=PRIMARY, // [IN] Initial or second value of data (Default=PRIMARY)
BOOL fExecute=TRUE, // [IN] True indicates execute statement (Default=TRUE)
WCHAR ** pwszInsert=NULL, // [OUT] SQL statement generated. NULL is returned in commands aren't supported (Default=NULL)
DBCOUNTITEM cRowsToInsert = 1
);
// @cmember Builds an update statement on table, executes if requested.
// Default behavior is to delete the last row inserted.<nl>
// Client must IMalloc->Free(pwszUpdate).
// Updates 1 row in table. Client must have at least one column marked
// or an error will occur. eValue is the type of MakeData data you are going to
// update the column to (the end result).
// If pwszSelect == NULL, client doesn't want statement returned.
HRESULT Update(
DBCOUNTITEM ulRowNumber=0, // [IN] Row number to update (Default=last row inserted into table)
EVALUE eValue=SECONDARY, // [IN] Kind of new value to set (Default=SECONDARY)
BOOL fExecute=TRUE, // [IN] True indicates execute statement (Default=TRUE)
WCHAR ** pwszUpdate=NULL, // [OUT] SQL statement generated (Default=NULL)
BOOL fSameWhereValuesAsSet = FALSE, // [IN] Whether to look for same value in where clause which is used in
// set clause and thus basically perform an update which doesn't
// change anything for the given row. (Default = FALSE, meaning
// the opposite of eValue will be used to generate the where clause,
// and thus the updated row will show a new value.)
DBCOUNTITEM ulWhereRowNumber=0 // [IN] if not 0 then update table set ulRowNumber where ulWhereRowNumber
);
// @cmember Builds a delete statement on table, executes if requested.
// Default behavior deletes all rows in table.<nl>
// Client must IMalloc->Free(pwszSelect).
// Deletes 1 row or all rows. If pstrSelect is NULL, client will not
// be returned the sql text of the delete statement. eValue is the current
// value of the data to be deleted.
// If pwszSelect == NULL, client doesn't want statement returned.
HRESULT Delete(
DBCOUNTITEM ulRowNumber=ALLROWS,// [IN] Row number to update (Default=ALLROWS)
EVALUE eValue=PRIMARY, // [IN] Initial or second value of data (Default=PRIMARY)
BOOL fExecute=TRUE, // [IN] True indicates execute statement (Default=TRUE)
WCHAR ** pwszSelect=NULL // [OUT] SQL statement generated (Default=NULL)
);
// @cmember Creates a SQL statement from one of the predefined statements
// and then executes that statement, Client must free any memory returned.
// If the client doesn't pass in a Command pointer for this function to
// work from, the private library has one it will use.
// Options include:<nl>
// (1)If the statement is a join that requires a second table, the second
// table name must be passed in. <nl>
// (2)Not executing statement, this would be interested when you want
// other information returned such as the sql statement.<nl>
// (3)Properties can be set and the errors associated with those properties
// can be returned. <nl>
// (4) The following must be IMalloc->Freed if passed in as valid addresses:<nl>
// ppwszStatement,prgColumns,prgPropertyErrors,prgpRowset.
// Client must release the following objects: <nl>
// - If pICommand is not null user must release this<nl>
// Client must free the following memory:<nl>
// - If prgPropertyErrors is not null user must free this<nl>
// - If pcRowset is zero then user must free prgpRowset<nl>
// - ppwszStatement<nl>
// - prgColumns<nl>
//
// This function takes a mandatory SQL statement.<nl>
HRESULT ExecuteCommand(
EQUERY eSQLStmt, // [IN] SQL statement to create
REFIID riid, // [IN] Interface pointer to return
WCHAR * pwszTableName=NULL, // [IN] Second TableName
WCHAR ** ppwszStatement=NULL, // [OUT] SQL statement generated
DBORDINAL * pcColumns=NULL, // [OUT] Count of columns
DB_LORDINAL ** prgColumns=NULL, // [OUT] Array of column numbers
EEXECUTE eExecute=EXECUTE_IFNOERROR,// [IN] TRUE = execute SQL Statement
ULONG cPropSets=0, // [IN] Count of property sets.
DBPROPSET rgPropSets[]=NULL, // [IN] Array of DBPROPSET structures.
DBROWCOUNT * pcRowsAffected=NULL, // [OUT] Pointer to memory in which to return the count
// of rows affected by a command that updates, deletes,
// or inserts rows.
IUnknown ** ppRowset=NULL, // [IN/OUT] Pointer to the rowset pointer.
ICommand ** ppICommand=NULL // [IN/OUT] If ppICommand == NULL, this function uses
// its own command object and then frees it, caller does nothing.
// <nl>
// If *ppICommand is not null, this value is used as the
// ICommand interface for all command operations in this function.
// Caller maintains responsiblity to release this interface.
// <nl>
// If *ppICommand is null, this function creates a new command object
// and places the ICommand interface to this object in *ppICommand.
// Caller assumes responsibility to release this interface.
);
// @cmember Creates a Rowset
HRESULT CreateRowset(
EQUERY eQuery, // [IN] Query to create
REFIID riid, // [IN] Interface pointer to return
ULONG cPropSets=0, // [IN] Count of property sets.
DBPROPSET* rgPropSets = NULL, // [IN] Array of DBPROPSET structures.
IUnknown ** ppRowset = NULL, // [OUT] Pointer to the rowset pointer.
DBID* pTableID = NULL, // {IN] TableID if needed (IOpenRowset)
DBORDINAL * pcColumns = NULL, // [OUT] Count of columns
DB_LORDINAL ** prgColumns = NULL, // [OUT] Array of column numbers
ULONG cRestrictions = 0, // [IN] cRestrictions
VARIANT* rgRestrictions = NULL, // [IN] rgRestrictions
IOpenRowset* pIOpenRowset = NULL // [IN] pIOpenRowset
);
// @cmember Sets properties on a command object and executes the sql statement
// Client must release and/or free any object and/or memory returned;
// If the client doesn't pass in a Command pointer for this function to
// work from, the private library has one it will use.
// Options include:<nl>
// (1)If the statement is a join that requires a second table, the second
// table name must be passed in. <nl>
// (2)Not executing statement, this would be interested when you want
// other information returned such as the sql statement.<nl>
// (3)Properties can be set and the errors associated with those properties
// can be returned. <nl>
// (4) Parameters can be set.<nl>
// (5) The following must be IMalloc->Freed if passed in as valid addresses:<nl>
// ppwszStatement,prgPropertyErrors,prgpRowset.<nl>
// Client must release the following objects:<nl>
// - If pICommand is not null user must release this<nl>
// Client must free the following memory:<nl>
// - If prgPropertyErrors is not null user must free this<nl>
// - If pcRowset is zero then user must free prgpRowset<nl>
//
// This function takes a mandatory SQL statement.
// This function will create a command object, set any properties passed in,
// set the SQL statement, and execute the statement if fExecute = TRUE;
// The user has the option of setting parameters, retrieving the count of
// rowsets, retrieving the array of rowsets, retrieving the interface pointer
// specified in the REFIID, and retrieving the command object.
HRESULT BuildCommand(
LPCWSTR pwszCommand, // [IN] SQL Statement to set
REFIID riid, // [IN] Interface pointer to return
EEXECUTE eExecute = EXECUTE_IFNOERROR, // [IN] When to execute the SQL Statement
ULONG cPropSets=0, // [IN] Count of property sets.
DBPROPSET rgPropSets[]=NULL, // [IN] Array of DBPROPSET structures.
DBPARAMS * pParams=NULL, // [IN] Parameters to pass to ::Execute
DBROWCOUNT * pcRowsAffected=NULL, // [OUT] Pointer to memory in which to return the count
// of rows affected by a command that updates, deletes,
// or inserts rows.
IUnknown ** ppRowset=NULL, // [IN/OUT] Pointer to the rowset pointer.
ICommand ** ppICommand=NULL, // [IN/OUT] If ppICommand == NULL, this function uses
// its own command object and then frees it, caller does nothing.
// <nl>
// If *ppICommand is not null, this value is used as the
// ICommand interface for all command operations in this function.
// Caller maintains responsiblity to release this interface.
// <nl>
// If *ppICommand is null, this function creates a new command object
// and places the ICommand interface to this object in *ppICommand.
// Caller assumes responsibility to release this interface.
IUnknown* pIUnkOuter = NULL // @parm [IN] Aggregate
);
// @cmember Creates a SQL statement from one of the predefined statements
// Client must free ppwszStatement and prgColumns.
// This function takes a one of the enum SQL Statements and creates the
// SQL statement with the columns and the CTable. The statement is then
// passed back to the user along with an array of column numbers in the
// order they will come back in the result set.
HRESULT CreateSQLStmt(
EQUERY eSQLStmt, // [IN] SQL statement to create
WCHAR * pwszTableName, // [IN] Second TableName
WCHAR ** ppwszStatement, // [OUT] SQL statement generated
DBORDINAL * pcColumns=NULL, // [OUT] Count of columns (Default = NULL)
DB_LORDINAL ** prgColumns=NULL,// [OUT] Array of column numbers (Default = NULL)
DBCOUNTITEM ulRowNumber = 1,// [IN] Row number to use
CTable * pTable2 = NULL, // [IN] Second table object to use
DBORDINAL iOrdinal = 0 // [IN] Col number to use, default 0 (all)
);
// @cmember Creates a list from the Ctable
// Client must free ppwszList, prgColumns.
// This function creates a list from the CTable. The list
// will be comma seperated. This function also returns an array of
// column numbers.
HRESULT CreateList(
ELIST_TYPE eListType, // @parm [IN] Type of list to create
LPWSTR * ppwszList, // @parm [OUT] List generated
DBORDINAL * pcColumns = NULL, // @parm [IN/OUT] In: Maximum number of columns that can be
// in the Column array. Ignored if *prgColumns==NULL.
// Out: Actual number of columns in finished array.
DB_LORDINAL ** pprgColumns = NULL, // @parm [IN/OUT] Array of column numbers, memory is allocated for caller
// if *pprgColumns == NULL, else it is assums the array is *pcColumns
// allocated by caller to hold all column numbers and the first column
// is a constant column such as 'ABC'.
ECOLS_IN_LIST eColsInList = ALL_COLS_IN_LIST, // @parm [IN] Type of columns in list (Default = ALL_COLS_IN_LIST)
ECOLUMNORDER eColOrder = FORWARD, // @parm [IN] Column list order, default FORWARD
EVALUE eValue = PRIMARY, // @parm [IN] Type of makedata (Default = PRIMARY)
DBCOUNTITEM ulRowNum = 1, // @parm [IN] Row number to use for literals, default 1
LPWSTR ** pprgColumnNames = NULL, // @parm[OUT] Column names, if null are not returned, (Default = NULL)
// Client must release each string and array of strings
DBORDINAL * prgColumns = NULL // @parm [IN] On input specifies desired columns,
// over-riding eColsInList. Default NULL.
);
// @cmember Creates a column list from the Ctable
// Client must free ppwszColList, prgColumns.
// This function creates a column list from the CTable. The column list
// will be comma seperated. This function also returns an array of
// column numbers.
HRESULT CreateColList(
ECOLUMNORDER eColOrder, // [IN] Column list order, default FORWARD
WCHAR ** ppwszColList, // [OUT] Column list generated
DBORDINAL * pcColumns, // [OUT] Count of columns
DB_LORDINAL ** prgColumns, // [OUT] Array of column numbers
ECOLS_IN_LIST eColsInList = ALL_COLS_IN_LIST,// [IN] Indicates which columns are included in list
BOOL fAddParams=FALSE, // [IN] TRUE if parameterized search criteria
// is added for each searchable column
BOOL fAddData=FALSE, // [IN] TRUE if data search criteria is
// added for each searchable column
WCHAR *** prgColumnNames=NULL,// [OUT] Column names, if null are not returned
EVALUE eValue=PRIMARY, // [IN] Type of makedata (Default = PRIMARY)
DBCOUNTITEM ulRowNumber = 1, // [IN] Row number to use
DBORDINAL iOrdinal = 0 // [IN] Col number to use, default 0 (all)
);
// @cmember Returns the columns in the query in query order and the
// base table ordinal value it cooresponds to.
// <nl>
// Since there is at least 1 EQUERY that encapsulates 2 select
// statements, there will be a need to check pXX1 and pXX2.
// <nl>
// Client is responsible for releasing memory.The actual strings in the array of
// column names is NOT to be released. The owner of the strings is CTable,
// and the CTable::DropTable() function will release that memory.
BOOL CTable::GetQueryInfo
(
EQUERY sqlStmt, // [in] SQL statement
DBORDINAL * pcColumns1, // [out] 1.Count of columns
DB_LORDINAL** prgColumns1, // [out] 1.Array of Column Ordinals
WCHAR *** prgColumnNames1, // [out] 1.Column names
DBORDINAL * pcColumns2, // [out] 2.Count of columns
DB_LORDINAL** prgColumns2, // [out] 2.Array of Column ordinals
WCHAR *** prgColumnNames2 // [out] 2.Column names
);
// @cmember Sets the member variables for a pre-existing table.
HRESULT SetExistingTable(WCHAR * pwszTableName = NULL); // [IN] Name of table, cannot be empty
// @cmember Sets table name if table name is currently NULL,
// else returns EFAIL.Can return E_OUTOFMEMORY.
HRESULT SetTableName(WCHAR * pTableName);
// @cmember Retrieves a correctly quoted Name
// Even handles correctly quoting qualified names...
HRESULT GetQuotedName(WCHAR* pwszName, WCHAR** ppwszQuoted, BOOL fFromCatalog = FALSE);
HRESULT GetQualifiedName(WCHAR* pwszCatalogName, WCHAR* pwszSchemaName, WCHAR* pwszTableName, WCHAR** ppwszQualifiedName,
BOOL fFromCatalog = FALSE);
// @cmember Retrieves LiteralInfo for the requested LITERAL
DBLITERALINFO* GetLiteralInfo(DBLITERAL dwliteral);
// @cmember Sets view name if view name is currently NULL,
// else returns EFAIL.Can return E_OUTOFMEMORY.
HRESULT SetViewName(WCHAR * pViewName);
// @cmember Sets which columns are used as search criteria
// in Select,Insert,Update,and Delete.
HRESULT SetColsUsed(CList <DBORDINAL,DBORDINAL>& rColNumList ); // [IN] Sets ccol.m_fUseInSQL
// @cmember Drops this table (which also drops index) from backend database.
HRESULT DropTable(BOOL fDropAlways = FALSE);
// @cmember Drops this table (which also drops index) from backend database.
HRESULT DropTable(DBID*);
// @cmember Drops the view on this table from backend database.
HRESULT DropView(void);
// @cmember Drops index on table.
HRESULT DropIndex(void);
// @cmember,mfunc Adds 1 to row count, should be called after insert is executed
// on this table outside of class.
// @@parm [IN] Number of rows to add to count (Default = 1)
void AddRow(DBCOUNTITEM ulRow=1){m_ulRows += ulRow; m_ulNextRow += ulRow;};
// @cmember,mfunc Removes 1 from row count, should be called after delete
// is executed on this table outside of class.
// @@parm [IN] Number of rows to substract from count (Default = 1)
void SubtractRow(DBCOUNTITEM ulRow=1){if(m_ulRows>0) m_ulRows -= ulRow; if(m_ulNextRow>0) m_ulNextRow -= ulRow;};
//Add a Column to the list
HRESULT AddColumn(CCol& rCol);
//Remove a Column from the table
HRESULT DropColumn(CCol& rCol);
//Remove a Column from the table; the column is given by its ordinal position
HRESULT DropColumn(DBORDINAL nOrdinalPos);
// @cmember Turn m_ColList.fUseInSQL to TRUE/FALSE
// [IN] Sets(TRUE) or clears(FALSE) ccol.m_fUseInSQL (Default=FALSE).<nl>
// TRUE means use every column in the where clause.<nl>
// FALSE means do not use any columns in where clause.<nl>
HRESULT AllColumnsForUse(
BOOL fValue=FALSE
);
// @cmember Number of rows in base table. This function executes a "select * from" and
// then counts all the rows on the table.
// Zero is returned if there was an error.
// Counts the rows in the table by seeing how many GetRows it
// goes thru. Yes, this is expensive for large databases. If table name
// is not set, return E_FAIL. Alloc (pwszSQLText).
DBCOUNTITEM CountRowsOnTable(IRowset *pIRowset=NULL);
// @cmember Number of rows in CTable object. Returns m_ulRows.
DBCOUNTITEM GetRowsOnCTable(void){return m_ulRows;};
// @cmember Number of columns in CTable.
// Zero is returned if there was an error.
DBORDINAL CountColumnsOnTable(void);
// @cmember,mfunc Returns TableName, client should not alter pointer.
WCHAR * GetTableName(void){return m_TableID.uName.pwszName;};
// @cmember,mfunc Returns ViewName, client should not alter pointer.
WCHAR * GetViewName(void){return m_pwszViewName;};
// @cmember,mfunc Returns TableID
DBID GetTableID(void){return m_TableID;};
// @cmember,mfunc Returns the reference of TableID
DBID& GetTableIDRef(void){return m_TableID;};
// @cmember,mfunc Sets TableID
void SetTableID(DBID d);
// @cmember,mfunc Returns m_fHasAuto
BOOL GetHasAuto(void){
return m_fHasAuto;}
// @cmember,mfunc Sets m_fHasAuto
void SetHasAuto(BOOL b){m_fHasAuto = b;}
// @cmember,mfunc Returns m_fHasAuto
BOOL GetHasUnique(void){
return m_fHasUnique;}
// @cmember,mfunc Sets m_fHasAuto
void SetHasUnique(BOOL b){m_fHasUnique = b;}
// @cmember,mfunc Returns m_fHasAuto
BOOL GetHasCLSID(void){
return m_fHasCLSID;}
// @cmember,mfunc Sets m_fHasAuto
void SetHasCLSID(BOOL b){m_fHasCLSID = b;}
// @cmember,mfunc Returns m_fHasDefault
BOOL GetHasDefault(void){
return m_fHasDefault;}
// @cmember,mfunc Sets m_fHasDeffault
void SetHasDefault(BOOL b){m_fHasDefault = b;}
// @cmember,mfunc Returns IndexName, client should not alter pointer.
WCHAR * GetIndexName(void){return m_pwszIndexName;}
// @cmember,mfunc Returns Module Name, client should not alter pointer.
WCHAR * GetModuleName(void);
// @cmember,mfunc Returns next row number for insert statement.
DBCOUNTITEM GetNextRowNumber(void){return m_ulNextRow;}
// @cmember Flag telling if Commands are supported on the CTable object.
BOOL GetCommandSupOnCTable(void) { return m_pIDBCreateCommand!=NULL; }
// @cmember,mfunc Sets I4 for SQL support, m_lSQLSupport.
// @@parmopt [IN] SQL Support (Default = 0)
void SetSQLSupport(LONG_PTR lSQLSupport=0)
{m_lSQLSupport=lSQLSupport;}
// @cmember,mfunc Returns I4 for SQL support, m_lSQLSupport.
LONG_PTR GetSQLSupport(void){return m_lSQLSupport;}
// @cmember Flag telling if the Provider is ReadOnly.
BOOL GetIsProviderReadOnly(void){return m_fProviderReadOnly;}
// @cmember Gets the columns to be used as search criteria in
// Select,Insert,Update,and Delete. Information on how to
// traverse the returned structure can be found in the MFC
// reference on CList.
HRESULT GetColsUsed(
CList <DBORDINAL,DBORDINAL>& rColNumList // [OUT] Gets ccol.m_fUseInSQLs
);
HRESULT SetExistingCols(
CList<CCol,CCol&> &InColList
);
// @cmember delete without using commands
HRESULT DeleteRows(
DBCOUNTITEM ulRowNumber=ALLROWS // @parm [IN] row # to pass (Default = ALLROWS)
);
// @cmember Sets m_pUnkOuter
IUnknown *SetUnkOuter(IUnknown *pUnkOuter = NULL) {
return m_pUnkOuter = pUnkOuter; }
// @cmember Gets m_pUnkOuter
IUnknown *GetUnkOuter(void) {
return m_pUnkOuter; }
// @cmember Sets the reference to the required rowset reference (for ITableDefinition)
IID *SetRIID(IID* riid = (struct _GUID*)&IID_IRowset) {
return m_riid = riid; }
// @cmember Gets the reference to the required rowset reference (for ITableDefinition)
IID *GetRIID(void) {
return m_riid; }
// @cmember Sets the property sets
DBPROPSET *SetPropertySets(
DBPROPSET *rgPropertySets = NULL,
ULONG cPropSets = 0
);
// @cmember Gets the property sets to be set or set by ITableDefinition::CreateTable
DBPROPSET *GetPropertySets(void) {
return m_rgPropertySets; }
// @cmember Sets the number of property sets for ITableDefinition::CreateTable
ULONG SetNoOfPropertySets(ULONG cPropertySets = 0) {
return m_cPropertySets = cPropertySets; }
// @cmember Gets the number of property sets
ULONG GetNoOfPropertySets(void) {
return m_cPropertySets; }
// @cmember Sets the column description array
DBCOLUMNDESC *SetColumnDesc(DBCOLUMNDESC *rgColumnDesc = NULL);
// @cmember Sets the column description array
DBCOLUMNDESC *SetColumnDesc(DBCOLUMNDESC *rgColumnDesc, DBORDINAL cColumnDesc);
// @cmember Gets the property sets to be set or set by ITableDefinition::CreateTable
DBCOLUMNDESC *GetColumnDesc(void) {
return m_rgColumnDesc; }
// @cmember Sets the number of column descriptors for ITableDefinition::CreateTable
DBORDINAL SetNoOfColumnDesc(DBORDINAL cColumnDesc = 0) {
return m_cColumnDesc = cColumnDesc; }
// @cmember Use &m_TableID as input TableID in ITableDefinition::CreateTable
BOOL SetInputTableID(void) {
return m_fInputTableID = TRUE;}
// @cmember Use NULL as input TableID in ITableDefinition::CreateTable
BOOL ResetInputTableID(void) {
return m_fInputTableID = FALSE;}
// @cmember Get m_fInputTableID
BOOL GetInputTableID(void) {
return m_fInputTableID;}
// @cmember SetBuildColumnDesc
BOOL SetBuildColumnDesc(BOOL v) {
return m_fBuildColumnDesc = v;}
// @cmember GetBuildColumnDesc
BOOL GetBuildColumnDesc(void) {
return m_fBuildColumnDesc; }
// @cmember Sets pointer to the return table DBID (in ITableDefinition::CreateTable)
DBID **SetDBID(DBID **ppTableID = NULL);
// @cmember Gets pointer to the return table DBID created by ITableDefinition::CreateTable
DBID **GetDBID(void);
// @cmember Sets pointer to the rowset interface to be created by ITableDefinition::CreateTable
IUnknown **SetRowset(IUnknown **ppRowset = NULL);
// @cmember Gets the pointer to the rowset interface created by ITableDefinition::CreateTable
IUnknown **GetRowset(void);
// @cmember Gets the column properties that could be read
ULONG GetColProps(void){
return m_fColProps; }
// @cmember Duplicate the column list, it's user responsability to free it
CList <CCol, CCol&> &DuplicateColList(CList <CCol, CCol&> &ColList);
// @cmember Set the column list
CList <CCol, CCol&> &SetColList(CList <CCol, CCol&> &ColList);
// @cmember Creates initial list of types,initializes m_ColList with columns of
// specified types.
HRESULT CreateColInfo(
CList<WCHAR *,WCHAR *>& rProviderTypesNameList, // [OUT] CList of WCHAR * of ProviderTypeNames
CList<DBTYPE,DBTYPE>& rProviderTypesList, // [OUT] CList of DBTYPE of ProviderTypes
EDATATYPES eDataTypes=ALLTYPES, // [IN] Data types (Default = ALLTYPES)
BOOL fFirstUpdateable = FALSE // [IN] TRUE means first column will not be autoinc (Default=FALSE)
);
// @cmember Creates initial list of types,initializes m_ColList with columns of
// specified types.
HRESULT CreateTypeColInfo(
CList<WCHAR *,WCHAR *>& rProviderTypesNameList, // [OUT] CList of WCHAR * of ProviderTypeNames
CList<DBTYPE,DBTYPE>& rProviderTypesList, // [OUT] CList of DBTYPE of ProviderTypes
EDATATYPES eDataTypes=ALLTYPES, // [IN] Data types (Default = ALLTYPES)
ULONG *pulAutoIncPrec=NULL // [OUT] Precision of largest Auto Inc column (optional)
);
// @cmember Checks columns for Updatability. Used in the createtable functions.
HRESULT MayWrite(
BOOL * fMayWrite=NULL // [OUT] Is Column Writeable (Default=NULL).
);
// @cmember Returns first numeric (4 byte or larger) column <nl>
HRESULT GetFirstNumericCol(CCol * pCCol);
// @cmember returns list of not nullable columns
HRESULT CTable::GetNullableCols (WCHAR **prgColName);
// @cmember Builds a variant which can represent the default value of a type
BOOL BuildDefaultValue(CCol& col, DBCOUNTITEM cRow, VARIANT *vDefault = NULL);
// @cmember Sets the default value of a column
BOOL SetDefaultValue(CCol& col, DBCOUNTITEM cRow);
// @cmember Sets the has default value of a column
BOOL SetHasDefaultValue(CCol& col, BOOL fHasDefaultValue);
// @cmember Gets a column that satisfies several criteria
BOOL GetColWithAttr(ULONG cCond, ULONG *rgCond, DBORDINAL *pcSelectedColumn);
BOOL GetColWithAttr(ULONG ulCond, DBORDINAL *pcSelectedColumn)
{ return GetColWithAttr(1, &ulCond, pcSelectedColumn); }
// @cmember get the order by column
HRESULT GetOrderByCol(
CCol * pCCol // @parm [in/out] Pointer to CCol object to copy
);
// @access Private
private:
// @cmember All functionality common to 3 CreateTable functions. <nl>
// Called from one of the overloaded CreateTable functions.Passing zero
// for ulIndex means do not but an Index on this table. eValue means
// to create table with eValue kind of data. <nl>
//
// 1) Get Table Name <nl>
// 2) Get Datatypes from Datasource <nl>
// 3) Determine if we'll use command with SQL or ITableDefinition <nl>
// 4) If using command, build sql/execute string for creating table <nl>
// 5) Create Table <nl>
// 4) Create Index, if requested <nl>
// 5) Fill table with rows, if requested <nl>
//
// create table SQL statement looks like:
// "create table <TableName> (col1 type,col2 type)"
HRESULT QCreateTable(
DBCOUNTITEM ulRowCount, // [IN] # of Rows to insert into table, 1 based
DBORDINAL ulIndex, // [IN] Column Number of index, 1 based
EVALUE eValue // [IN] Type of data to insert
);
// @cmember Returns System Time. Used to create table name.
// Client must IMalloc->Free returned string.
WCHAR * GetTime(void);
public:
// @cmember Checks if Table currently exists based on a tablename search.
// Make sure table is in Data Source, E_FAIL if table name is empty.
// If table is found set fExists to true. If function runs correctly
// but doesn't find the table name, function will return NOERROR, but fExists
// will be FALSE.
HRESULT DoesTableExist(
WCHAR * pwszTableName=NULL, // [IN] Table name to check for (Default=NULL)
BOOL * fExists=NULL // [OUT] TRUE if table is found (Default=NULL)
);
// @cmember Checks if Table currently exists based on a tablename search.
// Make sure table is in Data Source, E_FAIL if table name is empty.
// If table is found set fExists to true. If function runs correctly
// but doesn't find the table name, function will return NOERROR, but fExists
// will be FALSE.
HRESULT DoesTableExist(
DBID * pTableID=NULL, // [IN] Pointer to Table DBID to check for (Default=NULL)
BOOL * fExists=NULL // [OUT] TRUE if table is found (Default=NULL)
);
public:
// @cmember Checks if Index currently exists based on indexname search.
// If this index is on this table return true and fill in
// strIndexName and udwIndex, set fExists to true. If function runs correctly
// but doesn't find the table name, function will return NOERROR, but fExists
// will be FALSE. If strIndexName is empty, returns E_FAIL. Assumes table
// will have only 1 index.
HRESULT DoesIndexExist(
BOOL * fExists=NULL // [OUT] TRUE if index exists (Default=NULL)
);
// @cmember Used in Select to get literal prefix, makedata, and literal suffix
// Client must IMalloc->Free((*ppwszData)).
HRESULT GetLiteralAndValue(
CCol & col, // [IN] Col to grab prefix and suffix from
WCHAR ** ppwszData=NULL, // [OUT] Prefix, data, suffix like 'zbc' or #222 (Default=NULL)
DBCOUNTITEM ulRow=1, // [IN] Row number to pass to MakeData (Default=1)
DBORDINAL ulColNum=1, // [IN] Column number to pass to MakeData (Default=1)
EVALUE eValue=PRIMARY, // [IN] PRIMARY or SECONDARY data (Default=PRIMARY)
BOOL fColData=FALSE // [IN] Whether to use col to make the data (Default = FALSE)
);
// @cmember FormatVariantLiteral
// Formats a variant literal using ODBC canonical convert functions
HRESULT CTable::FormatVariantLiteral
(
DBTYPE wVariantType, // [IN] variant sub type
WCHAR * pwszData, // [IN] input data
WCHAR ** ppwszData // [OUT] formatted data
);
// @cmember Generates Table Name
// Looks like "MODULENAME_DATE_RANDOMNUMBER" example "persist_950101_9563".
HRESULT MakeTableName(WCHAR* pwszTableName);
// @cmember Fill m_ColList with information about current table
HRESULT SetTableColumnInfo(
WCHAR * pwszTableName = NULL, // [IN] Table Name
IUnknown *pIRowset=NULL // [IN] Rowset from command
);
// @cmember Fill m_ColList with information about current table
HRESULT GetTableColumnInfo(
DBID * pTableID, // [IN] Table ID
IUnknown *pIRowset=NULL // [IN] Rowset from command
);
// @cmember Builds m_ColList from information in rgColumnDesc
BOOL ColumnDesc2ColList(
DBCOLUMNDESC *rgColumnDesc, // [IN] An array of ColumnDesc build from m_ColList
DBORDINAL cColumnDesc // [IN] the number of elements in the array
);
// @cmember Fill m_ColList with information about current table
BOOL ColList2ColumnDesc(
DBCOLUMNDESC **rgColumnDesc, // [OUT] An array of ColumnDesc build from m_ColList
DBORDINAL *cColumnDesc = NULL // [OUT] the number of elements in the array
);
// @cmember Puts the elements of CCol in m_ColList.
HRESULT GetFromColumnsRowset(
IColumnsRowset * pIColumnsRowset, // [IN] IColumnsRowset pointer
DBORDINAL * cColsFound=NULL // [OUT] Total number of columns found (Default=NULL)
);
// @cmember Updates elements in m_ColList based on values read from column schema rowset
HRESULT AddInfoFromColumnsSchemaRowset(
IUnknown *pIUnknown, // [IN] session interface
WCHAR *pwszTableName = NULL, // [IN] table name (if null go for current table)
DBCOUNTITEM *cColsFound = NULL // [OUT] Total number of columns found (Default=NULL)
);
private:
// @cmember Puts the elements of CCol in m_ColList.
HRESULT SetFromIDBSCHEMATypes(
DBORDINAL * cColsFound=NULL // [OUT] Total number of columns found (Default=NULL)
);
// @cmember Puts the elements of CCol in m_ColList.
HRESULT SetFromIDBSCHEMAColumns(
DBORDINAL * cColsFound=NULL // [OUT] Total number of columns found (Default=NULL)
);
// @cmember Setups up cache for LiteralInfo
HRESULT SetupLiteralInfo();
// @cmember Sets the corresponding member function.
HRESULT SetModuleName(
WCHAR * pwszModuleName=NULL // [IN] Test Case Module Name (Default=NULL)
);
// @cmember Sets the column description array
BOOL IsCompatibleType(
DBCOUNTITEM cBindings,
DBBINDING* rgBindings,
void* pData,
CCol & rCol // @parm [IN] Element from the CCol List
);
// @cmember Creates DBPARAMBINDINFO and rgParamOrdinal array given desired
// bindings, column ordinals. User must free pParamOrdinals, pParamBindInfo.
HRESULT GetDBPARAMBINDINFO(
DBCOUNTITEM cBindings,
DBBINDING* rgBindings,
DB_LORDINAL * rgColOrds,
DB_UPARAMS ** ppParamOrdinals,
DBPARAMBINDINFO ** ppParamBindInfo
);
};
#endif // _CTable_
| 43.142985 | 124 | 0.707086 | windows-development |
6897f2c63bdd2a3756e2fecac69f44434b7dfe69 | 983 | hpp | C++ | include/h3api/H3AdventureMap/H3MapLearningStone.hpp | Patrulek/H3API | 91f10de37c6b86f3160706c1fdf4792f927e9952 | [
"MIT"
] | 14 | 2020-09-07T21:49:26.000Z | 2021-11-29T18:09:41.000Z | include/h3api/H3AdventureMap/H3MapLearningStone.hpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 2 | 2021-02-12T15:52:31.000Z | 2021-02-12T16:21:24.000Z | include/h3api/H3AdventureMap/H3MapLearningStone.hpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 8 | 2021-02-12T15:52:41.000Z | 2022-01-31T15:28:10.000Z | //////////////////////////////////////////////////////////////////////
// //
// Created by RoseKavalier: //
// rosekavalierhc@gmail.com //
// Created or last updated on: 2021-02-02 //
// ***You may use or distribute these files freely //
// so long as this notice remains present.*** //
// //
//////////////////////////////////////////////////////////////////////
#pragma once
#include "h3api/H3Base.hpp"
namespace h3
{
_H3API_DECLARE_(MapitemLearningStone);
#pragma pack(push, 4)
/** @brief data for learning stone on adventure map*/
struct H3MapitemLearningStone
{
/** @brief [00] heroes can only visit 32 learning stones*/
INT32 id;
};
#pragma pack(pop) /* align-4 */
} /* namespace h3 */
| 31.709677 | 70 | 0.385554 | Patrulek |
68991572218b30c6bf4aba3d0c0cc7ff3e92d902 | 2,900 | hpp | C++ | examples/src/example_types.hpp | bergmansj/jsoncons | 11db194bd3f0e3e89f29b3447e28d131db242501 | [
"BSL-1.0"
] | null | null | null | examples/src/example_types.hpp | bergmansj/jsoncons | 11db194bd3f0e3e89f29b3447e28d131db242501 | [
"BSL-1.0"
] | null | null | null | examples/src/example_types.hpp | bergmansj/jsoncons | 11db194bd3f0e3e89f29b3447e28d131db242501 | [
"BSL-1.0"
] | null | null | null | #ifndef EXAMPLE_TYPES
#define EXAMPLE_TYPES
#include <string>
#include <vector>
#include <jsoncons/json.hpp>
// book example
namespace ns {
struct book
{
std::string author;
std::string title;
double price;
};
} // namespace ns
namespace jsoncons {
template<class Json>
struct json_type_traits<Json, ns::book>
{
typedef typename Json::allocator_type allocator_type;
static bool is(const Json& j) noexcept
{
return j.is_object() && j.contains("author") &&
j.contains("title") && j.contains("price");
}
static ns::book as(const Json& j)
{
ns::book val;
val.author = j.at("author").template as<std::string>();
val.title = j.at("title").template as<std::string>();
val.price = j.at("price").template as<double>();
return val;
}
static Json to_json(const ns::book& val,
allocator_type allocator=allocator_type())
{
Json j(allocator);
j.try_emplace("author", val.author);
j.try_emplace("title", val.title);
j.try_emplace("price", val.price);
return j;
}
};
} // namespace jsoncons
// reputon example
namespace ns {
struct reputon
{
std::string rater;
std::string assertion;
std::string rated;
double rating;
friend bool operator==(const reputon& lhs, const reputon& rhs)
{
return lhs.rater == rhs.rater && lhs.assertion == rhs.assertion &&
lhs.rated == rhs.rated && lhs.rating == rhs.rating;
}
friend bool operator!=(const reputon& lhs, const reputon& rhs)
{
return !(lhs == rhs);
};
};
class reputation_object
{
std::string application;
std::vector<reputon> reputons;
// Make json_type_traits specializations friends to give accesses to private members
JSONCONS_TYPE_TRAITS_FRIEND;
public:
reputation_object()
{
}
reputation_object(const std::string& application, const std::vector<reputon>& reputons)
: application(application), reputons(reputons)
{}
friend bool operator==(const reputation_object& lhs, const reputation_object& rhs)
{
return (lhs.application == rhs.application) && (lhs.reputons == rhs.reputons);
}
friend bool operator!=(const reputation_object& lhs, const reputation_object& rhs)
{
return !(lhs == rhs);
};
};
} // ns
// Declare the traits. Specify which data members need to be serialized.
JSONCONS_MEMBER_TRAITS_DECL(ns::reputon, rater, assertion, rated, rating)
JSONCONS_MEMBER_TRAITS_DECL(ns::reputation_object, application, reputons)
#endif
| 27.358491 | 95 | 0.577586 | bergmansj |
689b3226db1d28a9b11fb792d01a92d89a8ad028 | 608 | cpp | C++ | src/GameHUD.cpp | eaymerich/blaster | cfe72ceb1cd2858ae419793460b0d452d1b4ee99 | [
"MIT"
] | null | null | null | src/GameHUD.cpp | eaymerich/blaster | cfe72ceb1cd2858ae419793460b0d452d1b4ee99 | [
"MIT"
] | null | null | null | src/GameHUD.cpp | eaymerich/blaster | cfe72ceb1cd2858ae419793460b0d452d1b4ee99 | [
"MIT"
] | null | null | null | #include "GameHUD.h"
GameHUD::GameHUD() :
scoreText{"SCORE"},
lifeText{"LIFE"} {
float charWidth = 2.0f / CHARS_PER_LINE;
scoreText.setPosition(-(charWidth * 18.0f), -(charWidth * 15.0f), 0.0f);
lifeText.setPosition(-(charWidth * 2.0f), -(charWidth * 15.0f), 0.0f);
background.setSize(2.0f, 0.3f);
background.setPosition(0.0f, -0.85f);
background.setColor(0.1f, 0.1f, 0.9f);
// Add elements to display
display.add(&background);
display.add(&scoreText);
display.add(&lifeText);
}
GameHUD::~GameHUD() {
}
void GameHUD::draw() const {
display.draw();
}
| 22.518519 | 76 | 0.628289 | eaymerich |
689b5169cee6fc6e1305dc1023bac61ea8eb2754 | 533 | hpp | C++ | EasyDx/MeshRenderer.hpp | LYP951018/EasyDX | 10b5a04c13af1fc6c3b405e309dc754a42530011 | [
"Apache-2.0"
] | 3 | 2017-03-12T07:26:56.000Z | 2017-11-20T13:01:46.000Z | EasyDx/MeshRenderer.hpp | LYP951018/EasyDX | 10b5a04c13af1fc6c3b405e309dc754a42530011 | [
"Apache-2.0"
] | 9 | 2019-04-27T08:36:01.000Z | 2021-11-25T16:36:02.000Z | EasyDx/MeshRenderer.hpp | LYP951018/EasyDX | 10b5a04c13af1fc6c3b405e309dc754a42530011 | [
"Apache-2.0"
] | 2 | 2018-04-16T09:41:56.000Z | 2021-11-01T06:17:58.000Z | #pragma once
#include "ComponentBase.hpp"
namespace dx
{
class Mesh;
struct Material;
class MeshRenderer : public ComponentBase
{
public:
MeshRenderer(std::shared_ptr<Mesh> mesh,
std::shared_ptr<Material> material);
Mesh& GetMesh() const;
std::shared_ptr<Mesh> SharedMesh() const { return m_mesh; }
Material& GetMaterial() const;
private:
std::shared_ptr<Mesh> m_mesh;
std::shared_ptr<Material> m_material;
};
} // namespace dx | 22.208333 | 67 | 0.613508 | LYP951018 |
689f544b333e56667e600020f48392c2ac61e1fc | 254 | cpp | C++ | example/error_handling.cpp | FatihBAKIR/liaw2019-process | 8f4a74ff5a71f8ade180c8a9baffd8b4c53de06d | [
"MIT"
] | null | null | null | example/error_handling.cpp | FatihBAKIR/liaw2019-process | 8f4a74ff5a71f8ade180c8a9baffd8b4c53de06d | [
"MIT"
] | null | null | null | example/error_handling.cpp | FatihBAKIR/liaw2019-process | 8f4a74ff5a71f8ade180c8a9baffd8b4c53de06d | [
"MIT"
] | null | null | null | #include <process>
#include <system_error>
int main()
{
try
{
std::process proc("does-not-exist", {});
}
catch (process_error & pe)
{
std::cout << "Process launch error for file: " << pe.path() << std::endl;
}
}
| 16.933333 | 81 | 0.527559 | FatihBAKIR |
68a2062277dc73ef696a5e5c0b5e297c99d6c117 | 3,063 | cc | C++ | tests/bit_array.cc | GameVTeam/kerfuffle | 07c2e4eff6f16885ee2c44a9aef8cde9b73a4b55 | [
"MIT"
] | null | null | null | tests/bit_array.cc | GameVTeam/kerfuffle | 07c2e4eff6f16885ee2c44a9aef8cde9b73a4b55 | [
"MIT"
] | 1 | 2020-08-19T15:46:56.000Z | 2020-08-19T15:46:56.000Z | tests/bit_array.cc | GameVTeam/kerfuffle | 07c2e4eff6f16885ee2c44a9aef8cde9b73a4b55 | [
"MIT"
] | null | null | null | //
// Created by 方泓睿 on 2020/8/6.
//
#include "helper.h"
#pragma clang dianostic push
#pragma ide diagnostic ignored "cert-err58-cpp"
using BitArray = kerfuffle::detail::BitArray<kerfuffle::ShortIndex, 6>;
using Bits = typename BitArray::Bits;
namespace kerfuffle {
namespace test {
class BitArrayTest : public testing::Test {
protected:
BitArray bitArray{};
public:
BitArrayTest() { bitArray.clear(); }
};
TEST_F(BitArrayTest, TestStaticMethods) {
bitArray.clear();
{
const Bits bits = bitArray.bits<3, 7>();
ASSERT_FALSE(bits);
ASSERT_FALSE(bits.get<0>());
ASSERT_FALSE(bits.get<1>());
ASSERT_FALSE(bits.get<2>());
ASSERT_FALSE(bits.get<3>());
ASSERT_FALSE(bits.get<4>());
ASSERT_FALSE(bits.get<5>());
ASSERT_FALSE(bits.get<6>());
}
{
Bits bits = bitArray.bits<3, 7>();
bits.set<4>();
}
{
const Bits bits = bitArray.bits<2, 13>();
ASSERT_FALSE(bits.get<0>());
ASSERT_FALSE(bits.get<1>());
ASSERT_FALSE(bits.get<2>());
ASSERT_FALSE(bits.get<3>());
ASSERT_FALSE(bits.get<4>());
ASSERT_FALSE(bits.get<5>());
ASSERT_FALSE(bits.get<6>());
ASSERT_FALSE(bits.get<7>());
ASSERT_FALSE(bits.get<8>());
ASSERT_FALSE(bits.get<9>());
ASSERT_FALSE(bits.get<10>());
ASSERT_FALSE(bits.get<11>());
ASSERT_TRUE(bits.get<12>());
}
{
Bits bits = bitArray.bits<2, 13>();
bits.reset<12>();
}
{
const Bits bits = bitArray.bits<3, 7>();
ASSERT_FALSE(bits);
ASSERT_FALSE(bits.get<0>());
ASSERT_FALSE(bits.get<1>());
ASSERT_FALSE(bits.get<2>());
ASSERT_FALSE(bits.get<3>());
ASSERT_FALSE(bits.get<4>());
ASSERT_FALSE(bits.get<5>());
ASSERT_FALSE(bits.get<6>());
}
}
TEST_F(BitArrayTest, TestDynamicMethods) {
bitArray.clear();
{
const Bits bits = bitArray.bits<3, 7>();
ASSERT_FALSE(bits);
ASSERT_FALSE(bits.get(0));
ASSERT_FALSE(bits.get(1));
ASSERT_FALSE(bits.get(2));
ASSERT_FALSE(bits.get(3));
ASSERT_FALSE(bits.get(4));
ASSERT_FALSE(bits.get(5));
ASSERT_FALSE(bits.get(6));
}
{
Bits bits = bitArray.bits<3, 7>();
bits.set(4);
}
{
const Bits bits = bitArray.bits<2, 13>();
ASSERT_FALSE(bits.get(0));
ASSERT_FALSE(bits.get(1));
ASSERT_FALSE(bits.get(2));
ASSERT_FALSE(bits.get(3));
ASSERT_FALSE(bits.get(4));
ASSERT_FALSE(bits.get(5));
ASSERT_FALSE(bits.get(6));
ASSERT_FALSE(bits.get(7));
ASSERT_FALSE(bits.get(8));
ASSERT_FALSE(bits.get(9));
ASSERT_FALSE(bits.get(10));
ASSERT_FALSE(bits.get(11));
ASSERT_TRUE(bits.get(12));
}
{
Bits bits = bitArray.bits<2, 13>();
bits.reset(12);
}
{
const Bits bits = bitArray.bits<3, 7>();
ASSERT_FALSE(bits);
ASSERT_FALSE(bits.get(0));
ASSERT_FALSE(bits.get(1));
ASSERT_FALSE(bits.get(2));
ASSERT_FALSE(bits.get(3));
ASSERT_FALSE(bits.get(4));
ASSERT_FALSE(bits.get(5));
ASSERT_FALSE(bits.get(6));
}
}
} // namespace test
} // namespace kerfuffle
#pragma clang dianostic pop | 21.41958 | 71 | 0.618022 | GameVTeam |
68a46d0d888a3945757d43dc6a3ccbe16b9359aa | 2,792 | cpp | C++ | src/network/debug_client.cpp | ybbhwxfj/block-db | 2482ff6631184ecbc6329db97a2c0f8e19a6711f | [
"Apache-2.0"
] | null | null | null | src/network/debug_client.cpp | ybbhwxfj/block-db | 2482ff6631184ecbc6329db97a2c0f8e19a6711f | [
"Apache-2.0"
] | null | null | null | src/network/debug_client.cpp | ybbhwxfj/block-db | 2482ff6631184ecbc6329db97a2c0f8e19a6711f | [
"Apache-2.0"
] | 1 | 2021-12-28T02:25:34.000Z | 2021-12-28T02:25:34.000Z | #include "network/debug_client.h"
//
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/boostorg/beast
//
//------------------------------------------------------------------------------
//
// Example: HTTP client, synchronous
//
//------------------------------------------------------------------------------
//[example_http_client
#include <boost/beast/core.hpp>
#include <boost/beast/http.hpp>
#include <boost/beast/version.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <cstdlib>
#include <iostream>
#include <string>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
// Performs an HTTP GET and prints the response
int debug_request(
const std::string &address,
uint16_t port,
const std::string &path, std::ostream &os) {
try {
int version = 11;
// The io_context is required for all I/O
net::io_context ioc;
// These objects perform our I/O
tcp::resolver resolver(ioc);
beast::tcp_stream stream(ioc);
// Look up the domain name
auto const results = resolver.resolve(address, std::to_string(port));
// Make the connection on the IP address we get from a lookup
stream.connect(results);
// Set up an HTTP GET request message
http::request<http::string_body> req{http::verb::get, path, version};
req.set(http::field::host, address);
req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
// Send the HTTP request to the remote host
http::write(stream, req);
// This buffer is used for reading and must be persisted
beast::flat_buffer buffer;
// Declare a container to hold the response
http::response<http::dynamic_body> res;
// Receive the HTTP response
http::read(stream, buffer, res);
// Write the message body to stream
os << beast::buffers_to_string(res.body().data());
// Gracefully close the socket
beast::error_code ec;
stream.socket().shutdown(tcp::socket::shutdown_both, ec);
// not_connected happens sometimes
// so don't bother reporting it.
//
if (ec && ec != beast::errc::not_connected)
throw beast::system_error{ec};
// If we get here then the connection is closed gracefully
}
catch (std::exception const &e) {
std::cerr << "Error: " << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//] | 28.783505 | 80 | 0.633596 | ybbhwxfj |
68a624183ed70e0d0f013c3facd7212d202f089b | 760 | cpp | C++ | src/JsonReplyWrapper.cpp | StudDev/poszhalusta_primite_proekt | 90220821392fa019c461cfd480f6ec454643f54e | [
"Apache-2.0"
] | null | null | null | src/JsonReplyWrapper.cpp | StudDev/poszhalusta_primite_proekt | 90220821392fa019c461cfd480f6ec454643f54e | [
"Apache-2.0"
] | 1 | 2020-06-29T21:19:08.000Z | 2020-06-29T21:19:08.000Z | src/JsonReplyWrapper.cpp | oleggator/yandex_disk_gui | 90220821392fa019c461cfd480f6ec454643f54e | [
"Apache-2.0"
] | null | null | null | #include <QtCore/QJsonDocument>
#include "JsonReplyWrapper.h"
JsonReplyWrapper::JsonReplyWrapper(QObject *parent)
: ReplyWrapper{parent} {
}
//TODO: check reply for nullptr
JsonReplyWrapper::JsonReplyWrapper(QNetworkReply *reply, QObject *parent)
: ReplyWrapper{reply, parent} {
}
JsonReplyWrapper::~JsonReplyWrapper() {
_reply->deleteLater();
}
const QJsonObject &JsonReplyWrapper::getJsonResponse() const {
return _jsonResponse;
}
bool JsonReplyWrapper::isError() const {
return _jsonResponse["error"].isNull() || getReply()->error();
}
void JsonReplyWrapper::handleFinishedReply() {
QJsonDocument doc = QJsonDocument::fromJson(getReply()->readAll());
_jsonResponse = doc.object();
emit jsonReply(_jsonResponse);
_reply->close();
}
| 23.030303 | 73 | 0.747368 | StudDev |
68a86ca46d7d640778a8dbe07a717774f55916b8 | 769 | cpp | C++ | sources/world/render/private/texture_single_component.cpp | suVrik/hooker.galore | 616e2692d7afab24b70bfb6aa14ad780eb7c451d | [
"MIT"
] | 4 | 2019-09-14T09:18:47.000Z | 2022-01-29T02:47:00.000Z | sources/world/render/private/texture_single_component.cpp | suVrik/hooker.galore | 616e2692d7afab24b70bfb6aa14ad780eb7c451d | [
"MIT"
] | null | null | null | sources/world/render/private/texture_single_component.cpp | suVrik/hooker.galore | 616e2692d7afab24b70bfb6aa14ad780eb7c451d | [
"MIT"
] | 1 | 2020-03-25T14:41:17.000Z | 2020-03-25T14:41:17.000Z | #include "world/render/texture_single_component.h"
#include <ghc/filesystem.hpp>
namespace hg {
const Texture& TextureSingleComponent::get(const std::string& name) const {
const std::string normalized_name = ghc::filesystem::path(name).lexically_normal().string();
if (auto result = m_textures.find(normalized_name); result != m_textures.end()) {
return result->second;
}
return m_default_texture;
}
const Texture* TextureSingleComponent::get_if(const std::string& name) const {
const std::string normalized_name = ghc::filesystem::path(name).lexically_normal().string();
if (auto result = m_textures.find(normalized_name); result != m_textures.end()) {
return &result->second;
}
return nullptr;
}
} // namespace hg
| 32.041667 | 96 | 0.711313 | suVrik |
68a8bab4b36791674841c15d443caa8deb5788b5 | 802 | cpp | C++ | C++/k-concatenation-maximum-sum.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 3,269 | 2018-10-12T01:29:40.000Z | 2022-03-31T17:58:41.000Z | C++/k-concatenation-maximum-sum.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 53 | 2018-12-16T22:54:20.000Z | 2022-02-25T08:31:20.000Z | C++/k-concatenation-maximum-sum.cpp | jaiskid/LeetCode-Solutions | a8075fd69087c5463f02d74e6cea2488fdd4efd1 | [
"MIT"
] | 1,236 | 2018-10-12T02:51:40.000Z | 2022-03-30T13:30:37.000Z | // Time: O(n)
// Space: O(1)
class Solution {
public:
int kConcatenationMaxSum(vector<int>& arr, int k) {
static const int MOD = 1e9 + 7;
if (k == 1) {
return max(maxSubKArray(arr, 1), 0) % MOD;
}
return (max(maxSubKArray(arr, 2), 0) +
(k - 2) * max(accumulate(arr.cbegin(), arr.cend(), 0ll), 0ll)) % MOD;
}
private:
int maxSubKArray(const vector<int>& nums, int k) {
int result = numeric_limits<int>::min();
int curr = numeric_limits<int>::min();
for (int i = 0; i < k; ++i) {
for (const auto& x : nums) {
curr = (curr == numeric_limits<int>::min()) ? x : max(curr + x, x);
result = max(result, curr);
}
}
return result;
}
};
| 28.642857 | 85 | 0.483791 | jaiskid |
68abd9626dc12b02b511e6a67700efa351f569f8 | 8,608 | cpp | C++ | src/MacierzKw.cpp | MarutTomasz/ZadanieUkladRownan | 5c488f5949b412053a0d59a5fc6bced461b7f711 | [
"MIT"
] | null | null | null | src/MacierzKw.cpp | MarutTomasz/ZadanieUkladRownan | 5c488f5949b412053a0d59a5fc6bced461b7f711 | [
"MIT"
] | null | null | null | src/MacierzKw.cpp | MarutTomasz/ZadanieUkladRownan | 5c488f5949b412053a0d59a5fc6bced461b7f711 | [
"MIT"
] | null | null | null | #include "MacierzKw.hh"
/********** SET I GET **********/
Wektor & MacierzKw::operator[] (int index) {
if (index < 0 || index >= ROZMIAR) {
cerr << "Poza zakresem" << endl;
exit(1);
}
return tab[index];
}
const Wektor & MacierzKw::operator[] (int index) const {
if (index < 0 || index >= ROZMIAR) {
cerr << "Poza zakresem" << endl;
exit(1);
}
return tab[index];
}
/********** KONSTRUKTORY **********/
MacierzKw::MacierzKw() {
Wektor W;
for (int i=0; i < ROZMIAR; i++)
tab[i] = W;
}
MacierzKw::MacierzKw(Wektor A, Wektor B, Wektor C) {
tab[0] = A;
tab[1] = B;
tab[2] = C;
}
/********** WCZYTYWANIE I WYSWIETLANIE **********/
std::istream & operator >> (std::istream &strm, MacierzKw &M) {
for (int i=0; i < ROZMIAR; i++)
cin >> M[i];
M.transponuj();
return strm;
}
std::ostream & operator << (std::ostream &strm, const MacierzKw &M) {
for (int i=0; i < ROZMIAR; i++)
cout << M[i] << endl;
return strm;
}
/********** OPERACJE MATEMATYCZNE **********/
MacierzKw MacierzKw::operator + (const MacierzKw &M) const {
MacierzKw Wynik;
for (int i=0; i < ROZMIAR; i++)
Wynik [i] = tab[i] + M[i];
return Wynik;
}
MacierzKw MacierzKw::operator - (const MacierzKw &M) const {
MacierzKw Wynik;
for (int i=0; i < ROZMIAR; i++)
Wynik [i] = tab[i] - M[i];
return Wynik;
}
MacierzKw MacierzKw::operator *(const MacierzKw &M) const {
MacierzKw Wynik;
MacierzKw KopiaM = M;
KopiaM.transponuj();
for (int i=0; i < ROZMIAR; i++)
for (int j=0; j < ROZMIAR; j++)
Wynik[i][j] = tab[i] * KopiaM[j];
return Wynik;
}
MacierzKw MacierzKw::operator *(double liczba) const {
MacierzKw Wynik;
for (int i=0; i < ROZMIAR; i++)
Wynik[i] = tab[i] * liczba;
return Wynik;
}
Wektor MacierzKw::operator *(const Wektor &W) const {
Wektor Wynik;
for (int i=0; i < ROZMIAR; i++)
Wynik[i] = tab[i] * W;
return Wynik;
}
MacierzKw operator *(double liczba, const MacierzKw &M) {
MacierzKw Wynik;
for (int i=0; i < ROZMIAR; i++)
Wynik[i] = M[i] * liczba;
return Wynik;
}
/********** OPERACJE POROWNANIA **********/
bool MacierzKw::operator == (const MacierzKw &M) const {
double epsilon = 0.000001;
for (int i=0; i < ROZMIAR; i++)
for (int j=0; j < ROZMIAR; j++)
if(abs(tab[i][j] - M[i][j]) > epsilon)
return false;
return true;
}
bool MacierzKw::operator != (const MacierzKw &M) const {
if( *this == M)
return false;
return true;
}
/********** METODY MACIERZOWE **********/
// Zamiana miejscami dwoch wybranych wierszy macierzy
void MacierzKw::przestaw_wiersze(int index1, int index2) {
if (index1 < 0 || index1 >= ROZMIAR) {
cerr << "Poza zakresem" << endl;
exit(1);
}
if (index2 < 0 || index2 >= ROZMIAR) {
cerr << "Poza zakresem" << endl;
exit(1);
}
Wektor pomocniczy = tab[index1];
tab[index1] = tab[index2];
tab[index2] = pomocniczy;
}
// Zamiana miejscami dwoch wybranych kolumn macierzy
void MacierzKw::przestaw_kolumny(int index1, int index2) {
(*this).transponuj();
(*this).przestaw_wiersze(index1,index2);
(*this).transponuj();
}
// Metoda pozwalajaca na transponowanie macierzy
void MacierzKw::transponuj() {
MacierzKw Kopia = (*this);
for (int i=0; i < ROZMIAR; i++)
for (int j=0; j < ROZMIAR; j++)
tab[j][i] = Kopia[i][j];
}
// Metoda pozwalajaca na oblicznie wyznacznikow roznymi metodami
double MacierzKw::wyznacznik(Wyz_Metoda metoda) const {
double wyznacznik;
MacierzKw P = *this;
switch(metoda){
case Gauss: {
int k;
double epsilon = 0.000000001;
int zmian_miejsc = 1;
wyznacznik = 1;
for(int i=0; i < ROZMIAR; i ++){
k = i+1;
while(abs(P[i][i]) < epsilon){ // Uzyskiwanie wartosci roznej od 0
if(k >= ROZMIAR) // na przekatnej macierzy kwadratowej
return 0;
P.przestaw_wiersze(i,k++);
zmian_miejsc *= -1;
}
wyznacznik = wyznacznik * P[i][i];
P[i] = P[i] / P[i][i];
for(int j=i+1; j < ROZMIAR; j++){ // Zerowanie elementow
P[j] = P[j] - (P[i] * P[j][i]); // pod przekatna
}
}
wyznacznik *= zmian_miejsc;
return wyznacznik;
}
case Sarrus: {
wyznacznik = 0;
wyznacznik = P[0][0]*P[1][1]*P[2][2] + P[0][1]*P[1][2]*P[2][0]\
+ P[0][2]*P[1][0]*P[2][1] - P[2][0]*P[1][1]*P[0][2]\
- P[2][1]*P[1][2]*P[0][0] - P[2][2]*P[1][0]*P[0][1];
return wyznacznik;
}
case Laplace: { // prowizorka dla 3x3
double wyznacznik = 0;
wyznacznik += tab[0][0] * (*this).wyznacznik2_2(0,0);
wyznacznik -= tab[0][1] * (*this).wyznacznik2_2(0,1);
wyznacznik += tab[0][2] * (*this).wyznacznik2_2(0,2);
return wyznacznik;
}
}
return 0;
}
double MacierzKw::wyznacznik2_2(int index1, int index2) const{ // prowizorka dla 3x3
double wyznacznik;
if (index1 < 0 || index1 >= ROZMIAR) {
cerr << "Poza zakresem" << endl;
exit(1);
}
if (index2 < 0 || index2 >= ROZMIAR) {
cerr << "Poza zakresem" << endl;
exit(1);
}
switch(index1) {
case 0: {
switch(index2) {
case 0: {
wyznacznik = tab[1][1] * tab[2][2] - tab[2][1] * tab[1][2];
return wyznacznik;
}
case 1: {
wyznacznik = tab[1][0] * tab[2][2] - tab[2][0] * tab[1][2];
return wyznacznik;
}
case 2: {
wyznacznik = tab[1][0] * tab[2][1] - tab[2][0] * tab[1][1];
return wyznacznik;
}
}
}
case 1:{
switch(index2) {
case 0: {
wyznacznik = tab[0][1] * tab[2][2] - tab[2][1] * tab[0][2];
return wyznacznik;
}
case 1: {
wyznacznik = tab[0][0] * tab[2][2] - tab[2][0] * tab[0][2];
return wyznacznik;
}
case 2: {
wyznacznik = tab[0][0] * tab[2][1] - tab[2][0] * tab[0][1];
return wyznacznik;
}
}
}
case 2: {
switch(index2) {
case 0: {
wyznacznik = tab[0][1] * tab[1][2] - tab[1][1] * tab[0][2];
return wyznacznik;
}
case 1: {
wyznacznik = tab[0][0] * tab[1][2] - tab[1][0] * tab[0][2];
return wyznacznik;
}
case 2: {
wyznacznik = tab[0][0] * tab[1][1] - tab[1][0] * tab[0][1];
return wyznacznik;
}
}
}
}
return 0;
}
// Funkcja pozwalajaca na utworzenie macierzy jednostkowej
MacierzKw MacierzJednostkowa() {
MacierzKw M;
for (int i=0; i < ROZMIAR; i++)
for (int j=0; j < ROZMIAR; j++)
if (i == j)
M[i][j] = 1;
return M;
}
MacierzKw MacierzKw::macierz_dopelnien () const{ // prowizorka dla 3x3
MacierzKw Dopelnien;
double znak = 1;
for (int i=0; i < ROZMIAR; i++)
for (int j=0; j < ROZMIAR; j++) {
Dopelnien[i][j] = (*this).wyznacznik2_2(i,j) * znak;
znak *= -1;
}
return Dopelnien;
}
MacierzKw MacierzKw::odwroc(Odw_Metoda metoda) const {
switch (metoda) {
case Definicja: { // wykorzystuje prowizorke dla 3x3
double epsilon = 0.000000001;
double wyznacznik;
MacierzKw Odwrotna;
MacierzKw Dopelnien;
wyznacznik = (*this).wyznacznik(Sarrus);
if (abs(wyznacznik) < epsilon){
cerr << "Macierz osobliwa, nieodwracalna" << endl;
exit(1);
}
Dopelnien = (*this).macierz_dopelnien();
Dopelnien.transponuj();
Odwrotna = (1/wyznacznik) * Dopelnien;
return Odwrotna;
}
case Gauss_Jordan: {
MacierzKw Odwrotna = MacierzJednostkowa();
MacierzKw P = *this;
int k;
double epsilon = 0.000000001;
for(int i=0; i < ROZMIAR; i ++){
k = i+1;
while(abs(P[i][i]) < epsilon){ // Uzyskiwanie wartosci roznej od 0
if(k >= ROZMIAR){ // na przekatnej macierzy kwadratowej
cout << "Macierz jest nieodwracalna, bo jest osobliwa" << endl;
exit(1);
}
P.przestaw_wiersze(i,k);
Odwrotna.przestaw_wiersze(i,k);
k++;
}
Odwrotna[i] = Odwrotna[i] / P[i][i];
P[i] = P[i] / P[i][i];
for(int j=i+1; j < ROZMIAR; j++){
Odwrotna[j] = Odwrotna[j] - (Odwrotna[i] * P[j][i]);
P[j] = P[j] - (P[i] * P[j][i]);
}
}
for(int i = ROZMIAR-1; i > 0; i--) {
for(int j=0; j < i; j++){
Odwrotna[j] = Odwrotna[j] - (Odwrotna[i] * P[j][i]);
P[j] = P[j] - (P[i] * P[j][i]);
}
}
return Odwrotna;
}
}
return (*this);
}
void MacierzKw::zmien_wiersz(int index, const Wektor W) {
if (index < 0 || index >= ROZMIAR) {
cerr << "Poza zakresem" << endl;
exit(1);
}
tab[index] = W;
}
void MacierzKw::zmien_kolumne(int index, const Wektor W) {
if (index < 0 || index >= ROZMIAR) {
cerr << "Poza zakresem" << endl;
exit(1);
}
(*this).transponuj();
tab[index] = W;
(*this).transponuj();
}
| 24.594286 | 84 | 0.554252 | MarutTomasz |
68b487067562f2510307c366f0ab03ee81ccd305 | 3,720 | cpp | C++ | Minesweeper/VoidEngine/Window/Input.cpp | VoidRune/Minesweeper | d36879cc89f4485199cf7000a326f14635305c07 | [
"MIT"
] | null | null | null | Minesweeper/VoidEngine/Window/Input.cpp | VoidRune/Minesweeper | d36879cc89f4485199cf7000a326f14635305c07 | [
"MIT"
] | null | null | null | Minesweeper/VoidEngine/Window/Input.cpp | VoidRune/Minesweeper | d36879cc89f4485199cf7000a326f14635305c07 | [
"MIT"
] | null | null | null | #include "Input.h"
unsigned int Input::keyStates[348];
unsigned int Input::keyPrevStates[348];
unsigned int Input::mouseButtonStates[7];
unsigned int Input::mouseButtonPrevStates[7];
int Input::mouseScrollState[2];
char Input::keyBuffer[8];
char Input::keyBufferIndex = 0;
char Input::keyBufferSearchIndex = 0;
vec2f Input::mousePosition = vec2f(0.0f, 0.0f);
vec2f Input::mouseLastPosition = vec2f(0.0f, 0.0f);
bool Input::mouseHasMoved = false;
int Input::mouseScroll = 0;
Input::Input() { }
Input::~Input() { }
vec2f Input::MousePosition() {
return mousePosition;
}
vec2f Input::MousePosDifference()
{
return { mousePosition.x - mouseLastPosition.x, mousePosition.y - mouseLastPosition.y };
}
bool Input::MouseHasMoved() {
return mouseHasMoved;
}
int Input::MouseDeltaPosition() {
return mouseScroll / 120;
}
bool Input::IsMouseKeyDown(const int& button) {
if (button < 0 || button > 7) return false;
if (mouseButtonStates[button] == true)
return true;
return false;
}
bool Input::IsMouseKeyPressed(const int& button) {
if (button < 0 || button > 7) return false;
if (mouseButtonStates[button] == true && mouseButtonPrevStates[button] == false)
return true;
return false;
}
bool Input::IsLeftMouseKeyDown()
{
if (mouseButtonStates[0] == true)
return true;
return false;
}
bool Input::IsLeftMouseKeyPressed()
{
if (mouseButtonStates[0] == true && mouseButtonPrevStates[0] == false)
return true;
return false;
}
bool Input::IsRightMouseKeyDown()
{
if (mouseButtonStates[1] == true)
return true;
return false;
}
bool Input::IsRightMouseKeyPressed()
{
if (mouseButtonStates[1] == true && mouseButtonPrevStates[1] == false)
return true;
return false;
}
bool Input::IsMouseKeyUp(const int& button) {
if (button < 0 || button > 7) return false;
if (mouseButtonStates[button] == false)
return true;
return false;
}
bool Input::IsMouseKeyReleased(const int& button) {
if (button < 0 || button > 7) return false;
if (mouseButtonStates[button] == false && mouseButtonPrevStates[button] == true)
return true;
return false;
}
bool Input::IsLeftMouseKeyUp()
{
if (mouseButtonStates[0] == false)
return true;
return false;
}
bool Input::IsLeftMouseKeyReleased()
{
if (mouseButtonStates[0] == false && mouseButtonPrevStates[0] == true)
return true;
return false;
}
bool Input::IsRightMouseKeyUp()
{
if (mouseButtonStates[1] == false)
return true;
return false;
}
bool Input::IsRightMouseKeyReleased()
{
if (mouseButtonStates[1] == false && mouseButtonPrevStates[1] == true)
return true;
return false;
}
bool Input::IsKeyDown(const int& key) {
if (key < 0 || key > 348) return false;
if (keyStates[key] == true)
return true;
return false;
}
bool Input::IsKeyPressed(const int& key) {
if (key < 0 || key > 348) return false;
if (keyStates[key] == true && keyPrevStates[key] == false)
return true;
return false;
}
bool Input::getCharInputBuffer(char* c)
{
if (keyBufferIndex - keyBufferSearchIndex > 0)
{
*c = keyBuffer[keyBufferSearchIndex];
keyBufferSearchIndex++;
return true;
}
return false;
}
double Input::GetMouseScroll(Scroll direction) {
return mouseScrollState[(int)direction];
}
void Input::Update() {
// Update keyboard states
for (int i = 0; i < 348; i++)
keyPrevStates[i] = keyStates[i];
// Update mouse states
for (int i = 0; i < 7; i++)
mouseButtonPrevStates[i] = mouseButtonStates[i];
mouseScrollState[0] = 0;
mouseScrollState[1] = 0;
keyBuffer[0] = 0;
keyBuffer[1] = 0;
keyBuffer[2] = 0;
keyBuffer[3] = 0;
keyBuffer[4] = 0;
keyBuffer[5] = 0;
keyBuffer[6] = 0;
keyBuffer[7] = 0;
keyBufferIndex = 0;
keyBufferSearchIndex = 0;
mouseLastPosition = mousePosition;
mouseScroll = 0;
mouseHasMoved = false;
}
| 22.275449 | 89 | 0.702957 | VoidRune |
68ce2d1d9f09620b7b59e03fb85093fee70bb08f | 2,015 | hh | C++ | src/c++/include/grm/KlibAligner.hh | vb-wayne/paragraph | 3f6f6f7a2a3ac209c7dbb21487ca4d9eaed5c14c | [
"Apache-2.0"
] | 111 | 2017-11-24T18:22:50.000Z | 2022-02-25T07:55:31.000Z | src/c++/include/grm/KlibAligner.hh | vb-wayne/paragraph | 3f6f6f7a2a3ac209c7dbb21487ca4d9eaed5c14c | [
"Apache-2.0"
] | 61 | 2018-01-01T19:58:06.000Z | 2022-03-09T12:01:17.000Z | src/c++/include/grm/KlibAligner.hh | vb-wayne/paragraph | 3f6f6f7a2a3ac209c7dbb21487ca4d9eaed5c14c | [
"Apache-2.0"
] | 30 | 2018-03-01T04:41:15.000Z | 2022-03-11T14:52:03.000Z | // -*- mode: c++; indent-tabs-mode: nil; -*-
//
// Paragraph
// Copyright (c) 2016-2019 Illumina, 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
//
//
/**
* \brief KlibAligner interface
*
* \file KlibAligner.hh
* \author Roman Petrovski
* \email rpetrovski@illumina.com
*
*/
#pragma once
#include <list>
#include <memory>
#include <string>
#include "common/Read.hh"
#include "graphcore/Graph.hh"
#include "graphcore/Path.hh"
namespace grm
{
struct KlibAlignerImpl;
/**
* Aligns using Klib local alignment against each path and picks the best
*/
class KlibAligner
{
public:
KlibAligner();
virtual ~KlibAligner();
KlibAligner(KlibAligner&& rhs) noexcept;
KlibAligner& operator=(KlibAligner&& rhs) noexcept;
/**
* Set the graph to align to
* @param g a graph
* @param paths list of paths
*/
void setGraph(graphtools::Graph const* g, std::list<graphtools::Path> const& paths);
/**
* Align a read to the graph and update the graph_* fields.
*
* We will align both the forward and the reverse strand and return
* the alignment which is unique, or with the better score, or default
* to the forward strand.
*
* @param read read structure
*/
void alignRead(common::Read& read);
unsigned attempted() const { return attempted_; }
unsigned mapped() const { return mapped_; }
private:
unsigned attempted_ = 0;
unsigned mapped_ = 0;
std::unique_ptr<KlibAlignerImpl> impl_;
};
}
| 23.430233 | 88 | 0.681886 | vb-wayne |
68cfc2d3343324d47bd400231381fad7f9944d79 | 3,780 | cpp | C++ | Nacro/SDK/FN_JournalObjectiveEntry_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_JournalObjectiveEntry_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2021-08-11T18:40:26.000Z | 2021-08-11T18:40:26.000Z | Nacro/SDK/FN_JournalObjectiveEntry_functions.cpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | // Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function JournalObjectiveEntry.JournalObjectiveEntry_C.Update
// (Public, HasDefaults, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortQuestObjectiveInfo* Objective (Parm, ZeroConstructor, IsPlainOldData)
void UJournalObjectiveEntry_C::Update(class UFortQuestObjectiveInfo* Objective)
{
static auto fn = UObject::FindObject<UFunction>("Function JournalObjectiveEntry.JournalObjectiveEntry_C.Update");
UJournalObjectiveEntry_C_Update_Params params;
params.Objective = Objective;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function JournalObjectiveEntry.JournalObjectiveEntry_C.UpdateProgress
// (Public, BlueprintCallable, BlueprintEvent)
// Parameters:
// class UFortQuestObjectiveInfo* Objective (Parm, ZeroConstructor, IsPlainOldData)
void UJournalObjectiveEntry_C::UpdateProgress(class UFortQuestObjectiveInfo* Objective)
{
static auto fn = UObject::FindObject<UFunction>("Function JournalObjectiveEntry.JournalObjectiveEntry_C.UpdateProgress");
UJournalObjectiveEntry_C_UpdateProgress_Params params;
params.Objective = Objective;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function JournalObjectiveEntry.JournalObjectiveEntry_C.SetData
// (Event, Public, BlueprintEvent)
// Parameters:
// class UObject** InData (Parm, ZeroConstructor, IsPlainOldData)
void UJournalObjectiveEntry_C::SetData(class UObject** InData)
{
static auto fn = UObject::FindObject<UFunction>("Function JournalObjectiveEntry.JournalObjectiveEntry_C.SetData");
UJournalObjectiveEntry_C_SetData_Params params;
params.InData = InData;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function JournalObjectiveEntry.JournalObjectiveEntry_C.Construct
// (BlueprintCosmetic, Event, Public, BlueprintEvent)
void UJournalObjectiveEntry_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function JournalObjectiveEntry.JournalObjectiveEntry_C.Construct");
UJournalObjectiveEntry_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function JournalObjectiveEntry.JournalObjectiveEntry_C.Handle Quests Updated
// (BlueprintCallable, BlueprintEvent)
void UJournalObjectiveEntry_C::Handle_Quests_Updated()
{
static auto fn = UObject::FindObject<UFunction>("Function JournalObjectiveEntry.JournalObjectiveEntry_C.Handle Quests Updated");
UJournalObjectiveEntry_C_Handle_Quests_Updated_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function JournalObjectiveEntry.JournalObjectiveEntry_C.ExecuteUbergraph_JournalObjectiveEntry
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void UJournalObjectiveEntry_C::ExecuteUbergraph_JournalObjectiveEntry(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function JournalObjectiveEntry.JournalObjectiveEntry_C.ExecuteUbergraph_JournalObjectiveEntry");
UJournalObjectiveEntry_C_ExecuteUbergraph_JournalObjectiveEntry_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 28.208955 | 146 | 0.746032 | Milxnor |
68d7af0ebe093d129bbeab993d586055b579f384 | 535 | hpp | C++ | seal-c/encryption_parameters.hpp | lambdageek/sealsharp | 63863f1542ada35d299453cf382f42c7c5544404 | [
"MIT"
] | 3 | 2019-01-07T20:32:13.000Z | 2020-01-19T17:30:58.000Z | seal-c/encryption_parameters.hpp | lambdageek/sealsharp | 63863f1542ada35d299453cf382f42c7c5544404 | [
"MIT"
] | 1 | 2019-01-31T19:15:42.000Z | 2019-01-31T19:15:42.000Z | seal-c/encryption_parameters.hpp | lambdageek/sealsharp | 63863f1542ada35d299453cf382f42c7c5544404 | [
"MIT"
] | null | null | null |
#ifndef _SEAL_C_ENCRYPTION_PARAMETERS_HPP
#define _SEAL_C_ENCRYPTION_PARAMETERS_HPP
#include <seal-c/types.h>
#include <seal/encryptionparams.h>
#include "wrap.hpp"
namespace seal_c {
namespace wrap {
template<>
struct Wrap<seal::EncryptionParameters*> : public WrapPair<seal::EncryptionParameters*, SEALEncryptionParametersRef> {};
template<>
struct Unwrap<SEALEncryptionParametersRef> : public WrapPair<seal::EncryptionParameters*, SEALEncryptionParametersRef> {};
} // namespace wrap
} // namespace seal_c
#endif
| 22.291667 | 124 | 0.781308 | lambdageek |
68e99e0dee0f4bcadbfd18aaadea1f5c7168293b | 4,955 | cpp | C++ | apps/opencs/view/filter/editwidget.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/opencs/view/filter/editwidget.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null | apps/opencs/view/filter/editwidget.cpp | Bodillium/openmw | 5fdd264d0704e33b44b1ccf17ab4fb721f362e34 | [
"Unlicense"
] | null | null | null |
#include "editwidget.hpp"
#include <QAbstractItemModel>
#include <QString>
#include <QApplication>
#include "../../model/world/data.hpp"
CSVFilter::EditWidget::EditWidget (CSMWorld::Data& data, QWidget *parent)
: QLineEdit (parent), mParser (data)
{
mPalette = palette();
connect (this, SIGNAL (textChanged (const QString&)), this, SLOT (textChanged (const QString&)));
QAbstractItemModel *model = data.getTableModel (CSMWorld::UniversalId::Type_Filters);
connect (model, SIGNAL (dataChanged (const QModelIndex &, const QModelIndex&)),
this, SLOT (filterDataChanged (const QModelIndex &, const QModelIndex&)),
Qt::QueuedConnection);
connect (model, SIGNAL (rowsRemoved (const QModelIndex&, int, int)),
this, SLOT (filterRowsRemoved (const QModelIndex&, int, int)),
Qt::QueuedConnection);
connect (model, SIGNAL (rowsInserted (const QModelIndex&, int, int)),
this, SLOT (filterRowsInserted (const QModelIndex&, int, int)),
Qt::QueuedConnection);
}
void CSVFilter::EditWidget::textChanged (const QString& text)
{
if (mParser.parse (text.toUtf8().constData()))
{
setPalette (mPalette);
emit filterChanged (mParser.getFilter());
}
else
{
QPalette palette (mPalette);
palette.setColor (QPalette::Text, Qt::red);
setPalette (palette);
/// \todo improve error reporting; mark only the faulty part
}
}
void CSVFilter::EditWidget::filterDataChanged (const QModelIndex& topLeft,
const QModelIndex& bottomRight)
{
textChanged (text());
}
void CSVFilter::EditWidget::filterRowsRemoved (const QModelIndex& parent, int start, int end)
{
textChanged (text());
}
void CSVFilter::EditWidget::filterRowsInserted (const QModelIndex& parent, int start, int end)
{
textChanged (text());
}
void CSVFilter::EditWidget::createFilterRequest (std::vector< std::pair< std::string, std::vector< std::string > > >& filterSource,
Qt::DropAction action)
{
const unsigned count = filterSource.size();
bool multipleElements = false;
switch (count) //setting multipleElements;
{
case 0: //empty
return; //nothing to do here
case 1: //only single
multipleElements = false;
break;
default:
multipleElements = true;
break;
}
Qt::KeyboardModifiers key = QApplication::keyboardModifiers();
QString oldContent (text());
bool replaceMode = false;
std::string orAnd;
switch (key) //setting replaceMode and string used to glue expressions
{
case Qt::ShiftModifier:
orAnd = "!or(";
replaceMode = false;
break;
case Qt::ControlModifier:
orAnd = "!and(";
replaceMode = false;
break;
default:
replaceMode = true;
break;
}
if (oldContent.isEmpty() || !oldContent.contains (QRegExp ("^!.*$", Qt::CaseInsensitive))) //if line edit is empty or it does not contain one shot filter go into replace mode
{
replaceMode = true;
}
if (!replaceMode)
{
oldContent.remove ('!');
}
std::stringstream ss;
if (multipleElements)
{
if (replaceMode)
{
ss<<"!or(";
} else {
ss << orAnd << oldContent.toUtf8().constData() << ',';
}
for (unsigned i = 0; i < count; ++i)
{
ss<<generateFilter (filterSource[i]);
if (i+1 != count)
{
ss<<", ";
}
}
ss<<')';
} else {
if (!replaceMode)
{
ss << orAnd << oldContent.toUtf8().constData() <<',';
} else {
ss<<'!';
}
ss << generateFilter (filterSource[0]);
if (!replaceMode)
{
ss<<')';
}
}
if (ss.str().length() >4)
{
clear();
insert (QString::fromUtf8(ss.str().c_str()));
}
}
std::string CSVFilter::EditWidget::generateFilter (std::pair< std::string, std::vector< std::string > >& seekedString) const
{
const unsigned columns = seekedString.second.size();
bool multipleColumns = false;
switch (columns)
{
case 0: //empty
return ""; //no column to filter
case 1: //one column to look for
multipleColumns = false;
break;
default:
multipleColumns = true;
break;
}
std::stringstream ss;
if (multipleColumns)
{
ss<<"or(";
for (unsigned i = 0; i < columns; ++i)
{
ss<<"string("<<'"'<<seekedString.second[i]<<'"'<<','<<'"'<<seekedString.first<<'"'<<')';
if (i+1 != columns)
ss<<',';
}
ss<<')';
} else {
ss<<"string"<<'('<<'"'<<seekedString.second[0]<<"\","<<'"'<<seekedString.first<<"\")";
}
return ss.str();
} | 25.280612 | 178 | 0.56226 | Bodillium |
68ebae7a9ea3f98702161aa2d6384fa7aa4ca3b1 | 284 | hpp | C++ | src/isle/cpp/species.hpp | chelseajohn/isle | f610b55a1e8b6d2584896eb649092b0524cc1f8c | [
"MIT"
] | 2 | 2021-01-14T17:47:01.000Z | 2021-07-16T22:31:25.000Z | src/isle/cpp/species.hpp | chelseajohn/isle | f610b55a1e8b6d2584896eb649092b0524cc1f8c | [
"MIT"
] | 21 | 2018-06-04T07:09:02.000Z | 2020-12-11T09:37:08.000Z | src/isle/cpp/species.hpp | chelseajohn/isle | f610b55a1e8b6d2584896eb649092b0524cc1f8c | [
"MIT"
] | 3 | 2021-01-18T19:18:29.000Z | 2021-03-26T03:27:15.000Z | /** \file
* \brief Enum Species.
*/
#ifndef SPECIES_HPP
#define SPECIES_HPP
namespace isle {
/// Mark particles and holes.
enum class Species {
PARTICLE, ///< 'Normal' particles.
HOLE ///< Anti-particlces, or holes.
};
}
#endif // ndef SPECIES_HPP
| 16.705882 | 45 | 0.605634 | chelseajohn |
1900777a9d7512fe526668ea659dbe4fd5966b91 | 4,070 | cpp | C++ | opengl-gui/src/Util.cpp | ChewyGumball/opengl_gui | b2bd1803f0cfb01db08c88da5091546076dfc2a3 | [
"MIT"
] | 2 | 2019-08-27T00:37:11.000Z | 2021-11-25T14:34:23.000Z | opengl-gui/src/Util.cpp | ChewyGumball/opengl_gui | b2bd1803f0cfb01db08c88da5091546076dfc2a3 | [
"MIT"
] | null | null | null | opengl-gui/src/Util.cpp | ChewyGumball/opengl_gui | b2bd1803f0cfb01db08c88da5091546076dfc2a3 | [
"MIT"
] | 2 | 2018-10-18T12:12:28.000Z | 2019-08-27T00:36:21.000Z | #include <string>
#include <vector>
#include <iostream>
#include <memory>
#include "Util.h"
namespace OpenGLGUI::Util {
Shader::Shader(const std::string &source, GLuint shaderType)
{
shaderID = glCreateShader(shaderType);
const GLchar *shaderSource = source.c_str();
glShaderSource(shaderID, 1, &shaderSource, 0);
glCompileShader(shaderID);
GLint isCompiled = 0;
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &isCompiled);
if (isCompiled == GL_FALSE)
{
GLint maxLength = 0;
glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &maxLength);
//The maxLength includes the NULL character
std::vector<GLchar> infoLog(maxLength);
glGetShaderInfoLog(shaderID, maxLength, &maxLength, &infoLog[0]);
//Don't leave garbage
glDeleteShader(shaderID);
//print out the error
std::cout << std::string(infoLog.begin(), infoLog.end());
//In this simple program, we'll just leave
shaderID = 0;
}
}
Shader::~Shader() {
if (shaderID != 0) {
glDeleteShader(shaderID);
}
}
ShaderProgram::ShaderProgram(const std::vector<std::shared_ptr<Shader>> &shaders)
{
shaderProgramID = glCreateProgram();
for (std::shared_ptr<Shader> s : shaders)
{
glAttachShader(shaderProgramID, s->ID());
}
glLinkProgram(shaderProgramID);
GLint isLinked = 0;
glGetProgramiv(shaderProgramID, GL_LINK_STATUS, &isLinked);
if (!isLinked) {
GLint maxLength = 0;
glGetProgramiv(shaderProgramID, GL_INFO_LOG_LENGTH, &maxLength);
//The maxLength includes the NULL character
std::vector<GLchar> infoLog(maxLength);
glGetProgramInfoLog(shaderProgramID, maxLength, &maxLength, &infoLog[0]);
//Don't leave garbage
glDeleteProgram(shaderProgramID);
//print out the error
std::cout << std::string(infoLog.begin(), infoLog.end());
//In this simple program, we'll just leave
shaderProgramID = 0;
}
}
ShaderProgram::~ShaderProgram() {
if (shaderProgramID != 0) {
glDeleteProgram(shaderProgramID);
}
}
void ShaderProgram::setUniform2f(const std::string &uniformName, glm::vec2 data)
{
GLint location = glGetUniformLocation(shaderProgramID, uniformName.c_str());
if (location == -1)
{
std::cout << "Could not find uniform '" << uniformName << "' in shader!" << std::endl;
return;
}
glUniform2f(location, data.x, data.y);
}
void ShaderProgram::setUniform3f(const std::string &uniformName, glm::vec3 data)
{
GLint location = glGetUniformLocation(shaderProgramID, uniformName.c_str());
if (location == -1)
{
std::cout << "Could not find uniform '" << uniformName << "' in shader!" << std::endl;
return;
}
glUniform3f(location, data.x, data.y, data.z);
}
void ShaderProgram::setUniform4f(const std::string &uniformName, glm::vec4 data)
{
GLint location = glGetUniformLocation(shaderProgramID, uniformName.c_str());
if (location == -1)
{
std::cout << "Could not find uniform '" << uniformName << "' in shader!" << std::endl;
return;
}
glUniform4f(location, data.x, data.y, data.z, data.w);
}
Texture::Texture(std::vector<unsigned char> bytes, int width, int height, GLuint inputFormat, GLuint storageFormat)
{
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
//Load image data
glTexImage2D(GL_TEXTURE_2D, 0, inputFormat, width, height, 0, storageFormat, GL_UNSIGNED_BYTE, bytes.data());
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture::Texture(std::string filename, int width, int height, GLuint inputFormat, GLuint storageFormat)
{
//Read image data
const unsigned char *imageData;
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
//Load image data
glTexImage2D(GL_TEXTURE_2D, 0, inputFormat, width, height, 0, storageFormat, GL_UNSIGNED_BYTE, imageData);
glBindTexture(GL_TEXTURE_2D, 0);
//delete image data
}
Util::Texture::~Texture()
{
glDeleteTextures(1, &textureID);
}
void Util::Texture::bind(GLuint textureUnit)
{
glActiveTexture(textureUnit); // Activate the texture unit first before binding texture
glBindTexture(GL_TEXTURE_2D, textureID);
}
}
| 26.601307 | 116 | 0.705405 | ChewyGumball |
190124c1ff440ef0b7e2f47bf656b2d9d5f0c59a | 3,649 | cpp | C++ | graph-source-code/131-D/12520672.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/131-D/12520672.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | graph-source-code/131-D/12520672.cpp | AmrARaouf/algorithm-detection | 59f3028d2298804870b32729415d71eec6116557 | [
"MIT"
] | null | null | null | //Language: GNU C++
#include <bits/stdc++.h>
#define SZ(X) ((int)(X).size())
#define ALL(X) (X).begin(), (X).end()
#define REP(I, N) for (int I = 0; I < (N); ++I)
#define REPP(I, A, B) for (int I = (A); I < (B); ++I)
#define PER(I, N) for (int I = (N); I >= 0; --I)
#define PERR(I, A, B) for (int I = (A); I >= B; --I)
#define ITR(I, A) for (__typeof((A).begin()) I=(A).begin(), _##i=(A).end(); I!=_##i; ++I)
#define RI(X) scanf("%d", &(X))
#define RII(X, Y) scanf("%d%d", &(X), &(Y))
#define RIII(X, Y, Z) scanf("%d%d%d", &(X), &(Y), &(Z))
#define DRI(X) int (X); scanf("%d", &X)
#define DRII(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define DRIII(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define RS(X) scanf("%s", (X))
#define CASET int ___T, case_n = 1; scanf("%d ", &___T); while (___T-- > 0)
#define MP make_pair
#define PB push_back
#define MS0(X) memset((X), 0, sizeof((X)))
#define MS1(X) memset((X), -1, sizeof((X)))
#define LEN(X) strlen(X)
#define PII pair<int,int>
#define VPII vector<pair<int,int> >
#define PLL pair<long long,long long>
#define F first
#define S second
#define LB(X) __builtin_ctz((X))
#define ONES(X) __builtin_popcount((X))
typedef long long LL;
using namespace std;
template <class T> inline void smax(T &x,T y){ x = max((x), (y));}
template <class T> inline void smin(T &x,T y){ x = min((x), (y));}
const int MOD = 1e9+7;
const int SIZE = 3000+10;
#define LOCALTEST 0 // change this to 1 to perform localtest on "in.txt"
int n;
vector<vector<int> > g;
int tim, dfslow[SIZE], dfscur[SIZE], was[SIZE], sccmade[SIZE];
vector<vector<int> > scc;
int cmp[SIZE];
int di[SIZE];
stack<int> st;
int onstack[SIZE];
void dfs(int u, int p) {
if (dfscur[u] != -1) return;
dfscur[u] = dfslow[u] = tim++;
onstack[u] = 1;
st.push(u);
REP(i,SZ(g[u])) {
int v = g[u][i];
if (v == p) continue;
if (dfscur[v] == -1) {
dfs(v, u);
smin(dfslow[u], dfslow[v]);
} else if (onstack[v]) {
smin(dfslow[u], dfscur[v]);
}
}
if (dfscur[u] == dfslow[u]) {
scc.PB(vector<int>());
while (!st.empty()) {
int tp = st.top();
st.pop();
cmp[tp] = SZ(scc)-1;
scc[SZ(scc)-1].PB(tp);
onstack[tp] = 0;
if (tp == u) break;
}
}
}
void dijkstra(int ring) {
set<PII> q;
REP(i,SZ(scc[ring])) q.insert(MP(0,scc[ring][i]));
MS0(was); memset(di, 0x3f3f3f3f, sizeof(di));
while (!q.empty()) {
PII f = *q.begin();
q.erase(q.begin());
int w = f.F, u = f.S;
if (was[u] || di[u] <= w) continue;
was[u] = 1;
di[u] = w;
REP(i,SZ(g[u])) {
int v = g[u][i];
q.insert(MP(di[u] + 1, v));
}
}
}
int main(){
if (LOCALTEST) {
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
}
while (RI(n) == 1) {
g.clear();
g.resize(n);
REP(i,n) {
DRII(x,y);
x--,y--;
g[x].PB(y); g[y].PB(x);
}
tim = 0; MS1(dfslow); MS1(dfscur); MS0(onstack); scc.clear();
REP(i,n) dfs(i,-1);
int ring = -1;
REP(i,SZ(scc)) {
//printf("scc %d: ",i);
//REP(j,SZ(scc[i])) printf("%d%c",scc[i][j],j==SZ(scc[i])-1?'\n':' ');
if (SZ(scc[i]) > 1) ring = i;
}
dijkstra(ring);
REP(i,n) {
printf("%d%c",di[i],i==n-1?'\n':' ');
}
}
return 0;
}
| 29.192 | 90 | 0.46177 | AmrARaouf |
1906c547679c2fc218a1ab339e3979cbd5ae2821 | 1,316 | cpp | C++ | avs_dx/DxVisuals/Interop/msvcrt.cpp | Const-me/vis_avs_dx | da1fd9f4323d7891dea233147e6ae16790ad9ada | [
"MIT"
] | 33 | 2019-01-28T03:32:17.000Z | 2022-02-12T18:17:26.000Z | avs_dx/DxVisuals/Interop/msvcrt.cpp | visbot/vis_avs_dx | 03e55f8932a97ad845ff223d3602ff2300c3d1d4 | [
"MIT"
] | 2 | 2019-11-18T17:54:58.000Z | 2020-07-21T18:11:21.000Z | avs_dx/DxVisuals/Interop/msvcrt.cpp | Const-me/vis_avs_dx | da1fd9f4323d7891dea233147e6ae16790ad9ada | [
"MIT"
] | 5 | 2019-02-16T23:00:11.000Z | 2022-03-27T15:22:10.000Z | #include "stdafx.h"
#include "msvcrt.h"
namespace msvcrt
{
class Dll
{
HMODULE hm = nullptr;
template<class T>
inline bool getProc( T& fn, const char* lpProcName )
{
fn = (T)GetProcAddress( hm, lpProcName );
if( nullptr == fn )
{
char buff[ 64 ];
sprintf_s( buff, "%s not found in msvcrt.dll\n", lpProcName );
OutputDebugStringA( buff );
return false;
}
return true;
}
public:
Dll()
{
hm = LoadLibraryA( "msvcrt.dll" );
if( nullptr == hm )
{
const HRESULT hr = getLastHr();
char buff[ 64 ];
sprintf_s( buff, "msvcrt.dll wasn't loaded, error 0x%08X\n", hr );
OutputDebugStringA( buff );
return;
}
getProc( fnNew, "??2@YAPAXI@Z" );
getProc( fnDelete, "??3@YAXPAX@Z" );
}
bool startup() const
{
return hm && fnNew && fnDelete;
}
~Dll()
{
fnNew = nullptr;
fnDelete = nullptr;
if( hm )
{
FreeLibrary( hm );
hm = nullptr;
}
}
void* ( __cdecl *fnNew )( size_t size ) = nullptr;
void( __cdecl *fnDelete )( void* ptr ) = nullptr;
};
const Dll& dll()
{
static const Dll s_dll;
return s_dll;
}
void* operatorNew( size_t size )
{
return dll().fnNew( size );
}
void operatorDelete( void* ptr )
{
dll().fnDelete( ptr );
}
bool startup()
{
return dll().startup();
}
}; | 16.45 | 70 | 0.576748 | Const-me |
190ac5c103ab3c4871fe0e316aa67603f9528de2 | 496 | cpp | C++ | hackerearth_grind/practice/basic_programming/implementation/a_special_number.cpp | soumyankar/CompetitiveCoding | c49b02cd86212415a1aa221f0496ec3a467d128d | [
"Apache-2.0"
] | null | null | null | hackerearth_grind/practice/basic_programming/implementation/a_special_number.cpp | soumyankar/CompetitiveCoding | c49b02cd86212415a1aa221f0496ec3a467d128d | [
"Apache-2.0"
] | null | null | null | hackerearth_grind/practice/basic_programming/implementation/a_special_number.cpp | soumyankar/CompetitiveCoding | c49b02cd86212415a1aa221f0496ec3a467d128d | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
long long int sumOfDigits(int n)
{
long long int ans=0;
while(n!=0)
{
ans+=n%10;
n/=10;
}
return ans;
}
int main()
{
int t;
cin >> t;
while(t--!=0)
{
long long int n,flag,i;
cin >> n;
for(i=n; ;i++)
{
flag = sumOfDigits(i) % 4;
if(flag == 0)
{
cout << i << "\n";
break;
}
}
}
} | 15.030303 | 38 | 0.366935 | soumyankar |
19122d2c70ff133b0c10f1a6e8e2af83b51fff18 | 1,273 | cpp | C++ | src/convection/incflo_godunov_ppm.cpp | michaeljbrazell/amr-wind | 97ca5242399103e0ed91bef318ab02f69a3166d6 | [
"BSD-3-Clause"
] | null | null | null | src/convection/incflo_godunov_ppm.cpp | michaeljbrazell/amr-wind | 97ca5242399103e0ed91bef318ab02f69a3166d6 | [
"BSD-3-Clause"
] | null | null | null | src/convection/incflo_godunov_ppm.cpp | michaeljbrazell/amr-wind | 97ca5242399103e0ed91bef318ab02f69a3166d6 | [
"BSD-3-Clause"
] | null | null | null | #include <incflo_godunov_ppm.H>
#include <incflo.H>
using namespace amrex;
void incflo::predict_ppm (int lev, Box const& bx, int ncomp,
Array4<Real> const& Imx,
Array4<Real> const& Ipx,
Array4<Real> const& Imy,
Array4<Real> const& Ipy,
Array4<Real> const& Imz,
Array4<Real> const& Ipz,
Array4<Real const> const& q,
Array4<Real const> const& vel)
{
const auto dx = Geom(lev).CellSizeArray();
const Box& domain = Geom(lev).Domain();
const Dim3 dlo = amrex::lbound(domain);
const Dim3 dhi = amrex::ubound(domain);
Real l_dtdx = m_dt / dx[0];
Real l_dtdy = m_dt / dx[1];
Real l_dtdz = m_dt / dx[2];
BCRec const* pbc = get_velocity_bcrec_device_ptr();
amrex::ParallelFor(bx, AMREX_SPACEDIM,
[=] AMREX_GPU_DEVICE (int i, int j, int k, int n) noexcept
{
Godunov_ppm_pred_x(i,j,k,n,l_dtdx,vel(i,j,k,0),q,Imx,Ipx,pbc[n],dlo.x,dhi.x);
Godunov_ppm_pred_y(i,j,k,n,l_dtdy,vel(i,j,k,1),q,Imy,Ipy,pbc[n],dlo.y,dhi.y);
Godunov_ppm_pred_z(i,j,k,n,l_dtdz,vel(i,j,k,2),q,Imz,Ipz,pbc[n],dlo.z,dhi.z);
});
}
| 36.371429 | 85 | 0.549097 | michaeljbrazell |
192549eba35fbc312a22c9b57177f2c63f6a5475 | 2,754 | cpp | C++ | src/brevity/tests/rep/Manager.cpp | LegalizeAdulthood/cimple | 5ec70784f2ee3e455a2258f82b07c0dacccb4093 | [
"MIT"
] | 4 | 2015-12-16T06:43:14.000Z | 2020-01-24T06:05:47.000Z | src/brevity/tests/rep/Manager.cpp | LegalizeAdulthood/cimple | 5ec70784f2ee3e455a2258f82b07c0dacccb4093 | [
"MIT"
] | null | null | null | src/brevity/tests/rep/Manager.cpp | LegalizeAdulthood/cimple | 5ec70784f2ee3e455a2258f82b07c0dacccb4093 | [
"MIT"
] | null | null | null | /*NOCHKSRC*/
//==============================================================================
//
// PLEASE DO NOT EDIT; THIS FILE WAS AUTOMATICALLY GENERATED BY GENCLASS 1.1.2
//
//==============================================================================
#include <cimple/Meta_Class.h>
#include <cimple/Meta_Property.h>
#include <cimple/Meta_Reference.h>
#include "Manager.h"
CIMPLE_NAMESPACE_BEGIN
using namespace cimple;
extern const Meta_Repository __meta_repository_8FB04575347F14F28B3F4E935D6199D7;
/*[1302]*/
extern const Meta_Property
_Employee_Id;
/*[1302]*/
extern const Meta_Property
_Employee_First;
/*[1302]*/
extern const Meta_Property
_Employee_Last;
/*[1302]*/
extern const Meta_Property
_Employee_Gender;
/*[1302]*/
extern const Meta_Property
_Employee_Active;
/*[1302]*/
extern const Meta_Property
_Employee_OutOfOffice;
/*[1302]*/
extern const Meta_Property
_Manager_NumEmployees;
/*[1325]*/
const Meta_Property
_Manager_NumEmployees =
{
CIMPLE_ATOMIC_INITIALIZER, /* refs */
CIMPLE_FLAG_PROPERTY|CIMPLE_FLAG_READ,
"NumEmployees",
0, /* meta_qualifiers */
0, /* num_meta_qaulifiers */
UINT32,
0, /* subscript */
CIMPLE_OFF(Manager,NumEmployees),
0, /* value */
};
/*[1302]*/
extern const Meta_Property
_Manager_Budget;
/*[1325]*/
const Meta_Property
_Manager_Budget =
{
CIMPLE_ATOMIC_INITIALIZER, /* refs */
CIMPLE_FLAG_PROPERTY|CIMPLE_FLAG_READ,
"Budget",
0, /* meta_qualifiers */
0, /* num_meta_qaulifiers */
UINT32,
0, /* subscript */
CIMPLE_OFF(Manager,Budget),
0, /* value */
};
/*[2025]*/
static Meta_Feature* _Manager_MFA[] =
{
(Meta_Feature*)(void*)&_Employee_Id,
(Meta_Feature*)(void*)&_Employee_First,
(Meta_Feature*)(void*)&_Employee_Last,
(Meta_Feature*)(void*)&_Employee_Gender,
(Meta_Feature*)(void*)&_Employee_Active,
(Meta_Feature*)(void*)&_Employee_OutOfOffice,
(Meta_Feature*)(void*)&Employee_SetOutOfOfficeState_method::static_meta_class,
(Meta_Feature*)(void*)&Employee_GetEmployeeCount_method::static_meta_class,
(Meta_Feature*)(void*)&_Manager_NumEmployees,
(Meta_Feature*)(void*)&_Manager_Budget,
};
/*[2072]*/
static const Meta_Feature_Local _locals[] =
{
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{0},
{1},
{1},
};
/*[2092]*/
const Meta_Class Manager::static_meta_class =
{
CIMPLE_ATOMIC_INITIALIZER, /* refs */
CIMPLE_FLAG_CLASS,
"Manager",
0, /* meta_qualifiers */
0, /* num_meta_qaulifiers */
_Manager_MFA,
CIMPLE_ARRAY_SIZE(_Manager_MFA),
sizeof(Manager),
_locals,
&Employee::static_meta_class,
1, /* num_keys */
&__meta_repository_8FB04575347F14F28B3F4E935D6199D7,
};
CIMPLE_NAMESPACE_END
| 21.184615 | 82 | 0.654684 | LegalizeAdulthood |
1929d5b9961c3ff8a27f540094bbe7cf42f73afa | 18,427 | hpp | C++ | deus/deus.hpp | messer-cpp/veiler | d827f01faba481f4fbb41515af2de8b3872d64c3 | [
"BSL-1.0"
] | 2 | 2015-10-31T05:47:45.000Z | 2018-03-25T01:28:44.000Z | deus/deus.hpp | messer-cpp/veiler | d827f01faba481f4fbb41515af2de8b3872d64c3 | [
"BSL-1.0"
] | null | null | null | deus/deus.hpp | messer-cpp/veiler | d827f01faba481f4fbb41515af2de8b3872d64c3 | [
"BSL-1.0"
] | 1 | 2020-05-12T11:15:07.000Z | 2020-05-12T11:15:07.000Z | //Copyright (C) 2012-2018 I
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include<utility>
#include<tuple>
#include<variant>
#include<type_traits>
#include<veiler/temple/integer.hpp>
#include<veiler/temple/type.hpp>
namespace veiler{
namespace deus{
namespace impl{
struct none{
template<typename... Args>
constexpr none(Args&&...)noexcept{}
};
struct default_guard{
template<typename T>
bool operator()(const T&)const{return true;}
};
struct default_action{
template<typename T>
void operator()(const T&)const{}
};
template<typename>class event;
template<typename>class state;
struct guard_tag{};
struct action_tag{};
struct both_tag{};
template<typename From, typename Event, typename To, typename Guard, typename Action>
struct transition : Guard, Action{
explicit constexpr transition()noexcept{}
template<typename G>
constexpr transition(guard_tag&&, G&& g):Guard(std::forward<G>(g)){}
template<typename A>
constexpr transition(action_tag&&, A&& a):Action(std::forward<A>(a)){}
template<typename G, typename A>
constexpr transition(both_tag&&, G&& g, A&& a):Guard(std::forward<G>(g)), Action(std::forward<A>(a)){}
template<typename A>
constexpr transition<From, Event, To, Guard, A> operator/(A&& a)const{
static_assert(std::is_same<Action, default_action>::value, "Veiler.Deus - cannot add two or more actions to transition.");
return transition<From, Event, To, Guard, A>(both_tag{}, std::forward<Guard>(*this), std::forward<A>(a));
}
template<typename E>
bool guard(E&& ev){return (*static_cast<Guard*>(this))(std::forward<E>(ev));}
template<typename E>
void action(E&& ev){(*static_cast<Action*>(this))(std::forward<E>(ev));}
};
template<typename State, typename Guard>
struct _guarded_state : Guard{
template<typename G>
constexpr _guarded_state(G&& g):Guard(std::forward<G>(g)){}
constexpr transition<State, none, none, Guard, default_action> operator--(int)const{
return transition<State, none, none, Guard, default_action>{guard_tag{}, std::forward<Guard>(*const_cast<_guarded_state<State, Guard>*>(this))};
}
};
template<typename State>
class state{
struct inner{
using state_type = State;
constexpr inner()noexcept = default;
constexpr transition<State, none, none, default_guard, default_action> operator--(int)const{return transition<State, none, none, default_guard, default_action>{};}
template<typename Guard>
constexpr _guarded_state<State, std::decay_t<Guard>> operator[](Guard&& g)const{return _guarded_state<State, std::decay_t<Guard>>{std::forward<Guard>(g)};}
};
public:
constexpr state()noexcept{}
template<typename Action>
constexpr transition<none, none, State, default_guard, std::decay_t<Action>> operator/(Action&& a)const{
return transition<none, none, State, default_guard, std::decay_t<Action>>{action_tag{}, std::forward<Action>(a)};
}
constexpr inner operator--(int)const{return inner{};}
};
template<typename Event, typename... Args>
struct event_args_wrapper{std::tuple<Args...> args;};
template<typename Event>
class event{
struct sysu{
constexpr sysu()noexcept = default;
template<typename State, typename From = typename std::decay<State>::type::state_type>
friend constexpr transition<From, Event, none, default_guard, default_action> operator-(State&& s, sysu&&)noexcept{
return transition<From, Event, none, default_guard, default_action>{};
}
};
template<typename Guard>
class _guarded_event : Guard{
struct sysu : private Guard{
template<typename G>
constexpr sysu(G&& g):Guard(std::forward<G>(g)){}
template<typename State, typename From = typename std::decay<State>::type::state_type>
friend constexpr transition<From, Event, none, Guard, default_action> operator-(State&& s, sysu&& g){
return transition<From, Event, none, Guard, default_action>{guard_tag{}, std::forward<Guard>(g)};
}
};
public:
template<typename G>
constexpr _guarded_event(G&& g):Guard(std::forward<G>(g)){}
constexpr sysu operator--(int){return sysu{std::forward<Guard>(*this)};}
};
public:
constexpr event()noexcept{}
constexpr sysu operator--(int)const noexcept{return sysu{};}
template<typename Guard>
constexpr _guarded_event<std::decay_t<Guard>> operator[](Guard&& g)const{return _guarded_event<std::decay_t<Guard>>{std::forward<Guard>(g)};}
template<typename... Args>
constexpr event_args_wrapper<Event, Args...> operator()(Args&&... args)const{return event_args_wrapper<Event, Args...>{{std::forward<Args>(args)...}};}
};
template<typename From, typename Event, typename To, typename Guard, typename Action>
constexpr transition<From, Event, To, Guard, Action> operator>(transition<From, Event, none, Guard, default_action>&& s, transition<none, none, To, default_guard, Action>&& e){
return transition<From, Event, To, Guard, Action>{both_tag{}, std::forward<Guard>(s), std::forward<Action>(e)};
}
template<typename From, typename Event, typename To, typename Action>
constexpr transition<From, Event, To, default_guard, Action> operator>(transition<From, Event, none, default_guard, default_action>&& s, transition<none, none, To, default_guard, Action>&& e){
return transition<From, Event, To, default_guard, Action>{action_tag{}, std::forward<Action>(e)};
}
template<typename From, typename Event, typename To, typename Guard>
constexpr transition<From, Event, To, Guard, default_action> operator>(transition<From, Event, none, Guard, default_action>&& s, const state<To>& e){
return transition<From, Event, To, Guard, default_action>{guard_tag{}, std::forward<Guard>(s)};
}
template<typename From, typename Event, typename To>
constexpr transition<From, Event, To, default_guard, default_action> operator>(transition<From, Event, none, default_guard, default_action>&& s, const state<To>& e){
return transition<From, Event, To, default_guard, default_action>{};
}
template<typename Statemachine>
class state_machine : public state<Statemachine>{
using TransitionTable = typename Statemachine::transition_table;
TransitionTable tt;
using Statuses = typename TransitionTable::Statuses;
template<typename Status>
class status_id{
template<typename T>
using cond = std::is_same<Status, T>;
public:
static constexpr std::make_signed_t<std::size_t> value = find_unique_type_index<Statuses, cond>::value;
};
class holder{
veiler::rebind<Statuses, std::variant> impl;
std::make_signed_t<std::size_t> state;
public:
holder(const holder&) = default;
holder(holder&&) = default;
template<template<typename>class Wrapper, typename T>
holder(Wrapper<T>&& t) : impl(T{}), state(status_id<T>::value){}
template<typename T, typename... Args>
void transit(Args&&... args){impl = T(std::forward<Args>(args)...);state = status_id<T>::value;}
friend bool operator==(const holder& lhs, long long rhs){return lhs.state == rhs;}
friend bool operator!=(const holder& lhs, long long rhs){return !(lhs == rhs);}
}state;
#if 0
template<typename Event, std::size_t N, typename F, typename G>
static void exec_events_impl(holder& state, TransitionTable& tt, F&& f, G&& g){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value){
f(state, tt);
return;
}
Event ev;
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>();
g(state, tt);
}
template<typename Event, std::size_t N, typename EventArgs, typename F, typename G>
static void exec_events_impl(holder& state, TransitionTable& tt, const EventArgs& args, F&& f, G&& g){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value){
f(state, tt, args);
return;
}
Event ev = (std::make_from_tuple<Event>)(args);
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>();
g(state, tt, args);
}
template<typename Event, std::size_t N = 0, bool = std::is_same<Event, type_at<type_at<TransitionTable,N>,1>>::value, bool = std::is_same<none, type_at<type_at<TransitionTable,N>,1>>::value, bool FinaleFlag = N != TransitionTable::size-1>
struct exec_events_{
static void exec(holder& state, TransitionTable& tt){
exec_events_impl<Event, N>(state, tt, [](holder& s, TransitionTable& t){exec_events_<Event, N, false, false, FinaleFlag>::exec(s, t);}, [](holder& s, TransitionTable& t){exec_events_<none, N, false, false, FinaleFlag>::exec(s, t);});
}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){
exec_events_impl<Event, N>(state, tt, args, [](holder& s, TransitionTable& t, const EventArgs& a){exec_events_<Event, N, false, false, FinaleFlag>::exec(s, t, a);}, [](holder& s, TransitionTable& t, auto&&){exec_events_<none, N, false, false, FinaleFlag>::exec(s, t);});
}
};
template<typename Event, std::size_t N, bool IsEvent, bool FinaleFlag>
struct exec_events_<Event, N, IsEvent, true, FinaleFlag>{
static void exec(holder& state, TransitionTable& tt){
exec_events_impl<none, N>(state, tt, [](holder& s, TransitionTable& t){exec_events_<Event, N, false, false, FinaleFlag>::exec(s, t);}, [](holder& s, TransitionTable& t){exec_events_<Event, N, false, false, FinaleFlag>::exec(s, t);});
}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){
exec_events_impl<none, N>(state, tt, args, [](holder& s, TransitionTable& t, const EventArgs& a){exec_events_<Event, N, false, false, FinaleFlag>::exec(s, t, a);}, [](holder& s, TransitionTable& t, const EventArgs& a){exec_events_<Event, N, false, false, FinaleFlag>::exec(s, t, a);});
}
};
template<typename Event, std::size_t N>
struct exec_events_<Event, N, false, false, true>{
static void exec(holder& state, TransitionTable& tt){
exec_events_<Event, N+1>::exec(state, tt);
}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){
exec_events_<Event, N+1>::exec(state, tt, args);
}
};
template<typename Event, std::size_t N>
struct exec_events_<Event, N, false, false, false>{
static void exec(holder& state, TransitionTable& tt){}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){}
};
#else
template<typename Event, std::size_t N = 0, bool = std::is_same<Event, type_at<type_at<TransitionTable,N>,1>>::value, bool = std::is_same<none, type_at<type_at<TransitionTable,N>,1>>::value, bool = N != TransitionTable::size-1>
struct exec_events_{
static void exec(holder& state, TransitionTable& tt){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value){
exec_events_<Event, N+1>::exec(state, tt);
return;
}
Event ev;
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>();
exec_events_<none, N+1>::exec(state, tt);
}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value){
exec_events_<Event, N+1>::exec(state, tt, args);
return;
}
Event ev = (std::make_from_tuple<Event>)(args);
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>(ev);
exec_events_<none, N+1>::exec(state, tt);
}
};
template<typename Event, std::size_t N, bool IsEvent>
struct exec_events_<Event, N, IsEvent, true, true>{
static void exec(holder& state, TransitionTable& tt){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value){
exec_events_<Event, N+1>::exec(state, tt);
return;
}
none ev;
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>();
exec_events_<Event, N+1>::exec(state, tt);
}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value){
exec_events_<Event, N+1>::exec(state, tt, args);
return;
}
none ev;
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>(ev);
exec_events_<Event, N+1>::exec(state, tt, args);
}
};
template<typename Event, std::size_t N>
struct exec_events_<Event, N, false, false, true>{
static void exec(holder& state, TransitionTable& tt){
exec_events_<Event, N+1>::exec(state, tt);
}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){
exec_events_<Event, N+1>::exec(state, tt, args);
}
};
template<typename Event, std::size_t N>
struct exec_events_<Event, N, true, false, false>{
static void exec(holder& state, TransitionTable& tt){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value)return;
Event ev;
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>();
}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value)return;
Event ev = (std::make_from_tuple<Event>)(args);
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>(ev);
}
};
template<typename Event, std::size_t N, bool IsEvent>
struct exec_events_<Event, N, IsEvent, true, false>{
static void exec(holder& state, TransitionTable& tt){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value)return;
none ev;
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>();
}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){
using transition = type_at<TransitionTable,N>;
if(state != status_id<type_at<transition,0>>::value)return;
none ev;
if(!std::get<N>(tt.table).guard(ev))return;
std::get<N>(tt.table).action(ev);
if(state != status_id<type_at<transition,2>>::value)
state.template transit<type_at<transition,2>>(ev);
}
};
template<typename Event, std::size_t N>
struct exec_events_<Event, N, false, false, false>{
static void exec(holder& state, TransitionTable& tt){}
template<typename EventArgs>
static void exec(holder& state, TransitionTable& tt, const EventArgs& args){}
};
#endif
template<typename Event>
void exec_events(){
exec_events_<Event>::exec(state, tt);
}
template<typename Event, typename EventArgs>
void exec_events(const EventArgs& args){
exec_events_<Event>::exec(state, tt, args);
}
public:
state_machine(const TransitionTable& table) : tt( table ), state(typename Statemachine::initial_state{}){}
state_machine(const state_machine& sm ) : tt( sm.tt ), state(typename Statemachine::initial_state{}){}
state_machine( state_machine&& sm ) : tt(std::move(sm.tt )), state(typename Statemachine::initial_state{}){}
template<typename Status>
bool is(const deus::impl::state<Status>&){return state == status_id<Status>::value;}
template<typename Event>
friend state_machine& operator<<=(state_machine& sm, const event<Event>& e){
sm.exec_events<Event>();
return sm;
}
template<typename Event, typename... Args>
friend state_machine& operator<<=(state_machine& sm, const event_args_wrapper<Event, Args...>& e){
sm.exec_events<Event>(e.args);
return sm;
}
};
template<typename StateMachine, typename Event>
auto forward_event(StateMachine&& sm, Event&& ev){
return sm --- ev --> sm / [&sm](auto&& x){sm <<= deus::impl::event<typename std::remove_cv<typename std::remove_reference<decltype(x)>::type>::type>{};};
}
template<typename TransitionTable, typename InitialState>
auto make_state_machine(const TransitionTable& tt, const InitialState&){
struct sm{
using transition_table = TransitionTable;
using initial_state = InitialState;
};
return state_machine<sm>(tt);
}
template<typename... Transitions>
struct transition_table{
std::tuple<Transitions...> table;
using Statuses = unique_types<type_tuple<type_at<Transitions,0>...,type_at<Transitions,2>...>>;
static constexpr std::size_t size = sizeof...(Transitions);
};
template<typename... Transitions>
constexpr auto make_transition_table(Transitions&&... transitions)
->transition_table<std::decay_t<Transitions>...>{
return transition_table<std::decay_t<Transitions>...>{{std::forward<Transitions>(transitions)...}};
}
}
using impl::state;
using impl::event;
using impl::transition;
using impl::state_machine;
using impl::forward_event;
using impl::make_state_machine;
using impl::transition_table;
using impl::make_transition_table;
}
}
| 44.617433 | 291 | 0.691214 | messer-cpp |
19375e858fa97b18555acfeef046084b1dee2f35 | 4,320 | cpp | C++ | apps/vaporgui/guis/instancetable.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | apps/vaporgui/guis/instancetable.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | apps/vaporgui/guis/instancetable.cpp | yyr/vapor | cdebac81212ffa3f811064bbd7625ffa9089782e | [
"BSD-3-Clause"
] | null | null | null | //************************************************************************
// *
// Copyright (C) 2006 *
// University Corporation for Atmospheric Research *
// All Rights Reserved *
// *
//************************************************************************/
//
// File: instancetable.cpp
//
// Author: Alan Norton
// National Center for Atmospheric Research
// PO 3000, Boulder, Colorado
//
// Date: October 2006
//
// Description: Implements the InstanceTable class
// This fits in the renderer tabs, enables the user to select
// copy, delete, and enable instances
//
#include "instancetable.h"
#include <qpixmap.h>
#include <qstringlist.h>
#include <qlineedit.h>
#include "instancetable.h"
#include "eventrouter.h"
#include <QTableWidget>
#include <QHeaderView>
#include <QString>
using namespace VAPoR;
InstanceTable::InstanceTable(QWidget* parent) : QTableWidget(parent) {
// Table size always 150 wide
selectedInstance = 0;
setRowCount(0);
setColumnCount(2);
setColumnWidth(0,80);
setColumnWidth(1,50);
verticalHeader()->hide();
setSelectionMode(QAbstractItemView::SingleSelection);
setSelectionBehavior(QAbstractItemView::SelectRows);
setFocusPolicy(Qt::ClickFocus);
QStringList headerList = QStringList() <<"Instance" <<" View ";
setHorizontalHeaderLabels(headerList);
horizontalHeader()->setDefaultAlignment(Qt::AlignLeft);
setMaximumWidth(150);
setMaximumHeight(120);
setMinimumHeight(120);
setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
connect(this,SIGNAL(cellChanged(int,int)), this, SLOT(changeChecked(int,int)));
connect(this, SIGNAL(itemSelectionChanged()), this, SLOT(selectInstance()));
}
InstanceTable::~InstanceTable(){
for (int i = 0; i<rowCount(); i++){
if (item(i,0)) delete item(i,0);
if (item(i,1)) delete item(i,1);
}
}
//Build the table, based on instances in eventrouter
void InstanceTable::rebuild(EventRouter* myRouter){
int numInsts = 1;
//All instance info is in VizWinMgr.
VAPoR::Params::ParamsBaseType renderBaseType = myRouter->getParamsBaseType();
VAPoR::VizWinMgr* vizMgr = VizWinMgr::getInstance();
int winnum = vizMgr->getActiveViz();
if (winnum >= 0)
numInsts = vizMgr->getNumInstances(winnum,renderBaseType);
assert(numInsts > 0);
//create items as needed
//Also insert labels in first column
if (rowCount() > numInsts) selectRow(0); //avoid crash if selected row is too high
if(rowCount() != numInsts) setRowCount(numInsts);
for (int r = 0; r<numInsts; r++){
RenderParams* rParams = (RenderParams*)vizMgr->getParams(winnum,renderBaseType,r);
bool isEnabled = rParams->isEnabled();
if (!item(r,0)) { //need to create new items..
QString instanceName = QString(" Instance: ") + QString::number(r+1) + " ";
QTableWidgetItem *item0 = new QTableWidgetItem(instanceName);
QTableWidgetItem *item1 = new QTableWidgetItem(" ");
item0->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled);
item1->setFlags(item1->flags() & ~(Qt::ItemIsEditable));
if (isEnabled)item1->setCheckState(Qt::Checked);
else item1->setCheckState(Qt::Unchecked);
setItem(r,0, item0);
setItem(r,1, item1);
} else {
if (isEnabled && item(r,1)->checkState() != Qt::Checked)item(r,1)->setCheckState(Qt::Checked);
else if (!isEnabled && item(r,1)->checkState() != Qt::Unchecked)item(r,1)->setCheckState(Qt::Unchecked);
}
}
if(selectedInstance != vizMgr->getCurrentInstanceIndex(winnum, renderBaseType)){
selectedInstance = vizMgr->getCurrentInstanceIndex(winnum, renderBaseType);
selectRow(selectedInstance);
}
}
//Slots:
void InstanceTable::selectInstance(){
QList<QModelIndex> selectList = selectedIndexes();
int newSelection = selectList[0].row();
if (newSelection == selectedInstance) return;
selectedInstance = newSelection;
emit changeCurrentInstance(selectedInstance);
}
void InstanceTable::changeChecked(int row, int col){
if (col != 1) return;
QTableWidgetItem* checkedItem = item(row,col);
bool val = (checkedItem->checkState() == Qt::Checked);
emit enableInstance(val, row);
}
void InstanceTable::checkEnabledBox(bool val, int instance){
item(instance,1)->setCheckState(val ? Qt::Checked : Qt::Unchecked);
}
| 32 | 107 | 0.684028 | yyr |
19388597e077be2db928e863add0ca2254cf5cba | 5,966 | cpp | C++ | BaldLionEngine/src/BaldLion/Core/Memory/MemoryManager.cpp | Efore/BaldLionEngine | ebd915805533a767b67690ca8749d1454a6fd379 | [
"Apache-2.0"
] | null | null | null | BaldLionEngine/src/BaldLion/Core/Memory/MemoryManager.cpp | Efore/BaldLionEngine | ebd915805533a767b67690ca8749d1454a6fd379 | [
"Apache-2.0"
] | null | null | null | BaldLionEngine/src/BaldLion/Core/Memory/MemoryManager.cpp | Efore/BaldLionEngine | ebd915805533a767b67690ca8749d1454a6fd379 | [
"Apache-2.0"
] | null | null | null | #include "blpch.h"
#include "MemoryManager.h"
namespace BaldLion
{
namespace Memory
{
FreeListAllocator* MemoryManager::s_freeListMainAllocator;
FreeListAllocator* MemoryManager::s_freeListRendererAllocator;
FreeListAllocator* MemoryManager::s_freeListECSAllocator;
LinearAllocator* MemoryManager::s_linearFrameAllocator;
StackAllocator* MemoryManager::s_stackAllocator;
std::unordered_map<void*, AllocationInfo> MemoryManager::s_allocationMap;
void* MemoryManager::s_memory;
std::mutex MemoryManager::s_mutex;
std::mutex MemoryManager::s_arrayMutex;
size_t MemoryManager::s_memorySize = 0;
void MemoryManager::Init(size_t memoryAllocationSize)
{
if (s_memorySize > 0) return;
s_memorySize = 1024ULL * 1024 * 1024 * 2; //2GB
s_memory = malloc(s_memorySize);
if (s_memory == nullptr)
{
BL_LOG_CORE_ERROR ("Not enough memory! 2GB of RAM needed.");
return;
}
s_freeListMainAllocator = new (s_memory) FreeListAllocator("Main FreeList Allocator", s_memorySize - sizeof(FreeListAllocator), AddPointerOffset(s_memory, sizeof(FreeListAllocator)));
const size_t frameAllocatorSize = 400 * 1024 * 1024; //~400MB
void* frameAllocatorStart = s_freeListMainAllocator->Allocate(frameAllocatorSize, __alignof(LinearAllocator));
s_linearFrameAllocator = new (frameAllocatorStart) LinearAllocator("Linear Frame Allocator", frameAllocatorSize - sizeof(LinearAllocator), AddPointerOffset(frameAllocatorStart, sizeof(LinearAllocator)));
const size_t stackAllocatorSize = 400 * 1024 * 1024; //~400MB
void* stackAllocatorStart = s_freeListMainAllocator->Allocate(stackAllocatorSize, __alignof(StackAllocator));
s_stackAllocator = new (stackAllocatorStart) StackAllocator("Stack Allocator", stackAllocatorSize - sizeof(StackAllocator), AddPointerOffset(stackAllocatorStart, sizeof(StackAllocator)));
const size_t ecsSize = 200 * 1024 * 1024; //200MB
void *ecsAllocatorStart = s_freeListMainAllocator->Allocate(ecsSize, __alignof(FreeListAllocator));
s_freeListECSAllocator = new (ecsAllocatorStart) FreeListAllocator("Renderer FreeList Allocator", ecsSize - sizeof(FreeListAllocator), AddPointerOffset(ecsAllocatorStart, sizeof(FreeListAllocator)));
const size_t rendererSize = 1024ULL * 1024 * 1024; //1GB
void *rendererAllocatorStart = s_freeListMainAllocator->Allocate(rendererSize, __alignof(FreeListAllocator));
s_freeListRendererAllocator = new (rendererAllocatorStart) FreeListAllocator("Renderer FreeList Allocator", rendererSize - sizeof(FreeListAllocator), AddPointerOffset(rendererAllocatorStart, sizeof(FreeListAllocator)));
}
void MemoryManager::Delete(AllocationType allocationType)
{
switch (allocationType)
{
case BaldLion::Memory::AllocationType::FreeList_Main:
break;
case BaldLion::Memory::AllocationType::Linear_Frame:
if(s_linearFrameAllocator != nullptr)
s_linearFrameAllocator->Delete();
break;
case BaldLion::Memory::AllocationType::Stack:
if (s_stackAllocator != nullptr)
s_stackAllocator->Delete();
break;
case BaldLion::Memory::AllocationType::FreeList_Renderer:
break;
case BaldLion::Memory::AllocationType::FreeList_ECS:
break;
default:
break;
}
}
void MemoryManager::Stop()
{
if (s_linearFrameAllocator != nullptr)
{
s_linearFrameAllocator->Delete();
Delete(s_linearFrameAllocator);
}
if (s_stackAllocator != nullptr)
{
s_stackAllocator->Delete();
Delete(s_stackAllocator);
}
if (s_freeListRendererAllocator != nullptr)
{
s_freeListRendererAllocator->Delete();
Delete(s_freeListRendererAllocator);
}
if (s_freeListECSAllocator != nullptr)
{
s_freeListECSAllocator->Delete();
Delete(s_freeListECSAllocator);
}
s_freeListMainAllocator->Delete();
s_freeListMainAllocator->~FreeListAllocator();
free(s_memory);
}
Allocator* MemoryManager::GetAllocator(AllocationType allocationType)
{
switch (allocationType)
{
case BaldLion::Memory::AllocationType::FreeList_Main:
return s_freeListMainAllocator;
case BaldLion::Memory::AllocationType::Linear_Frame:
return s_linearFrameAllocator;
case BaldLion::Memory::AllocationType::Stack:
return s_stackAllocator;
case BaldLion::Memory::AllocationType::FreeList_Renderer:
return s_freeListRendererAllocator;
case BaldLion::Memory::AllocationType::FreeList_ECS:
return s_freeListECSAllocator;
default:
break;
}
return nullptr;
}
size_t MemoryManager::GetAllocatorSize(AllocationType allocationType)
{
switch (allocationType)
{
case BaldLion::Memory::AllocationType::FreeList_Main:
return s_freeListMainAllocator->Size();
case BaldLion::Memory::AllocationType::Linear_Frame:
return s_linearFrameAllocator->Size();
case BaldLion::Memory::AllocationType::Stack:
return s_stackAllocator->Size();
case BaldLion::Memory::AllocationType::FreeList_Renderer:
return s_freeListRendererAllocator->Size();
case BaldLion::Memory::AllocationType::FreeList_ECS:
return s_freeListECSAllocator->Size();
default:
break;
}
return 0;
}
size_t MemoryManager::GetAllocatorUsedMemory(AllocationType allocationType)
{
switch (allocationType)
{
case BaldLion::Memory::AllocationType::FreeList_Main:
return s_freeListMainAllocator->GetUsedMemory();
case BaldLion::Memory::AllocationType::Linear_Frame:
return s_linearFrameAllocator->GetUsedMemory();
case BaldLion::Memory::AllocationType::Stack:
return s_stackAllocator->GetUsedMemory();
case BaldLion::Memory::AllocationType::FreeList_Renderer:
return s_freeListRendererAllocator->GetUsedMemory();
case BaldLion::Memory::AllocationType::FreeList_ECS:
return s_freeListECSAllocator->GetUsedMemory();
default:
break;
}
return 0;
}
size_t MemoryManager::GetMemorySize()
{
return s_memorySize;
}
}
} | 29.83 | 222 | 0.752095 | Efore |
193c01958bfd467dd6a38942486f63e1c7c3d873 | 973 | hpp | C++ | macOS/bootstrap/bootstrap.hpp | unknownv2/CoreHook.ProcessInjection | 8c07124f54d748c7e33d40397c4adb5c5af9d382 | [
"MIT"
] | 1 | 2021-07-21T19:13:35.000Z | 2021-07-21T19:13:35.000Z | macOS/bootstrap/bootstrap.hpp | unknownv2/CoreHook.ProcessInjection | 8c07124f54d748c7e33d40397c4adb5c5af9d382 | [
"MIT"
] | 1 | 2018-07-04T23:17:48.000Z | 2018-07-05T12:16:38.000Z | macOS/bootstrap/bootstrap.hpp | unknownv2/CoreHook.ProcessInjection | 8c07124f54d748c7e33d40397c4adb5c5af9d382 | [
"MIT"
] | 1 | 2019-05-16T00:37:08.000Z | 2019-05-16T00:37:08.000Z | #ifndef bootstrap_hpp
#define bootstrap_hpp
#include <stdio.h>
#define DLLEXPORT __attribute__((visibility("default")))
extern "C" void bootstrap(ptrdiff_t offset, void *param, size_t psize, void *dummy) DLLEXPORT;
#define BYTE unsigned char
#define FunctionNameMax 256
struct BinaryLoaderArgs
{
bool Verbose;
bool WaitForDebugger;
bool StartAssembly;
char Reserved[5];
char BinaryFilePath[PATH_MAX];
char CoreRootPath[PATH_MAX];
char CoreLibrariesPath[PATH_MAX];
};
struct AssemblyFunctionCall
{
char Assembly[FunctionNameMax];
char Class[FunctionNameMax];
char Function[FunctionNameMax];
BYTE Arguments[FunctionNameMax];
};
struct DotnetAssemblyFunctionCall
{
char coreRunLib[PATH_MAX];
char binaryLoaderFunctionName[FunctionNameMax];
char assemblyCallFunctionName[FunctionNameMax];
BinaryLoaderArgs binaryLoaderArgs;
AssemblyFunctionCall assemblyFunctionCall;
};
#endif /* bootstrap_hpp */
| 23.166667 | 94 | 0.758479 | unknownv2 |
19478360b04b61f899891b68293abf09f92a59e5 | 10,254 | cpp | C++ | src/httphandlerfactory.cpp | sputnik-maps/maps-express | 2da1d5601d3f7a74c5eab79a6716736d223bf2f6 | [
"MIT"
] | 6 | 2017-06-20T13:14:20.000Z | 2019-09-18T06:12:37.000Z | src/httphandlerfactory.cpp | sputnik-maps/maps-express | 2da1d5601d3f7a74c5eab79a6716736d223bf2f6 | [
"MIT"
] | 1 | 2018-04-29T14:01:56.000Z | 2018-04-29T14:01:56.000Z | src/httphandlerfactory.cpp | sputnik-maps/maps-express | 2da1d5601d3f7a74c5eab79a6716736d223bf2f6 | [
"MIT"
] | 5 | 2017-06-20T13:39:22.000Z | 2019-09-18T06:13:02.000Z | #include "httphandlerfactory.h"
#include <proxygen/httpserver/RequestHandler.h>
#include <proxygen/lib/http/HTTPMessage.h>
#include "config.h"
#include "couchbase_cacher.h"
#include "json_util.h"
#include "mon_handler.h"
#include "nodes_monitor.h"
#include "status_monitor.h"
#include "tile_cacher.h"
#include "tile_handler.h"
#include "tile_processing_manager.h"
#include "util.h"
using json_util::FromJson;
using json_util::FromJsonOrErr;
using endpoint_t = HttpHandlerFactory::endpoint_t;
using endpoints_map_t = std::unordered_map<std::string, endpoint_t>;
class ServerUpdateObserver : public Config::ConfigObserver {
public:
ServerUpdateObserver(HttpHandlerFactory& hhf) : hhf_(hhf) {}
private:
void OnUpdate(std::shared_ptr<Json::Value> value) override {
hhf_.UpdateConfig(std::move(value));
}
HttpHandlerFactory& hhf_;
};
static FilterTable::zoom_groups_t MakeZoomGroups(uint min_z, uint max_z) {
FilterTable::zoom_groups_t zoom_groups;
for (uint i = min_z; i <= max_z; ++i) {
zoom_groups.insert(i);
}
return zoom_groups;
}
static std::shared_ptr<endpoints_map_t> ParseEndpoints(const Json::Value jendpoints,
DataManager& data_manager) {
if (!jendpoints.isObject()) {
return nullptr;
}
auto endpoints_map = std::make_shared<endpoints_map_t>(jendpoints.size());
for (auto itr = jendpoints.begin() ; itr != jendpoints.end() ; ++itr) {
const std::string endpoint_path = itr.key().asString();
if (endpoints_map->find(endpoint_path) != endpoints_map->end()) {
LOG(ERROR) << "Duplicate endpoint path: " << endpoint_path;
continue;
}
endpoint_t endpoint;
const Json::Value& jendpoint = *itr;
for (const auto& jparams : jendpoint) {
auto params = std::make_shared<EndpointParams>();
params->minzoom = FromJson<int>(jparams["minzoom"], 0);
params->maxzoom = FromJson<int>(jparams["maxzoom"], 19);
int zoom_offset = FromJson<int>(jparams["data_zoom_offset"], 0);
if (zoom_offset > 0) {
LOG(ERROR) << "\"data_zoom_offset must be negative o zero";
LOG(ERROR) << "Skipping endpoint \"" << endpoint_path << '"';
continue;
}
params->zoom_offset = static_cast<uint>(-zoom_offset);
std::string provider_name = FromJson<std::string>(jparams["data_provider"], "");
if (!provider_name.empty()) {
auto data_provider = data_manager.GetProvider(provider_name);
if (!data_provider) {
LOG(ERROR) << "Data provider \"" << provider_name << "\" for endpoint \""
<< endpoint_path << "\" not found!";
LOG(ERROR) << "Skipping endpoint \"" << endpoint_path << '"';
continue;
}
params->data_provider = std::move(data_provider);
}
params->style_name = FromJson<std::string>(jparams["style"], "");
params->allow_layers_query = FromJson<bool>(jparams["allow_layers_query"], false);
std::string type = FromJson<std::string>(jparams["type"], "static");
if (type == "static") {
params->type = EndpointType::static_files;
if (!params->data_provider) {
LOG(ERROR) << "No data provider for endpoint '" << endpoint_path << "' specified!";
LOG(ERROR) << "Skipping endpoint \"" << endpoint_path << '"';
continue;
}
} else if (type == "render") {
params->type = EndpointType::render;
params->allow_utf_grid = FromJson<bool>(jparams["allow_utfgrid"], false);
params->utfgrid_key = FromJson<std::string>(jparams["utfgrid_key"], "");
if (params->allow_utf_grid && params->utfgrid_key.empty()) {
LOG(ERROR) << "No utfgrid key for endpoint '" << endpoint_path << "' provided!";
params->allow_utf_grid = false;
}
if (params->style_name.empty()) {
LOG(ERROR) << "No style name for endpoint '" << endpoint_path << "' provided!";
LOG(ERROR) << "Skipping endpoint \"" << endpoint_path << '"';
continue;
}
} else if (type == "mvt") {
params->type = EndpointType::mvt;
if (!params->data_provider) {
LOG(ERROR) << "No data provider for endpoint '" << endpoint_path << "' specified!";
LOG(ERROR) << "Skipping endpoint \"" << endpoint_path << '"';
continue;
}
auto filter_map_path = FromJson<std::string>(jparams["filter_map"]);
if (filter_map_path) {
uint last_zoom = FromJson<uint>(jparams["last_zoom"], params->maxzoom + 1);
FilterTable::zoom_groups_t zoom_groups = MakeZoomGroups(params->minzoom, params->maxzoom);
params->filter_table = FilterTable::MakeFilterTable(*filter_map_path, &zoom_groups,
1, params->minzoom, last_zoom);
}
} else {
LOG(ERROR) << "Invalid type '" << type << "' for endpoint '" << endpoint_path << "' provided!";
continue;
}
const Json::Value& jmetatile_size = jparams["metatile_size"];
if (jmetatile_size.isString()) {
if (jmetatile_size.asString() == "auto") {
if (!params->data_provider) {
LOG(ERROR) << "Auto metatile size can be used only with data provider!";
} else {
params->auto_metatile_size = true;
}
}
} else if (jmetatile_size.isUInt()) {
uint metatile_size = jmetatile_size.asUInt();
params->metatile_height = metatile_size;
params->metatile_width = metatile_size;
} else {
params->metatile_height = FromJson<uint>(jparams["metatile_height"], 1);
params->metatile_width = FromJson<uint>(jparams["metatile_width"], 1);
}
endpoint.push_back(std::move(params));
}
(*endpoints_map)[endpoint_path] = std::move(endpoint);
}
return endpoints_map;
}
HttpHandlerFactory::HttpHandlerFactory(Config& config, std::shared_ptr<StatusMonitor> monitor,
std::string internal_port, NodesMonitor* nodes_monitor) :
monitor_(std::move(monitor)),
render_manager_(config),
data_manager_(config),
internal_port_(std::move(internal_port)),
config_(config),
nodes_monitor_(nodes_monitor)
{
update_observer_ = std::make_unique<ServerUpdateObserver>(*this);
std::shared_ptr<const Json::Value> jserver_ptr = config.GetValue("server", update_observer_.get());
assert(jserver_ptr);
const Json::Value& jserver = *jserver_ptr;
const Json::Value& jendpoints = jserver["endpoints"];
auto endpoints_ptr = ParseEndpoints(jendpoints, data_manager_);
if (!endpoints_ptr || endpoints_ptr->empty()) {
LOG(WARNING) << "No endpoints provided";
}
std::atomic_store(&endpoints_, endpoints_ptr);
uint max_processing_tasks = FromJson<uint>(jserver["max_tasks"], 200);
uint unlock_threshold = FromJson<uint>(jserver["unlock_threshold"], 180);
processing_manager_ = std::make_unique<TileProcessingManager>(render_manager_, max_processing_tasks,
unlock_threshold);
auto jcacher_ptr = config.GetValue("cacher");
if (jcacher_ptr) {
const Json::Value& jcacher = *jcacher_ptr;
const Json::Value& jconn_str= jcacher["conn_str"];
if (!jconn_str.isString()) {
LOG(FATAL) << "No connection string for Couchbase provided!";
}
std::string conn_str = jconn_str.asString();
std::string user = FromJson<std::string>(jcacher["user"], "");
std::string password = FromJson<std::string>(jcacher["password"], "");
uint num_workers = FromJson<uint>(jcacher["workers"], 2);
auto cb_cacher = std::make_shared<CouchbaseCacher>(conn_str, user, password, num_workers);
cb_cacher->WaitForInit();
cacher_ = std::move(cb_cacher);
}
if (!cacher_) {
LOG(INFO) << "Starting without cacher";
}
render_manager_.WaitForInit();
}
HttpHandlerFactory::~HttpHandlerFactory() {}
void HttpHandlerFactory::onServerStart(folly::EventBase* evb) noexcept {
timer_->timer = folly::HHWheelTimer::newTimer(
evb,
std::chrono::milliseconds(folly::HHWheelTimer::DEFAULT_TICK_INTERVAL),
folly::AsyncTimeout::InternalEnum::NORMAL,
std::chrono::seconds(60));
}
void HttpHandlerFactory::onServerStop() noexcept {
if (nodes_monitor_) {
nodes_monitor_->Unregister();
}
timer_->timer.reset();
}
proxygen::RequestHandler* HttpHandlerFactory::onRequest(proxygen::RequestHandler*,
proxygen::HTTPMessage* msg) noexcept {
const std::string& path = msg->getPath();
// if (path.back() != '/') {
// path.push_back('/');
// }
const auto method = msg->getMethod();
using proxygen::HTTPMethod;
if (method == HTTPMethod::GET && path == "/mon") {
return new MonHandler(monitor_);
}
auto endpoints = std::atomic_load(&endpoints_);
return new TileHandler(internal_port_, *timer_->timer, *processing_manager_,
endpoints, cacher_, nodes_monitor_);
}
bool HttpHandlerFactory::UpdateConfig(std::shared_ptr<Json::Value> update) {
auto endpoints_map = ParseEndpoints((*update)["endpoints"], data_manager_);
if (!endpoints_map) {
return false;
}
std::atomic_store(&endpoints_, endpoints_map);
return true;
}
| 43.449153 | 111 | 0.579871 | sputnik-maps |
19481ea85a85eefcf9d4776da4dc8717b532fc66 | 1,157 | cpp | C++ | GraphicsFramework/GraphicsFramework/core/Object.cpp | sidu7/GraphicsFramework | c81c021a9a1d479c3c18eba533318ce84481ca5c | [
"Apache-2.0"
] | null | null | null | GraphicsFramework/GraphicsFramework/core/Object.cpp | sidu7/GraphicsFramework | c81c021a9a1d479c3c18eba533318ce84481ca5c | [
"Apache-2.0"
] | null | null | null | GraphicsFramework/GraphicsFramework/core/Object.cpp | sidu7/GraphicsFramework | c81c021a9a1d479c3c18eba533318ce84481ca5c | [
"Apache-2.0"
] | null | null | null | #include "Object.h"
#include "../utils/JSONHelper.h"
#include "ShapeManager.h"
#include "../opengl/Shader.h"
#include "Components/Components.h"
#include "../opengl/Renderer.h"
#include "../opengl/Texture.h"
#include "Components/Transform.h"
#include "Components/Material.h"
#include "Components/RotateInCircle.h"
#include "Components/Move.h"
#include "Components/Shape.h"
Object::Object()
{
}
Object::~Object()
{
for(auto index : mIndices)
{
delete mComponents[index];
}
}
void Object::Update()
{
for(auto index : mIndices)
{
mComponents[index]->Update();
}
}
void Object::Serialize(const rapidjson::Value::Object& data)
{
rapidjson::Value::Array components = data["Components"].GetArray();
for (unsigned int i = 0; i < components.Size(); ++i)
{
std::string type = components[i]["Type"].GetString();
Component* component = ComponentManager::Instance().NewComponent(type);
component->Serialize(components[i].GetObject());
component->mOwner = this;
AddComponent(component);
}
}
void Object::AddComponent(Component* component)
{
auto index = component->GetIndex();
mComponents[index] = component;
mIndices.push_back(index);
}
| 21.830189 | 73 | 0.707865 | sidu7 |
1949fbe3865c516c2e371721ee5d6187e7415673 | 176 | cpp | C++ | Lab7/src/Task3.cpp | Inaceat/SP | 983e2de5900db8f36b2b04f95c3b4318f9c8f6fe | [
"MIT"
] | 1 | 2019-12-10T10:34:28.000Z | 2019-12-10T10:34:28.000Z | Lab7/src/Task3.cpp | Inaceat/SP | 983e2de5900db8f36b2b04f95c3b4318f9c8f6fe | [
"MIT"
] | null | null | null | Lab7/src/Task3.cpp | Inaceat/SP | 983e2de5900db8f36b2b04f95c3b4318f9c8f6fe | [
"MIT"
] | 1 | 2019-11-26T05:20:30.000Z | 2019-11-26T05:20:30.000Z | #include "stdafx.h"
#include "Tasks.hpp"
#include "ChategClient.hpp"
void Task3::Do()
{
auto client = new Chateg::ChategClient();
client->Start();
delete client;
}
| 9.777778 | 42 | 0.659091 | Inaceat |
194b6c791974be4a28e56f25eaa89616b891f376 | 8,019 | cpp | C++ | src/Components.cpp | SwellLay/BaconPlugs | b081ed8a6cb8eb0cee85378e8a9c4aa1d27b757b | [
"Apache-2.0"
] | null | null | null | src/Components.cpp | SwellLay/BaconPlugs | b081ed8a6cb8eb0cee85378e8a9c4aa1d27b757b | [
"Apache-2.0"
] | null | null | null | src/Components.cpp | SwellLay/BaconPlugs | b081ed8a6cb8eb0cee85378e8a9c4aa1d27b757b | [
"Apache-2.0"
] | null | null | null | #include "BaconPlugs.hpp"
#include <jansson.h>
struct InternalFontMgr
{
static std::map< std::string, int > fontMap;
static int get( NVGcontext *vg, std::string resName )
{
if( fontMap.find( resName ) == fontMap.end() )
{
fontMap[ resName ] = nvgCreateFont( vg, resName.c_str(), assetPlugin( plugin, resName ).c_str() );
}
return fontMap[ resName ];
}
};
std::map< std::string, int > InternalFontMgr::fontMap;
struct InternalRoundedBorder : virtual TransparentWidget
{
bool doFill;
NVGcolor fillColor;
InternalRoundedBorder( Vec pos, Vec sz, NVGcolor fc )
{
box.pos = pos;
box.size = sz;
doFill = true;
fillColor = fc;
}
InternalRoundedBorder( Vec pos, Vec sz )
{
box.pos = pos;
box.size = sz;
doFill = false;
}
void draw( NVGcontext *vg ) override
{
nvgBeginPath( vg );
nvgRoundedRect( vg, 0, 0, box.size.x, box.size.y, 5 );
if( doFill )
{
nvgFillColor( vg, fillColor );
nvgFill( vg );
}
nvgStrokeColor( vg, COLOR_BLACK );
nvgStroke( vg );
}
};
struct InternalTextLabel : virtual TransparentWidget
{
int memFont = -1;
std::string label;
int pxSize;
int align;
NVGcolor color;
InternalTextLabel( Vec pos, const char* lab, int px, int al, NVGcolor col ) : label( lab ), pxSize( px ), align( al ), color( col )
{
box.pos = pos;
}
void draw( NVGcontext *vg ) override {
if( memFont < 0 )
memFont = InternalFontMgr::get( vg, "res/Monitorica-Bd.ttf" );
nvgBeginPath( vg );
nvgFontFaceId( vg, memFont );
nvgFontSize( vg, pxSize );
nvgFillColor( vg, color );
nvgTextAlign( vg, align );
nvgText( vg, 0, 0, label.c_str(), NULL );
}
};
struct InternalPlugLabel : virtual TransparentWidget
{
int memFont = -1;
BaconBackground::LabelStyle st;
BaconBackground::LabelAt at;
std::string label;
InternalPlugLabel( Vec portPos, BaconBackground::LabelAt l, BaconBackground::LabelStyle s, const char* ilabel );
void draw( NVGcontext *vg ) override;
};
void BaconBackground::draw( NVGcontext *vg )
{
if( memFont < 0 )
memFont = InternalFontMgr::get( vg, "res/Monitorica-Bd.ttf" );
nvgBeginPath( vg );
nvgRect( vg, 0, 0, box.size.x, box.size.y );
nvgFillColor( vg, BaconBackground::bg );
nvgFill( vg );
nvgBeginPath( vg );
nvgMoveTo( vg, 0, 0 );
nvgLineTo( vg, box.size.x, 0 );
nvgLineTo( vg, box.size.x, box.size.y );
nvgLineTo( vg, 0, box.size.y );
nvgLineTo( vg, 0, 0 );
nvgStrokeColor( vg, BaconBackground::bgOutline );
nvgStroke( vg );
nvgFontFaceId( vg, memFont );
nvgFontSize( vg, 14 );
nvgFillColor( vg, COLOR_BLACK );
nvgStrokeColor( vg, COLOR_BLACK );
nvgTextAlign( vg, NVG_ALIGN_CENTER|NVG_ALIGN_BOTTOM );
nvgText( vg, box.size.x / 2, box.size.y - 5, "Bacon Music", NULL );
nvgFontFaceId( vg, memFont );
nvgFontSize( vg, 16 );
nvgFillColor( vg, COLOR_BLACK );
nvgStrokeColor( vg, COLOR_BLACK );
nvgTextAlign( vg, NVG_ALIGN_CENTER|NVG_ALIGN_TOP );
nvgText( vg, box.size.x / 2, 5, title.c_str(), NULL );
for( auto w : children )
{
nvgTranslate( vg, w->box.pos.x, w->box.pos.y );
w->draw( vg );
nvgTranslate( vg, -w->box.pos.x, -w->box.pos.y );
}
for( auto it = rects.begin(); it != rects.end(); ++it )
{
col_rect_t tu = *it;
Rect r = std::get< 0 >(tu);
NVGcolor c = std::get< 1 >(tu);
bool f = std::get< 2 >(tu);
nvgBeginPath( vg );
nvgRect( vg, r.pos.x, r.pos.y, r.size.x, r.size.y );
if( f )
{
nvgFillColor( vg, c );
nvgFill( vg );
}
else
{
nvgStrokeColor( vg, c );
nvgStroke( vg );
}
}
}
InternalPlugLabel::InternalPlugLabel( Vec portPos, BaconBackground::LabelAt l, BaconBackground::LabelStyle s, const char* ilabel )
:
st( s ), at( l ), label( ilabel )
{
box.size.x = 24 + 5;
box.size.y = 24 + 5 + 20;
// switch on position but for now just do above
box.pos.x = portPos.x - 2.5;
box.pos.y = portPos.y - 2.5 - 17;
}
void InternalPlugLabel::draw( NVGcontext *vg )
{
if( memFont < 0 )
memFont = InternalFontMgr::get( vg, "res/Monitorica-Bd.ttf" );
NVGcolor txtCol = COLOR_BLACK;
switch( st ) {
case( BaconBackground::SIG_IN ) :
{
nvgBeginPath( vg );
nvgRoundedRect( vg, 0, 0, box.size.x, box.size.y, 5 );
nvgStrokeColor( vg, COLOR_BLACK );
nvgStroke( vg );
break;
}
case( BaconBackground::SIG_OUT ) :
{
nvgBeginPath( vg );
nvgRoundedRect( vg, 0, 0, box.size.x, box.size.y, 5 );
nvgFillColor( vg, BaconBackground::highlight );
nvgFill( vg );
nvgStrokeColor( vg, COLOR_BLACK );
nvgStroke( vg );
txtCol = COLOR_WHITE;
break;
}
case( BaconBackground::OTHER ) :
{
nvgBeginPath( vg );
nvgRoundedRect( vg, 0, 0, box.size.x, box.size.y, 5 );
nvgStrokeColor( vg, COLOR_RED );
nvgStroke( vg );
break;
}
}
nvgFontFaceId( vg, memFont );
nvgFontSize( vg, 13 );
nvgFillColor( vg, txtCol );
nvgTextAlign( vg, NVG_ALIGN_CENTER|NVG_ALIGN_TOP );
nvgText( vg, box.size.x / 2, 3, label.c_str(), NULL );
}
BaconBackground *BaconBackground::addLabel( Vec pos, const char* lab, int px, int align, NVGcolor col )
{
addChild( new InternalTextLabel( pos, lab, px, align, col ) );
return this;
}
BaconBackground *BaconBackground::addPlugLabel( Vec plugPos, LabelAt l, LabelStyle s, const char* ilabel )
{
addChild( new InternalPlugLabel( plugPos, l, s, ilabel ) );
return this;
}
BaconBackground *BaconBackground::addRoundedBorder( Vec pos, Vec sz )
{
addChild( new InternalRoundedBorder( pos, sz ) );
return this;
}
BaconBackground *BaconBackground::addRoundedBorder( Vec pos, Vec sz, NVGcolor fill )
{
addChild( new InternalRoundedBorder( pos, sz, fill ) );
return this;
}
NVGcolor BaconBackground::bg = nvgRGBA( 220, 220, 210, 255 );
NVGcolor BaconBackground::bgOutline = nvgRGBA( 180, 180, 170, 255 );
NVGcolor BaconBackground::highlight = nvgRGBA( 90, 90, 60, 255 );
BaconBackground::BaconBackground( Vec size, const char* lab ) : title( lab )
{
box.pos = Vec( 0, 0 );
box.size = size;
}
FramebufferWidget* BaconBackground::wrappedInFramebuffer()
{
FramebufferWidget *fb = new FramebufferWidget();
fb->box = box;
fb->addChild( this );
return fb;
}
BaconBackground *BaconBackground::addLabelsForHugeKnob( Vec topLabelPos,
const char* knobLabel,
const char* zeroLabel,
const char* oneLabel,
Vec &putKnobHere )
{
addLabel( topLabelPos, knobLabel, 14, NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE );
addLabel( Vec( topLabelPos.x + 10, topLabelPos.y + 72 ),
oneLabel, 13, NVG_ALIGN_LEFT | NVG_ALIGN_TOP );
addLabel( Vec( topLabelPos.x - 10, topLabelPos.y + 72 ),
zeroLabel, 13, NVG_ALIGN_RIGHT | NVG_ALIGN_TOP );
putKnobHere.y = topLabelPos.y + 10;
putKnobHere.x = topLabelPos.x - 28;
return this;
}
BaconBackground *BaconBackground::addLabelsForLargeKnob( Vec topLabelPos,
const char* knobLabel,
const char* zeroLabel,
const char* oneLabel,
Vec &putKnobHere )
{
addLabel( topLabelPos, knobLabel, 14, NVG_ALIGN_CENTER | NVG_ALIGN_MIDDLE );
addLabel( Vec( topLabelPos.x + 10, topLabelPos.y + 48 ),
oneLabel, 13, NVG_ALIGN_LEFT | NVG_ALIGN_TOP );
addLabel( Vec( topLabelPos.x - 10, topLabelPos.y + 48 ),
zeroLabel, 13, NVG_ALIGN_RIGHT | NVG_ALIGN_TOP );
putKnobHere.y = topLabelPos.y + 10;
putKnobHere.x = topLabelPos.x - 18;
return this;
}
| 27.091216 | 133 | 0.598828 | SwellLay |
194c55840cd663a5469b08b9d3889f3cdf14ae42 | 538 | cpp | C++ | Main course/Homework4/Problem1/Source files/MovingAverager.cpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | Main course/Homework4/Problem1/Source files/MovingAverager.cpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | Main course/Homework4/Problem1/Source files/MovingAverager.cpp | nia-flo/FMI-OOP | 9d6ab384b5b7a48e76965ca5bff1e6a995b1bcba | [
"MIT"
] | null | null | null | #include "MovingAverager.hpp"
MovingAverager::MovingAverager(const std::string& id, size_t windowSize)
: Averager(id),
windowSize(windowSize)
{
}
int MovingAverager::read() const
{
if (this->messages.size() < this->windowSize || this->windowSize == 0)
{
return this->Averager::read();
}
int sum = 0;
for (int i = 0; i < this->windowSize; i++)
{
sum += this->messages[this->messages.size() - i - 1].data;
}
return sum / this->windowSize;
}
Averager* MovingAverager::clone() const
{
return new MovingAverager(*this);
}
| 19.214286 | 72 | 0.667286 | nia-flo |
194d3882de93eb3670f030525233322fb26c1457 | 1,364 | cpp | C++ | Codechef/CHEFFILT2.cpp | jceplaras/competitiveprogramming | d92cbedd31d9aa812a6084aea50e573886e5e6e4 | [
"MIT"
] | null | null | null | Codechef/CHEFFILT2.cpp | jceplaras/competitiveprogramming | d92cbedd31d9aa812a6084aea50e573886e5e6e4 | [
"MIT"
] | null | null | null | Codechef/CHEFFILT2.cpp | jceplaras/competitiveprogramming | d92cbedd31d9aa812a6084aea50e573886e5e6e4 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <cmath>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <string>
#include <vector>
#define FOR(i,a,b) for (int i = a; i <= b; i++)
#define FORN(i,N) for (int i = 0; i < N; i++)
#define FORD(i,a,b) for (int i = a; i >= b; i--)
#define MOD 1000000007
#define L 4
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef pair<int,int> pii;
typedef vector<pii> vpii;
ull DP[100001][1024];
int store[100001];
int main() {
int T,N;
char temp[11];
scanf("%d",&T);
while(T--) {
int target = 0;
scanf("%s",temp);
FORN(i,L)
if(temp[i] == 'w')
target = target + (1 << i);
scanf("%d",&N);
//printf("t: %d\n",target);
FORN(x,N) {
scanf("%s",temp);
int val = 0;
FORN(i,L)
if(temp[i] == '+')
val = val + ( 1 << i);
store[x+1] = val;
}
DP[0][0] = 1;
for(int i=1;i<=N;i++) {
for(int j=0;j<=1023;j++) {
DP[i][j] = (DP[i-1][j]%MOD + DP[i-1][j ^ store[i]]%MOD)%MOD;
}
}
printf("%llu\n",DP[N][target]);
FORN(i,N+1) {
FORN(j,16) {
printf("%3d ",DP[i][j]);
}
printf("\n");
}
FORN(j,1024)
DP[0][j] = 0;
}
return 0;
}
| 16.839506 | 68 | 0.495601 | jceplaras |
194dd687dae0075f8a48fd71e1355d9575ea9383 | 1,557 | cpp | C++ | src/jgw_play.cpp | jonathanmarp/jgw | 0ca017bd5e0073028afe0e0daafc362fc4994e06 | [
"MIT"
] | 5 | 2021-03-21T06:34:56.000Z | 2021-05-05T03:11:18.000Z | src/jgw_play.cpp | jonathanmarp/jgw | 0ca017bd5e0073028afe0e0daafc362fc4994e06 | [
"MIT"
] | 14 | 2021-04-02T09:06:47.000Z | 2022-03-02T05:12:11.000Z | src/jgw_play.cpp | thekotekjournal/jgw | 4a260af2260ea45c9607b29eee9104fe471cd126 | [
"MIT"
] | 6 | 2021-04-02T04:47:14.000Z | 2021-05-05T03:45:48.000Z | /* Library C++ */
#include <iostream>
#include "../app/include/sound.h"
#include "../app/include/structure.h"
#include "../app/include/fileshelp.h"
#include "../app/include/jgw_play.h"
void JGW_PLAY::SetStructRefrenchToZero(std::vector<compileSound>& __BUFF__)
{
__BUFF__[__BUFF__.size() - 1].S_HZ = 0;
__BUFF__[__BUFF__.size() - 1].D_DURATION = 0;
}
void JGW_PLAY::PrintDev(int& index, double& SSH_Z, float& CCS_Z)
{
std::cout << index + 1 << ". " << (double)SSH_Z << "Hz | ";
std::cout << CCS_Z << "ms" << std::endl;
}
void JGW_PLAY::StartMusic(std::string nameFile)
{
FILESHELP FSH_I(nameFile.c_str());
switch(FSH_I.itsExist()) {
case false: {
std::cout << "Undefined File Name : " << nameFile << std::endl;
}
break;
}
FSH_I.F_openFile();
std::vector<compileSound> compilingSoundGet;
for(int i = 0; i < FSH_I.getVarFile().tellg(); i += 1)
{
compileSound _BUFF_;
FSH_I.getVarFile().seekg(i * sizeof(compileSound));
FSH_I.getVarFile().read((char*)&_BUFF_, sizeof(compileSound));
for(int j = 0; j < _BUFF_.duplicate; j++) {
compilingSoundGet.push_back(_BUFF_);
}
}
SetStructRefrenchToZero(compilingSoundGet);
for(int i = 0; i < compilingSoundGet.size(); i++)
{
#ifdef _DEV
PrintDev(i, compilingSoundGet[i].S_HZ, compilingSoundGet[i].D_DURATION);
#endif
sound snd;
snd.tone((double)compilingSoundGet[i].S_HZ, (int)compilingSoundGet[i].D_DURATION);
}
FSH_I.F_closeFile();
}
int JGW_PLAY::main(int argc, const char* argv[]) {
for(int i = 0; i < argc; i++) {
StartMusic(argv[i]);
}
return 0;
} | 24.328125 | 84 | 0.662813 | jonathanmarp |
19526bf04fa98be8c7080adc417ac2586ef9752b | 1,205 | cpp | C++ | yelp/LT-418 Sentence Screen Fitting.cpp | yekesit/OA-or-Interview-Questions | 89c0a4db10c4ffde6d49835c0621f9ec2e04f141 | [
"MIT"
] | null | null | null | yelp/LT-418 Sentence Screen Fitting.cpp | yekesit/OA-or-Interview-Questions | 89c0a4db10c4ffde6d49835c0621f9ec2e04f141 | [
"MIT"
] | null | null | null | yelp/LT-418 Sentence Screen Fitting.cpp | yekesit/OA-or-Interview-Questions | 89c0a4db10c4ffde6d49835c0621f9ec2e04f141 | [
"MIT"
] | null | null | null | //
// Created by Ke Ye on 2019-08-08.
//
#include <iostream>
#include <vector>
using namespace std;
// Review here. Since the filling task can be repetitive, so we should record some previous situation to save time
// if there are much more loops in the future.
class Solution{
public:
int wordsTyping(vector<string>& sentence, int rows, int cols) {
int num = 0;
int size = sentence.size();
vector<int> cnt(size);
for(int i = 0; i < rows; i++){
int cur_start = num % size;
if(cnt[cur_start]){
num += cnt[cur_start];
}
else{
int len = 0;
int cur_cnt = 0;
int right = cur_start;
while(len + sentence[right].size() <= cols){
len += sentence[right].size() + 1;
right = (right + 1) % size;
cur_cnt++;
}
// Can not use idx and right to get count directly since right can increase from size - 1 to 0....
cnt[cur_start] = cur_cnt;
num += cur_cnt;
}
}
return num / size;
}
};
int main() {
} | 28.690476 | 114 | 0.493776 | yekesit |
195ace1041792a7a12199ef9db96ec4c5c252ad8 | 1,381 | cpp | C++ | src/test/vector_test.cpp | Coolnesss/max-flow | 12e5acd32206f4b2f63e111600e7fa8f6eec9411 | [
"Apache-2.0"
] | null | null | null | src/test/vector_test.cpp | Coolnesss/max-flow | 12e5acd32206f4b2f63e111600e7fa8f6eec9411 | [
"Apache-2.0"
] | 2 | 2016-10-02T18:58:33.000Z | 2016-10-15T13:50:39.000Z | src/test/vector_test.cpp | Coolnesss/max-flow | 12e5acd32206f4b2f63e111600e7fa8f6eec9411 | [
"Apache-2.0"
] | null | null | null | typedef long long ll;
#include "catch.hpp"
#include "../data-structures/vector.h"
TEST_CASE( "Vector allocates zeros for size n", "[vector]" ) {
int n = 10;
vector<int> v(n);
for(int i = 0; i < n; i++) {
REQUIRE(v[i] == 0);
}
}
TEST_CASE( "Vector retains elements", "[vector]" ) {
int n = 10;
vector<int> v(n);
for(int i = 0; i < n; i++) {
v[i] = i;
}
for(int i = 0; i < n; i++) {
REQUIRE(v[i] == i);
}
}
TEST_CASE("Vector of vectors retains elements", "[vector]" ) {
int n = 2;
vector<vector<int>> v(n, vector<int>(n));
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
v[i][j] = i;
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
REQUIRE(v[i][j] == i);
}
}
}
TEST_CASE("Vector clear sets all values to blank", "[vector]" ) {
vector<ll> v(10);
for(int i = 0; i < 10; i++) {
v[i] = 18*i;
}
v.clear();
for(auto a : v) {
REQUIRE(a == 0);
}
}
TEST_CASE("push_back allocates space dynamically and retains elements", "[vector]" ) {
vector<int> v;
int n = 20;
for(int i = 0; i < n; i++) {
v.push_back(i);
}
REQUIRE(v.size() == 20);
for(int i = 0; i < n; i++) {
REQUIRE(v[i] == i);
}
} | 19.180556 | 86 | 0.43664 | Coolnesss |
1962b799269954123b3617d370ffd1701df2f62e | 497 | cpp | C++ | AED/6/6q6.cpp | Iigorsf/AED | 2151ef562be8088cd76efe7afb9e73b165027fa1 | [
"MIT"
] | null | null | null | AED/6/6q6.cpp | Iigorsf/AED | 2151ef562be8088cd76efe7afb9e73b165027fa1 | [
"MIT"
] | null | null | null | AED/6/6q6.cpp | Iigorsf/AED | 2151ef562be8088cd76efe7afb9e73b165027fa1 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int matriz[6][4], maior;
for( int i=0; i<6; i++){
for( int j=0; j<4; j++){
cin>>matriz[i][j];
}
}
for( int i=0; i<6; i++){
maior = matriz[i][0];
for( int j=0; j<4; j++){
if(matriz[i][j]>maior){
maior=matriz[i][j];
}
}
for( int j=0; j<4; j++){
matriz[i][j]=matriz[i][j]*maior;
}
}
for( int i=0; i<6; i++){
for( int j=0; j<4; j++){
cout<<matriz[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
| 15.060606 | 34 | 0.466801 | Iigorsf |
196a2b24c8368e877fc4abf5be65ded478dfd3de | 1,057 | cpp | C++ | dynamic_programming/alphacode.cpp | ankit2001/CP_Algos | eadc0f9cd92a5a01791e3171dfe894e6db948b2b | [
"MIT"
] | 1 | 2020-08-11T17:50:01.000Z | 2020-08-11T17:50:01.000Z | dynamic_programming/alphacode.cpp | ankit2001/CP_Algos | eadc0f9cd92a5a01791e3171dfe894e6db948b2b | [
"MIT"
] | null | null | null | dynamic_programming/alphacode.cpp | ankit2001/CP_Algos | eadc0f9cd92a5a01791e3171dfe894e6db948b2b | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
string s;
while (cin >> s) {
if (s == "0") {
break;
}
int len = s.length();
long long dp[len + 1];
bool vis[len + 1];
memset (vis, false, sizeof(vis));
function <long long(int)> alphacode = [&] (int n) {
if(n >= len) {
return 1ll;
}
auto &ans = dp[n];
auto &seen = vis[n];
if (!seen) {
seen = true;
if (n == len - 1) {
if (s[n] != '0') {
ans = 1ll;
} else {
ans = 0ll;
}
return ans;
}
if (s[n] == '0') {
return 0ll;
}
if (s[n + 1] == '0') {
ans = alphacode(n + 2);
return ans;
} else {
ans = alphacode(n + 1);
if ((s[n] - '0') * 10 + (s[n + 1] - '0') <= 26) {
ans += alphacode(n + 2);
}
}
}
return ans;
};
cout << alphacode(0) << "\n";
}
} | 21.14 | 59 | 0.375591 | ankit2001 |
196ce0d6a01b2638a5ac77fa4ce3d8ae5f8fc2a8 | 8,065 | cpp | C++ | src/CWindowManager.cpp | AGLExport/ilm-manager | 6ba0d1f9466693c9c9f30447d50c6b91b40712d2 | [
"Apache-2.0"
] | null | null | null | src/CWindowManager.cpp | AGLExport/ilm-manager | 6ba0d1f9466693c9c9f30447d50c6b91b40712d2 | [
"Apache-2.0"
] | null | null | null | src/CWindowManager.cpp | AGLExport/ilm-manager | 6ba0d1f9466693c9c9f30447d50c6b91b40712d2 | [
"Apache-2.0"
] | 1 | 2020-01-16T11:37:36.000Z | 2020-01-16T11:37:36.000Z | #include "CWindowManager.hpp"
#include <string>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <unistd.h>
//-----------------------------------------------------------------------------
CWindowManager::CWindowManager()
{
}
//-----------------------------------------------------------------------------
CWindowManager::~CWindowManager()
{
}
//-----------------------------------------------------------------------------
CWindowManager CWindowManager::m_Win;
CWindowManager* CWindowManager::getInstance()
{
return &m_Win;
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void CWindowManager::ILMSurfaceCallbackFunctionStatic(t_ilm_uint id, struct ilmSurfaceProperties* sp, t_ilm_notification_mask m)
{
CWindowManager *pwin = CWindowManager::getInstance();
pwin->ILMSurfaceCallbackFunction(id, sp, m);
}
//-----------------------------------------------------------------------------
void CWindowManager::ILMCallBackFunctionStatic(ilmObjectType object, t_ilm_uint id, t_ilm_bool created, void *user_data)
{
CWindowManager *pwin = CWindowManager::getInstance();
pwin->ILMCallBackFunction(object, id, created);
}
//-----------------------------------------------------------------------------
void CWindowManager::ILMSurfaceCallbackFunction(t_ilm_uint id, struct ilmSurfaceProperties* sp, t_ilm_notification_mask m)
{
if ((unsigned)m & ILM_NOTIFICATION_CONFIGURED)
{
#ifdef _USER_DEBUG_
printf("CWindowManager::ILMSurfaceCallbackFunction: surface (%d) configured \n",id);
#endif
this->HandlingSurface(id, sp->origSourceWidth, sp->origSourceHeight);
}
}
//-----------------------------------------------------------------------------
void CWindowManager::ILMCallBackFunction(ilmObjectType object, t_ilm_uint id, t_ilm_bool created)
{
struct ilmSurfaceProperties sp;
if ( object == ILM_SURFACE )
{
if (created == ILM_TRUE )
{
ilm_getPropertiesOfSurface(id, &sp);
if ((sp.origSourceWidth != 0) && (sp.origSourceHeight !=0))
{ // surface is already configured
#ifdef _USER_DEBUG_
printf("CWindowManager::ILMCallBackFunction: surface (%d) is already configured \n",id);
#endif
this->HandlingSurface(id, sp.origSourceWidth, sp.origSourceHeight);
}
else
{
// wait for configured event
#ifdef _USER_DEBUG_
printf("CWindowManager::ILMCallBackFunction: surface (%d) wait for configured event \n",id);
#endif
ilm_surfaceAddNotification(id,&ILMSurfaceCallbackFunctionStatic);
ilm_commitChanges();
}
}
else
{
#ifdef _USER_DEBUG_
printf("CWindowManager::ILMCallBackFunction: surface (%d) remove \n",id);
#endif
ilm_surfaceRemoveNotification(id);
this->RemoveSurface(id);
}
}
else if (object == ILM_LAYER)
{
#ifdef _USER_DEBUG_
if (created == ILM_TRUE )
printf("CWindowManager::ILMCallBackFunction: layer (%u) created\n",id);
else
printf("CWindowManager::ILMCallBackFunction: layer (%u) destroyed\n",id);
#endif
}
}
//-----------------------------------------------------------------------------
bool CWindowManager::HandlingSurface(t_ilm_uint id, t_ilm_uint width, t_ilm_uint height)
{
t_ilm_uint lid = 0;
t_ilm_uint x=0, y=0, z=0;
ilmInputDevice mask = 0;
std::string surfacename, layername;
if (this->m_Config->GetSurfaceInfoById(id, surfacename, layername, x, y, z, mask) == true)
{
CIVISurface *psurface = new CIVISurface();
CIVILayer *player = NULL;
player = this->GetLayerByName(layername);
if (player != NULL)
{
psurface->ConfiguredSurface(id, x, y, z, width, height, mask);
player->AddSurface(psurface);
ilm_commitChanges();
}
}
#ifdef _USER_DEBUG_
printf("layer-add-surfaces: surface (%u) configured with:\n"
" dst region: x:0 y:0 w:%u h:%u\n"
" src region: x:0 y:0 w:%u h:%u\n"
" input mask: %X\n"
" visibility: TRUE\n"
" added to layer\n", id, width, height, width, height, (unsigned int)mask);
#endif
return true;
}
//-----------------------------------------------------------------------------
bool CWindowManager::RemoveSurface(t_ilm_uint id)
{
CIVISurface* psurface = this->GetSurfaceById(id);
if (psurface != NULL)
{
CIVILayer *player = psurface->GetParentLayer();
player->RemoveSurface(psurface);
ilm_commitChanges();
delete psurface;
return true;
}
return false;
}
//-----------------------------------------------------------------------------
bool CWindowManager::WindowManagerInitialize()
{
while (ilm_init() == ILM_FAILED)
{
usleep(10000); //10ms
}
this->m_Config = new (std::nothrow)CILMConfig();
this->ScreenSearch();
this->CreateLayers();
::ilm_registerNotification(ILMCallBackFunctionStatic, (void*)this);
return true;
}
//-----------------------------------------------------------------------------
bool CWindowManager::CreateLayers()
{
int layernum;
layernum = this->m_Config->GetLayerNum();
for(int i=0;i < layernum;i++)
{
std::string layername, screenname;
if (this->m_Config->GetLayerName(i, layername) == true )
{
if (this->m_Config->GetLayerAttachScreen(i, screenname) == true )
{
t_ilm_uint id, width, height, x, y, z;
CIVIScreen* psc = this->GetScreenByName(screenname);
if (psc != NULL)
{
if (this->m_Config->GetLayerInfo(i, id, width, height, x, y, z) == true)
{
CIVILayer * ivilayer = new (std::nothrow) CIVILayer();
ivilayer->CreateLayer(x, y, z, width, height, id, layername);
psc->AddLayer(ivilayer);
}
}
}
}
}
return true;
}
//-----------------------------------------------------------------------------
CIVIScreen* CWindowManager::GetScreenByName(std::string name)
{
int num = m_Screen.size();
for(int i=0;i < num;i++)
{
if (this->m_Screen[i]->GetScreenName() == name)
{
return this->m_Screen[i];
}
}
return NULL;
}
//-----------------------------------------------------------------------------
CIVILayer* CWindowManager::GetLayerByName(std::string layername)
{
int num = m_Screen.size();
for(int i=0;i < num;i++)
{
CIVILayer* pLayer = this->m_Screen[i]->GetLayerByName(layername);
if (pLayer != NULL)
{
return pLayer;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
CIVILayer* CWindowManager::GetLayerById(t_ilm_uint id)
{
int num = m_Screen.size();
for(int i=0;i < num;i++)
{
CIVILayer* pLayer = this->m_Screen[i]->GetLayerById(id);
if (pLayer != NULL)
{
return pLayer;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
CIVISurface* CWindowManager::GetSurfaceById(t_ilm_uint id)
{
int num = m_Screen.size();
for(int i=0;i < num;i++)
{
CIVISurface* psurface = this->m_Screen[i]->GetSurfaceById(id);
if (psurface != NULL)
{
return psurface;
}
}
return NULL;
}
//-----------------------------------------------------------------------------
bool CWindowManager::ScreenSearch()
{
struct ilmScreenProperties screenProperties;
t_ilm_uint* screen_IDs = NULL;
t_ilm_uint screen_ID = 0;
t_ilm_uint screen_count = 0;
t_ilm_uint choosen_width = 0;
t_ilm_uint choosen_height = 0;
int i;
ilm_getScreenIDs(&screen_count, &screen_IDs);
for (int i = 0; i < screen_count; i++)
{
ilm_getPropertiesOfScreen(screen_IDs[i], &screenProperties);
CIVIScreen *psc = new(std::nothrow) CIVIScreen();
if ( psc != NULL)
{
std::string screenname, connectorname = std::string(screenProperties.connectorName);
if (this->m_Config->GetScreenNameByConnectorName(connectorname, screenname) == true)
{
psc->SetParameter(screen_IDs[i], screenname, connectorname, screenProperties.screenWidth, screenProperties.screenHeight);
int num = this->m_Screen.size();
this->m_Screen.resize(num+1);
this->m_Screen[num] = psc;
}
}
}
::free(screen_IDs);
return true;
}
//-----------------------------------------------------------------------------
| 26.617162 | 128 | 0.566894 | AGLExport |
196dfc719a1a0bf84ab9173208b49f035b469815 | 3,697 | cpp | C++ | tests/src/calc_helper.cpp | DmitryDzz/calculator-comrade-lib | 107930ef7df88b330b800993028b35d08d5d78f6 | [
"MIT"
] | 4 | 2021-01-18T03:11:14.000Z | 2022-01-29T09:17:06.000Z | tests/src/calc_helper.cpp | DmitryDzz/calculator-comrade-lib | 107930ef7df88b330b800993028b35d08d5d78f6 | [
"MIT"
] | 32 | 2018-10-11T22:05:14.000Z | 2019-05-26T16:25:38.000Z | tests/src/calc_helper.cpp | DmitryDzz/calculator-comrade-lib | 107930ef7df88b330b800993028b35d08d5d78f6 | [
"MIT"
] | null | null | null | /**
* Calculator Comrade Library
* License: https://github.com/DmitryDzz/calculator-comrade-lib/blob/master/LICENSE
* Author: Dmitry Dzakhov
* Email: info@robot-mitya.ru
*/
#include "calc_helper.h"
#define S1 ((int8_t)1)
using calculatorcomrade::Register;
using calculatorcomrade::Button;
int64_t calculatorcomrade::getAbsIntValue(Register &r) {
int64_t result = 0;
int64_t factor = 1;
int8_t digits = r.getSize();
for (int i = 0; i < digits; i++, factor *= 10)
result += factor * r.getDigit((int8_t)i);
return result;
}
int64_t calculatorcomrade::getIntValue(Register &r) {
return r.isNegative() ? -getAbsIntValue(r) : getAbsIntValue(r);
}
void calculatorcomrade::setValue(Register &r, int64_t value) {
setValue(r, value, 0);
}
void calculatorcomrade::setValue(Register &r, int64_t value, int8_t digitsAfterPoint) {
int8_t digits = r.getSize();
bool isNegative = value < 0;
std::string text = std::to_string(isNegative ? -value : value);
auto totalDigits = (int8_t) text.size();
if (digitsAfterPoint < totalDigits) {
int8_t intDigits = totalDigits - digitsAfterPoint;
r.setError(intDigits > digits, intDigits > digits);
if (r.hasError()) {
r.setPointPos(digits - (intDigits - digits));
for (int16_t i = 0; i < digits; i++) {
char digitChar = text[digits - i - 1];
std::string digitText(1, digitChar);
r.setDigit((int8_t)i, (int8_t)std::stoi(digitText));
}
} else {
if (totalDigits > digits) {
r.setPointPos(digits - intDigits);
for (int16_t i = 0; i < digits; i++) {
char digitChar = text[digits - i - 1];
std::string digitText(1, digitChar);
r.setDigit((int8_t)i, (int8_t)std::stoi(digitText));
}
} else {
r.setPointPos(digitsAfterPoint);
for (int16_t i = 0; i < digits; i++) {
char digitChar = i < totalDigits ? text[totalDigits - i - 1] : '0';
std::string digitText(1, digitChar);
r.setDigit((int8_t)i, (int8_t)std::stoi(digitText));
}
}
}
} else { // means: (digitsAfterPoint >= totalDigits)
r.setError(false, false);
int8_t newTotalDigits = digitsAfterPoint + S1;
int16_t delta = newTotalDigits > digits ? newTotalDigits - digits : (int16_t) 0;
if (newTotalDigits - totalDigits >= digits) {
r.setPointPos(0);
} else {
r.setPointPos(delta > (int8_t) 0 ? (int8_t) (digitsAfterPoint - delta) : digitsAfterPoint);
}
for (int16_t i = 0; i < digits; i++) {
int16_t charIndex = totalDigits - delta - S1 - i;
char digitChar = charIndex >= 0 ? text[charIndex] : '0';
std::string digitText(1, digitChar);
r.setDigit((int8_t)i, (int8_t)std::stoi(digitText));
}
}
r.setNegative(isNegative);
}
void calculatorcomrade::evaluateText(Register &r, std::string *output) {
int8_t size = r.getSize();
if (size == 0) {
*output = "Empty";
return;
}
auto digitsInGroup = static_cast<int8_t>(size == 6 ? 3 : 4);
*output = "";
if (r.hasError())
*output += "[Err]";
if (r.isNegative())
*output += "–";
for (int8_t i = 0; i < size; i++) {
if (i % digitsInGroup == 0 && i != 0)
*output += " ";
*output += std::to_string(r.getDigit(size - i - S1));
if (i == size - r.getPointPos() - S1)
*output += ".";
}
}
| 34.551402 | 103 | 0.554233 | DmitryDzz |
1971188caa8747a255a45c7478e34dce6ea1288b | 1,135 | cpp | C++ | sources/2015/2015_03.cpp | tbielak/AoC_cpp | 69f36748536e60a1b88f9d44a285feff20df8470 | [
"MIT"
] | 2 | 2021-02-01T13:19:37.000Z | 2021-02-25T10:39:46.000Z | sources/2015/2015_03.cpp | tbielak/AoC_cpp | 69f36748536e60a1b88f9d44a285feff20df8470 | [
"MIT"
] | null | null | null | sources/2015/2015_03.cpp | tbielak/AoC_cpp | 69f36748536e60a1b88f9d44a285feff20df8470 | [
"MIT"
] | null | null | null | #include "2015_03.h"
namespace Day03_2015
{
int part_one(const string& s)
{
int x = 0;
int y = 0;
t_visitedLocations visited;
visited.insert(make_pair(x, y));
for (auto c : s)
{
if ('^' == c) y--;
if ('v' == c) y++;
if ('>' == c) x--;
if ('<' == c) x++;
visited.insert(make_pair(x, y));
}
return (int)visited.size();
}
int part_two(const string& s)
{
int x[2] = { 0, 0 };
int y[2] = { 0, 0 };
t_visitedLocations visited;
visited.insert(make_pair(x[0], y[0]));
int i = 0;
for (auto c : s)
{
if ('^' == c) y[i]--;
if ('v' == c) y[i]++;
if ('>' == c) x[i]--;
if ('<' == c) x[i]++;
visited.insert(make_pair(x[i], y[i]));
i ^= 1;
}
return (int)visited.size();
}
t_output main(const t_input& input)
{
string line = input[0];
auto t0 = chrono::steady_clock::now();
auto p1 = part_one(line);
auto p2 = part_two(line);
auto t1 = chrono::steady_clock::now();
vector<string> solutions;
solutions.push_back(to_string(p1));
solutions.push_back(to_string(p2));
return make_pair(solutions, chrono::duration<double>((t1 - t0) * 1000).count());
}
}
| 18.916667 | 82 | 0.553304 | tbielak |
1973007b1fc2d1651caffc6edd2faaf7f2e20760 | 2,206 | cpp | C++ | Kaminec/kits/JsonKit/Library.cpp | kaniol-lck/Kaminec | bdbb6645035d6124a3772742362e683938b389fb | [
"BSD-2-Clause"
] | 23 | 2017-06-23T11:58:27.000Z | 2022-03-05T06:58:49.000Z | Kaminec/kits/JsonKit/Library.cpp | kaniol-lck/Kaminec | bdbb6645035d6124a3772742362e683938b389fb | [
"BSD-2-Clause"
] | 4 | 2017-12-08T11:41:19.000Z | 2021-04-03T17:50:39.000Z | Kaminec/kits/JsonKit/Library.cpp | kaniol-lck/Kaminec | bdbb6645035d6124a3772742362e683938b389fb | [
"BSD-2-Clause"
] | 5 | 2019-02-19T13:03:42.000Z | 2021-11-04T13:58:04.000Z | #include "Library.h"
#include "kits/Ruler/Ruler.h"
#include "assistance/utility.h"
#include "assistance/systeminfo.h"
#include <QUrl>
#include <QDebug>
Library::Library(const QVariant &libraryVariant) :
libraryVariant_(libraryVariant),
name_(value(libraryVariant_, "name").toString()),
nameList_(name_.split(":"))
{}
QString Library::name() const
{
return name_;
}
QString Library::package() const
{
return nameList_.at(0);
}
QString Library::packageName() const
{
return nameList_.at(1);
}
QString Library::version() const
{
return nameList_.at(2);
}
QString Library::fileName() const
{
if(isNatives())
return QString("%1-%2-%3.jar")
.arg(packageName(), version(), nativeKey());
else
return QString("%1-%2.jar")
.arg(packageName(), version());
}
int Library::size() const
{
return isNatives()?value(libraryVariant_, "downloads", "classifiers", nativeKey(), "size").toInt():
value(libraryVariant_, "downloads", "artifact", "size").toInt();
}
QString Library::sha1() const
{
return isNatives()?value(libraryVariant_, "downloads", "classifiers", nativeKey(), "sha1").toString():
value(libraryVariant_, "downloads", "artifact", "sha1").toString();
}
QString Library::path() const
{
if(isNatives())
return QString("<libraries>/%1/%2/%3/%2-%3-%4.jar")
.arg(package().replace(".", "/"), packageName(), version(), nativeKey());
else
return QString("<libraries>/%1/%2/%3/%2-%3.jar")
.arg(package().replace(".", "/"), packageName(), version());
}
QUrl Library::url() const
{
return isNatives()?value(libraryVariant_, "downloads", "classifiers", nativeKey(), "url").toUrl():
value(libraryVariant_, "downloads", "artifact", "url").toUrl();
}
QString Library::nativeKey() const
{
return value(libraryVariant_, "natives", sysName()).toString()
.replace("${arch}", QString::number(sysWordSize()));
}
bool Library::isNatives() const
{
return libraryVariant_.toMap().contains("natives") &&
value(libraryVariant_, "natives").toMap().contains(sysName());
}
bool Library::isAllow() const
{
if(libraryVariant_.toMap().contains("rules")){
Ruler ruler(value(libraryVariant_, "rules"));
return ruler.isAllow();
}else{
return true;
}
}
| 23.221053 | 103 | 0.674977 | kaniol-lck |
197993a7d4e72c93beca0516f5ddf9a9626db320 | 1,269 | cpp | C++ | rpzwh_2_dtm/cpps/solarianLED.cpp | blusky-cloud/Raspi-Code | 6296a04d34819eed9b3a899bf9ae8c3cd4423c1d | [
"BSL-1.0"
] | 1 | 2022-02-08T02:32:56.000Z | 2022-02-08T02:32:56.000Z | rpzwh_2_dtm/cpps/solarianLED.cpp | blusky-cloud/Raspi-Code | 6296a04d34819eed9b3a899bf9ae8c3cd4423c1d | [
"BSL-1.0"
] | null | null | null | rpzwh_2_dtm/cpps/solarianLED.cpp | blusky-cloud/Raspi-Code | 6296a04d34819eed9b3a899bf9ae8c3cd4423c1d | [
"BSL-1.0"
] | null | null | null | #include <iostream>
#include <wiringPi.h>
#include <csignal>
// global flag used to exit from the main loop
bool RUNNING = true;
// Blink an LED
void blink_led(int led, int time) {
digitalWrite(led, HIGH);
delay(time);
digitalWrite(led, LOW);
delay(time);
}
// Callback handler if CTRL-C signal is detected
void my_handler(int s) {
std::cout << "Detected CTRL-C signal no. " << s << '\n';
RUNNING = false;
}
int main() {
// Register a callback function to be called if the user presses CTRL-C
std::signal(SIGINT, my_handler);
// Initialize wiringPi and allow the use of BCM pin numbering
wiringPiSetupGpio();
std::cout << "Controlling the GPIO pins with wiringPi\n";
// Define the 3 pins we are going to use
int red = 16;//, yellow = 22, green = 6;
// Setup the pins
pinMode(red, OUTPUT);
// pinMode(yellow, OUTPUT);
// pinMode(green, OUTPUT);
int time = 1000; // interval at which a pin is turned HIGH/LOW
int count = 0;
while(RUNNING && count < 10) {
blink_led(red, time);
// blink_led(yellow, time);
// blink_led(green, time);
++count;
}
std::cout << "Program ended ...\n";
}
| 25.38 | 76 | 0.588652 | blusky-cloud |
19858eb4249b6fe8b496190023cf7166a77780ba | 129 | cpp | C++ | dependencies/physx-4.1/source/foundation/src/PsAssert.cpp | realtehcman/-UnderwaterSceneProject | 72cbd375ef5e175bed8f4e8a4d117f5340f239a4 | [
"MIT"
] | null | null | null | dependencies/physx-4.1/source/foundation/src/PsAssert.cpp | realtehcman/-UnderwaterSceneProject | 72cbd375ef5e175bed8f4e8a4d117f5340f239a4 | [
"MIT"
] | null | null | null | dependencies/physx-4.1/source/foundation/src/PsAssert.cpp | realtehcman/-UnderwaterSceneProject | 72cbd375ef5e175bed8f4e8a4d117f5340f239a4 | [
"MIT"
] | null | null | null | version https://git-lfs.github.com/spec/v1
oid sha256:81996102777c13296c4e54e89a255faa84d682e88c4ec0130d884d277924cdd8
size 3192
| 32.25 | 75 | 0.883721 | realtehcman |
199036f162864709822bb64d4dd0d57b689c307f | 485 | cpp | C++ | title/remove_special_char.cpp | hurenhe2008/algorithm | 2afb03bf91a9d234df5396e6b1d7fe8f57daa6c7 | [
"MIT"
] | null | null | null | title/remove_special_char.cpp | hurenhe2008/algorithm | 2afb03bf91a9d234df5396e6b1d7fe8f57daa6c7 | [
"MIT"
] | null | null | null | title/remove_special_char.cpp | hurenhe2008/algorithm | 2afb03bf91a9d234df5396e6b1d7fe8f57daa6c7 | [
"MIT"
] | null | null | null |
/*
@func
remove_special_char - remove special char in string and
adjust valid chars to front.
@params
array - the unsigned int array
num - the array size
@return
the remove special char numbers
*/
unsigned remove_special_char(char *str, char ch)
{
unsigned cnt = 0;
while(*str) {
if (ch == *str) {
*str = '\0'; /*use '\0' instead ch, think about str's end is ch*/
++cnt;
}
else {
*(str - cnt) = *str;
}
}
return cnt;
}
| 16.166667 | 71 | 0.581443 | hurenhe2008 |
1994a2a0d61bc0c34ccff380cb0844352e9eb80c | 9,212 | hpp | C++ | include/fl/filter/gaussian/update_policy/multi_sensor_sigma_point_update_policy.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 17 | 2015-07-03T06:53:05.000Z | 2021-05-15T20:55:12.000Z | include/fl/filter/gaussian/update_policy/multi_sensor_sigma_point_update_policy.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 3 | 2015-02-20T12:48:17.000Z | 2019-12-18T08:45:13.000Z | include/fl/filter/gaussian/update_policy/multi_sensor_sigma_point_update_policy.hpp | aeolusbot-tommyliu/fl | a50d0c9620a8f86e0cd14a5e22ee0f022d00bd02 | [
"MIT"
] | 15 | 2015-02-20T11:34:14.000Z | 2021-05-15T20:55:13.000Z | /*
* This is part of the fl library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2015 Max Planck Society,
* Autonomous Motion Department,
* Institute for Intelligent Systems
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file multi_sensor_sigma_point_update_policy.hpp
* \date August 2015
* \author Jan Issac (jan.issac@gmail.com)
*/
#pragma once
#include <Eigen/Dense>
#include <fl/util/meta.hpp>
#include <fl/util/types.hpp>
#include <fl/util/traits.hpp>
#include <fl/util/descriptor.hpp>
#include <fl/model/sensor/joint_sensor_iid.hpp>
#include <fl/filter/gaussian/transform/point_set.hpp>
#include <fl/filter/gaussian/quadrature/sigma_point_quadrature.hpp>
namespace fl
{
// Forward declarations
template <typename...> class MultiSensorSigmaPointUpdatePolicy;
/**
* \internal
*/
template <
typename SigmaPointQuadrature,
typename NonJoinSensor
>
class MultiSensorSigmaPointUpdatePolicy<
SigmaPointQuadrature,
NonJoinSensor>
{
static_assert(
std::is_base_of<
internal::JointSensorIidType, NonJoinSensor
>::value,
"\n\n\n"
"====================================================================\n"
"= Static Assert: You are using the wrong observation model type =\n"
"====================================================================\n"
" Observation model type must be a JointSensor<...>. \n"
" For single observation model, use the regular Gaussian filter \n"
" or the regular SigmaPointUpdatePolicy if you are specifying \n"
" the update policy explicitly fo the GaussianFilter. \n"
"====================================================================\n"
);
};
/**
* \brief Represents an update policy update for multiple sensors. This instance
* expects a \a JointSensor<>. The model is forwarded as
* NonAdditive<JointSensor> to the actual
* implementation. In case you want to use the model as Additive, you may
* specify this explicitly using Additive<JointSensor> or
* UseAsAdditive<JointSensor>::Type
*/
template <
typename SigmaPointQuadrature,
typename MultipleOfLocalSensor
>
class MultiSensorSigmaPointUpdatePolicy<
SigmaPointQuadrature,
JointSensor<MultipleOfLocalSensor>>
: public MultiSensorSigmaPointUpdatePolicy<
SigmaPointQuadrature,
NonAdditive<JointSensor<MultipleOfLocalSensor>>>
{ };
/**
* \brief Represents an update policy update functor for multiple sensors.
* This instance expects a \a NonAdditive<JointSensor<>>.
* The implementation exploits factorization in the joint observation.
* The update is performed for each sensor separately.
*/
template <
typename SigmaPointQuadrature,
typename MultipleOfLocalSensor
>
class MultiSensorSigmaPointUpdatePolicy<
SigmaPointQuadrature,
NonAdditive<JointSensor<MultipleOfLocalSensor>>>
: public Descriptor
{
public:
typedef JointSensor<MultipleOfLocalSensor> JointModel;
typedef typename JointModel::State State;
typedef typename JointModel::Obsrv Obsrv;
typedef typename JointModel::LocalObsrv LocalObsrv;
typedef typename JointModel::LocalNoise LocalObsrvNoise;
template <typename Belief>
void operator()(JointModel& obsrv_function,
const SigmaPointQuadrature& quadrature,
const Belief& prior_belief,
const Obsrv& y,
Belief& posterior_belief)
{
auto& sensor_model = obsrv_function.local_sensor();
/* ------------------------------------------ */
/* - Determine the number of quadrature - */
/* - points needed for the given quadrature - */
/* - in conjunction with the joint Gaussian - */
/* - p(State, LocalObsrvNoise) - */
/* ------------------------------------------ */
enum : signed int
{
NumberOfPoints = SigmaPointQuadrature::number_of_points(
JoinSizes<
SizeOf<State>::Value,
SizeOf<LocalObsrvNoise>::Value
>::Size)
};
/* ------------------------------------------ */
/* - PointSets - */
/* - [p_X, p_Q] ~ p(State, LocalObsrvNoise) - */
/* ------------------------------------------ */
PointSet<State, NumberOfPoints> p_X;
PointSet<LocalObsrvNoise, NumberOfPoints> p_Q;
/* ------------------------------------------ */
/* - PointSet [p_Y] = h(p_X, p_Q) - */
/* ------------------------------------------ */
PointSet<LocalObsrv, NumberOfPoints> p_Y;
/* ------------------------------------------ */
/* - Transform p(State, LocalObsrvNoise) to - */
/* - point sets [p_X, p_Q] - */
/* ------------------------------------------ */
quadrature.transform_to_points(
prior_belief,
Gaussian<LocalObsrvNoise>(sensor_model.noise_dimension()),
p_X,
p_Q);
/* ------------------------------------------ */
/* - Compute expected moments of the state - */
/* - E[X], Cov(X, X) - */
/* ------------------------------------------ */
auto W = p_X.covariance_weights_vector().asDiagonal();
auto mu_x = p_X.mean();
auto X = p_X.centered_points();
auto c_xx_inv = (X * W * X.transpose()).inverse().eval();
/* ------------------------------------------ */
/* - Temporary accumulators which will be - */
/* - used to updated the belief - */
/* ------------------------------------------ */
auto C = c_xx_inv;
auto D = State();
D.setZero(mu_x.size());
const int sensor_count = obsrv_function.count_local_models();
const int dim_y = y.size() / sensor_count;
/* ------------------------------------------ */
/* - lambda of the sensor observation - */
/* - function - */
/* ------------------------------------------ */
auto&& h = [&](const State& x, const LocalObsrvNoise& w)
{
return sensor_model.observation(x, w);
};
for (int i = 0; i < sensor_count; ++i)
{
// validate sensor value, i.e. make sure it is finite
if (!is_valid(y, i * dim_y, i * dim_y + dim_y)) continue;
// select current sensor and propagate the points through h(x, w)
sensor_model.id(i);
quadrature.propagate_points(h, p_X, p_Q, p_Y);
// comute expected moments of the observation and validate
auto mu_y = p_Y.mean();
if (!is_valid(mu_y, 0, dim_y)) continue;
// update accumulatorsa according to the equations in PAPER REF
auto Y = p_Y.centered_points();
auto c_xy = (X * W * Y.transpose()).eval();
auto c_yx = c_xy.transpose().eval();
auto A_i = (c_yx * c_xx_inv).eval();
auto c_yy_given_x = (
(Y * W * Y.transpose()) - c_yx * c_xx_inv * c_xy
).eval();
auto innovation = (y.middleRows(i * dim_y, dim_y) - mu_y).eval();
C += A_i.transpose() * solve(c_yy_given_x, A_i);
D += A_i.transpose() * solve(c_yy_given_x, innovation);
}
/* ------------------------------------------ */
/* - Update belief according to PAPER REF - */
/* ------------------------------------------ */
// make sure the posterior has the correct dimension
posterior_belief.dimension(prior_belief.dimension());
posterior_belief.covariance(C.inverse());
posterior_belief.mean(mu_x + posterior_belief.covariance() * D);
}
virtual std::string name() const
{
return "MultiSensorSigmaPointUpdatePolicy<"
+ this->list_arguments(
"SigmaPointQuadrature",
"NonAdditive<SensorFunction>")
+ ">";
}
virtual std::string description() const
{
return "Multi-Sensor Sigma Point based filter update policy "
"for joint observation model of multiple local observation "
"models with non-additive noise.";
}
private:
/**
* \brief Checks whether all vector components within the range (start, end)
* are finiate, i.e. not NAN nor Inf.
*/
template <typename Vector>
bool is_valid(Vector&& vector, int start, int end) const
{
for (int k = start; k < end; ++k)
{
if (!std::isfinite(vector(k))) return false;
}
return true;
}
};
}
| 35.844358 | 80 | 0.518563 | aeolusbot-tommyliu |
1996fdaa0551891e72d438070b60e5bb7fb1420e | 5,847 | cpp | C++ | test/configuration_test.cpp | fuersten/csvsqldb | 1b766ddf253805e31f9840cd3081cba559018a06 | [
"BSD-3-Clause"
] | 5 | 2015-09-10T08:53:41.000Z | 2020-05-30T18:42:20.000Z | test/configuration_test.cpp | fuersten/csvsqldb | 1b766ddf253805e31f9840cd3081cba559018a06 | [
"BSD-3-Clause"
] | 20 | 2015-09-29T16:16:07.000Z | 2021-06-13T08:08:05.000Z | test/configuration_test.cpp | fuersten/csvsqldb | 1b766ddf253805e31f9840cd3081cba559018a06 | [
"BSD-3-Clause"
] | 3 | 2015-09-09T22:51:44.000Z | 2020-11-11T13:19:42.000Z | //
// csvsqldb test
//
// BSD 3-Clause License
// Copyright (c) 2015, Lars-Christian Fürstenberg
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
#include "test.h"
#include "test/test_util.h"
#include "libcsvsqldb/base/exception.h"
#include "libcsvsqldb/base/default_configuration.h"
#include "libcsvsqldb/base/lua_configuration.h"
#include "libcsvsqldb/base/global_configuration.h"
#include <set>
class MyGlobalConfiguration : public csvsqldb::GlobalConfiguration
{
public:
struct Test {
int32_t wtf;
};
virtual void doConfigure(const csvsqldb::Configuration::Ptr& configuration)
{
test.wtf = configuration->get("test.wtf", 4711);
}
Test test;
};
class ConfigurationTestCase
{
public:
void setUp()
{
}
void tearDown()
{
}
void configTest()
{
csvsqldb::Configuration::Ptr config(
std::make_shared<csvsqldb::LuaConfiguration>(CSVSQLDB_TEST_PATH + std::string("/testdata/luaengine/test.lua")));
MPF_TEST_ASSERTEQUAL(10474, config->get("port", 9999));
MPF_TEST_ASSERT(std::fabs(47.11 - config->get("factor", 8.15)) < 0.0001);
MPF_TEST_ASSERTEQUAL("Thor", config->get("hostname", "horst"));
MPF_TEST_ASSERTEQUAL(100, config->get("server.threads", 10));
MPF_TEST_ASSERTEQUAL("LUA", config->get("server.api.code", "php"));
MPF_TEST_ASSERT(std::fabs(47.11 - config->get<double>("factor")) < 0.0001);
MPF_TEST_ASSERTEQUAL(true, config->get<bool>("daemonize"));
MPF_TEST_ASSERTEQUAL(2, config->get<int32_t>("debug.level.tcp_server"));
MPF_TEST_EXPECTS(csvsqldb::LuaConfiguration("not existent configuration"), csvsqldb::FilesystemException);
}
void configCheck()
{
csvsqldb::Configuration::Ptr config(
std::make_shared<csvsqldb::LuaConfiguration>(CSVSQLDB_TEST_PATH + std::string("/testdata/luaengine/test.lua")));
MPF_TEST_ASSERTEQUAL(true, config->hasProperty("daemonize"));
MPF_TEST_ASSERTEQUAL(true, config->hasProperty("server.api.code"));
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("not_available_entry"));
MPF_TEST_ASSERTEQUAL(1, config->get<int32_t>("debug.global_level"));
csvsqldb::StringVector properties;
MPF_TEST_ASSERTEQUAL(3u, config->getProperties("debug.level", properties));
std::set<std::string> props(properties.begin(), properties.end());
MPF_TEST_ASSERT(props.find("tcp_server") != props.end());
MPF_TEST_ASSERT(props.find("connection") != props.end());
MPF_TEST_ASSERT(props.find("filesystem") != props.end());
}
void defaultConfigTest()
{
csvsqldb::Configuration::Ptr config(std::make_shared<csvsqldb::DefaultConfiguration>());
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("application.daemonize"));
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("not_available_entry"));
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("logging.device"));
MPF_TEST_ASSERTEQUAL(false, config->hasProperty("debug.global_level"));
csvsqldb::StringVector properties;
MPF_TEST_ASSERTEQUAL(0u, config->getProperties("debug.level", properties));
MPF_TEST_EXPECTS(config->get<int32_t>("debug.global_level"), csvsqldb::ConfigurationException);
}
void globalConfigTest()
{
csvsqldb::Configuration::Ptr config(
std::make_shared<csvsqldb::LuaConfiguration>(CSVSQLDB_TEST_PATH + std::string("/testdata/luaengine/test.lua")));
csvsqldb::GlobalConfiguration::create<MyGlobalConfiguration>();
csvsqldb::GlobalConfiguration::instance<MyGlobalConfiguration>()->configure(config);
MPF_TEST_ASSERTEQUAL(1, csvsqldb::GlobalConfiguration::instance<MyGlobalConfiguration>()->debug.global_level);
MPF_TEST_ASSERTEQUAL(3, csvsqldb::GlobalConfiguration::instance<MyGlobalConfiguration>()->debug.level["connection"]);
MPF_TEST_ASSERTEQUAL(815, csvsqldb::config<MyGlobalConfiguration>()->test.wtf);
}
};
MPF_REGISTER_TEST_START("ApplicationTestSuite", ConfigurationTestCase);
MPF_REGISTER_TEST(ConfigurationTestCase::configTest);
MPF_REGISTER_TEST(ConfigurationTestCase::configCheck);
MPF_REGISTER_TEST(ConfigurationTestCase::defaultConfigTest);
MPF_REGISTER_TEST(ConfigurationTestCase::globalConfigTest);
MPF_REGISTER_TEST_END();
| 41.764286 | 125 | 0.725158 | fuersten |
199ba2a1a5ab75d21a4eea2a1a314c03e1d56c92 | 298 | cpp | C++ | 121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp | gupabhi100/Leetcode- | a0bb35c57efb17dc2c5105287582b4f680eacf82 | [
"MIT"
] | null | null | null | 121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp | gupabhi100/Leetcode- | a0bb35c57efb17dc2c5105287582b4f680eacf82 | [
"MIT"
] | null | null | null | 121-best-time-to-buy-and-sell-stock/121-best-time-to-buy-and-sell-stock.cpp | gupabhi100/Leetcode- | a0bb35c57efb17dc2c5105287582b4f680eacf82 | [
"MIT"
] | null | null | null | class Solution {
public:
int maxProfit(vector<int> &prices) {
int max_profit = 0;
int min_price=INT_MAX;
for(int i=0;i<prices.size();i++) {
min_price=min(min_price, prices[i]);
max_profit=max(max_profit,prices[i]-min_price);
}
return max_profit;
}
}; | 22.923077 | 55 | 0.610738 | gupabhi100 |
199ce77d7426a268dfd6bfb95c796485ea554c82 | 1,176 | cpp | C++ | local/codes/c1068_1.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | 1 | 2021-02-22T03:39:24.000Z | 2021-02-22T03:39:24.000Z | local/codes/c1068_1.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | null | null | null | local/codes/c1068_1.cpp | Tony031218/OI | 562f5f45d0448f4eab77643b99b825405a123d92 | [
"MIT"
] | null | null | null | /*************************************************************
* > File Name : c1068_1.cpp
* > Author : Tony
* > Created Time : 2019/09/22 15:09:20
* > Algorithm : 数位
**************************************************************/
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
inline LL read() {
LL x = 0; LL f = 1; char ch = getchar();
while (!isdigit(ch)) {if (ch == '-') f = -1; ch = getchar();}
while (isdigit(ch)) {x = x * 10 + ch - 48; ch = getchar();}
return x * f;
}
int main() {
LL T = read();
while (T--) {
LL n = read();
LL tmp = n, len = 0;
while (tmp) {
len++;
tmp /= 10;
}
bool ok = false;
for (LL i = max(0LL, n - 9 * len); i <= n; ++i) {
LL sum = i; tmp = i;
while (tmp) {
sum += tmp % 10;
tmp /= 10;
}
if (sum == n) {
printf("%lld\n", i);
ok = true;
break;
}
}
if (!ok) {
printf("Stupid SiriusRen\n");
}
}
return 0;
} | 25.565217 | 65 | 0.332483 | Tony031218 |
199e6e5a24a13f3bb750ca0cfb4278098c43727d | 1,284 | hpp | C++ | src/mlpack/methods/ann/init_rules/init_rules_traits.hpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 675 | 2019-02-07T01:23:19.000Z | 2022-03-28T05:45:10.000Z | src/mlpack/methods/ann/init_rules/init_rules_traits.hpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 843 | 2019-01-25T01:06:46.000Z | 2022-03-16T11:15:53.000Z | src/mlpack/methods/ann/init_rules/init_rules_traits.hpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 83 | 2019-02-20T06:18:46.000Z | 2022-03-20T09:36:09.000Z | /**
* @file init_rules_traits.hpp
* @author Marcus Edel
*
* This provides the InitTraits class, a template class to get information
* about various initialization methods.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_ANN_INIT_RULES_INIT_RULES_TRAITS_HPP
#define MLPACK_METHODS_ANN_INIT_RULES_INIT_RULES_TRAITS_HPP
namespace mlpack {
namespace ann {
/**
* This is a template class that can provide information about various
* initialization methods. By default, this class will provide the weakest
* possible assumptions on the initialization method, and each initialization
* method should override values as necessary. If a initialization method
* doesn't need to override a value, then there's no need to write a InitTraits
* specialization for that class.
*/
template<typename InitRuleType>
class InitTraits
{
public:
/**
* This is true if the initialization method is used for a single layer.
*/
static const bool UseLayer = true;
};
} // namespace ann
} // namespace mlpack
#endif
| 31.317073 | 79 | 0.764019 | RMaron |
199e8b1405588dfd1b1d19c6930bd7f41e37ac29 | 7,487 | hpp | C++ | include/ripple/algorithm/reduce.hpp | robclu/ripple | 734dfa77e100a86b3c60589d41ca627e41d4a783 | [
"MIT"
] | 4 | 2021-04-25T16:38:12.000Z | 2021-12-23T08:32:15.000Z | include/ripple/algorithm/reduce.hpp | robclu/ripple | 734dfa77e100a86b3c60589d41ca627e41d4a783 | [
"MIT"
] | null | null | null | include/ripple/algorithm/reduce.hpp | robclu/ripple | 734dfa77e100a86b3c60589d41ca627e41d4a783 | [
"MIT"
] | null | null | null | /**=--- ripple/algorithm/reduce.hpp ------------------------ -*- C++ -*- ---==**
*
* Ripple
*
* Copyright (c) 2019 - 2021 Rob Clucas.
*
* This file is distributed under the MIT License. See LICENSE for details.
*
*==-------------------------------------------------------------------------==*
*
* \file reduce.hpp
* \brief This file implements a reduction on a block.
*
*==------------------------------------------------------------------------==*/
#ifndef RIPPLE_ALGORITHM_REDUCE_HPP
#define RIPPLE_ALGORITHM_REDUCE_HPP
#include "kernel/reduce_cpp_.hpp"
#include "kernel/reduce_cuda_.cuh"
#include <ripple/container/host_block.hpp>
namespace ripple {
/**
* \note There is supposedly hardware support for certain predicates, see:
*
* #collectives-cg-reduce
*
* In the CUDA programming guide, however, it's been tested on sm_80 and sm_86
* and there is very little difference in performance compared to the
* implementations below, which work with both the host and device reduction
* versions, so these are preferred. Perhaps there is more difference in
* performance for different use cases than those which were tested.
*
*/
/*==--- [predicates] -------------------------------------------------------==*/
/**
* Functor which can be used with the reduction to perform a reduction sum.
*/
struct SumReducer {
/**
* Adds the data pointed to by the one iterator to the other.
* \param a An iterator to the data to add to.
* \param b An iterator to the data to add.
* \tparam T The type of the iterator.
*/
template <typename T>
ripple_all auto inplace(T& a, const T& b) const noexcept -> void {
*a += *b;
}
/**
* Adds the data \p a and \p b and returns the result.
* \param a The first data to add.
* \param b The second data to add.
* \tparam T The type of the data.
* \return The addition of the two elements.
*/
template <typename T>
ripple_all auto
operator()(const T& a, const T& b) const noexcept -> T {
return T{a + b};
}
};
/**
* Functor which can be used with the reduction to perform a reduction
* subtraction.
*/
struct SubtractionReducer {
/**
* Subtracts the data pointed to by the one iterator from the other.
* \param a An iterator to the data to subtract from.
* \param b An iterator to the data to suctract with.
* \tparam T The type of the iterator.
*/
template <typename T>
ripple_all auto inplace(T& a, const T& b) const noexcept -> void {
*a -= *b;
}
/**
* Subtracts the data \p b from \p a and returns the result.
* \param a The first data to subtract from.
* \param b The second data to subtract with.
* \tparam T The type of the data.
* \return The subtraction of b from a.
*/
template <typename T>
ripple_all auto
operator()(const T& a, const T& b) const noexcept -> T {
return a - b;
}
};
/**
* Functor which can be used with the reduction to find a max value over a
* dataset.
*/
struct MaxReducer {
/**
* Sets the \p a data to the max of \p a and \p b.
* \param a The component to set to the max.
* \param b The compoennt to comapare with.
* \tparam T The type of the iterator.
*/
template <typename T>
ripple_all auto inplace(T& a, const T& b) const noexcept -> void {
*a = std::max(*a, *b);
}
/**
* Returns the max of \p a and \p b
* \param a The first input for comparison.
* \param b The second input for comparison
* \tparam T The type of the data.
* \return The max of a and b.
*/
template <typename T>
ripple_all auto
operator()(const T& a, const T& b) const noexcept -> T {
return std::max(a, b);
}
};
/**
* Functor which can be used with the reduction to find a min value over a
* dataset.
*/
struct MinReducer {
/**
* Sets the \p a data to the min of \p a and \p b.
* \param a The component to set to the min.
* \param b The compoennt to comapare with.
* \tparam T The type of the iterator.
*/
template <typename T>
ripple_all auto operator()(T& a, const T& b) const noexcept -> void {
*a = std::min(*a, *b);
}
/**
* Returns the min of \p a and \p b
* \param a The first input for comparison.
* \param b The second input for comparison
* \tparam T The type of the data.
* \return The min of a and b.
*/
template <typename T>
ripple_all auto
operator()(const T& a, const T& b) const noexcept -> T {
return std::min(a, b);
}
};
/*==--- [interface] --------------------------------------------------------==*/
/**
* Reduces the \p block using the \p pred, returning the result.
*
* The pred must have the following overloads form:
*
* ~~~.cpp
* ripple_all auto inplace(T<&> into, <const> T<&> from) const ->
* -> void {}
*
* and
*
* ripple_all auto operator()(const T<&> a, <const> T<&> b) const
* -> T {}'
* ~~~
*
* where T is an iterator over the type T, or a pointer, for thee inplace
* version, and is a reference of value for the operator overload version.
*
* For the inplace version, the predicate *must modify* the data pointed to by
* the `into` iterator (first argument), as appropriate, using the `from`
* iterator. Modifying the `from` iterator may cause unexpectd results, so
* make it const if it should not be modified.
*
* \note Even though the signatures are different, the CUDA coop groups reduce
* implementation doesn't choose the correct one if we make both
* operator() overloads.
*
* This overload is for device blocks.
*
* \param block The block to reduce.
* \param pred The predicate for the reduction.
* \tparam T The type of the data in the block.
* \tparam Dims The number of dimensions in the block.
* \tparam Pred The type of the predicate.
*/
template <typename T, size_t Dims, typename Pred>
auto reduce(const DeviceBlock<T, Dims>& block, Pred&& pred) noexcept -> T {
return kernel::gpu::reduce(block, ripple_forward(pred));
}
/**
* Reduces the \p block using the \p pred, returning the result.
*
* The pred must have the following overloads form:
*
* ~~~.cpp
* ripple_all auto inplace(T<&> into, <const> T<&> from) const ->
* -> void {}
*
* and
*
* ripple_all auto operator()(const T<&> a, <const> T<&> b) const
* -> T {}'
* ~~~
*
* where T is an iterator over the type T, or a pointer, for thee inplace
* version, and is a reference of value for the operator overload version.
*
* For the inplace version, the predicate *must modify* the data pointed to by
* the `into` iterator (first argument), as appropriate, using the `from`
* iterator. Modifying the `from` iterator may cause unexpectd results, so
* make it const if it should not be modified.
*
* \note Even though the signatures are different, the CUDA coop groups reduce
* implementation doesn't choose the correct one if we make both
* operator() overloads.
*
* This overload is for host blocks.
*
* \param block The block to reduce.
* \param pred The predicate for the reduction.
* \tparam T The type of the data in the block.
* \tparam Dims The number of dimensions in the block.
* \tparam Pred The type of the predicate.
*/
template <typename T, size_t Dims, typename Pred>
auto reduce(const HostBlock<T, Dims>& block, Pred&& pred) noexcept -> T {
return kernel::cpu::reduce(block, ripple_forward(pred));
}
} // namespace ripple
#endif // RIPPLE_ALGORITHM_REDUCE_HPP
| 30.559184 | 80 | 0.627488 | robclu |
19a35a7d8f443c94914d5258249e275ed64e54c1 | 1,208 | cc | C++ | src/sycltest/SYCLCore/chooseDevice.cc | alexstrel/pixeltrack-standalone | 0b625eef0ef0b5c0f018d9b466457c5575b3442c | [
"Apache-2.0"
] | 9 | 2021-03-02T08:40:18.000Z | 2022-01-24T14:31:40.000Z | src/sycltest/SYCLCore/chooseDevice.cc | alexstrel/pixeltrack-standalone | 0b625eef0ef0b5c0f018d9b466457c5575b3442c | [
"Apache-2.0"
] | 158 | 2020-03-22T19:46:40.000Z | 2022-03-24T09:51:35.000Z | src/sycltest/SYCLCore/chooseDevice.cc | alexstrel/pixeltrack-standalone | 0b625eef0ef0b5c0f018d9b466457c5575b3442c | [
"Apache-2.0"
] | 26 | 2020-03-20T15:18:41.000Z | 2022-03-14T16:58:07.000Z | #include <iostream>
#include <vector>
#include <CL/sycl.hpp>
#include "chooseDevice.h"
namespace cms::sycltools {
std::vector<sycl::device> const& enumerateDevices(bool verbose) {
static const std::vector<sycl::device> devices = sycl::device::get_devices(sycl::info::device_type::all);
if (verbose) {
std::cerr << "Found " << devices.size() << " SYCL devices:" << std::endl;
for (auto const& device : devices)
std::cerr << " - " << device.get_info<cl::sycl::info::device::name>() << std::endl;
std::cerr << std::endl;
}
return devices;
}
sycl::device chooseDevice(edm::StreamID id) {
auto const& devices = enumerateDevices();
// For startes we "statically" assign the device based on
// edm::Stream number. This is suboptimal if the number of
// edm::Streams is not a multiple of the number of CUDA devices
// (and even then there is no load balancing).
//
// TODO: improve the "assignment" logic
auto const& device = devices[id % devices.size()];
std::cerr << "EDM stream " << id << " offload to " << device.get_info<cl::sycl::info::device::name>() << std::endl;
return device;
}
} // namespace cms::sycltools
| 35.529412 | 119 | 0.634934 | alexstrel |
19a51864a93d2ea589724e919e60d8aab24c4616 | 1,352 | cc | C++ | src/mouse.cc | klantz81/input-devices | f0df3af537b38eb446fc5a49a0b6a524a4e1a10b | [
"MIT"
] | 15 | 2016-04-01T08:16:14.000Z | 2020-03-16T03:02:40.000Z | src/mouse.cc | klantz81/input-devices | f0df3af537b38eb446fc5a49a0b6a524a4e1a10b | [
"MIT"
] | null | null | null | src/mouse.cc | klantz81/input-devices | f0df3af537b38eb446fc5a49a0b6a524a4e1a10b | [
"MIT"
] | 1 | 2019-12-18T01:28:50.000Z | 2019-12-18T01:28:50.000Z | #include "mouse.h"
cMouse::cMouse() {
active = false;
mouse_ev = new input_event();
mouse_st = new mouse_state();
for (int i = 0; i < KEY_CNT; i++) mouse_st->button[i] = 0;
for (int i = 0; i < REL_CNT; i++) mouse_st->axis[i] = 0;
mouse_fd = open(MOUSE_DEV, O_RDONLY | O_NONBLOCK);
if (mouse_fd > -1) {
ioctl(mouse_fd, EVIOCGNAME(256), name);
ioctl(mouse_fd, EVIOCGVERSION, &version);
std::cout << " Name: " << name << std::endl;
std::cout << "Version: " << version << std::endl << std::endl;
active = true;
pthread_create(&thread, 0, &cMouse::loop, this);
}
}
cMouse::~cMouse() {
if (mouse_fd > -1) {
active = false;
pthread_join(thread, 0);
close(mouse_fd);
}
mouse_fd = 0;
delete mouse_st;
delete mouse_ev;
}
void* cMouse::loop(void *obj) {
while (reinterpret_cast<cMouse *>(obj)->active) reinterpret_cast<cMouse *>(obj)->readEv();
}
void cMouse::readEv() {
int bytes = read(mouse_fd, mouse_ev, sizeof(*mouse_ev));
if (bytes > 0) {
if (mouse_ev->type & EV_REL)
mouse_st->axis[mouse_ev->code] += mouse_ev->value;
if (mouse_ev->type & EV_KEY)
mouse_st->button[mouse_ev->code] = mouse_ev->value;
}
}
mouse_position cMouse::mousePosition() {
mouse_position m;
m.x = mouse_st->axis[REL_X];
m.y = mouse_st->axis[REL_Y];
return m;
}
__s32 cMouse::buttonState(int n) {
return mouse_st->button[n];
}
| 24.142857 | 91 | 0.64497 | klantz81 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.