blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ad96f2dd3de9d69e4a932e4f8e7ab91cfa70741a | 8105733df657df6cb42b5a39bfe64a1c2f40f1f2 | /Library/movement-pointtranslation2d_.h | 71997af948f7f606771c30a305a716aef23f4cc2 | [] | no_license | beakie/Studio | 27c1eddade1185f47c2aa71be6c277b392c320a3 | debe855132e72779fd635379d2964b60a97a3047 | refs/heads/master | 2020-12-14T07:22:03.188593 | 2015-06-26T14:38:53 | 2015-06-26T14:38:53 | 31,416,473 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,521 | h | movement-pointtranslation2d_.h | #ifndef MOVEMENT_POINTTRANSLATION2D_H
#define MOVEMENT_POINTTRANSLATION2D_H
#include "space2d.h"
#include "movement-bonefixedpointlist.h"
#include "movement-bonemap.h"
#include "movement-jointlist.h"
#include "movement-pointlist.h"
namespace Movement
{
template <typename TVALUE>
Common::Vector2<TVALUE> getTranslatedPoint(const Common::ICollection<Common::Matrix3<TVALUE>, UInt8>& jointList, const BoneMap& boneMap, const int parentBoneIndex, const Common::Vector2<TVALUE>& position)
{
return Space2d::multiplyPlotByMatrix<TVALUE>(position, boneMap.getBoneTransformMatrix<Common::Matrix3<TVALUE>>(jointList, parentBoneIndex));
}
template <typename TVALUE>
PointList<Common::Vector2<TVALUE>> getTranslatedJointPositions(const Common::ICollection<Common::Matrix3<TVALUE>, UInt8>& jointList, const BoneMap& boneMap, const Common::ICollection<Common::Vector2<TVALUE>, UInt8>& jointPositions)
{
PointList<Common::Vector2<TVALUE>> translatedJoints = PointList<Common::Vector2<TVALUE>>(jointPositions.count());
for (UInt8 i = 0; i < jointPositions.count(); i++)
translatedJoints.Points[i]->operator=(getTranslatedPoint<TVALUE>(jointList, boneMap, i, jointPositions.operator[](i)));
return translatedJoints;
}
template <typename TVALUE>
BoneFixedPointList<Common::Vector2<TVALUE>> getTranslatedPoints(const Common::ICollection<Common::Matrix3<TVALUE>, UInt8>& jointList, const BoneMap& boneMap, const BoneFixedPointList<Common::Vector2<TVALUE>>& boneFixedPositions)
{
BoneFixedPointList<Common::Vector2<TVALUE>> translatedPoints = BoneFixedPointList<Common::Vector2<TVALUE>>(boneFixedPositions.PointCount);
for (UInt8 i = 0; i < boneFixedPositions.PointCount; i++)
translatedPoints.Points[i]->operator=(getTranslatedPoint<TVALUE>(jointList, boneMap, boneFixedPositions.BoneIndex[i], *boneFixedPositions.Points[i]));
return translatedPoints;
}
//template <typename TVALUE>
//Common::Vector2<TVALUE> getTranslatedPoint(const JointList<Common::Matrix3<TVALUE>>& jointList, const BoneMap& boneMap, const int parentBoneIndex, const Common::Vector2<TVALUE>& position)
//{
// return Space2d::multiplyPlotByMatrix<TVALUE>(position, boneMap.getBoneTransformMatrix<Common::Matrix3<TVALUE>>(jointList, parentBoneIndex));
//}
//template <typename TVALUE>
//PointList<Common::Vector2<TVALUE>> getTranslatedJointPositions(const JointList<Common::Matrix3<TVALUE>>& jointList, const BoneMap& boneMap, const PointList<Common::Vector2<TVALUE>>& jointPositions)
//{
// PointList<Common::Vector2<TVALUE>> translatedJoints = PointList<Common::Vector2<TVALUE>>(jointPositions.PointCount);
// for (UInt8 i = 0; i < jointPositions.PointCount; i++)
// translatedJoints.Points[i]->operator=(getTranslatedPoint<TVALUE>(jointList, boneMap, i, *jointPositions.Points[i]));
// return translatedJoints;
//}
//template <typename TVALUE>
//BoneFixedPointList<Common::Vector2<TVALUE>> getTranslatedPoints(const JointList<Common::Matrix3<TVALUE>>& jointList, const BoneMap& boneMap, const BoneFixedPointList<Common::Vector2<TVALUE>>& boneFixedPositions)
//{
// BoneFixedPointList<Common::Vector2<TVALUE>> translatedPoints = BoneFixedPointList<Common::Vector2<TVALUE>>(boneFixedPositions.PointCount);
// for (UInt8 i = 0; i < boneFixedPositions.PointCount; i++)
// translatedPoints.Points[i]->operator=(getTranslatedPoint<TVALUE>(jointList, boneMap, boneFixedPositions.BoneIndex[i], *boneFixedPositions.Points[i]));
// return translatedPoints;
//}
}
#endif // MOVEMENT_POINTTRANSLATION2D_H
|
b5bb49813a79b69fe697adc1628de96d54ef8502 | dcc4cf1b34bbe254d976447ae957388d7507a70f | /games-generated/Crash Course Game/Export/mac64/cpp/obj/include/com/stencyl/models/scene/ScrollingBitmap.h | 89838bb7a1e5f6f37c1af2c7f3ebd33d7cdc5226 | [
"MIT"
] | permissive | dylanmarcus/stencylworks | fe2bfd4e0bf16915bc9a7babcb681d7de5365dd5 | 06bc44e5d04101f61c70cabd64b23c69ef043c43 | refs/heads/master | 2020-12-25T23:47:22.985344 | 2015-04-22T02:21:18 | 2015-04-22T02:21:18 | 34,361,979 | 1 | 0 | null | 2015-04-22T02:21:18 | 2015-04-22T01:40:02 | C++ | UTF-8 | C++ | false | false | 2,568 | h | ScrollingBitmap.h | #ifndef INCLUDED_com_stencyl_models_scene_ScrollingBitmap
#define INCLUDED_com_stencyl_models_scene_ScrollingBitmap
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#include <flash/display/Sprite.h>
HX_DECLARE_CLASS4(com,stencyl,models,scene,ScrollingBitmap)
HX_DECLARE_CLASS2(flash,display,Bitmap)
HX_DECLARE_CLASS2(flash,display,DisplayObject)
HX_DECLARE_CLASS2(flash,display,DisplayObjectContainer)
HX_DECLARE_CLASS2(flash,display,IBitmapDrawable)
HX_DECLARE_CLASS2(flash,display,InteractiveObject)
HX_DECLARE_CLASS2(flash,display,Sprite)
HX_DECLARE_CLASS2(flash,events,EventDispatcher)
HX_DECLARE_CLASS2(flash,events,IEventDispatcher)
namespace com{
namespace stencyl{
namespace models{
namespace scene{
class HXCPP_CLASS_ATTRIBUTES ScrollingBitmap_obj : public ::flash::display::Sprite_obj{
public:
typedef ::flash::display::Sprite_obj super;
typedef ScrollingBitmap_obj OBJ_;
ScrollingBitmap_obj();
Void __construct(Dynamic img,Float dx,Float dy,hx::Null< Float > __o_px,hx::Null< Float > __o_py,hx::Null< int > __o_ID);
public:
static hx::ObjectPtr< ScrollingBitmap_obj > __new(Dynamic img,Float dx,Float dy,hx::Null< Float > __o_px,hx::Null< Float > __o_py,hx::Null< int > __o_ID);
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
~ScrollingBitmap_obj();
HX_DO_RTTI;
static void __boot();
static void __register();
void __Mark(HX_MARK_PARAMS);
void __Visit(HX_VISIT_PARAMS);
::String __ToString() const { return HX_CSTRING("ScrollingBitmap"); }
virtual Void stop( );
Dynamic stop_dyn();
virtual Void start( );
Dynamic start_dyn();
virtual Void resetPositions( );
Dynamic resetPositions_dyn();
virtual Void updateParallax( );
Dynamic updateParallax_dyn();
virtual Void updateAuto( Float elapsedTime);
Dynamic updateAuto_dyn();
int backgroundID;
Float parallaxY;
Float parallaxX;
Float yVelocity;
Float xVelocity;
Float yPos;
Float xPos;
Float yP;
Float xP;
Float cacheHeight;
Float cacheWidth;
bool parallax;
bool running;
Float curStep;
Float speed;
::flash::display::Bitmap image9;
::flash::display::Bitmap image8;
::flash::display::Bitmap image7;
::flash::display::Bitmap image6;
::flash::display::Bitmap image5;
::flash::display::Bitmap image4;
::flash::display::Bitmap image3;
::flash::display::Bitmap image2;
::flash::display::Bitmap image1;
};
} // end namespace com
} // end namespace stencyl
} // end namespace models
} // end namespace scene
#endif /* INCLUDED_com_stencyl_models_scene_ScrollingBitmap */
|
9a43426ead73c6c452ad2ad9cac0411cf6964596 | c8a38e65e71de888fc5b22fbd027bbaa0f3f6ef1 | /Cpp/351.cpp | fa9247f42465652577931d1e8c7b8c247ef24ef5 | [] | no_license | skywhat/leetcode | e451a10cdab0026d884b8ed2b03e305b92a3ff0f | 6aaf58b1e1170a994affd6330d90b89aaaf582d9 | refs/heads/master | 2023-03-30T15:54:27.062372 | 2023-03-30T06:51:20 | 2023-03-30T06:51:20 | 90,644,891 | 82 | 27 | null | null | null | null | UTF-8 | C++ | false | false | 1,169 | cpp | 351.cpp | class Solution {
private:
vector<vector<int>> skip;
public:
Solution() {
skip.assign(10, vector<int>(10, 0));
skip[1][3] = skip[3][1] = 2;
skip[1][7] = skip[7][1] = 4;
skip[3][9] = skip[9][3] = 6;
skip[7][9] = skip[9][7] = 8;
skip[2][8] = skip[8][2] = skip[4][6] = skip[6][4] = skip[1][9]
= skip[9][1] = skip[3][7] = skip[7][3] = 5;
}
int numberOfPatterns(int m, int n) {
int res = 0;
vector<bool> visit(10, false);
for (int i = m; i <= n; ++i) {
res += dfs(visit, 1, i - 1) * 4;
res += dfs(visit, 2, i - 1) * 4;
res += dfs(visit, 5, i - 1);
}
return res;
}
int dfs(vector<bool> visit, int start, int remaining) {
if (remaining == 0) {
return 1;
}
int res = 0;
visit[start] = true;
for (int i = 1; i <= 9; ++i) {
if (visit[i]) {
continue;
}
if (skip[start][i] == 0 || visit[skip[start][i]]) {
res += dfs(visit, i, remaining - 1);
}
}
return res;
}
};
|
413dc4bc3920c2306719b4b213d214260564851b | 864db9cc8bc7b3732df904d9a22bb2a56919fc5f | /simulator/SimulatorObj.cpp | 0ede66df56d22588d5c2299e5e5a787b2b71f328 | [] | no_license | omrib40/Ship-Simulator | 157c806639e9687d1fa0ace5dde77a2de838cc93 | 360fa13b6ad378729c57d2788ba93aec77ee2d9a | refs/heads/master | 2022-09-08T02:16:04.446774 | 2020-05-31T07:36:08 | 2020-05-31T07:36:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,962 | cpp | SimulatorObj.cpp | #include "SimulatorObj.h"
/**
* This function sets the ship map of the simulator and the calculator ship map
*/
void SimulatorObj::setShipAndCalculator(std::unique_ptr<Ship> &getShip,const string& file_path){
this->simShip = std::make_unique<Ship>(*getShip);
simCalc.readShipPlan(file_path);
}
/**
* This function iterates over the travel cargo_data files and checks if there are ports
* with cargo_data files that doesn't exist in the route.
* also it compares the number of cargo files in this travel vs the route length and notify
* if num of cargo files > route length.
*/
void SimulatorObj::compareRoutePortsVsCargoDataPorts(std::unique_ptr<Ship> &ship,std::unique_ptr<Travel> &travel){
auto vecPorts = ship->getRoute();
int numOfCargoFiles = 0;
map<string,vector<fs::path>> travelCargoDataFiles(travel->getMap());
/*Erase all ports that exist in the travel map as their cargo files are necessary*/
for(auto &port : vecPorts){
if(travelCargoDataFiles.find(port->get_name()) != travelCargoDataFiles.end())
travelCargoDataFiles.erase(port->get_name());
}
for(auto &pair : travelCargoDataFiles)
travel->setNewGeneralError(ERROR_NO_PORT_EXIST_IN_TRAVEL(pair.first));
/*Count how many valid cargo files exist in this travel folder*/
for(auto &pair : travel->getMap())
numOfCargoFiles += (int)pair.second.size();
if(numOfCargoFiles > (int)ship->getRoute().size())
travel->setNewGeneralError(ERROR_TOO_MANY_CARGO_FILES);
}
/**
* This function initialize the list of travels from given -travel_path path
*/
void SimulatorObj::initListOfTravels(string &path){
string msg = " only sub folders allowed in main folder, file won't be included in the program";
for(const auto &entry : fs::directory_iterator(path)){
if(!entry.is_directory()){
this->generalErrors.emplace_back(ERROR_NOT_DIRECTORY(entry, msg));
continue;
}
string travelName = entry.path().filename().string();
if(!isValidTravelName(travelName)) {
this->generalErrors.emplace_back(ERROR_TRAVEL_NAME(travelName));
continue;
}
std::unique_ptr<Travel> currTravel = std::make_unique<Travel>(travelName);
map<string,vector<fs::path>> currPorts;
for(const auto &deep_entry : fs::directory_iterator(entry.path())){
string fileName = deep_entry.path().filename().string();
if(isValidPortFileName(fileName)){
string portName = extractPortNameFromFile(fileName);
int portNum = extractPortNumFromFile(fileName);
insertPortFile(currTravel,portName,portNum,deep_entry.path());
}
else if(isValidShipRouteFileName(fileName)){
if(!currTravel->getRoutePath().empty())
currTravel->setNewGeneralError(ERROR_ROUTE_MANY_FILES(fileName));
else
currTravel->setRoutePath(deep_entry.path());
}
else if(isValidShipMapFileName(fileName)){
if(!currTravel->getPlanPath().empty())
currTravel->setNewGeneralError(ERROR_PLAN_MANY_FILES(fileName));
else
currTravel->setPlanPath(deep_entry.path());
}
else{
currTravel->setNewGeneralError(ERROR_INVALID_FILE(fileName));
}
}
this->TravelsVec.emplace_back(std::move(currTravel));
}
}
/**
* This function get a travel folder map:= <portName,list of files with same portName>
* and assigns at list[portNum] the given entry which corresponds to map[portName][portNum-1] --> portName_portNum.cargo_data
*/
void SimulatorObj::insertPortFile(std::unique_ptr<Travel> &currTravel, string &portName, int portNum, const fs::path &entry) {
auto &travelMap = currTravel->getMap();
if(travelMap.find(portName) != travelMap.end()){
if((int)travelMap[portName].size() < portNum){
travelMap[portName].resize(portNum);
}
}
else{/*case no such entry found in the map, then it's first time this portName occurs*/
vector<fs::path> vec(portNum);
travelMap.insert(make_pair(portName,vec));
}
travelMap[portName].at(portNum-1) = entry;
}
vector<std::unique_ptr<Travel>>& SimulatorObj::getTravels(){
return this->TravelsVec;
}
std::unique_ptr<Ship>& SimulatorObj::getShip(){
return this->simShip;
}
/**
* This function creates a file that shows the result of the cartesian multiplication of the simulator
*/
void SimulatorObj::createResultsFile(){
std::ofstream inFile;
int sumInstructions = 0,sumErrors = 0;
const char comma = ',';
list<string> travels;
list<string> algorithmNames;
string path = mainOutputPath;
map<string,map<string,pair<int,int>>> output_map;
if(isResultsEmpty()){
NO_RESULT_FILE;
return;
}
initOutputMap(output_map);
path.append(PATH_SEPARATOR);
path.append("simulation.results");
inFile.open(path);
if(inFile.fail()){
ERROR_RESULTS_FILE;
exit(EXIT_FAILURE);
}
for(auto &travel : this->TravelsVec) {//Get travel Names
if(!travel->isErroneous())
travels.emplace_back(travel->getName());
}
for(auto &algName : this->TravelsVec.front()->getAlgResultsMap())//Get algorithm names
algorithmNames.emplace_back(algName.first);
SimulatorObj::sortAlgorithmsForResults(output_map, algorithmNames);
inFile << "RESULTS" << comma;
for(string &travel_name : travels)
inFile << travel_name << comma;
inFile << "Sum" << comma << "Errors" << '\n';
for(auto& algName : algorithmNames){
inFile << algName << comma;
for(auto &travelName : travels){
if(output_map[travelName][algName].second == -1)
inFile << output_map[travelName][algName].second << comma;
else{
inFile << output_map[travelName][algName].first << comma;
sumInstructions += output_map[travelName][algName].first;
}
sumErrors += output_map[travelName][algName].second;
}
inFile << sumInstructions << comma << (sumErrors*-1) << '\n';
sumInstructions = 0;
sumErrors = 0;
}
inFile.close();
}
/**
* This function creates a file that shows all the errors existed in the simulator run,
* errors list - container didn't arrived to it's destination, container didn't picked up as the destination of
* it isn't doesn't exist in any following ports
*/
void SimulatorObj::createErrorsFile() {
const string spaces = " ";//6spaces
const string lineSep = "====================================================================================================";
std::ofstream inFile;
string path = mainOutputPath;
if(isErrorsEmpty()){
NO_ERROR_FILE;
return;
}
path.append(PATH_SEPARATOR);
path.append("simulation.errors");
inFile.open(path);
if (inFile.fail()) {
ERROR_ERRORS_FILE;
return;
}
if(!generalErrors.empty()){
inFile << "Simulator General Errors:" << '\n';
for(auto &msg : generalErrors){
inFile << spaces << msg << '\n';
}
inFile << lineSep+lineSep << '\n';
}
for(auto &travel : TravelsVec){
if(travel->isErrorsExists()){
inFile << travel->getName() << " Errors:" << '\n'; //Travel name
if(!travel->getGeneralErrors().empty()){
inFile << spaces << "General:" << '\n';
for(string &msg : travel->getGeneralErrors()){
inFile << spaces + spaces << msg << '\n';
}
}
for(auto &pair : travel->getErrorsMap()){
if(!pair.second.empty()){
inFile << spaces << pair.first + ":" << '\n'; //algorithm name
for(string &msg : pair.second){
inFile << spaces + spaces << msg << '\n'; //error msg list for this alg in this travel
}
}
}
inFile << lineSep+lineSep << '\n';
}
}
inFile.close();
}
/**
* This function initialize the output result map
*/
void SimulatorObj::initOutputMap(map<string,map<string,pair<int,int>>>& outputMap){
for(auto& travel : this->TravelsVec){
if(!travel->isErroneous())
outputMap.insert(make_pair(travel->getName(),travel->getAlgResultsMap()));
}
}
/**
* This function checks if the results are empty --> if true simulation.results wont be created
*/
bool SimulatorObj:: isResultsEmpty() {
for(auto& travel : this->TravelsVec)
if(!travel->getAlgResultsMap().empty())
return false;
return true;
}
/**
* This function checks if the errors list are empty --> if true simulation.errors wont be created
*/
bool SimulatorObj:: isErrorsEmpty(){
for(auto& travel: this->TravelsVec)
if(!travel->getGeneralErrors().empty() || !travel->getErrorsMap().empty())
return false;
if(!generalErrors.empty())
return false;
return true;
}
/**
* This function runs the current algorithm on the current travel
*/
void SimulatorObj::runAlgorithm(pair<string,std::unique_ptr<AbstractAlgorithm>> &alg, std::unique_ptr<Travel> &travel){
list<string> simCurrAlgErrors;
map<string,int> visitNumbersByPort;
int res = 0;
vector<std::shared_ptr<Port>> route = simShip->getRoute();
res = checkIfFatalErrorOccurred("alg");
if(res != -1) {
string algInstructionsFolder = SimulatorObj::createAlgorithmOutDirectory(alg.first, mainOutputPath,travel->getName());
for (int portNum = 0; portNum < (int) route.size() && res != -1; portNum++) {
string portName = route[portNum]->get_name();
pPort = simShip->getPortByName(portName);
currPortNum = portNum;
int visitNumber = visitNumbersByPort[portName];
fs::path portPath = getPathOfCurrentPort(travel,portName,visitNumber);
res = runCurrentPort(portName, portPath, alg, simCurrAlgErrors, algInstructionsFolder,
++visitNumbersByPort[portName],travel);
compareIgnoredAlgErrsVsSimErrs(portName, visitNumber, simCurrAlgErrors);
}
}
compareFatalAlgErrsVsSimErrs(simCurrAlgErrors);
travel->getErrorsMap().insert(make_pair(alg.first,simCurrAlgErrors));
prepareNextIteration();
}
/**
* This function gets the full file path of the given port in the given travel at the X time we visit there
* Note* some ports in the ship route might not have a files,then it creates an empty path for them.
*/
fs::path SimulatorObj::getPathOfCurrentPort(std::unique_ptr<Travel> &travel,string& portName,int visitNumber){
auto &vec = travel->getMap()[portName];
fs::path result;
if(vec.empty()) {
vec.resize(1);
result = fs::path();
}
else{
try{
result = vec.at(visitNumber);
}
catch(const std::exception& e){
result = fs::path();
}
}
/*Case there is no file --> create empty file for algorithm*/
if(result.empty()){
string newPath = travel->getPlanPath().parent_path().string() + PATH_SEPARATOR + portName + "_" + std::to_string(visitNumber+1) + ".cargo_data";
result = fs::path(newPath);
std::ofstream inFile;
inFile.open(newPath);
inFile.close();
}
return result;
}
int SimulatorObj::checkIfFatalErrorOccurred(string type){
if(type == "alg" && (algErrorCodes[3] || algErrorCodes[4] || algErrorCodes[7] || algErrorCodes[8]))
return -1;
else if(simErrorCodes[3] || simErrorCodes[4] || simErrorCodes[7] || simErrorCodes[8])
return -1;
else
return 0;
}
/**
* This function compares the fatal errors between algorithm and simulator
*/
void SimulatorObj::compareFatalAlgErrsVsSimErrs(list<string> &simCurrAlgErrors){
if(algErrorCodes[3] != simErrorCodes[3])
simCurrAlgErrors.emplace_back(ERROR_PLAN_FATAL);
if(algErrorCodes[4] != simErrorCodes[4])
simCurrAlgErrors.emplace_back(ERROR_DUPLICATE_XY);
if(algErrorCodes[7] != simErrorCodes[7])
simCurrAlgErrors.emplace_back(ERROR_TRAVEL_FATAL);
if(algErrorCodes[8] != simErrorCodes[8])
simCurrAlgErrors.emplace_back(ERROR_TRAVEL_SINGLEPORT);
}
/**
* This function compares ignored errors between algorithm and simulator
*/
void SimulatorObj::compareIgnoredAlgErrsVsSimErrs(string &portName,int visitNumber,list<string> &simCurrAlgErrors){
if(algErrorCodes[16] != simErrorCodes[16])
simCurrAlgErrors.emplace_back(ERROR_NO_CARGO_TOLOAD(portName, visitNumber));
}
/**
* This function runs the current algorithm over the current port at the travel route
*/
int SimulatorObj::runCurrentPort(string &portName,fs::path &portPath,pair<string,std::unique_ptr<AbstractAlgorithm>> &alg,
list<string> &simCurrAlgErrors,string &algOutputFolder,int visitNumber,std::unique_ptr<Travel> &travel){
string inputPath,outputPath;
int instructionsCount, errorsCount, algReturnValue;
std::optional<pair<int,int>> result;
pair<int,int> intAndError;
SimulatorValidation validator(this);
inputPath = portPath.string();
outputPath = algOutputFolder + PATH_SEPARATOR + portName + "_" + std::to_string(visitNumber) + ".crane_instructions";
try {
algReturnValue = alg.second->getInstructionsForCargo(inputPath,outputPath);
}
catch(...){
simCurrAlgErrors.emplace_back(ERROR_ALG_FAILED);
return -1;
}
updateErrorCodes(algReturnValue, "alg");
result = validator.validateAlgorithm(outputPath,inputPath,simCurrAlgErrors,portName,visitNumber);
if(!result) return -1; //case there was an error in validateAlgorithm
/*Incrementing the instructions count and errors count*/
intAndError = result.value();
instructionsCount = std::get<0>(intAndError);
errorsCount = std::get<1>(intAndError);
if(travel->getAlgResultsMap().find(alg.first) == travel->getAlgResultsMap().end())
travel->getAlgResultsMap().insert(make_pair(alg.first,pair<int,int>()));
std::get<0>(travel->getAlgResultsMap()[alg.first]) += instructionsCount;
std::get<1>(travel->getAlgResultsMap()[alg.first]) += errorsCount;
this->pPort->getContainerVec(Type::PRIORITY)->clear();
this->pPort->getContainerVec(Type::LOAD)->clear();
return errorsCount;
}
/**
* This function updates the error codes
*/
void SimulatorObj::updateErrorCodes(int num, string type){
std::array<bool,NUM_OF_ERRORS> numArr{false};
initArrayOfErrors(numArr,num);
for(int i = 0; i < NUM_OF_ERRORS; i++){
if(numArr[i] && type == "alg")
this->algErrorCodes[i] = true;
else if(numArr[i] && type == "sim"){
this->simErrorCodes[i] = true;
}
}
}
/**
* This function reset simulator parameters to next travel
*/
void SimulatorObj:: prepareNextIteration() {
this->algErrorCodes = std::array<bool,NUM_OF_ERRORS>{false};
this->simErrorCodes = std::array<bool,NUM_OF_ERRORS>{false};
this->currPortNum = 0;
}
WeightBalanceCalculator SimulatorObj::getCalc() {
return simCalc;
}
/**
* This function sorts the algorithms output info list and assigning the order to the algorithms list
* such that:
* 1.sorting is based on --> 0 errors count(0 before -1..), then lowest instructions count
*/
void SimulatorObj::sortAlgorithmsForResults(map<string,map<string,pair<int,int>>>& outputInfo, list<string> &algorithm){
map<string,pair<int,int>> algAndValues;
vector<std::tuple<string,int,int>> sortedVec;
for(auto &alg : algorithm){
algAndValues.insert(make_pair(alg,pair<int,int>()));
}
/*Gather the overall score of travel X algorithms*/
for(auto &algName : algorithm){
for(auto &travel : outputInfo){
if(travel.second.find(algName) != travel.second.end()){
algAndValues[algName].first += travel.second[algName].first;
algAndValues[algName].second += travel.second[algName].second;
}
}
}
for(auto &alg: algAndValues){
std::tuple<string,int,int> tup;
std::get<0>(tup) = alg.first;
std::get<1>(tup) = alg.second.first;
std::get<2>(tup) = alg.second.second;
sortedVec.emplace_back(tup);
}
/*first will occur algorithms with 0 errors and lowest instructions*/
std::sort(sortedVec.begin(),sortedVec.end(),[](const std::tuple<string,int,int> &t1,const std::tuple<string,int,int> &t2)
->bool {
if(std::get<2>(t1) == std::get<2>(t2)){
return std::get<1>(t1) < std::get<1>(t2);
} else
return std::get<2>(t1) > std::get<2>(t2);
});
algorithm.clear();
for(auto& alg : sortedVec){
algorithm.emplace_back(std::get<0>(alg));
}
}
/**
* This function create an algorithm output directory per algorithm and travel in the main output directory
*/
string SimulatorObj::createAlgorithmOutDirectory(const string &algName,const string &outputDirectory,const string &travelName){
string algOutDirectory = outputDirectory + PATH_SEPARATOR + algName + "_" + travelName + "_" + "crane_instructions";
fs::path directoryPath(algOutDirectory);
fs::path parentDirectory(outputDirectory);
if(!fs::exists(directoryPath)){
fs::create_directory(directoryPath,parentDirectory);
}
return algOutDirectory;
}
std::shared_ptr<Port> SimulatorObj::getPort() {
return pPort;
}
/**
* This function sorts the given vector of containers by the it's distance from it's destination
* first occurences will be containers with lowest distance...
*/
void SimulatorObj::sortContainersByPriority(vector<Container>* &priorityVec){
auto routeVec = this->getShip()->getRoute();
map<string,int> portNamePriority;
for(int i = currPortNum+1; i < (int)routeVec.size(); i++){
if(portNamePriority.find((*routeVec[i]).get_name()) == portNamePriority.end())
portNamePriority.insert({routeVec[i]->get_name(),i});
}
std::sort(priorityVec->begin(),priorityVec->end(),[&portNamePriority](Container& cont1,Container& cont2) -> bool
{
string cont1PortDst = cont1.getDest()->get_name();
string cont2PortDst = cont2.getDest()->get_name();
if(portNamePriority.find(cont1PortDst) == portNamePriority.end())
portNamePriority.insert({cont1PortDst,INT_MAX});
if(portNamePriority.find(cont2PortDst) == portNamePriority.end())
portNamePriority.insert({cont2PortDst,INT_MAX});
return portNamePriority[cont1PortDst] < portNamePriority[cont2PortDst];
});
}
int SimulatorObj::getPortNum(){
return this->currPortNum;
}
|
b11d210bb370a794e41be342628a1e526a5497e0 | 402e0edb12a18788dee3e1e077ada9e7bbdeca24 | /stl-test/Tests/array_view/array_view/Negative/test7.cpp | 185e96658c0772b6e6566f4bb00dbc6ac97a2d09 | [
"LicenseRef-scancode-unknown-license-reference",
"NCSA"
] | permissive | david-salinas/hcc | b275590b8ecc17c13896c3ba812087ffdcde9709 | 11a0fbdc010bcdce970793949def68cc1a05506a | refs/heads/clang_tot_upgrade | 2021-01-09T05:58:54.970186 | 2019-12-05T17:53:12 | 2019-12-05T20:47:03 | 157,601,581 | 0 | 0 | NOASSERTION | 2018-11-14T19:42:00 | 2018-11-14T19:41:59 | null | UTF-8 | C++ | false | false | 105 | cpp | test7.cpp | //#error
#include <array_view>
int main()
{
int arr[3][3][3];
std::array_view<int, 2> av(arr);
}
|
4520baeaf4ac1b1c2e5dd6f6be0633881c8f9b77 | f3a7c6a127df972e50db179832020b19d1832354 | /src/AnaNim3Add.h | 0450e7fbdaf80451bbfd80d58e9c18929d519874 | [] | no_license | knakano0524/e1039-trigger-tune | 0e647c8a21fa75a61b5dd9fa18bdd1277eeed46a | 3f06fd542a2e37fb58767d3598b2ba106b545150 | refs/heads/master | 2023-04-09T12:52:10.432304 | 2021-04-22T01:32:31 | 2021-04-22T01:32:31 | 360,341,399 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 609 | h | AnaNim3Add.h | #ifndef _ANA_NIM3_ADD__H_
#define _ANA_NIM3_ADD__H_
#include <map>
#include "RoadMap.h"
#include "RoadList.h"
#include "AnaNim3.h"
class TH1;
class AnaGmc;
class AnaNim3Add : public AnaNim3 {
protected:
RoadMap* m_road_map_pos_top;
RoadMap* m_road_map_pos_bot;
RoadMap* m_road_map_neg_top;
RoadMap* m_road_map_neg_bot;
///
/// Parameters
///
public:
AnaNim3Add(const std::string label="nim3_add");
virtual ~AnaNim3Add();
virtual void Init(AnaGmc* ana_gmc);
virtual void End();
virtual void Analyze();
protected:
virtual void ProcessOneEvent();
};
#endif // _ANA_NIM3_ADD__H_
|
5d80a965a5c89531bf1d96024f37b7bb8ac3bfb1 | 4d28185e7a78a569f9a449f39f183cac3024f711 | /source/Host/common/TaskPool.cpp | 73f761b5cf63a4761d8b93b5ee6e52de8456d3bb | [
"NCSA",
"Apache-2.0",
"LLVM-exception"
] | permissive | apple/swift-lldb | 2789bf44f648609a1674ee520ac20b64c95de072 | d74be846ef3e62de946df343e8c234bde93a8912 | refs/heads/stable | 2023-04-06T00:28:15.882479 | 2019-10-25T22:46:59 | 2019-10-25T22:46:59 | 44,838,862 | 780 | 291 | Apache-2.0 | 2020-01-10T19:28:43 | 2015-10-23T21:13:18 | C++ | UTF-8 | C++ | false | false | 3,557 | cpp | TaskPool.cpp | //===--------------------- TaskPool.cpp -------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "lldb/Host/TaskPool.h"
#include "lldb/Host/ThreadLauncher.h"
#include "lldb/Utility/Log.h"
#include <cstdint>
#include <queue>
#include <thread>
namespace lldb_private {
namespace {
class TaskPoolImpl {
public:
static TaskPoolImpl &GetInstance();
void AddTask(std::function<void()> &&task_fn);
private:
TaskPoolImpl();
static lldb::thread_result_t WorkerPtr(void *pool);
static void Worker(TaskPoolImpl *pool);
std::queue<std::function<void()>> m_tasks;
std::mutex m_tasks_mutex;
uint32_t m_thread_count;
};
} // end of anonymous namespace
TaskPoolImpl &TaskPoolImpl::GetInstance() {
static TaskPoolImpl g_task_pool_impl;
return g_task_pool_impl;
}
void TaskPool::AddTaskImpl(std::function<void()> &&task_fn) {
TaskPoolImpl::GetInstance().AddTask(std::move(task_fn));
}
TaskPoolImpl::TaskPoolImpl() : m_thread_count(0) {}
unsigned GetHardwareConcurrencyHint() {
// std::thread::hardware_concurrency may return 0 if the value is not well
// defined or not computable.
static const unsigned g_hardware_concurrency =
std::max(1u, std::thread::hardware_concurrency());
return g_hardware_concurrency;
}
void TaskPoolImpl::AddTask(std::function<void()> &&task_fn) {
const size_t min_stack_size = 8 * 1024 * 1024;
std::unique_lock<std::mutex> lock(m_tasks_mutex);
m_tasks.emplace(std::move(task_fn));
if (m_thread_count < GetHardwareConcurrencyHint()) {
m_thread_count++;
// Note that this detach call needs to happen with the m_tasks_mutex held.
// This prevents the thread from exiting prematurely and triggering a linux
// libc bug (https://sourceware.org/bugzilla/show_bug.cgi?id=19951).
llvm::Expected<HostThread> host_thread =
lldb_private::ThreadLauncher::LaunchThread(
"task-pool.worker", WorkerPtr, this, min_stack_size);
if (host_thread) {
host_thread->Release();
} else {
LLDB_LOG(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST),
"failed to launch host thread: {}",
llvm::toString(host_thread.takeError()));
}
}
}
lldb::thread_result_t TaskPoolImpl::WorkerPtr(void *pool) {
Worker((TaskPoolImpl *)pool);
return {};
}
void TaskPoolImpl::Worker(TaskPoolImpl *pool) {
while (true) {
std::unique_lock<std::mutex> lock(pool->m_tasks_mutex);
if (pool->m_tasks.empty()) {
pool->m_thread_count--;
break;
}
std::function<void()> f = std::move(pool->m_tasks.front());
pool->m_tasks.pop();
lock.unlock();
f();
}
}
void TaskMapOverInt(size_t begin, size_t end,
const llvm::function_ref<void(size_t)> &func) {
const size_t num_workers = std::min<size_t>(end, GetHardwareConcurrencyHint());
std::atomic<size_t> idx{begin};
auto wrapper = [&idx, end, &func]() {
while (true) {
size_t i = idx.fetch_add(1);
if (i >= end)
break;
func(i);
}
};
std::vector<std::future<void>> futures;
futures.reserve(num_workers);
for (size_t i = 0; i < num_workers; i++)
futures.push_back(TaskPool::AddTask(wrapper));
for (size_t i = 0; i < num_workers; i++)
futures[i].wait();
}
} // namespace lldb_private
|
83e70714aa3deff8caac725be36626b1dd9ea216 | 17fad22ea601cd68f1a46818b19f1f5002043b2c | /Desarrollo/ModernZ/Classes/Player.cpp | fcc786cabef3a2ee0b18468450b2123f74c2d458 | [] | no_license | mcalonso/TFG | 460d0c8a2003b97bfd81f22e53b675835c6c3fc4 | 4b301fd05f6b6ac7fe63d2d8238e1d0fbd93504a | refs/heads/master | 2021-01-23T05:50:36.365937 | 2017-08-28T22:31:36 | 2017-08-28T22:31:36 | 92,992,005 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,947 | cpp | Player.cpp | #include "Player.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "Definitions.h"
USING_NS_CC;
Player::Player(cocos2d::Layer *layer, int type, b2Vec2 pos, b2World* w) {
_world = w;
visibleSize = Director::getInstance()->getVisibleSize();
origin = Director::getInstance()->getVisibleOrigin();
typePlayer = type;
if (type == 2) {
spritePlayer = Sprite::createWithSpriteFrameName(Sprite_Nereita);
////////////////////////////////////////////////////////////////////////////////
// now lets animate the sprite we moved
walkFrames.reserve(10);
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk0.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk1.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk2.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk3.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk4.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk5.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk6.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk7.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk8.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlWalk9.png", Rect(0, 0, 360, 469)));
// create the animation out of the frames
walkAnimation = Animation::createWithSpriteFrames(walkFrames, 0.0f);
walkAnimate = Animate::create(walkAnimation);
/*********************************************************************************/
// now lets animate the sprite we moved
stopFrames.reserve(1);
stopFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlStop.png", Rect(0, 0, 360, 469)));
// create the animation out of the frames
stopAnimation = Animation::createWithSpriteFrames(stopFrames, 0.1f);
stopAnimate = Animate::create(stopAnimation);
/*********************************************************************************/
// now lets animate the sprite we moved
jumpUpFrames.reserve(1);
jumpUpFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlJump1.png", Rect(0, 0, 410, 469)));
// create the animation out of the frames
jumpUpAnimation = Animation::createWithSpriteFrames(jumpUpFrames, 0.1f);
jumpUpAnimate = Animate::create(jumpUpAnimation);
/*********************************************************************************/
// now lets animate the sprite we moved
jumpDownFrames.reserve(1);
jumpDownFrames.pushBack(SpriteFrame::create("player/GirlWalk/girlJump2.png", Rect(0, 0, 410, 469)));
// create the animation out of the frames
jumpDownAnimation = Animation::createWithSpriteFrames(jumpDownFrames, 0.1f);
jumpDownAnimate = Animate::create(jumpDownAnimation);
////////////////////////////////////////////////////////////////////////////////
spritePlayer->setScale(0.15f);
initBody(b2Vec2(pos.x * MPP, pos.x * MPP), b2Vec2(30 * MPP, 33 * MPP));
initFixture(b2Vec2(30 * MPP, 33 * MPP));
}
else if (type == 1) {
spritePlayer = Sprite::createWithSpriteFrameName(Sprite_Ignatius);
////////////////////////////////////////////////////////////////////////////////
// now lets animate the sprite we moved
walkFrames.reserve(6);
walkFrames.pushBack(SpriteFrame::create("player/PlayerWalk/playerOriginal1.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/PlayerWalk/playerOriginal2.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/PlayerWalk/playerOriginal3.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/PlayerWalk/playerOriginal4.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/PlayerWalk/playerOriginal5.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/PlayerWalk/playerOriginal6.png", Rect(0, 0, 360, 469)));
// create the animation out of the frames
walkAnimation = Animation::createWithSpriteFrames(walkFrames, 0.1f);
walkAnimate = Animate::create(walkAnimation);
/*********************************************************************************/
// now lets animate the sprite we moved
stopFrames.reserve(1);
stopFrames.pushBack(SpriteFrame::create("player/PlayerWalk/playerOriginal1.png", Rect(0, 0, 360, 469)));
// create the animation out of the frames
stopAnimation = Animation::createWithSpriteFrames(stopFrames, 0.1f);
stopAnimate = Animate::create(stopAnimation);
/*********************************************************************************/
// now lets animate the sprite we moved
jumpUpFrames.reserve(1);
jumpUpFrames.pushBack(SpriteFrame::create("player/PlayerWalk/playerSaltando1.png", Rect(0, 0, 410, 469)));
// create the animation out of the frames
jumpUpAnimation = Animation::createWithSpriteFrames(jumpUpFrames, 0.1f);
jumpUpAnimate = Animate::create(jumpUpAnimation);
/*********************************************************************************/
// now lets animate the sprite we moved
jumpDownFrames.reserve(1);
jumpDownFrames.pushBack(SpriteFrame::create("player/PlayerWalk/playerSaltando2.png", Rect(0, 0, 410, 469)));
// create the animation out of the frames
jumpDownAnimation = Animation::createWithSpriteFrames(jumpDownFrames, 0.1f);
jumpDownAnimate = Animate::create(jumpDownAnimation);
////////////////////////////////////////////////////////////////////////////////
spritePlayer->setScale(0.2f);
initBody(b2Vec2(pos.x * MPP, pos.x * MPP), b2Vec2(35 * MPP, 42 * MPP));
initFixture(b2Vec2(35 * MPP, 42 * MPP));
}
else {
spritePlayer = Sprite::createWithSpriteFrameName(Sprite_Zombi1);
////////////////////////////////////////////////////////////////////////////////
// now lets animate the sprite we atack
atackFrames.reserve(6);
atackFrames.pushBack(SpriteFrame::create("player/Zombie1/zAtack1.png", Rect(0, 0, 360, 469)));
atackFrames.pushBack(SpriteFrame::create("player/Zombie1/zAtack2.png", Rect(0, 0, 360, 469)));
atackFrames.pushBack(SpriteFrame::create("player/Zombie1/zAtack3.png", Rect(0, 0, 360, 469)));
atackFrames.pushBack(SpriteFrame::create("player/Zombie1/zAtack4.png", Rect(0, 0, 360, 469)));
atackFrames.pushBack(SpriteFrame::create("player/Zombie1/zAtack5.png", Rect(0, 0, 360, 469)));
atackFrames.pushBack(SpriteFrame::create("player/Zombie1/zAtack6.png", Rect(0, 0, 360, 469)));
atackFrames.pushBack(SpriteFrame::create("player/Zombie1/zAtack7.png", Rect(0, 0, 360, 469)));
atackFrames.pushBack(SpriteFrame::create("player/Zombie1/zAtack8.png", Rect(0, 0, 360, 469)));
// create the animation out of the frames
atackAnimation = Animation::createWithSpriteFrames(atackFrames, 0.1f);
atackAnimate = Animate::create(atackAnimation);
/*********************************************************************************/
// now lets animate the sprite we moved
walkFrames.reserve(10);
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk1.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk2.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk3.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk4.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk5.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk6.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk7.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk8.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk9.png", Rect(0, 0, 360, 469)));
walkFrames.pushBack(SpriteFrame::create("player/Zombie1/zWalk10.png", Rect(0, 0, 360, 469)));
// create the animation out of the frames
walkAnimation = Animation::createWithSpriteFrames(walkFrames, 0.1f);
walkAnimate = Animate::create(walkAnimation);
/*********************************************************************************/
// now lets animate the sprite we stop
stopFrames.reserve(1);
stopFrames.pushBack(SpriteFrame::create("player/Zombie1/zStop.png", Rect(0, 0, 360, 469)));
// create the animation out of the frames
stopAnimation = Animation::createWithSpriteFrames(stopFrames, 0.1f);
stopAnimate = Animate::create(stopAnimation);
////////////////////////////////////////////////////////////////////////////////
spritePlayer->setScale(0.2f);
initBody(b2Vec2(pos.x * MPP, pos.x * MPP), b2Vec2(35 * MPP, 42 * MPP));
initFixture(b2Vec2(35 * MPP, 42 * MPP));
}
// run it and repeat it forever
spritePlayer->runAction(stopAnimate);
spritePlayer->setPosition(pos.x, pos.y);
m_pBody->SetTransform(b2Vec2(pos.x * MPP, pos.y * MPP), m_pBody->GetAngle());
jumping = false;
layer->addChild(spritePlayer);
}
void Player::updatePlayer()
{
spritePlayer->setPosition(Vec2(m_pBody->GetPosition().x * PPM, (m_pBody->GetPosition().y * PPM)));
if (jumping) {
if (m_pBody->GetLinearVelocity().y < 0) { setAction(3); }
}
}
void Player::setAction(int type) {
spritePlayer->stopAllActions();
if (type == 0) {
stopAnimation = Animation::createWithSpriteFrames(stopFrames, 10.1f);
stopAnimate = Animate::create(stopAnimation);
spritePlayer->runAction(RepeatForever::create(stopAnimate));
}
else if (type == 1) {
walkAnimation = Animation::createWithSpriteFrames(walkFrames, 0.1f);
walkAnimate = Animate::create(walkAnimation);
spritePlayer->runAction(RepeatForever::create(walkAnimate));
}
else if (type == 2) {
jumpUpAnimation = Animation::createWithSpriteFrames(jumpUpFrames, 0.1f);
jumpUpAnimate = Animate::create(jumpUpAnimation);
spritePlayer->runAction(RepeatForever::create(jumpUpAnimate));
}
else if (type == 3) {
jumpDownAnimation = Animation::createWithSpriteFrames(jumpDownFrames, 0.1f);
jumpDownAnimate = Animate::create(jumpDownAnimation);
spritePlayer->runAction(RepeatForever::create(jumpDownAnimate));
}
}
void Player::setJumping(bool j) {
jumping = j;
setAction(0);
}
void Player::jump(int dir) {
if (!jumping)
{
m_pBody->ApplyLinearImpulse(b2Vec2(m_pBody->GetLinearVelocity().x, jumpForce), m_pBody->GetWorldCenter(), true);
jumping = true;
setAction(2);
}
}
void Player::move(int d) {
dir = d;
m_pBody->ApplyLinearImpulse(b2Vec2(velPlayer*dir, 0), m_pBody->GetWorldCenter(), true);
if (dir == -1) { spritePlayer->setRotationY(180);}
else spritePlayer->setRotationY(360);
if (!jumping) setAction(1);
}
void Player::stopPlayer() {
m_pBody->SetLinearVelocity(b2Vec2(0, m_pBody->GetLinearVelocity().y));
if (!jumping) setAction(0);
}
void Player::initBody(b2Vec2 pos, b2Vec2 tam) {
CCLOG("Create body in: %f %f", pos.x, pos.y);
b2BodyDef bodyDef;
bodyDef.position.Set(pos.x + (tam.x), -1 * (pos.y - (tam.y)));
bodyDef.type = b2_dynamicBody;
m_pBody = _world->CreateBody(&bodyDef);
m_pBody->SetLinearDamping(0);
}
void Player::initFixture(b2Vec2 tam) {
b2FixtureDef fixtureDef;
b2PolygonShape polyShape;
polyShape.SetAsBox((tam.x), (tam.y));
fixtureDef.shape = &polyShape;
fixtureDef.friction = 0;
fixtureDef.restitution = 0;
fixtureDef.density = 5;
b2Fixture* fixture = m_pBody->CreateFixture(&fixtureDef);
fixture->SetUserData((void*)DATA_PLAYER);
polyShape.SetAsBox(tam.x / 2, tam.y / 2, b2Vec2(0, -tam.y), 0);
fixtureDef.isSensor = true;
b2Fixture* sensorFixture = m_pBody->CreateFixture(&fixtureDef);
if(typePlayer == 1)sensorFixture->SetUserData((void*)DATA_PLAYER_SENSOR1);
else sensorFixture->SetUserData((void*)DATA_PLAYER_SENSOR2);
} |
bff6569f653fa62842190a3b234dfbe03ecdcc4e | a40025449c53ae38c46214a513d9dfbd9d5d33d5 | /NTField.h | 7fce6c585d09d6302cee2a113ee891bfb8e62c85 | [] | no_license | jbRedstone/5777.sem2.ex2b | c436b9fb903b01cace7557bc8c3465f9fe5ebe05 | 7a74fbf7f6d2c1a11e1c5359e59406be7787a70c | refs/heads/master | 2021-01-20T06:23:26.239995 | 2017-05-01T15:08:50 | 2017-05-01T15:08:50 | 89,874,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 309 | h | NTField.h | #pragma once
#include "Validator.h"
class NTField
{
public:
NTField(string request);
NTField get();
virtual bool getValidity();
void validSet(bool b);
virtual void refill();
virtual void validate();
virtual void printField();
protected:
string m_request;
bool m_valid;
};
|
8a96dfa239adb8bdc266d35108c7c3a33b2e19dd | a68915de1f53c464380ee322e3582aed15a87632 | /grasp_exp/CommThread.cpp | 295239fca735c740e4b8103aa531819f2211c7df | [] | no_license | amitmil274/feedback_experiment | 08c470af4c9602e7344346e7d8df0ad8a14cda56 | 4958ab23072280b043e24ac3c56eaad59bbe8180 | refs/heads/master | 2016-08-12T05:36:52.498280 | 2016-03-23T08:24:44 | 2016-03-23T08:24:44 | 54,306,211 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,298 | cpp | CommThread.cpp | #include <math.h>
#include <windows.h>
#include <list>
#include <vector>
#include "Haptic.h"
#include "FileHandle.h"
#include "Protocol.h"
#include "dhdc.h"
#include "drdc.h"
#include <Eigen/Geometry>
#include "Eigen/Eigen"
#include "PracticalSocket\PracticalSocket.h"
#include "sigma_comm.h"
#include "ITPteleoperation.h"
#include "..\VS_GUI_SERVER\CommonDS.h"
#include "Haptic.h"
using namespace std;
using namespace Eigen;
extern Sigma_Comm commOUT,commIN;
extern bool SimulationOn;
extern Timer timer;
double limit=1/1000;
double CurrentSendFreqTime=0.0;
int servo=0;
void* NetworkOUT(void* pUserData)
{
int servolast=servo;
while(SimulationOn)
{
commOUT.msgHeader.sequence=servo++;
// COMMUNICATION
if(commOUT.Check_Flag(BASIC_PROGRAM)) { // when UI allows 'Server' run
if ((timer.time-CurrentSendFreqTime)>=limit)
{
CurrentSendFreqTime=timer.time;
commOUT.Send_UDP();
}
}
if(servo%100 == 1) {
// Update SUI data
commOUT.Send_TCP();
}
}
return NULL;
}
void* NetworkIN(void* pUserData)
{
if(commOUT.Check_Flag(BASIC_PROGRAM)) { // when UI allows 'Server' run
commIN.Send_UDP();
}
while(SimulationOn)
{
// COMMUNICATION
if(commIN.Check_Flag(BASIC_PROGRAM)) { // when UI allows 'Server' run
commIN.Recv_UDP();
}
}
return NULL;
}
|
985e2571ee1e2f3cdec02ba480b9a1970e3ba971 | 6019ecf75b8d3fe7c54f6694aa525dcf5d00d92c | /Entity.cpp | 8f6ad0c57867ddf9f923e11e009498cf9b05943f | [] | no_license | tdepke2/Venture | 527a8628c846ba50ea9ccf5351e7c5cefbc8874b | bc3f66e467d25e1ad8a6154ec839981d1b9e4630 | refs/heads/master | 2020-04-04T15:22:56.805253 | 2018-12-18T01:16:44 | 2018-12-18T01:16:44 | 156,035,478 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,562 | cpp | Entity.cpp | #include "Entity.h"
#include "Tile.h"
#include "Window.h"
#include <algorithm>
#include <cassert>
using namespace std;
unordered_map<int, vector<PairXYi>> Entity::_radiusLookup;
Entity::Entity() {
init();
_position = PairXYi(-1, -1);
}
Entity::~Entity() {}
Entity::Entity(const Entity& entity) : Object(entity) {
lightRadius = entity.lightRadius;
_position = PairXYi(-1, -1);
}
bool Entity::setPosition(Window& win, const PairXYi& position) {
if (position.x < 0 || position.x >= win.tileArraySize.x || position.y < 0 || position.y >= win.tileArraySize.y || win.tileArray[position.y][position.x]->solid || win.tileArray[position.y][position.x]->entity != nullptr) {
return false;
}
win.tileArray[position.y][position.x]->entity = this;
if (_position != PairXYi(-1, -1)) {
assert(win.tileArray[_position.y][_position.x]->entity == this);
win.tileArray[_position.y][_position.x]->entity = nullptr;
}
_position = position;
return true;
}
const PairXYi& Entity::getPosition() const {
return _position;
}
void Entity::init(int lightRadius) {
this->lightRadius = lightRadius;
}
void Entity::init(const vector<string>& data, int& index) {
Object::init(data, index);
init(stoi(data[index]));
index += 1;
}
bool Entity::move(Window& win, int dx, int dy) {
return setPosition(win, PairXYi(_position.x + dx, _position.y + dy));
}
void Entity::resetPosition(Window& win) {
if (win.tileArraySize != PairXYi(0, 0)) {
assert(win.tileArray[_position.y][_position.x]->entity == this);
win.tileArray[_position.y][_position.x]->entity = nullptr;
}
_position = PairXYi(-1, -1);
}
void Entity::update(Window& win, const PairXYi& playerPos) {
_updateLight(win, playerPos);
}
string Entity::toString() const {
return Object::toString() + "," + to_string(lightRadius);
}
Entity* Entity::makeCopy() const {
return new Entity(*this);
}
void Entity::_updateLight(Window& win, const PairXYi& playerPos) {
if (lightRadius <= 0 || abs(_position.x - playerPos.x) - lightRadius > (win.getSize().x - 2) / 4 || abs(_position.y - playerPos.y) - lightRadius > (win.getSize().y - 2) / 2) {
return;
}
_traceCircle(win, 3, lightRadius / 3);
_traceCircle(win, 2, lightRadius * 2 / 3);
_traceCircle(win, 1, lightRadius);
}
void Entity::_traceCircle(Window& win, short val, int radius) {
auto mapIter = _radiusLookup.find(radius);
if (mapIter == _radiusLookup.end()) {
pair<int, vector<PairXYi>> newPair;
newPair.first = radius;
mapIter = _radiusLookup.insert(newPair).first;
if (radius <= 0) {
return;
}
Window winTemp;
winTemp.tileArraySize = PairXYi(radius + 1, radius + 1);
winTemp.tileArray = new Tile**[winTemp.tileArraySize.y];
for (int y = 0; y < winTemp.tileArraySize.y; ++y) {
winTemp.tileArray[y] = new Tile*[winTemp.tileArraySize.x];
for (int x = 0; x < winTemp.tileArraySize.x; ++x) {
winTemp.tileArray[y][x] = new Tile;
}
}
int x = -radius, y = 0, error1 = 2 - radius * 2, error2; // Bresenham circle algorithm, draw a circle into winTemp centered at (radius, radius). http://members.chello.at/~easyfilter/bresenham.html
do {
_traceLine(winTemp, 1, radius, radius, radius + x, radius - y);
mapIter->second.push_back(PairXYi(-x, y));
error2 = error1;
if (error2 <= y) {
++y;
error1 += y * 2 + 1;
}
if (error2 > x || error1 > y) {
++x;
error1 += x * 2 + 1;
}
} while (x < 0);
for (int y = 1; y < radius; ++y) {
int x = 1;
while (winTemp.tileArray[y][x]->lightLevel == 0) {
++x;
}
while (x < radius) {
if (winTemp.tileArray[y][x]->lightLevel == 0) {
_traceLine(winTemp, 1, radius, radius, x, y);
mapIter->second.push_back(PairXYi(radius - x, radius - y));
}
++x;
}
}
for (int y = 0; y < winTemp.tileArraySize.y; ++y) {
for (int x = 0; x < winTemp.tileArraySize.x; ++x) {
delete winTemp.tileArray[y][x];
}
delete[] winTemp.tileArray[y];
}
delete[] winTemp.tileArray;
}
if (_position.x - radius >= 0 && _position.x + radius < win.tileArraySize.x && _position.y - radius >= 0 && _position.y + radius < win.tileArraySize.y) {
for (const PairXYi& p : mapIter->second) {
_traceLine(win, val, _position.x, _position.y, _position.x + p.x, _position.y + p.y);
_traceLine(win, val, _position.x, _position.y, _position.x + p.y, _position.y - p.x);
_traceLine(win, val, _position.x, _position.y, _position.x - p.x, _position.y - p.y);
_traceLine(win, val, _position.x, _position.y, _position.x - p.y, _position.y + p.x);
}
} else {
for (const PairXYi& p : mapIter->second) {
_traceLine(win, val, _position.x, _position.y, min(_position.x + p.x, win.tileArraySize.x - 1), min(_position.y + p.y, win.tileArraySize.y - 1));
_traceLine(win, val, _position.x, _position.y, min(_position.x + p.y, win.tileArraySize.x - 1), max(_position.y - p.x, 0));
_traceLine(win, val, _position.x, _position.y, max(_position.x - p.x, 0), max(_position.y - p.y, 0));
_traceLine(win, val, _position.x, _position.y, max(_position.x - p.y, 0), min(_position.y + p.x, win.tileArraySize.y - 1));
}
}
}
void Entity::_traceLine(Window& win, short val, int x0, int y0, int x1, int y1) {
int dx = abs(x1 - x0), dy = -abs(y1 - y0); // Bresenham line algorithm.
int sx = x0 < x1 ? 1 : -1, sy = y0 < y1 ? 1 : -1;
int error1 = dx + dy, error2;
if (val > win.tileArray[y0][x0]->lightLevel) {
win.tileArray[y0][x0]->lightLevel = val;
}
while ((x0 != x1 || y0 != y1) && win.tileArray[y0][x0]->transparent) {
error2 = error1 * 2;
if (error2 >= dy) {
error1 += dy;
x0 += sx;
}
if (error2 <= dx) {
error1 += dx;
y0 += sy;
}
if (val > win.tileArray[y0][x0]->lightLevel) {
win.tileArray[y0][x0]->lightLevel = val;
}
}
} |
5e3fbb8b54f1b69d7e695dae0ebf68cdf40d615d | 17f6c821db03b40ab4cf7b36b56bcfc77a7961cb | /0383-Container With Most Water/0383-Container With Most Water.cpp | 0c764ff0699e9dec1578bcb5c2eabeea785713fd | [
"MIT"
] | permissive | yinyinyin123/LintCode | 62868a57a33ebf3e2fba8bcb52c6cdc3ab467e9d | 43072b8b867946c7a1ce4938201397949399abb7 | refs/heads/master | 2021-08-19T05:57:48.221252 | 2017-11-24T22:22:42 | 2017-11-24T22:22:42 | 113,461,517 | 2 | 1 | null | 2017-12-07T14:36:25 | 2017-12-07T14:36:24 | null | UTF-8 | C++ | false | false | 627 | cpp | 0383-Container With Most Water.cpp | class Solution {
public:
/*
* @param heights: a vector of integers
* @return: an integer
*/
int maxArea(vector<int> &heights) {
// write your code here
int maxA = 0;
int n = heights.size();
int start = 0, end = n - 1;
while (start < end) {
if (heights[start] <= heights[end]) {
maxA = max(maxA, heights[start] * (end - start));
++start;
}
else {
maxA = max(maxA, heights[end] * (end - start));
--end;
}
}
return maxA;
}
};
|
49e3d45af1485a27b8d5519e119eb13e8e3e01d1 | ae5d25e7f3a2b71e51021400edaa318cdea4c5b0 | /Graph.cpp | 5391b933bb0fde52fc462ad8157ffd9674f7336d | [] | no_license | aaron9292/Dijkstra_Algorithm | c61277e5540e86da7010f4afed10cb6a63701bef | 1785ae64953ae18066a6ea29cd9461895b38dba9 | refs/heads/master | 2023-04-07T09:30:48.937314 | 2020-12-01T16:32:43 | 2020-12-01T16:32:43 | 359,663,479 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | cpp | Graph.cpp | //
// Created by Erik Peterson on 11/5/20.
//
#include "Graph.h"
void Graph::addVertex(Vertex *vertex) {
vertices.push_back(vertex);
}
const std::vector<Vertex *>& Graph::getVertices() const {
return vertices;
}
void Graph::clear() {
vertices.clear();
}
|
d25746ad41679732fe7e45efe161ee6e23fefbd1 | 3126862ea13962984a9161a9ebd2032a4fc455bc | /08_basic_object_oriented_programming/08_x_chapter_8_comprehensive_quiz/MonsterType.cpp | 61981b63a9a66c3eefa1030514fecb9ad8b2953c | [] | no_license | nieyu/learncpp_com | f9a5d191e4e4c416efcceb216bac10f5246e17ea | f2e53f3cee75fc7f91dfd3c8a5a85d09ba5313e3 | refs/heads/master | 2023-01-05T16:45:07.526075 | 2020-11-04T13:59:56 | 2020-11-04T13:59:56 | 299,284,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 131 | cpp | MonsterType.cpp | //
// MonsterType.cpp
// 08_x_chapter_8_comprehensive_quiz
//
// Created by nie yu on 2020/11/1.
//
#include "MonsterType.hpp"
|
a32b3d286a56dbdc7cd8d23fa66456596040b340 | 0d89c8127f6883812e755ada997815db3beab4b2 | /gameFiles/gsObjects/state-objects/button.cpp | 4c145e6930600b748abfbd5b03bb7816972112a9 | [] | no_license | ChanceRbrts/Sodium_Room | b8f43213e194e3e08dce22f451dde4abcb774d7e | 02df1b81f68b3fd1f087429ee59bc3b9d7fc790e | refs/heads/master | 2023-04-12T17:44:32.189458 | 2021-02-08T19:46:13 | 2021-02-08T19:46:13 | 238,605,972 | 0 | 1 | null | 2020-10-11T01:34:07 | 2020-02-06T04:17:15 | C++ | UTF-8 | C++ | false | false | 3,998 | cpp | button.cpp | #include "button.h"
Button::Button(double X, double Y, int direction, std::string pressedValue) : Instance(X, Y, 2, 1){
multiPress = false;
pressedVal = pressedValue;
maxPress = 1;
setUp(direction);
}
Button::Button(double X, double Y, int direction, std::string pressedValue, int maxPressed) : Instance(X, Y, 2, 1){
multiPress = (maxPressed > 0);
maxPress = maxPressed;
pressedVal = pressedValue;
setUp(direction);
}
void Button::setUp(int dir){
pressed = 0;
pressDown = false;
prevPress = false;
immovable = true;
pressDir = dir;
pEpsilon = 0.15;
name = "Button";
// Retrieve the game state from the button (if it exists)
int value = GameState::getType(pressedVal);
int pressVal = GameState::getType(pressedVal+"_pressed");
if (value == SAV_BOOL){
pressed = GameState::getSaveB(pressedVal) ? 1 : 0;
} else if (value == SAV_INT){
pressed = GameState::getSaveI(pressedVal);
}
if (pressVal == SAV_BOOL){
pressDown = GameState::getSaveB(pressedVal+"_pressed");
}
// Based on which direction needs to be held to press the button...
// Top = 0, Right = 1, Bottom = 2, Left = 3
w = dir%2 == 0 ? 64 : 16;
h = dir%2 == 0 ? 16 : 64;
// A bit of redundancy here, fix if dimensions are correct.
x += (dir == 1) ? 16 : 0;
y += (dir == 0) ? 16 : 0;
// x += dir%2 == 0 ? 0 : (dir == 1 ? 16 : 0);
// y += dir%2 == 0 ? (dir == 0 ? 16 : 0) : 0;
}
void Button::unpushCheck(double deltaTime){
if (!multiPress) return;
std::map<Instance *, double>::iterator insts = collWith.begin();
std::vector<Instance *> toRemove;
// Remove stuff that's no longer colliding with the object.
for (; insts != collWith.end(); insts++){
Instance* o = insts->first;
collWith[o] -= deltaTime;
if (collWith[o] < 0){
toRemove.push_back(o);
}
}
for (int i = 0; i < toRemove.size(); i++){
collWith.erase(toRemove[i]);
}
if (collWith.begin() == collWith.end()){
pressDown = false;
GameState::setSaveB(pressedVal+"_pressed", false);
}
}
void Button::changePress(double deltaTime){
double* toChange = pressDir%2 == 0 ? &h : &w;
double* adjustX = pressDir%2 == 0 ? &dY : &dX;
bool toAdjust = pressDir < 2;
*toChange = pressDown ? 8 : 16;
if (toAdjust){
*adjustX += (pressDown ? 8 : -8)/deltaTime;
}
}
void Button::update(double deltaTime, bool* keyPressed, bool* keyHeld){
dX = 0;
dY = 0;
unpushCheck(deltaTime);
if (prevPress != pressDown){
changePress(deltaTime);
}
prevPress = pressDown;
}
void Button::collided(Instance* o, double deltaTime){
// Make sure the dX/dY lines up with the direction the button is.
// Based on which direction needs to be held to press the button...
// Top = 0, Right = 1, Bottom = 2, Left = 3
int sign = pressDir < 2 ? -1 : 1;
if (pressDir%2 == 0 && (o->getCollDY()*sign >= 0 || o->x >= x+w || o->x+o->w <= x)) return;
if (pressDir%2 == 1 && (o->getCollDX()*sign >= 0 || o->y >= y+h || o->y+o->h <= y)) return;
if (multiPress){
std::map<Instance *, double>::iterator obj = collWith.find(o);
if (obj != collWith.end()){
collWith[o] = pEpsilon;
} else collWith.insert({o, pEpsilon});
}
// Make sure the button hasn't already been pressed.
if ((pressed && !multiPress) || pressDown) return;
// Finally, update the game state with what the button directs it to.
pressDown = true;
changeState();
if (multiPress) GameState::setSaveI(pressedVal, pressed);
else GameState::setSaveB(pressedVal, pressed != 0);
GameState::setSaveB(pressedVal+"_pressed", true);
}
void Button::makePermanent(){
GameState::makePermament(pressedVal);
GameState::makePermament(pressedVal+"_pressed");
}
void Button::changeState(){
if (!multiPress) return;
pressed = (pressed+1) % maxPress;
}
|
d2a1a3ea622c88370c859f819cb83f549c1da669 | ec64f779d97653373bee9aab2d78b161b7810eef | /shade.cc | f90d2f18be1d11560fc26d5e87368b7eff730cd9 | [] | no_license | Judy-zdw/cc3k-maze-game | 3ca3b94de79de3bd4dc1eebffc2a55833a8cb95e | df46aa558c61342084cbbd6660a727646cea0f28 | refs/heads/master | 2020-04-17T15:55:59.145333 | 2019-01-20T23:37:32 | 2019-01-20T23:37:32 | 166,719,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 351 | cc | shade.cc | #include "shade.h"
using namespace std;
Shade::Shade(double max_HP, double HP, double Atk, double Def, double extra_Atk, double extra_Def, int Gold):
Hero{max_HP, HP, Atk, Def, extra_Atk, extra_Def, Gold} {}
int Shade::attack(Unit* toattack) {
return toattack->beattacked(this);
}
bool Shade::use(Unit *touse) {
return touse->beused(this);
}
|
1269dfafef2dd7da1143214077f3b3343c68561d | feaf5ed8ba4045ba149a77db276533bdb7b0a66f | /2.ClassExercise/EP18-1.cpp | 74a89aab91f2a42ab7c5a3da5b0cf392dba090eb | [] | no_license | OuyangRuihong/Euler | 7f3f7289ef82d39bd5be8ef8de4b3db479a51f6c | 5836445bb3ff5cd0da5be4f9f686ac17f12c4fef | refs/heads/master | 2020-05-09T13:43:21.020986 | 2019-09-17T13:16:08 | 2019-09-17T13:16:08 | 181,164,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 870 | cpp | EP18-1.cpp | /*************************************************************************
> File Name: EP18.cpp
> Author:OuyangRuihong
> Mail:845540021@qq.com
> Created Time: 2019年08月14日 星期三 18时08分45秒
************************************************************************/
#include<iostream>
#include<cstring>
#include<map>
#include<vector>
using namespace std;
#define MAX_N 20
int val[MAX_N + 5][MAX_N + 5];
int main() {
for (int i = 0; i< MAX_N; i++) {
for (int j = 0; j <= i; j++) {
cin >> val[i][j];
}
}
for (int i = MAX_N - 2; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
//val[i][j] += val[i + 1][j] > val[i + 1][j + 1] ? val[i + 1][j] : val[i + 1][j + 1];
val[i][j] += max(val[i + 1][j], val[i + 1][j + 1]);
}
}
cout << val[0][0] << endl;
return 0;
}
|
f4418fb695d847a48b3bb6548885e257155b3ba8 | a7a07a846494d90e947c4463398d80aa1ec9d9eb | /ArrtModel/Model/ConversionManager.h | 64c1b0bebe93c7026ea46ebfd2ec3e61bd6b5537 | [
"LicenseRef-scancode-generic-cla",
"LGPL-2.0-or-later",
"LGPL-2.1-or-later",
"MIT",
"GFDL-1.3-only",
"GPL-1.0-or-later",
"GPL-2.0-or-later",
"GPL-3.0-only",
"LicenseRef-scancode-warranty-disclaimer",
"GPL-2.0-only",
"LGPL-2.1-only"
] | permissive | isabella232/azure-remote-rendering-asset-tool | 33794f69b6e594c9565ca1131e668f6b8d301d5b | 7eeb1b750399a77a7224ea5316728b4252e7ddba | refs/heads/master | 2023-03-10T16:08:59.958874 | 2020-12-08T14:56:34 | 2020-12-08T14:56:34 | 324,980,896 | 0 | 0 | MIT | 2021-02-24T10:21:32 | 2020-12-28T10:28:06 | null | UTF-8 | C++ | false | false | 5,994 | h | ConversionManager.h | #pragma once
#include <Model/IncludesAzureRemoteRendering.h>
#include <Model/IncludesAzureStorage.h>
#include <QCoreApplication>
#include <QElapsedTimer>
#include <QMap>
#include <QObject>
#include <QTime>
#include <QTimer>
#include <shared_mutex>
class AzureStorageManager;
class ArrFrontend;
class Configuration;
// struct representing an conversion. It holds the current status and the parameters used (input/output)
struct Conversion
{
// Parameters below holds the data for a RR::StartAssetConversionAsync (where the strings are const char*)
// taken from arr_asset_conversion_input_sas_params
std::string m_input_storage_account_name;
std::string m_input_blob_container_name;
std::string m_input_folder;
std::string m_input_asset_relative_path;
azure::storage::storage_uri m_inputContainer;
// taken from arr_asset_conversion_output_sas_params
std::string m_output_storage_account_name;
std::string m_output_blob_container_name;
std::string m_output_folder;
std::string m_output_asset_relative_path;
azure::storage::storage_uri m_outputContainer;
std::string m_renderingSettings;
std::string m_materialOverrides;
// optional: this indicates the local directory we are synchronizing from
std::wstring m_synchronizeFromLocalDir;
// status of the conversion
enum Status
{
UNKNOWN,
NOT_STARTED,
START_REQUESTED,
FAILED_TO_START,
STARTING,
SYNCHRONIZING,
CONVERTING,
COMPLETED,
CANCELED,
SYNCHRONIZATION_FAILED,
CONVERSION_FAILED
} m_status = NOT_STARTED;
std::string m_conversionUUID;
// stop/watch timer used to time the conversion
QTime m_startConversionTime;
QTime m_endConversionTime;
QString m_name;
bool isActive() const { return m_status == START_REQUESTED || m_status == STARTING || m_status == SYNCHRONIZING || m_status == CONVERTING; }
bool isFinished() const { return m_status == FAILED_TO_START || m_status == COMPLETED || m_status == CANCELED || m_status == SYNCHRONIZATION_FAILED || m_status == CONVERSION_FAILED || m_status == UNKNOWN; }
void updateConversionStatus(Status newStatus, const QString& message = QString());
std::string getInputModelFullPath() const
{
return m_input_folder + m_input_asset_relative_path;
}
std::string getInputModelDirectory() const
{
std::string dir = getInputModelFullPath();
const auto lastSlash = dir.find_last_of('/');
if (lastSlash == std::string::npos)
{
return {};
}
else
{
return dir.substr(0, lastSlash + 1);
}
}
bool changeRootDirectory(std::string directory)
{
std::string fullPath = getInputModelFullPath();
if (directory != m_input_folder && fullPath._Starts_with(directory))
{
m_input_folder = std::move(directory);
m_input_asset_relative_path = fullPath.substr(m_input_folder.length());
return true;
}
else
{
return false;
}
}
// return the name of the model
QString getModelName() const
{
return QString::fromStdString(m_input_asset_relative_path).section('/', -1).section('.', 0, -2);
}
// return the default name that would be given to this conversion if m_name is not set. Id is the conversion id, which might be used in the default name
QString getDefaultName(int id) const
{
const QString name = getModelName();
if (!name.isEmpty())
{
return name;
}
else
{
return QCoreApplication::tr("Conversion %1").arg(id);
}
}
RR::ApiHandle<RR::ConversionStatusAsync> m_statusAsync = nullptr;
RR::ApiHandle<RR::StartAssetConversionAsync> m_conversionCall = nullptr;
};
// class used to control conversions in ARRT. It will keep track of the current conversions and the past ones, and allow the user to start new ones or
// cancel/remove them
class ConversionManager : public QObject
{
Q_OBJECT
public:
typedef uint ConversionId;
ConversionManager(ArrFrontend* client, AzureStorageManager* storageManager, Configuration* configuration, QObject* parent = nullptr);
~ConversionManager();
int getConversionsCount() const;
ConversionId getConversionId(int idx) const;
const Conversion* getConversion(ConversionId id) const;
Conversion* getConversion(ConversionId id);
ConversionId addNewConversion();
// the blob provider is used to generate the Sas tokens
void startConversion(ConversionId id, const AzureStorageManager* storageManager);
void removeConversion(ConversionId id);
void setConversionName(ConversionId id, const QString& name);
bool isEnabled() const;
// return the number of running conversions
int runningConversionCount() const;
static const QString s_default_input_container;
static const QString s_default_output_container;
Q_SIGNALS:
void onEnabledChanged();
void conversionUpdated(ConversionId id);
void conversionAdded(ConversionId id);
void conversionRemoved(ConversionId id);
void runningConversionCountChanged();
void conversionCompleted(ConversionId id, bool success);
private:
ArrFrontend* const m_frontend;
// this is only needed to generate SAS from the input urls. <TODO> see if it can be removed
AzureStorageManager* const m_storageManager;
Configuration* const m_configuration;
// map from conversion ID to conversion data
QMap<ConversionId, Conversion*> m_conversions;
ConversionId m_highestId = 0;
QTimer* m_updateTimer = nullptr;
bool m_enabled = false;
int m_runningConversionCount = 0;
int m_secondsUntilNextUpdate = 0;
//update all of the active conversions
void updateConversions(bool updateRemotely);
void changeConversionCount(int delta);
};
|
fd506fc59f96621e236f74cceaa0e3dc284d70e4 | 40701615742c3fade8f3b9313dfe05e48ab51ddc | /mainsys.cpp | 8262c3c71b1ebb71b6df9bfa2efac4b23766cbc9 | [] | no_license | chinchillawang/Memory-Management | bc39aabd0123a99e40389f59e48b46067e67edda | af4687477c8956810e23ab9fb10bf688e6230120 | refs/heads/master | 2021-05-28T19:15:29.522351 | 2015-06-08T14:45:01 | 2015-06-08T14:45:01 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 5,321 | cpp | mainsys.cpp | #include "memsys.h"
#include <cstdlib>
#include <iostream>
using namespace mainsys;
using namespace std;
MemPackage::MemPackage(unsigned int request) :TotalInfo(request) //有点小问题
{
bool *p = (bool*)malloc(request + SIZE_BLOCK_M + 1); //需求,满足需求的内存块头信息,该内存块的归属标记
if (p == nullptr) //内存申请失败时,返回错误信息并退出程序
{
cerr << "内存不足,无法创建新的内存包" << endl;
exit(EXIT_FAILURE);
}
headSpace = rootTree = (MemBlock*)p; //管理域头地址和空闲内存搜索树指向第一个内存块
next = pre = nullptr; //内存块信息的初始化
headSpace->left = headSpace->right = headSpace->pre = nullptr;
headSpace->parent = headSpace;
headSpace->totalSize = request;
headSpace->usedSize = 0;
p = (bool*)headSpace + SIZE_BLOCK_M + 1; //设置内存块的归属标记为1
*p = 1;
}
MemBlock* MemPackage::divideBlock(MemBlock *target)
{
bool *p; //标记指针
MemBlock *secondBlock;
p = (bool*)target;
p = p + SIZE_BLOCK_M + target->usedSize + 1; //标记指针从target向后移动的内存单元
secondBlock = (MemBlock*)p;
secondBlock->pre = target; //初始化新块的信息
secondBlock->left = secondBlock->parent = secondBlock->right = nullptr;
secondBlock->totalSize = target->totalSize - target->usedSize - SIZE_BLOCK_M - 1; //分割出的新块的总管理空间
secondBlock->usedSize = 0;
p = (bool*)secondBlock + SIZE_BLOCK_M + 1; //设置内存块的归属标记为1
*p = 1;
return secondBlock;
}
MemBlock* MemPackage::mergeBlock(MemBlock *target)
{
MemBlock *newBlock, *tmp;
newBlock = target; tmp = mergeBlock(target, false); //只要后面的块是空的,就向后合并
while (tmp != nullptr)
{
newBlock = tmp;
tmp = mergeBlock(newBlock, false);
}
tmp = mergeBlock(newBlock, true); //只要前面的块是空的,就向前合并
while (tmp != nullptr)
{
newBlock = tmp;
tmp = mergeBlock(newBlock, true);
}
return newBlock; //返回合并好的块
}
MemBlock* MemPackage::mergeBlock(MemBlock *target, bool direction)
{
if (direction) //向前合并
{
MemBlock *pl;
if (target->pre != nullptr) //这个块不是第一个块
{
pl = target->pre;
if (pl->usedSize == 0)
pl->totalSize = pl->totalSize + target->totalSize + SIZE_BLOCK_M - 1; //新块管理空间的大小
return pl;
}
else
return nullptr; //无法再向前合并时,返回空指针
}
else //向后合并
{
MemBlock *pn;
bool *endp, *p;
endp = (bool*)headSpace + getTS();
p = (bool*)target;
p = p + target->totalSize + SIZE_BLOCK_M + 1; //移动到这个块的末尾
if (p != endp) //标记指针p没有移到管理域最后
{
p++; //标记指针移到下一个块
pn = (MemBlock*)p;
if (pn->usedSize == 0)
target->totalSize = target->totalSize + pn->totalSize + SIZE_BLOCK_M + 1;
return target;
}
else
return nullptr; //无法再向后合并时,返回空指针
}
}
void* MemPackage::getBlock(unsigned int request)
{
void *user = nullptr;
if (request > getTS() - getUS()) //需求大于未分配空间时,返回空指针
return user;
else
{
//在空闲内存管理树中遍历结点
}
}
MainSys::MainSys() :TotalInfo(PACKAGE_SIZE)
{
headPackage = latestPackage = (MemPackage*)malloc(sizeof(MemPackage));
if (headPackage == nullptr) //内存不足时,无法初始化主系统
{
cerr << "内存不足,无法初始化主系统" << endl;
exit(EXIT_FAILURE);
}
}
void MainSys::addPackageNode(unsigned int packageSize)
{
MemPackage *pn = (MemPackage*)malloc(packageSize);
if (pn == nullptr)
{
cerr << "内存不足" << endl;
exit(EXIT_FAILURE);
}
pn->pre = latestPackage;
pn->next = nullptr;
latestPackage->next = pn;
latestPackage = pn;
}
void MainSys::deletePackageNode(MemPackage *packageNode) //删除包结点
{
if (packageNode->pre == nullptr) //第一个结点一直保留
return;
else
{
if (packageNode->next == nullptr) //最后一个结点时
{
MemPackage *pl = packageNode->pre; //前一个内存包结点
pl->next = nullptr; //将内存包从链表尾删去
free(packageNode); //释放该结点
}
else //结点在中间时
{
MemPackage *pl, *pn;
pl = packageNode->pre; //前一个内存包结点
pn = packageNode->next; //后一个内存包结点
pl->next = pn; //将packageNode从内存包链表中删除
pn->pre = pl;
free(packageNode); //释放该结点
}
}
}
void* MainSys::getBlock(unsigned int request)
{
void *user;
if (request > getTS() - getUS()) //需求大于可分配空间时,添加内存包
{
addPackageNode(request + SIZE_BLOCK_M);
user = latestPackage->getBlock(request);
}
else //需求小于等于可分配空间时,按顺序遍历每个内存包
{
MemPackage *p = headPackage;
while (p->next != nullptr) //不是最后一个结点
{
if (request <= p->getTS() - p->getUS()) //发现一个可用空间大于需求的内存包
{
user = p->getBlock(request); //调用内存包的内存分配函数
break;
}
else
continue; //该内存包不合要求
}
if (user == nullptr) //最后未能成功分配符合要求的内存块,则新建一个内存包
{
addPackageNode(request + SIZE_BLOCK_M);
user = latestPackage->getBlock(request);
}
}
}
void* |
27dfba17eb01a458ec5120e82c8f2f722188fba3 | 3640c0855a78cfb3119694cd571d1f1e8838ca1c | /aoj/ALDS1/10/B/main.cpp | 2154fa957257436f91dc36e7e66a0f96ef806d80 | [] | no_license | gom74/procon | 22bbf773299514ac1b733afd9527852275593728 | 606395611ecf0a56b27849069364370e0519038d | refs/heads/master | 2022-09-21T19:00:48.956709 | 2020-06-05T18:02:26 | 2020-06-05T18:02:26 | 261,773,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | cpp | main.cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
ll rec(int left, int right, vector<vector<ll> > &dp, vector<int> &R, vector<int> &C) {
int N = dp.size();
if (dp.at(left).at(right) != LLONG_MAX) {
return dp.at(left).at(right);
}
if (left == right) {
return dp.at(left).at(right) = 0;
}
ll res = LLONG_MAX;
for (int i = left; i < right; ++i) {
res = min(res, rec(left, i, dp, R, C) + rec(i + 1, right, dp, R, C) + 1LL * R.at(left) * C.at(i) * C.at(right));
}
return dp.at(left).at(right) = res;
}
int main() {
cin.tie(0);
ios::sync_with_stdio(false);
int N;
cin >> N;
vector<int> R(N), C(N);
for (int i = 0; i < N; ++i) {
cin >> R.at(i) >> C.at(i);
}
vector<vector<ll> > dp(N, vector<ll>(N, LLONG_MAX));
cout << rec(0, N - 1, dp, R, C) << endl;
return 0;
} |
1d70ed8f901f16cba8d25d40c4d6646b492e6f37 | 70cfbcb6a23f607a8e15c60b0d5afdd27b09e6e0 | /Envelope.Math/Math/SevenPointPattern.h | 246a51b2cec76427c6a82081841dd240377d7f8b | [] | no_license | Hengle/AirCushionSimulation | 3e87077ef0cfc9731c7e8badf517e223e99a6ca9 | fa7a0c50edf16a8223a0fb94ddc7191ffd2f673b | refs/heads/master | 2023-03-17T16:28:24.714791 | 2020-10-11T19:08:03 | 2020-10-11T19:08:03 | null | 0 | 0 | null | null | null | null | MacCyrillic | C++ | false | false | 3,115 | h | SevenPointPattern.h | #pragma once
#include "utils.h"
#include "BigPointPattern.h"
namespace EnvelopeMath {
/**
* @class SevenPointPattern
*
* @brief Шаблон, состо€щий из 9 точек.
* *
* *
* *****
*
* @author Vs
* @date 05.04.2013
*/
class DllExport SevenPointPattern : public BigPointPattern
{
protected:
TPoint p_cur;
TPoint p_l;
TPoint p_r;
TPoint p_t;
protected:
TPoint p_ll;
TPoint p_rr;
TPoint p_tt;
public:
SevenPointPattern(void);
SevenPointPattern(const TPoint & cur, const TPoint & l, const TPoint & r , const TPoint & t, const TPoint & ll, const TPoint & rr, const TPoint & tt);
~SevenPointPattern(void);
TVector GetCurvatureVec(OrientationDirection od, SideDirection sd ) const
{
TVector res;
switch (od)
{
case HORIZONTAL:
switch (sd)
{
case LEFT:
res = curvatureVec(p_ll , p_l, p_cur, p_t);
break;
case RIGHT:
res = curvatureVec(p_cur, p_r, p_rr , p_t);
break;
case BOTTOM:
throw std::exception ("GetCurvatureVec - incompatible directions");
break;
case TOP:
throw std::exception ("GetCurvatureVec - incompatible directions");
break;
default:
throw std::exception ("GetCurvatureVec - unknown SideDirection");
break;
}
break;
case VERTICAL:
switch (sd)
{
case LEFT:
throw std::exception ("GetCurvatureVec - incompatible directions");
break;
case RIGHT:
throw std::exception ("GetCurvatureVec - incompatible directions");
break;
case BOTTOM:
// нулевой вектор
break;
case TOP:
res = curvatureVec(p_cur, p_t, p_tt, p_l);
break;
default:
throw std::exception ("GetCurvatureVec - unknown SideDirection");
break;
}
break;
default:
throw std::exception ("GetCurvatureVec - unknown OrientationDirection");
break;
}
return res;
};
double GetCurvature(OrientationDirection od, SideDirection sd) const
{
double res;
switch (od)
{
case HORIZONTAL:
switch (sd)
{
case LEFT:
res = curvature(p_ll , p_l, p_cur, p_t);
break;
case RIGHT:
res = curvature(p_cur, p_r, p_rr , p_t);
break;
case BOTTOM:
throw std::exception ("GetCurvature - incompatible directions");
break;
case TOP:
throw std::exception ("GetCurvature - incompatible directions");
break;
default:
throw std::exception ("GetCurvature - unknown SideDirection");
break;
}
break;
case VERTICAL:
switch (sd)
{
case LEFT:
throw std::exception ("GetCurvature - incompatible directions");
break;
case RIGHT:
throw std::exception ("GetCurvature - incompatible directions");
break;
case BOTTOM:
res = 0.0;
break;
case TOP:
res = curvature(p_cur, p_t, p_tt, p_l);
break;
default:
throw std::exception ("GetCurvature - unknown SideDirection");
break;
}
break;
default:
throw std::exception ("GetCurvature - unknown OrientationDirection");
break;
}
return res;
};
};
} |
bc8865bdb6b9089ab43286baff0a609c9f2df70f | e5e5e8b07e8cd21f23fd4befbc7e7aceb1bf61f5 | /src/blockchain_db/lmdb/db_lmdb.cpp | 7f0be25991bafac39958caf61915b94d6333e00c | [
"BSD-3-Clause",
"MIT"
] | permissive | sumoprojects/sumokoin | c4074f7b4f40c909b9d9dc9ce01521adb3cccb3e | 2857d0bffd36bf2aa579ef80518f4cb099c98b05 | refs/heads/master | 2022-03-04T02:21:41.550045 | 2021-08-22T04:32:04 | 2021-08-22T04:32:04 | 89,453,021 | 175 | 245 | NOASSERTION | 2021-08-22T04:32:05 | 2017-04-26T07:45:08 | C++ | UTF-8 | C++ | false | false | 192,814 | cpp | db_lmdb.cpp | // Copyright (c) 2014-2021, The Monero Project
// 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.
#ifndef _WIN32
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
#endif
#include "db_lmdb.h"
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <boost/circular_buffer.hpp>
#include "string_tools.h"
#include "file_io_utils.h"
#include "common/util.h"
#include "common/pruning.h"
#include "cryptonote_basic/cryptonote_format_utils.h"
#include "profile_tools.h"
#include "ringct/rctOps.h"
#undef MONERO_DEFAULT_LOG_CATEGORY
#define MONERO_DEFAULT_LOG_CATEGORY "blockchain.db.lmdb"
#if defined(__i386) || defined(__x86_64)
#define MISALIGNED_OK 1
#endif
using epee::string_tools::pod_to_hex;
using namespace crypto;
// Increase when the DB structure changes
#define VERSION 5
namespace
{
#pragma pack(push, 1)
// This MUST be identical to output_data_t, without the extra rct data at the end
struct pre_rct_output_data_t
{
crypto::public_key pubkey; //!< the output's public key (for spend verification)
uint64_t unlock_time; //!< the output's unlock time (or height)
uint64_t height; //!< the height of the block which created the output
};
#pragma pack(pop)
template <typename T>
inline void throw0(const T &e)
{
LOG_PRINT_L0(e.what());
throw e;
}
template <typename T>
inline void throw1(const T &e)
{
LOG_PRINT_L1(e.what());
throw e;
}
#define MDB_val_set(var, val) MDB_val var = {sizeof(val), (void *)&val}
#define MDB_val_sized(var, val) MDB_val var = {val.size(), (void *)val.data()}
#define MDB_val_str(var, val) MDB_val var = {strlen(val) + 1, (void *)val}
template<typename T>
struct MDB_val_copy: public MDB_val
{
MDB_val_copy(const T &t) :
t_copy(t)
{
mv_size = sizeof (T);
mv_data = &t_copy;
}
private:
T t_copy;
};
template<>
struct MDB_val_copy<cryptonote::blobdata>: public MDB_val
{
MDB_val_copy(const cryptonote::blobdata &bd) :
data(new char[bd.size()])
{
memcpy(data.get(), bd.data(), bd.size());
mv_size = bd.size();
mv_data = data.get();
}
private:
std::unique_ptr<char[]> data;
};
template<>
struct MDB_val_copy<const char*>: public MDB_val
{
MDB_val_copy(const char *s):
size(strlen(s)+1), // include the NUL, makes it easier for compares
data(new char[size])
{
mv_size = size;
mv_data = data.get();
memcpy(mv_data, s, size);
}
private:
size_t size;
std::unique_ptr<char[]> data;
};
}
namespace cryptonote
{
int BlockchainLMDB::compare_uint64(const MDB_val *a, const MDB_val *b)
{
uint64_t va, vb;
memcpy(&va, a->mv_data, sizeof(va));
memcpy(&vb, b->mv_data, sizeof(vb));
return (va < vb) ? -1 : va > vb;
}
int BlockchainLMDB::compare_hash32(const MDB_val *a, const MDB_val *b)
{
uint32_t *va = (uint32_t*) a->mv_data;
uint32_t *vb = (uint32_t*) b->mv_data;
for (int n = 7; n >= 0; n--)
{
if (va[n] == vb[n])
continue;
return va[n] < vb[n] ? -1 : 1;
}
return 0;
}
int BlockchainLMDB::compare_string(const MDB_val *a, const MDB_val *b)
{
const char *va = (const char*) a->mv_data;
const char *vb = (const char*) b->mv_data;
const size_t sz = std::min(a->mv_size, b->mv_size);
int ret = strncmp(va, vb, sz);
if (ret)
return ret;
if (a->mv_size < b->mv_size)
return -1;
if (a->mv_size > b->mv_size)
return 1;
return 0;
}
}
namespace
{
/* DB schema:
*
* Table Key Data
* ----- --- ----
* blocks block ID block blob
* block_heights block hash block height
* block_info block ID {block metadata}
*
* txs_pruned txn ID pruned txn blob
* txs_prunable txn ID prunable txn blob
* txs_prunable_hash txn ID prunable txn hash
* txs_prunable_tip txn ID height
* tx_indices txn hash {txn ID, metadata}
* tx_outputs txn ID [txn amount output indices]
*
* output_txs output ID {txn hash, local index}
* output_amounts amount [{amount output index, metadata}...]
*
* spent_keys input hash -
*
* txpool_meta txn hash txn metadata
* txpool_blob txn hash txn blob
*
* alt_blocks block hash {block data, block blob}
*
* Note: where the data items are of uniform size, DUPFIXED tables have
* been used to save space. In most of these cases, a dummy "zerokval"
* key is used when accessing the table; the Key listed above will be
* attached as a prefix on the Data to serve as the DUPSORT key.
* (DUPFIXED saves 8 bytes per record.)
*
* The output_amounts table doesn't use a dummy key, but uses DUPSORT.
*/
const char* const LMDB_BLOCKS = "blocks";
const char* const LMDB_BLOCK_HEIGHTS = "block_heights";
const char* const LMDB_BLOCK_INFO = "block_info";
const char* const LMDB_TXS = "txs";
const char* const LMDB_TXS_PRUNED = "txs_pruned";
const char* const LMDB_TXS_PRUNABLE = "txs_prunable";
const char* const LMDB_TXS_PRUNABLE_HASH = "txs_prunable_hash";
const char* const LMDB_TXS_PRUNABLE_TIP = "txs_prunable_tip";
const char* const LMDB_TX_INDICES = "tx_indices";
const char* const LMDB_TX_OUTPUTS = "tx_outputs";
const char* const LMDB_OUTPUT_TXS = "output_txs";
const char* const LMDB_OUTPUT_AMOUNTS = "output_amounts";
const char* const LMDB_SPENT_KEYS = "spent_keys";
const char* const LMDB_TXPOOL_META = "txpool_meta";
const char* const LMDB_TXPOOL_BLOB = "txpool_blob";
const char* const LMDB_ALT_BLOCKS = "alt_blocks";
const char* const LMDB_HF_STARTING_HEIGHTS = "hf_starting_heights";
const char* const LMDB_HF_VERSIONS = "hf_versions";
const char* const LMDB_PROPERTIES = "properties";
const char zerokey[8] = {0};
const MDB_val zerokval = { sizeof(zerokey), (void *)zerokey };
const std::string lmdb_error(const std::string& error_string, int mdb_res)
{
const std::string full_string = error_string + mdb_strerror(mdb_res);
return full_string;
}
inline void lmdb_db_open(MDB_txn* txn, const char* name, int flags, MDB_dbi& dbi, const std::string& error_string)
{
if (auto res = mdb_dbi_open(txn, name, flags, &dbi))
throw0(cryptonote::DB_OPEN_FAILURE((lmdb_error(error_string + " : ", res) + std::string(" - you may want to start with --db-salvage")).c_str()));
}
} // anonymous namespace
#define CURSOR(name) \
if (!m_cur_ ## name) { \
int result = mdb_cursor_open(*m_write_txn, m_ ## name, &m_cur_ ## name); \
if (result) \
throw0(DB_ERROR(lmdb_error("Failed to open cursor: ", result).c_str())); \
}
#define RCURSOR(name) \
if (!m_cur_ ## name) { \
int result = mdb_cursor_open(m_txn, m_ ## name, (MDB_cursor **)&m_cur_ ## name); \
if (result) \
throw0(DB_ERROR(lmdb_error("Failed to open cursor: ", result).c_str())); \
if (m_cursors != &m_wcursors) \
m_tinfo->m_ti_rflags.m_rf_ ## name = true; \
} else if (m_cursors != &m_wcursors && !m_tinfo->m_ti_rflags.m_rf_ ## name) { \
int result = mdb_cursor_renew(m_txn, m_cur_ ## name); \
if (result) \
throw0(DB_ERROR(lmdb_error("Failed to renew cursor: ", result).c_str())); \
m_tinfo->m_ti_rflags.m_rf_ ## name = true; \
}
namespace cryptonote
{
typedef struct mdb_block_info_1
{
uint64_t bi_height;
uint64_t bi_timestamp;
uint64_t bi_coins;
uint64_t bi_weight; // a size_t really but we need 32-bit compat
uint64_t bi_diff;
crypto::hash bi_hash;
} mdb_block_info_1;
typedef struct mdb_block_info_2
{
uint64_t bi_height;
uint64_t bi_timestamp;
uint64_t bi_coins;
uint64_t bi_weight; // a size_t really but we need 32-bit compat
uint64_t bi_diff;
crypto::hash bi_hash;
uint64_t bi_cum_rct;
} mdb_block_info_2;
typedef struct mdb_block_info_3
{
uint64_t bi_height;
uint64_t bi_timestamp;
uint64_t bi_coins;
uint64_t bi_weight; // a size_t really but we need 32-bit compat
uint64_t bi_diff;
crypto::hash bi_hash;
uint64_t bi_cum_rct;
uint64_t bi_long_term_block_weight;
} mdb_block_info_3;
typedef struct mdb_block_info_4
{
uint64_t bi_height;
uint64_t bi_timestamp;
uint64_t bi_coins;
uint64_t bi_weight; // a size_t really but we need 32-bit compat
uint64_t bi_diff_lo;
uint64_t bi_diff_hi;
crypto::hash bi_hash;
uint64_t bi_cum_rct;
uint64_t bi_long_term_block_weight;
} mdb_block_info_4;
typedef mdb_block_info_4 mdb_block_info;
typedef struct blk_height {
crypto::hash bh_hash;
uint64_t bh_height;
} blk_height;
typedef struct pre_rct_outkey {
uint64_t amount_index;
uint64_t output_id;
pre_rct_output_data_t data;
} pre_rct_outkey;
typedef struct outkey {
uint64_t amount_index;
uint64_t output_id;
output_data_t data;
} outkey;
typedef struct outtx {
uint64_t output_id;
crypto::hash tx_hash;
uint64_t local_index;
} outtx;
std::atomic<uint64_t> mdb_txn_safe::num_active_txns{0};
std::atomic_flag mdb_txn_safe::creation_gate = ATOMIC_FLAG_INIT;
mdb_threadinfo::~mdb_threadinfo()
{
MDB_cursor **cur = &m_ti_rcursors.m_txc_blocks;
unsigned i;
for (i=0; i<sizeof(mdb_txn_cursors)/sizeof(MDB_cursor *); i++)
if (cur[i])
mdb_cursor_close(cur[i]);
if (m_ti_rtxn)
mdb_txn_abort(m_ti_rtxn);
}
mdb_txn_safe::mdb_txn_safe(const bool check) : m_txn(NULL), m_tinfo(NULL), m_check(check)
{
if (check)
{
while (creation_gate.test_and_set());
num_active_txns++;
creation_gate.clear();
}
}
mdb_txn_safe::~mdb_txn_safe()
{
if (!m_check)
return;
LOG_PRINT_L3("mdb_txn_safe: destructor");
if (m_tinfo != nullptr)
{
mdb_txn_reset(m_tinfo->m_ti_rtxn);
memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
} else if (m_txn != nullptr)
{
if (m_batch_txn) // this is a batch txn and should have been handled before this point for safety
{
LOG_PRINT_L0("WARNING: mdb_txn_safe: m_txn is a batch txn and it's not NULL in destructor - calling mdb_txn_abort()");
}
else
{
// Example of when this occurs: a lookup fails, so a read-only txn is
// aborted through this destructor. However, successful read-only txns
// ideally should have been committed when done and not end up here.
//
// NOTE: not sure if this is ever reached for a non-batch write
// transaction, but it's probably not ideal if it did.
LOG_PRINT_L3("mdb_txn_safe: m_txn not NULL in destructor - calling mdb_txn_abort()");
}
mdb_txn_abort(m_txn);
}
num_active_txns--;
}
void mdb_txn_safe::uncheck()
{
num_active_txns--;
m_check = false;
}
void mdb_txn_safe::commit(std::string message)
{
if (message.size() == 0)
{
message = "Failed to commit a transaction to the db";
}
if (auto result = mdb_txn_commit(m_txn))
{
m_txn = nullptr;
throw0(DB_ERROR(lmdb_error(message + ": ", result).c_str()));
}
m_txn = nullptr;
}
void mdb_txn_safe::abort()
{
LOG_PRINT_L3("mdb_txn_safe: abort()");
if(m_txn != nullptr)
{
mdb_txn_abort(m_txn);
m_txn = nullptr;
}
else
{
LOG_PRINT_L0("WARNING: mdb_txn_safe: abort() called, but m_txn is NULL");
}
}
uint64_t mdb_txn_safe::num_active_tx() const
{
return num_active_txns;
}
void mdb_txn_safe::prevent_new_txns()
{
while (creation_gate.test_and_set());
}
void mdb_txn_safe::wait_no_active_txns()
{
while (num_active_txns > 0);
}
void mdb_txn_safe::allow_new_txns()
{
creation_gate.clear();
}
void lmdb_resized(MDB_env *env)
{
mdb_txn_safe::prevent_new_txns();
MGINFO("LMDB map resize detected.");
MDB_envinfo mei;
mdb_env_info(env, &mei);
uint64_t old = mei.me_mapsize;
mdb_txn_safe::wait_no_active_txns();
int result = mdb_env_set_mapsize(env, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to set new mapsize: ", result).c_str()));
mdb_env_info(env, &mei);
uint64_t new_mapsize = mei.me_mapsize;
MGINFO("LMDB Mapsize increased." << " Old: " << old / (1024 * 1024) << "MiB" << ", New: " << new_mapsize / (1024 * 1024) << "MiB");
mdb_txn_safe::allow_new_txns();
}
inline int lmdb_txn_begin(MDB_env *env, MDB_txn *parent, unsigned int flags, MDB_txn **txn)
{
int res = mdb_txn_begin(env, parent, flags, txn);
if (res == MDB_MAP_RESIZED) {
lmdb_resized(env);
res = mdb_txn_begin(env, parent, flags, txn);
}
return res;
}
inline int lmdb_txn_renew(MDB_txn *txn)
{
int res = mdb_txn_renew(txn);
if (res == MDB_MAP_RESIZED) {
lmdb_resized(mdb_txn_env(txn));
res = mdb_txn_renew(txn);
}
return res;
}
inline void BlockchainLMDB::check_open() const
{
if (!m_open)
throw0(DB_ERROR("DB operation attempted on a not-open DB instance"));
}
void BlockchainLMDB::do_resize(uint64_t increase_size)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
CRITICAL_REGION_LOCAL(m_synchronization_lock);
const uint64_t add_size = 1LL << 30;
// check disk capacity
try
{
boost::filesystem::path path(m_folder);
boost::filesystem::space_info si = boost::filesystem::space(path);
if(si.available < add_size)
{
MERROR("!! WARNING: Insufficient free space to extend database !!: " <<
(si.available >> 20L) << " MB available, " << (add_size >> 20L) << " MB needed");
return;
}
}
catch(...)
{
// print something but proceed.
MWARNING("Unable to query free disk space.");
}
MDB_envinfo mei;
mdb_env_info(m_env, &mei);
MDB_stat mst;
mdb_env_stat(m_env, &mst);
// add 1Gb per resize, instead of doing a percentage increase
uint64_t new_mapsize = (uint64_t) mei.me_mapsize + add_size;
// If given, use increase_size instead of above way of resizing.
// This is currently used for increasing by an estimated size at start of new
// batch txn.
if (increase_size > 0)
new_mapsize = mei.me_mapsize + increase_size;
new_mapsize += (new_mapsize % mst.ms_psize);
mdb_txn_safe::prevent_new_txns();
if (m_write_txn != nullptr)
{
if (m_batch_active)
{
throw0(DB_ERROR("lmdb resizing not yet supported when batch transactions enabled!"));
}
else
{
throw0(DB_ERROR("attempting resize with write transaction in progress, this should not happen!"));
}
}
mdb_txn_safe::wait_no_active_txns();
int result = mdb_env_set_mapsize(m_env, new_mapsize);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to set new mapsize: ", result).c_str()));
boost::filesystem::path path(m_folder);
boost::filesystem::space_info si = boost::filesystem::space(path);
std::optional<uint64_t> space_available = si.available;
if (space_available)
{
if ((*space_available / (1024 * 1024)) < 4294)
MGINFO_RED("Warning you are running low on disk space!\n" << "LMDB Mapsize increased." << " Old: " << mei.me_mapsize / (1024 * 1024) << "MiB" << ", New: " << new_mapsize / (1024 * 1024) << "MiB" << ", Available disk remaining: " << *space_available / (1024 * 1024) << "MiB" );
else if ((*space_available / (1024 * 1024)) >= 4294)
MGINFO("LMDB Mapsize increased." << " Old: " << mei.me_mapsize / (1024 * 1024) << "MiB" << ", New: " << new_mapsize / (1024 * 1024) << "MiB" << ", Available disk remaining: " << *space_available / (1024 * 1024) << "MiB" );
}
else
{
MGINFO("LMDB Mapsize increased." << " Old: " << mei.me_mapsize / (1024 * 1024) << "MiB" << ", New: " << new_mapsize / (1024 * 1024) << "MiB");
}
mdb_txn_safe::allow_new_txns();
}
// threshold_size is used for batch transactions
bool BlockchainLMDB::need_resize(uint64_t threshold_size) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
#if defined(ENABLE_AUTO_RESIZE)
MDB_envinfo mei;
mdb_env_info(m_env, &mei);
MDB_stat mst;
mdb_env_stat(m_env, &mst);
// size_used doesn't include data yet to be committed, which can be
// significant size during batch transactions. For that, we estimate the size
// needed at the beginning of the batch transaction and pass in the
// additional size needed.
uint64_t size_used = mst.ms_psize * mei.me_last_pgno;
MDEBUG("DB map size: " << mei.me_mapsize);
MDEBUG("Space used: " << size_used);
MDEBUG("Space remaining: " << mei.me_mapsize - size_used);
MDEBUG("Size threshold: " << threshold_size);
float resize_percent = RESIZE_PERCENT;
MDEBUG(boost::format("Percent used: %.04f Percent threshold: %.04f") % (100.*size_used/mei.me_mapsize) % (100.*resize_percent));
if (threshold_size > 0)
{
if (mei.me_mapsize - size_used < threshold_size)
{
MINFO("Threshold met (size-based)");
return true;
}
else
return false;
}
if ((double)size_used / mei.me_mapsize > resize_percent)
{
MINFO("Threshold met (percent-based)");
return true;
}
return false;
#else
return false;
#endif
}
void BlockchainLMDB::check_and_resize_for_batch(uint64_t batch_num_blocks, uint64_t batch_bytes)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
MTRACE("[" << __func__ << "] " << "checking DB size");
const uint64_t min_increase_size = 512 * (1 << 20);
uint64_t threshold_size = 0;
uint64_t increase_size = 0;
if (batch_num_blocks > 0)
{
threshold_size = get_estimated_batch_size(batch_num_blocks, batch_bytes);
MDEBUG("calculated batch size: " << threshold_size);
// The increased DB size could be a multiple of threshold_size, a fixed
// size increase (> threshold_size), or other variations.
//
// Currently we use the greater of threshold size and a minimum size. The
// minimum size increase is used to avoid frequent resizes when the batch
// size is set to a very small numbers of blocks.
increase_size = (threshold_size > min_increase_size) ? threshold_size : min_increase_size;
MDEBUG("increase size: " << increase_size);
}
// if threshold_size is 0 (i.e. number of blocks for batch not passed in), it
// will fall back to the percent-based threshold check instead of the
// size-based check
if (need_resize(threshold_size))
{
MGINFO("[batch] DB resize needed");
do_resize(increase_size);
}
}
uint64_t BlockchainLMDB::get_estimated_batch_size(uint64_t batch_num_blocks, uint64_t batch_bytes) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
uint64_t threshold_size = 0;
// batch size estimate * batch safety factor = final size estimate
// Takes into account "reasonable" block size increases in batch.
float batch_safety_factor = 1.7f;
float batch_fudge_factor = batch_safety_factor * batch_num_blocks;
// estimate of stored block expanded from raw block, including denormalization and db overhead.
// Note that this probably doesn't grow linearly with block size.
float db_expand_factor = 4.5f;
uint64_t num_prev_blocks = 500;
// For resizing purposes, allow for at least 4k average block size.
uint64_t min_block_size = 4 * 1024;
uint64_t block_stop = 0;
uint64_t m_height = height();
if (m_height > 1)
block_stop = m_height - 1;
uint64_t block_start = 0;
if (block_stop >= num_prev_blocks)
block_start = block_stop - num_prev_blocks + 1;
uint32_t num_blocks_used = 0;
uint64_t total_block_size = 0;
MDEBUG("[" << __func__ << "] " << "m_height: " << m_height << " block_start: " << block_start << " block_stop: " << block_stop);
size_t avg_block_size = 0;
if (batch_bytes)
{
avg_block_size = batch_bytes / batch_num_blocks;
goto estim;
}
if (m_height == 0)
{
MDEBUG("No existing blocks to check for average block size");
}
else if (m_cum_count >= num_prev_blocks)
{
avg_block_size = m_cum_size / m_cum_count;
MDEBUG("average block size across recent " << m_cum_count << " blocks: " << avg_block_size);
m_cum_size = 0;
m_cum_count = 0;
}
else
{
MDB_txn *rtxn;
mdb_txn_cursors *rcurs;
bool my_rtxn = block_rtxn_start(&rtxn, &rcurs);
for (uint64_t block_num = block_start; block_num <= block_stop; ++block_num)
{
// we have access to block weight, which will be greater or equal to block size,
// so use this as a proxy. If it's too much off, we might have to check actual size,
// which involves reading more data, so is not really wanted
size_t block_weight = get_block_weight(block_num);
total_block_size += block_weight;
// Track number of blocks being totalled here instead of assuming, in case
// some blocks were to be skipped for being outliers.
++num_blocks_used;
}
if (my_rtxn) block_rtxn_stop();
avg_block_size = total_block_size / (num_blocks_used ? num_blocks_used : 1);
MDEBUG("average block size across recent " << num_blocks_used << " blocks: " << avg_block_size);
}
estim:
if (avg_block_size < min_block_size)
avg_block_size = min_block_size;
MDEBUG("estimated average block size for batch: " << avg_block_size);
// bigger safety margin on smaller block sizes
if (batch_fudge_factor < 5000.0)
batch_fudge_factor = 5000.0;
threshold_size = avg_block_size * db_expand_factor * batch_fudge_factor;
return threshold_size;
}
void BlockchainLMDB::add_block(const block& blk, size_t block_weight, uint64_t long_term_block_weight, const difficulty_type& cumulative_difficulty, const uint64_t& coins_generated,
uint64_t num_rct_outs, const crypto::hash& blk_hash)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
uint64_t m_height = height();
CURSOR(block_heights)
blk_height bh = {blk_hash, m_height};
MDB_val_set(val_h, bh);
if (mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &val_h, MDB_GET_BOTH) == 0)
throw1(BLOCK_EXISTS("Attempting to add block that's already in the db"));
if (m_height > 0)
{
MDB_val_set(parent_key, blk.prev_id);
int result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &parent_key, MDB_GET_BOTH);
if (result)
{
LOG_PRINT_L3("m_height: " << m_height);
LOG_PRINT_L3("parent_key: " << blk.prev_id);
throw0(DB_ERROR(lmdb_error("Failed to get top block hash to check for new block's parent: ", result).c_str()));
}
blk_height *prev = (blk_height *)parent_key.mv_data;
if (prev->bh_height != m_height - 1)
throw0(BLOCK_PARENT_DNE("Top block is not new block's parent"));
}
int result = 0;
MDB_val_set(key, m_height);
CURSOR(blocks)
CURSOR(block_info)
// this call to mdb_cursor_put will change height()
cryptonote::blobdata block_blob(block_to_blob(blk));
MDB_val_sized(blob, block_blob);
result = mdb_cursor_put(m_cur_blocks, &key, &blob, MDB_APPEND);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to add block blob to db transaction: ", result).c_str()));
mdb_block_info bi;
bi.bi_height = m_height;
bi.bi_timestamp = blk.timestamp;
bi.bi_coins = coins_generated;
bi.bi_weight = block_weight;
bi.bi_diff_hi = ((cumulative_difficulty >> 64) & 0xffffffffffffffff).convert_to<uint64_t>();
bi.bi_diff_lo = (cumulative_difficulty & 0xffffffffffffffff).convert_to<uint64_t>();
bi.bi_hash = blk_hash;
bi.bi_cum_rct = num_rct_outs;
if (blk.major_version >= 4)
{
uint64_t last_height = m_height-1;
MDB_val_set(h, last_height);
if ((result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &h, MDB_GET_BOTH)))
throw1(BLOCK_DNE(lmdb_error("Failed to get block info: ", result).c_str()));
const mdb_block_info *bi_prev = (const mdb_block_info*)h.mv_data;
bi.bi_cum_rct += bi_prev->bi_cum_rct;
}
bi.bi_long_term_block_weight = long_term_block_weight;
MDB_val_set(val, bi);
result = mdb_cursor_put(m_cur_block_info, (MDB_val *)&zerokval, &val, MDB_APPENDDUP);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to add block info to db transaction: ", result).c_str()));
result = mdb_cursor_put(m_cur_block_heights, (MDB_val *)&zerokval, &val_h, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to add block height by hash to db transaction: ", result).c_str()));
// we use weight as a proxy for size, since we don't have size but weight is >= size
// and often actually equal
m_cum_size += block_weight;
m_cum_count++;
}
void BlockchainLMDB::remove_block()
{
int result;
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
uint64_t m_height = height();
if (m_height == 0)
throw0(BLOCK_DNE ("Attempting to remove block from an empty blockchain"));
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(block_info)
CURSOR(block_heights)
CURSOR(blocks)
MDB_val_copy<uint64_t> k(m_height - 1);
MDB_val h = k;
if ((result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &h, MDB_GET_BOTH)))
throw1(BLOCK_DNE(lmdb_error("Attempting to remove block that's not in the db: ", result).c_str()));
// must use h now; deleting from m_block_info will invalidate it
mdb_block_info *bi = (mdb_block_info *)h.mv_data;
blk_height bh = {bi->bi_hash, 0};
h.mv_data = (void *)&bh;
h.mv_size = sizeof(bh);
if ((result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &h, MDB_GET_BOTH)))
throw1(DB_ERROR(lmdb_error("Failed to locate block height by hash for removal: ", result).c_str()));
if ((result = mdb_cursor_del(m_cur_block_heights, 0)))
throw1(DB_ERROR(lmdb_error("Failed to add removal of block height by hash to db transaction: ", result).c_str()));
if ((result = mdb_cursor_del(m_cur_blocks, 0)))
throw1(DB_ERROR(lmdb_error("Failed to add removal of block to db transaction: ", result).c_str()));
if ((result = mdb_cursor_del(m_cur_block_info, 0)))
throw1(DB_ERROR(lmdb_error("Failed to add removal of block info to db transaction: ", result).c_str()));
}
uint64_t BlockchainLMDB::add_transaction_data(const crypto::hash& blk_hash, const std::pair<transaction, blobdata_ref>& txp, const crypto::hash& tx_hash, const crypto::hash& tx_prunable_hash)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
uint64_t m_height = height();
int result;
uint64_t tx_id = get_tx_count();
CURSOR(txs_pruned)
CURSOR(txs_prunable)
CURSOR(txs_prunable_hash)
CURSOR(txs_prunable_tip)
CURSOR(tx_indices)
MDB_val_set(val_tx_id, tx_id);
MDB_val_set(val_h, tx_hash);
result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &val_h, MDB_GET_BOTH);
if (result == 0) {
txindex *tip = (txindex *)val_h.mv_data;
throw1(TX_EXISTS(std::string("Attempting to add transaction that's already in the db (tx id ").append(boost::lexical_cast<std::string>(tip->data.tx_id)).append(")").c_str()));
} else if (result != MDB_NOTFOUND) {
throw1(DB_ERROR(lmdb_error(std::string("Error checking if tx index exists for tx hash ") + epee::string_tools::pod_to_hex(tx_hash) + ": ", result).c_str()));
}
const cryptonote::transaction &tx = txp.first;
txindex ti;
ti.key = tx_hash;
ti.data.tx_id = tx_id;
ti.data.unlock_time = tx.unlock_time;
ti.data.block_id = m_height; // we don't need blk_hash since we know m_height
val_h.mv_size = sizeof(ti);
val_h.mv_data = (void *)&ti;
result = mdb_cursor_put(m_cur_tx_indices, (MDB_val *)&zerokval, &val_h, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to add tx data to db transaction: ", result).c_str()));
const cryptonote::blobdata_ref &blob = txp.second;
MDB_val_sized(blobval, blob);
unsigned int unprunable_size = tx.unprunable_size;
if (unprunable_size == 0)
{
std::stringstream ss;
binary_archive<true> ba(ss);
bool r = const_cast<cryptonote::transaction&>(tx).serialize_base(ba);
if (!r)
throw0(DB_ERROR("Failed to serialize pruned tx"));
unprunable_size = ss.str().size();
}
if (unprunable_size > blob.size())
throw0(DB_ERROR("pruned tx size is larger than tx size"));
MDB_val pruned_blob = {unprunable_size, (void*)blob.data()};
result = mdb_cursor_put(m_cur_txs_pruned, &val_tx_id, &pruned_blob, MDB_APPEND);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to add pruned tx blob to db transaction: ", result).c_str()));
MDB_val prunable_blob = {blob.size() - unprunable_size, (void*)(blob.data() + unprunable_size)};
result = mdb_cursor_put(m_cur_txs_prunable, &val_tx_id, &prunable_blob, MDB_APPEND);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to add prunable tx blob to db transaction: ", result).c_str()));
if (get_blockchain_pruning_seed())
{
MDB_val_set(val_height, m_height);
result = mdb_cursor_put(m_cur_txs_prunable_tip, &val_tx_id, &val_height, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to add prunable tx id to db transaction: ", result).c_str()));
}
if (tx.version > 1)
{
MDB_val_set(val_prunable_hash, tx_prunable_hash);
result = mdb_cursor_put(m_cur_txs_prunable_hash, &val_tx_id, &val_prunable_hash, MDB_APPEND);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to add prunable tx prunable hash to db transaction: ", result).c_str()));
}
return tx_id;
}
// TODO: compare pros and cons of looking up the tx hash's tx index once and
// passing it in to functions like this
void BlockchainLMDB::remove_transaction_data(const crypto::hash& tx_hash, const transaction& tx)
{
int result;
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(tx_indices)
CURSOR(txs_pruned)
CURSOR(txs_prunable)
CURSOR(txs_prunable_hash)
CURSOR(txs_prunable_tip)
CURSOR(tx_outputs)
MDB_val_set(val_h, tx_hash);
if (mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &val_h, MDB_GET_BOTH))
throw1(TX_DNE("Attempting to remove transaction that isn't in the db"));
txindex *tip = (txindex *)val_h.mv_data;
MDB_val_set(val_tx_id, tip->data.tx_id);
if ((result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, NULL, MDB_SET)))
throw1(DB_ERROR(lmdb_error("Failed to locate pruned tx for removal: ", result).c_str()));
result = mdb_cursor_del(m_cur_txs_pruned, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Failed to add removal of pruned tx to db transaction: ", result).c_str()));
result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, NULL, MDB_SET);
if (result == 0)
{
result = mdb_cursor_del(m_cur_txs_prunable, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Failed to add removal of prunable tx to db transaction: ", result).c_str()));
}
else if (result != MDB_NOTFOUND)
throw1(DB_ERROR(lmdb_error("Failed to locate prunable tx for removal: ", result).c_str()));
result = mdb_cursor_get(m_cur_txs_prunable_tip, &val_tx_id, NULL, MDB_SET);
if (result && result != MDB_NOTFOUND)
throw1(DB_ERROR(lmdb_error("Failed to locate tx id for removal: ", result).c_str()));
if (result == 0)
{
result = mdb_cursor_del(m_cur_txs_prunable_tip, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Error adding removal of tx id to db transaction", result).c_str()));
}
if (tx.version > 1)
{
if ((result = mdb_cursor_get(m_cur_txs_prunable_hash, &val_tx_id, NULL, MDB_SET)))
throw1(DB_ERROR(lmdb_error("Failed to locate prunable hash tx for removal: ", result).c_str()));
result = mdb_cursor_del(m_cur_txs_prunable_hash, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Failed to add removal of prunable hash tx to db transaction: ", result).c_str()));
}
remove_tx_outputs(tip->data.tx_id, tx);
result = mdb_cursor_get(m_cur_tx_outputs, &val_tx_id, NULL, MDB_SET);
if (result == MDB_NOTFOUND)
LOG_PRINT_L1("tx has no outputs to remove: " << tx_hash);
else if (result)
throw1(DB_ERROR(lmdb_error("Failed to locate tx outputs for removal: ", result).c_str()));
if (!result)
{
result = mdb_cursor_del(m_cur_tx_outputs, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Failed to add removal of tx outputs to db transaction: ", result).c_str()));
}
// Don't delete the tx_indices entry until the end, after we're done with val_tx_id
if (mdb_cursor_del(m_cur_tx_indices, 0))
throw1(DB_ERROR("Failed to add removal of tx index to db transaction"));
}
uint64_t BlockchainLMDB::add_output(const crypto::hash& tx_hash,
const tx_out& tx_output,
const uint64_t& local_index,
const uint64_t unlock_time,
const rct::key *commitment)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
uint64_t m_height = height();
uint64_t m_num_outputs = num_outputs();
int result = 0;
CURSOR(output_txs)
CURSOR(output_amounts)
if (tx_output.target.type() != typeid(txout_to_key))
throw0(DB_ERROR("Wrong output type: expected txout_to_key"));
if (tx_output.amount == 0 && !commitment)
throw0(DB_ERROR("RCT output without commitment"));
outtx ot = {m_num_outputs, tx_hash, local_index};
MDB_val_set(vot, ot);
result = mdb_cursor_put(m_cur_output_txs, (MDB_val *)&zerokval, &vot, MDB_APPENDDUP);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to add output tx hash to db transaction: ", result).c_str()));
outkey ok;
MDB_val data;
MDB_val_copy<uint64_t> val_amount(tx_output.amount);
result = mdb_cursor_get(m_cur_output_amounts, &val_amount, &data, MDB_SET);
if (!result)
{
mdb_size_t num_elems = 0;
result = mdb_cursor_count(m_cur_output_amounts, &num_elems);
if (result)
throw0(DB_ERROR(std::string("Failed to get number of outputs for amount: ").append(mdb_strerror(result)).c_str()));
ok.amount_index = num_elems;
}
else if (result != MDB_NOTFOUND)
throw0(DB_ERROR(lmdb_error("Failed to get output amount in db transaction: ", result).c_str()));
else
ok.amount_index = 0;
ok.output_id = m_num_outputs;
ok.data.pubkey = boost::get < txout_to_key > (tx_output.target).key;
ok.data.unlock_time = unlock_time;
ok.data.height = m_height;
if (tx_output.amount == 0)
{
ok.data.commitment = *commitment;
data.mv_size = sizeof(ok);
}
else
{
data.mv_size = sizeof(pre_rct_outkey);
}
data.mv_data = &ok;
if ((result = mdb_cursor_put(m_cur_output_amounts, &val_amount, &data, MDB_APPENDDUP)))
throw0(DB_ERROR(lmdb_error("Failed to add output pubkey to db transaction: ", result).c_str()));
return ok.amount_index;
}
void BlockchainLMDB::add_tx_amount_output_indices(const uint64_t tx_id,
const std::vector<uint64_t>& amount_output_indices)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(tx_outputs)
int result = 0;
size_t num_outputs = amount_output_indices.size();
MDB_val_set(k_tx_id, tx_id);
MDB_val v;
v.mv_data = num_outputs ? (void *)amount_output_indices.data() : (void*)"";
v.mv_size = sizeof(uint64_t) * num_outputs;
// LOG_PRINT_L1("tx_outputs[tx_hash] size: " << v.mv_size);
result = mdb_cursor_put(m_cur_tx_outputs, &k_tx_id, &v, MDB_APPEND);
if (result)
throw0(DB_ERROR(std::string("Failed to add <tx hash, amount output index array> to db transaction: ").append(mdb_strerror(result)).c_str()));
}
void BlockchainLMDB::remove_tx_outputs(const uint64_t tx_id, const transaction& tx)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
std::vector<std::vector<uint64_t>> amount_output_indices_set = get_tx_amount_output_indices(tx_id, 1);
const std::vector<uint64_t> &amount_output_indices = amount_output_indices_set.front();
if (amount_output_indices.empty())
{
if (tx.vout.empty())
LOG_PRINT_L2("tx has no outputs, so no output indices");
else
throw0(DB_ERROR("tx has outputs, but no output indices found"));
}
bool is_pseudo_rct = tx.version >= 2 && tx.vin.size() == 1 && tx.vin[0].type() == typeid(txin_gen);
for (size_t i = tx.vout.size(); i-- > 0;)
{
uint64_t amount = is_pseudo_rct ? 0 : tx.vout[i].amount;
remove_output(amount, amount_output_indices[i]);
}
}
void BlockchainLMDB::remove_output(const uint64_t amount, const uint64_t& out_index)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(output_amounts);
CURSOR(output_txs);
MDB_val_set(k, amount);
MDB_val_set(v, out_index);
auto result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_GET_BOTH);
if (result == MDB_NOTFOUND)
throw1(OUTPUT_DNE("Attempting to get an output index by amount and amount index, but amount not found"));
else if (result)
throw0(DB_ERROR(lmdb_error("DB error attempting to get an output", result).c_str()));
const pre_rct_outkey *ok = (const pre_rct_outkey *)v.mv_data;
MDB_val_set(otxk, ok->output_id);
result = mdb_cursor_get(m_cur_output_txs, (MDB_val *)&zerokval, &otxk, MDB_GET_BOTH);
if (result == MDB_NOTFOUND)
{
throw0(DB_ERROR("Unexpected: global output index not found in m_output_txs"));
}
else if (result)
{
throw1(DB_ERROR(lmdb_error("Error adding removal of output tx to db transaction", result).c_str()));
}
result = mdb_cursor_del(m_cur_output_txs, 0);
if (result)
throw0(DB_ERROR(lmdb_error(std::string("Error deleting output index ").append(boost::lexical_cast<std::string>(out_index).append(": ")).c_str(), result).c_str()));
// now delete the amount
result = mdb_cursor_del(m_cur_output_amounts, 0);
if (result)
throw0(DB_ERROR(lmdb_error(std::string("Error deleting amount for output index ").append(boost::lexical_cast<std::string>(out_index).append(": ")).c_str(), result).c_str()));
}
void BlockchainLMDB::prune_outputs(uint64_t amount)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(output_amounts);
CURSOR(output_txs);
MINFO("Pruning outputs for amount " << amount);
MDB_val v;
MDB_val_set(k, amount);
int result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_SET);
if (result == MDB_NOTFOUND)
return;
if (result)
throw0(DB_ERROR(lmdb_error("Error looking up outputs: ", result).c_str()));
// gather output ids
mdb_size_t num_elems;
mdb_cursor_count(m_cur_output_amounts, &num_elems);
MINFO(num_elems << " outputs found");
std::vector<uint64_t> output_ids;
output_ids.reserve(num_elems);
while (1)
{
const pre_rct_outkey *okp = (const pre_rct_outkey *)v.mv_data;
output_ids.push_back(okp->output_id);
MDEBUG("output id " << okp->output_id);
result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_NEXT_DUP);
if (result == MDB_NOTFOUND)
break;
if (result)
throw0(DB_ERROR(lmdb_error("Error counting outputs: ", result).c_str()));
}
if (output_ids.size() != num_elems)
throw0(DB_ERROR("Unexpected number of outputs"));
result = mdb_cursor_del(m_cur_output_amounts, MDB_NODUPDATA);
if (result)
throw0(DB_ERROR(lmdb_error("Error deleting outputs: ", result).c_str()));
for (uint64_t output_id: output_ids)
{
MDB_val_set(v, output_id);
result = mdb_cursor_get(m_cur_output_txs, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (result)
throw0(DB_ERROR(lmdb_error("Error looking up output: ", result).c_str()));
result = mdb_cursor_del(m_cur_output_txs, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Error deleting output: ", result).c_str()));
}
}
void BlockchainLMDB::add_spent_key(const crypto::key_image& k_image)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(spent_keys)
MDB_val k = {sizeof(k_image), (void *)&k_image};
if (auto result = mdb_cursor_put(m_cur_spent_keys, (MDB_val *)&zerokval, &k, MDB_NODUPDATA)) {
if (result == MDB_KEYEXIST)
throw1(KEY_IMAGE_EXISTS("Attempting to add spent key image that's already in the db"));
else
throw1(DB_ERROR(lmdb_error("Error adding spent key image to db transaction: ", result).c_str()));
}
}
void BlockchainLMDB::remove_spent_key(const crypto::key_image& k_image)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(spent_keys)
MDB_val k = {sizeof(k_image), (void *)&k_image};
auto result = mdb_cursor_get(m_cur_spent_keys, (MDB_val *)&zerokval, &k, MDB_GET_BOTH);
if (result != 0 && result != MDB_NOTFOUND)
throw1(DB_ERROR(lmdb_error("Error finding spent key to remove", result).c_str()));
if (!result)
{
result = mdb_cursor_del(m_cur_spent_keys, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Error adding removal of key image to db transaction", result).c_str()));
}
}
BlockchainLMDB::~BlockchainLMDB()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
// batch transaction shouldn't be active at this point. If it is, consider it aborted.
if (m_batch_active)
{
try { batch_abort(); }
catch (...) { /* ignore */ }
}
if (m_open)
close();
}
BlockchainLMDB::BlockchainLMDB(bool batch_transactions): BlockchainDB()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
// initialize folder to something "safe" just in case
// someone accidentally misuses this class...
m_folder = "thishsouldnotexistbecauseitisgibberish";
m_batch_transactions = batch_transactions;
m_write_txn = nullptr;
m_write_batch_txn = nullptr;
m_batch_active = false;
m_cum_size = 0;
m_cum_count = 0;
// reset may also need changing when initialize things here
m_hardfork = nullptr;
}
void BlockchainLMDB::check_mmap_support()
{
#ifndef _WIN32
const boost::filesystem::path mmap_test_file = m_folder / boost::filesystem::unique_path();
int mmap_test_fd = ::open(mmap_test_file.string().c_str(), O_RDWR | O_CREAT, 0600);
if (mmap_test_fd < 0)
throw0(DB_ERROR((std::string("Failed to check for mmap support: open failed: ") + strerror(errno)).c_str()));
epee::misc_utils::auto_scope_leave_caller scope_exit_handler = epee::misc_utils::create_scope_leave_handler([mmap_test_fd, &mmap_test_file]() {
::close(mmap_test_fd);
boost::filesystem::remove(mmap_test_file.string());
});
if (write(mmap_test_fd, "mmaptest", 8) != 8)
throw0(DB_ERROR((std::string("Failed to check for mmap support: write failed: ") + strerror(errno)).c_str()));
void *mmap_res = mmap(NULL, 8, PROT_READ, MAP_SHARED, mmap_test_fd, 0);
if (mmap_res == MAP_FAILED)
throw0(DB_ERROR("This filesystem does not support mmap: use --data-dir to place the blockchain on a filesystem which does"));
munmap(mmap_res, 8);
#endif
}
void BlockchainLMDB::open(const std::string& filename, const int db_flags)
{
int result;
int mdb_flags = MDB_NORDAHEAD;
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
if (m_open)
throw0(DB_OPEN_FAILURE("Attempted to open db, but it's already open"));
boost::filesystem::path direc(filename);
if (boost::filesystem::exists(direc))
{
if (!boost::filesystem::is_directory(direc))
throw0(DB_OPEN_FAILURE("LMDB needs a directory path, but a file was passed"));
}
else
{
if (!boost::filesystem::create_directories(direc))
throw0(DB_OPEN_FAILURE(std::string("Failed to create directory ").append(filename).c_str()));
}
// check for existing LMDB files in base directory
boost::filesystem::path old_files = direc.parent_path();
if (boost::filesystem::exists(old_files / CRYPTONOTE_BLOCKCHAINDATA_FILENAME)
|| boost::filesystem::exists(old_files / CRYPTONOTE_BLOCKCHAINDATA_LOCK_FILENAME))
{
LOG_PRINT_L0("Found existing LMDB files in " << old_files.string());
LOG_PRINT_L0("Move " << CRYPTONOTE_BLOCKCHAINDATA_FILENAME << " and/or " << CRYPTONOTE_BLOCKCHAINDATA_LOCK_FILENAME << " to " << filename << ", or delete them, and then restart");
throw DB_ERROR("Database could not be opened");
}
std::optional<bool> is_hdd_result = tools::is_hdd(filename.c_str());
if (is_hdd_result)
{
if (is_hdd_result.value())
MCLOG_RED(el::Level::Warning, "global", "The blockchain is on a rotating drive: this will be very slow, use an SSD if possible");
}
m_folder = filename;
check_mmap_support();
#ifdef __OpenBSD__
if ((mdb_flags & MDB_WRITEMAP) == 0) {
MCLOG_RED(el::Level::Info, "global", "Running on OpenBSD: forcing WRITEMAP");
mdb_flags |= MDB_WRITEMAP;
}
#endif
// set up lmdb environment
if ((result = mdb_env_create(&m_env)))
throw0(DB_ERROR(lmdb_error("Failed to create lmdb environment: ", result).c_str()));
if ((result = mdb_env_set_maxdbs(m_env, 32)))
throw0(DB_ERROR(lmdb_error("Failed to set max number of dbs: ", result).c_str()));
int threads = tools::get_max_concurrency();
if (threads > 110 && /* maxreaders default is 126, leave some slots for other read processes */
(result = mdb_env_set_maxreaders(m_env, threads+16)))
throw0(DB_ERROR(lmdb_error("Failed to set max number of readers: ", result).c_str()));
size_t mapsize = DEFAULT_MAPSIZE;
if (db_flags & DBF_FAST)
mdb_flags |= MDB_NOSYNC;
if (db_flags & DBF_FASTEST)
mdb_flags |= MDB_NOSYNC | MDB_WRITEMAP | MDB_MAPASYNC;
if (db_flags & DBF_RDONLY)
mdb_flags = MDB_RDONLY;
if (db_flags & DBF_SALVAGE)
mdb_flags |= MDB_PREVSNAPSHOT;
if (auto result = mdb_env_open(m_env, filename.c_str(), mdb_flags, 0644))
throw0(DB_ERROR(lmdb_error("Failed to open lmdb environment: ", result).c_str()));
MDB_envinfo mei;
mdb_env_info(m_env, &mei);
uint64_t cur_mapsize = (uint64_t)mei.me_mapsize;
if (cur_mapsize < mapsize)
{
if (auto result = mdb_env_set_mapsize(m_env, mapsize))
throw0(DB_ERROR(lmdb_error("Failed to set max memory map size: ", result).c_str()));
mdb_env_info(m_env, &mei);
cur_mapsize = (uint64_t)mei.me_mapsize;
LOG_PRINT_L1("LMDB memory map size: " << cur_mapsize);
}
if (need_resize())
{
LOG_PRINT_L0("LMDB memory map needs to be resized, doing that now.");
do_resize();
}
int txn_flags = 0;
if (mdb_flags & MDB_RDONLY)
txn_flags |= MDB_RDONLY;
// get a read/write MDB_txn, depending on mdb_flags
mdb_txn_safe txn;
if (auto mdb_res = mdb_txn_begin(m_env, NULL, txn_flags, txn))
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", mdb_res).c_str()));
// open necessary databases, and set properties as needed
// uses macros to avoid having to change things too many places
// also change blockchain_prune.cpp to match
lmdb_db_open(txn, LMDB_BLOCKS, MDB_INTEGERKEY | MDB_CREATE, m_blocks, "Failed to open db handle for m_blocks");
lmdb_db_open(txn, LMDB_BLOCK_INFO, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for m_block_info");
lmdb_db_open(txn, LMDB_BLOCK_HEIGHTS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_heights, "Failed to open db handle for m_block_heights");
lmdb_db_open(txn, LMDB_TXS, MDB_INTEGERKEY | MDB_CREATE, m_txs, "Failed to open db handle for m_txs");
lmdb_db_open(txn, LMDB_TXS_PRUNED, MDB_INTEGERKEY | MDB_CREATE, m_txs_pruned, "Failed to open db handle for m_txs_pruned");
lmdb_db_open(txn, LMDB_TXS_PRUNABLE, MDB_INTEGERKEY | MDB_CREATE, m_txs_prunable, "Failed to open db handle for m_txs_prunable");
lmdb_db_open(txn, LMDB_TXS_PRUNABLE_HASH, MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED | MDB_CREATE, m_txs_prunable_hash, "Failed to open db handle for m_txs_prunable_hash");
if (!(mdb_flags & MDB_RDONLY))
lmdb_db_open(txn, LMDB_TXS_PRUNABLE_TIP, MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED | MDB_CREATE, m_txs_prunable_tip, "Failed to open db handle for m_txs_prunable_tip");
lmdb_db_open(txn, LMDB_TX_INDICES, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_tx_indices, "Failed to open db handle for m_tx_indices");
lmdb_db_open(txn, LMDB_TX_OUTPUTS, MDB_INTEGERKEY | MDB_CREATE, m_tx_outputs, "Failed to open db handle for m_tx_outputs");
lmdb_db_open(txn, LMDB_OUTPUT_TXS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_output_txs, "Failed to open db handle for m_output_txs");
lmdb_db_open(txn, LMDB_OUTPUT_AMOUNTS, MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED | MDB_CREATE, m_output_amounts, "Failed to open db handle for m_output_amounts");
lmdb_db_open(txn, LMDB_SPENT_KEYS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_spent_keys, "Failed to open db handle for m_spent_keys");
lmdb_db_open(txn, LMDB_TXPOOL_META, MDB_CREATE, m_txpool_meta, "Failed to open db handle for m_txpool_meta");
lmdb_db_open(txn, LMDB_TXPOOL_BLOB, MDB_CREATE, m_txpool_blob, "Failed to open db handle for m_txpool_blob");
lmdb_db_open(txn, LMDB_ALT_BLOCKS, MDB_CREATE, m_alt_blocks, "Failed to open db handle for m_alt_blocks");
// this subdb is dropped on sight, so it may not be present when we open the DB.
// Since we use MDB_CREATE, we'll get an exception if we open read-only and it does not exist.
// So we don't open for read-only, and also not drop below. It is not used elsewhere.
if (!(mdb_flags & MDB_RDONLY))
lmdb_db_open(txn, LMDB_HF_STARTING_HEIGHTS, MDB_CREATE, m_hf_starting_heights, "Failed to open db handle for m_hf_starting_heights");
lmdb_db_open(txn, LMDB_HF_VERSIONS, MDB_INTEGERKEY | MDB_CREATE, m_hf_versions, "Failed to open db handle for m_hf_versions");
lmdb_db_open(txn, LMDB_PROPERTIES, MDB_CREATE, m_properties, "Failed to open db handle for m_properties");
mdb_set_dupsort(txn, m_spent_keys, compare_hash32);
mdb_set_dupsort(txn, m_block_heights, compare_hash32);
mdb_set_dupsort(txn, m_tx_indices, compare_hash32);
mdb_set_dupsort(txn, m_output_amounts, compare_uint64);
mdb_set_dupsort(txn, m_output_txs, compare_uint64);
mdb_set_dupsort(txn, m_block_info, compare_uint64);
if (!(mdb_flags & MDB_RDONLY))
mdb_set_dupsort(txn, m_txs_prunable_tip, compare_uint64);
mdb_set_compare(txn, m_txs_prunable, compare_uint64);
mdb_set_dupsort(txn, m_txs_prunable_hash, compare_uint64);
mdb_set_compare(txn, m_txpool_meta, compare_hash32);
mdb_set_compare(txn, m_txpool_blob, compare_hash32);
mdb_set_compare(txn, m_alt_blocks, compare_hash32);
mdb_set_compare(txn, m_properties, compare_string);
if (!(mdb_flags & MDB_RDONLY))
{
result = mdb_drop(txn, m_hf_starting_heights, 1);
if (result && result != MDB_NOTFOUND)
throw0(DB_ERROR(lmdb_error("Failed to drop m_hf_starting_heights: ", result).c_str()));
}
// get and keep current height
MDB_stat db_stats;
if ((result = mdb_stat(txn, m_blocks, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
LOG_PRINT_L2("Setting m_height to: " << db_stats.ms_entries);
uint64_t m_height = db_stats.ms_entries;
bool compatible = true;
MDB_val_str(k, "version");
MDB_val v;
auto get_result = mdb_get(txn, m_properties, &k, &v);
if(get_result == MDB_SUCCESS)
{
const uint32_t db_version = *(const uint32_t*)v.mv_data;
if (db_version > VERSION)
{
MWARNING("Existing lmdb database was made by a later version (" << db_version << "). We don't know how it will change yet.");
compatible = false;
}
#if VERSION > 0
else if (db_version < VERSION)
{
if (mdb_flags & MDB_RDONLY)
{
txn.abort();
mdb_env_close(m_env);
m_open = false;
MFATAL("Existing lmdb database needs to be converted, which cannot be done on a read-only database.");
MFATAL("Please run sumokoind once to convert the database.");
return;
}
// Note that there was a schema change within version 0 as well.
// See commit e5d2680094ee15889934fe28901e4e133cda56f2 2015/07/10
// We don't handle the old format previous to that commit.
txn.commit();
m_open = true;
migrate(db_version);
return;
}
#endif
}
else
{
// if not found, and the DB is non-empty, this is probably
// an "old" version 0, which we don't handle. If the DB is
// empty it's fine.
if (VERSION > 0 && m_height > 0)
compatible = false;
}
if (!compatible)
{
txn.abort();
mdb_env_close(m_env);
m_open = false;
MFATAL("Existing lmdb database is incompatible with this version.");
MFATAL("Please delete the existing database and resync.");
return;
}
if (!(mdb_flags & MDB_RDONLY))
{
// only write version on an empty DB
if (m_height == 0)
{
MDB_val_str(k, "version");
MDB_val_copy<uint32_t> v(VERSION);
auto put_result = mdb_put(txn, m_properties, &k, &v, 0);
if (put_result != MDB_SUCCESS)
{
txn.abort();
mdb_env_close(m_env);
m_open = false;
MERROR("Failed to write version to database.");
return;
}
}
}
// commit the transaction
txn.commit();
m_open = true;
// from here, init should be finished
}
void BlockchainLMDB::close()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
if (m_batch_active)
{
LOG_PRINT_L3("close() first calling batch_abort() due to active batch transaction");
batch_abort();
}
this->sync();
m_tinfo.reset();
// FIXME: not yet thread safe!!! Use with care.
mdb_env_close(m_env);
m_open = false;
}
void BlockchainLMDB::sync()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
if (is_read_only())
return;
// Does nothing unless LMDB environment was opened with MDB_NOSYNC or in part
// MDB_NOMETASYNC. Force flush to be synchronous.
if (auto result = mdb_env_sync(m_env, true))
{
throw0(DB_ERROR(lmdb_error("Failed to sync database: ", result).c_str()));
}
}
void BlockchainLMDB::safesyncmode(const bool onoff)
{
MINFO("switching safe mode " << (onoff ? "on" : "off"));
mdb_env_set_flags(m_env, MDB_NOSYNC|MDB_MAPASYNC, !onoff);
}
void BlockchainLMDB::reset()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_safe txn;
if (auto result = lmdb_txn_begin(m_env, NULL, 0, txn))
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
if (auto result = mdb_drop(txn, m_blocks, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_blocks: ", result).c_str()));
if (auto result = mdb_drop(txn, m_block_info, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_block_info: ", result).c_str()));
if (auto result = mdb_drop(txn, m_block_heights, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_block_heights: ", result).c_str()));
if (auto result = mdb_drop(txn, m_txs_pruned, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_txs_pruned: ", result).c_str()));
if (auto result = mdb_drop(txn, m_txs_prunable, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_txs_prunable: ", result).c_str()));
if (auto result = mdb_drop(txn, m_txs_prunable_hash, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_txs_prunable_hash: ", result).c_str()));
if (auto result = mdb_drop(txn, m_txs_prunable_tip, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_txs_prunable_tip: ", result).c_str()));
if (auto result = mdb_drop(txn, m_tx_indices, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_tx_indices: ", result).c_str()));
if (auto result = mdb_drop(txn, m_tx_outputs, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_tx_outputs: ", result).c_str()));
if (auto result = mdb_drop(txn, m_output_txs, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_output_txs: ", result).c_str()));
if (auto result = mdb_drop(txn, m_output_amounts, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_output_amounts: ", result).c_str()));
if (auto result = mdb_drop(txn, m_spent_keys, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_spent_keys: ", result).c_str()));
(void)mdb_drop(txn, m_hf_starting_heights, 0); // this one is dropped in new code
if (auto result = mdb_drop(txn, m_hf_versions, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_hf_versions: ", result).c_str()));
if (auto result = mdb_drop(txn, m_properties, 0))
throw0(DB_ERROR(lmdb_error("Failed to drop m_properties: ", result).c_str()));
// init with current version
MDB_val_str(k, "version");
MDB_val_copy<uint32_t> v(VERSION);
if (auto result = mdb_put(txn, m_properties, &k, &v, 0))
throw0(DB_ERROR(lmdb_error("Failed to write version to database: ", result).c_str()));
txn.commit();
m_cum_size = 0;
m_cum_count = 0;
}
std::vector<std::string> BlockchainLMDB::get_filenames() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
std::vector<std::string> filenames;
boost::filesystem::path datafile(m_folder);
datafile /= CRYPTONOTE_BLOCKCHAINDATA_FILENAME;
boost::filesystem::path lockfile(m_folder);
lockfile /= CRYPTONOTE_BLOCKCHAINDATA_LOCK_FILENAME;
filenames.push_back(datafile.string());
filenames.push_back(lockfile.string());
return filenames;
}
bool BlockchainLMDB::remove_data_file(const std::string& folder) const
{
const std::string filename = folder + "/data.mdb";
try
{
boost::filesystem::remove(filename);
}
catch (const std::exception &e)
{
MERROR("Failed to remove " << filename << ": " << e.what());
return false;
}
return true;
}
std::string BlockchainLMDB::get_db_name() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
return std::string("lmdb");
}
// TODO: this?
bool BlockchainLMDB::lock()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
return false;
}
// TODO: this?
void BlockchainLMDB::unlock()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
}
#define TXN_PREFIX(flags); \
mdb_txn_safe auto_txn; \
mdb_txn_safe* txn_ptr = &auto_txn; \
if (m_batch_active) \
txn_ptr = m_write_txn; \
else \
{ \
if (auto mdb_res = lmdb_txn_begin(m_env, NULL, flags, auto_txn)) \
throw0(DB_ERROR(lmdb_error(std::string("Failed to create a transaction for the db in ")+__FUNCTION__+": ", mdb_res).c_str())); \
} \
#define TXN_PREFIX_RDONLY() \
MDB_txn *m_txn; \
mdb_txn_cursors *m_cursors; \
mdb_txn_safe auto_txn; \
bool my_rtxn = block_rtxn_start(&m_txn, &m_cursors); \
if (my_rtxn) auto_txn.m_tinfo = m_tinfo.get(); \
else auto_txn.uncheck()
#define TXN_POSTFIX_RDONLY()
#define TXN_POSTFIX_SUCCESS() \
do { \
if (! m_batch_active) \
auto_txn.commit(); \
} while(0)
// The below two macros are for DB access within block add/remove, whether
// regular batch txn is in use or not. m_write_txn is used as a batch txn, even
// if it's only within block add/remove.
//
// DB access functions that may be called both within block add/remove and
// without should use these. If the function will be called ONLY within block
// add/remove, m_write_txn alone may be used instead of these macros.
#define TXN_BLOCK_PREFIX(flags); \
mdb_txn_safe auto_txn; \
mdb_txn_safe* txn_ptr = &auto_txn; \
if (m_batch_active || m_write_txn) \
txn_ptr = m_write_txn; \
else \
{ \
if (auto mdb_res = lmdb_txn_begin(m_env, NULL, flags, auto_txn)) \
throw0(DB_ERROR(lmdb_error(std::string("Failed to create a transaction for the db in ")+__FUNCTION__+": ", mdb_res).c_str())); \
} \
#define TXN_BLOCK_POSTFIX_SUCCESS() \
do { \
if (! m_batch_active && ! m_write_txn) \
auto_txn.commit(); \
} while(0)
void BlockchainLMDB::add_txpool_tx(const crypto::hash &txid, const cryptonote::blobdata_ref &blob, const txpool_tx_meta_t &meta)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(txpool_meta)
CURSOR(txpool_blob)
MDB_val k = {sizeof(txid), (void *)&txid};
MDB_val v = {sizeof(meta), (void *)&meta};
if (auto result = mdb_cursor_put(m_cur_txpool_meta, &k, &v, MDB_NODUPDATA)) {
if (result == MDB_KEYEXIST)
throw1(DB_ERROR("Attempting to add txpool tx metadata that's already in the db"));
else
throw1(DB_ERROR(lmdb_error("Error adding txpool tx metadata to db transaction: ", result).c_str()));
}
MDB_val_sized(blob_val, blob);
if (auto result = mdb_cursor_put(m_cur_txpool_blob, &k, &blob_val, MDB_NODUPDATA)) {
if (result == MDB_KEYEXIST)
throw1(DB_ERROR("Attempting to add txpool tx blob that's already in the db"));
else
throw1(DB_ERROR(lmdb_error("Error adding txpool tx blob to db transaction: ", result).c_str()));
}
}
void BlockchainLMDB::update_txpool_tx(const crypto::hash &txid, const txpool_tx_meta_t &meta)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(txpool_meta)
CURSOR(txpool_blob)
MDB_val k = {sizeof(txid), (void *)&txid};
MDB_val v;
auto result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, MDB_SET);
if (result != 0)
throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta to update: ", result).c_str()));
result = mdb_cursor_del(m_cur_txpool_meta, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Error adding removal of txpool tx metadata to db transaction: ", result).c_str()));
v = MDB_val({sizeof(meta), (void *)&meta});
if ((result = mdb_cursor_put(m_cur_txpool_meta, &k, &v, MDB_NODUPDATA)) != 0) {
if (result == MDB_KEYEXIST)
throw1(DB_ERROR("Attempting to add txpool tx metadata that's already in the db"));
else
throw1(DB_ERROR(lmdb_error("Error adding txpool tx metadata to db transaction: ", result).c_str()));
}
}
uint64_t BlockchainLMDB::get_txpool_tx_count(relay_category category) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
int result;
uint64_t num_entries = 0;
TXN_PREFIX_RDONLY();
if (category == relay_category::all)
{
// No filtering, we can get the number of tx the "fast" way
MDB_stat db_stats;
if ((result = mdb_stat(m_txn, m_txpool_meta, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_txpool_meta: ", result).c_str()));
num_entries = db_stats.ms_entries;
}
else
{
// Filter unrelayed tx out of the result, so we need to loop over transactions and check their meta data
RCURSOR(txpool_meta);
RCURSOR(txpool_blob);
MDB_val k;
MDB_val v;
MDB_cursor_op op = MDB_FIRST;
while (1)
{
result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, op);
op = MDB_NEXT;
if (result == MDB_NOTFOUND)
break;
if (result)
throw0(DB_ERROR(lmdb_error("Failed to enumerate txpool tx metadata: ", result).c_str()));
const txpool_tx_meta_t &meta = *(const txpool_tx_meta_t*)v.mv_data;
if (meta.matches(category))
++num_entries;
}
}
TXN_POSTFIX_RDONLY();
return num_entries;
}
bool BlockchainLMDB::txpool_has_tx(const crypto::hash& txid, relay_category tx_category) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(txpool_meta)
MDB_val k = {sizeof(txid), (void *)&txid};
MDB_val v;
auto result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, MDB_SET);
if (result != 0 && result != MDB_NOTFOUND)
throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta: ", result).c_str()));
if (result == MDB_NOTFOUND)
return false;
bool found = true;
if (tx_category != relay_category::all)
{
const txpool_tx_meta_t &meta = *(const txpool_tx_meta_t*)v.mv_data;
found = meta.matches(tx_category);
}
TXN_POSTFIX_RDONLY();
return found;
}
void BlockchainLMDB::remove_txpool_tx(const crypto::hash& txid)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(txpool_meta)
CURSOR(txpool_blob)
MDB_val k = {sizeof(txid), (void *)&txid};
auto result = mdb_cursor_get(m_cur_txpool_meta, &k, NULL, MDB_SET);
if (result != 0 && result != MDB_NOTFOUND)
throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta to remove: ", result).c_str()));
if (!result)
{
result = mdb_cursor_del(m_cur_txpool_meta, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Error adding removal of txpool tx metadata to db transaction: ", result).c_str()));
}
result = mdb_cursor_get(m_cur_txpool_blob, &k, NULL, MDB_SET);
if (result != 0 && result != MDB_NOTFOUND)
throw1(DB_ERROR(lmdb_error("Error finding txpool tx blob to remove: ", result).c_str()));
if (!result)
{
result = mdb_cursor_del(m_cur_txpool_blob, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Error adding removal of txpool tx blob to db transaction: ", result).c_str()));
}
}
bool BlockchainLMDB::get_txpool_tx_meta(const crypto::hash& txid, txpool_tx_meta_t &meta) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(txpool_meta)
MDB_val k = {sizeof(txid), (void *)&txid};
MDB_val v;
auto result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, MDB_SET);
if (result == MDB_NOTFOUND)
return false;
if (result != 0)
throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta: ", result).c_str()));
meta = *(const txpool_tx_meta_t*)v.mv_data;
TXN_POSTFIX_RDONLY();
return true;
}
bool BlockchainLMDB::get_txpool_tx_blob(const crypto::hash& txid, cryptonote::blobdata &bd, relay_category tx_category) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(txpool_blob)
MDB_val k = {sizeof(txid), (void *)&txid};
MDB_val v;
// if filtering, make sure those requirements are met before copying blob
if (tx_category != relay_category::all)
{
RCURSOR(txpool_meta)
auto result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, MDB_SET);
if (result == MDB_NOTFOUND)
return false;
if (result != 0)
throw1(DB_ERROR(lmdb_error("Error finding txpool tx meta: ", result).c_str()));
const txpool_tx_meta_t& meta = *(const txpool_tx_meta_t*)v.mv_data;
if (!meta.matches(tx_category))
return false;
}
auto result = mdb_cursor_get(m_cur_txpool_blob, &k, &v, MDB_SET);
if (result == MDB_NOTFOUND)
return false;
if (result != 0)
throw1(DB_ERROR(lmdb_error("Error finding txpool tx blob: ", result).c_str()));
bd.assign(reinterpret_cast<const char*>(v.mv_data), v.mv_size);
TXN_POSTFIX_RDONLY();
return true;
}
cryptonote::blobdata BlockchainLMDB::get_txpool_tx_blob(const crypto::hash& txid, relay_category tx_category) const
{
cryptonote::blobdata bd;
if (!get_txpool_tx_blob(txid, bd, tx_category))
throw1(DB_ERROR("Tx not found in txpool: "));
return bd;
}
uint32_t BlockchainLMDB::get_blockchain_pruning_seed() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(properties)
MDB_val_str(k, "pruning_seed");
MDB_val v;
int result = mdb_cursor_get(m_cur_properties, &k, &v, MDB_SET);
if (result == MDB_NOTFOUND)
return 0;
if (result)
throw0(DB_ERROR(lmdb_error("Failed to retrieve pruning seed: ", result).c_str()));
if (v.mv_size != sizeof(uint32_t))
throw0(DB_ERROR("Failed to retrieve or create pruning seed: unexpected value size"));
uint32_t pruning_seed;
memcpy(&pruning_seed, v.mv_data, sizeof(pruning_seed));
TXN_POSTFIX_RDONLY();
return pruning_seed;
}
static bool is_v1_tx(MDB_cursor *c_txs_pruned, MDB_val *tx_id)
{
MDB_val v;
int ret = mdb_cursor_get(c_txs_pruned, tx_id, &v, MDB_SET);
if (ret)
throw0(DB_ERROR(lmdb_error("Failed to find transaction pruned data: ", ret).c_str()));
if (v.mv_size == 0)
throw0(DB_ERROR("Invalid transaction pruned data"));
return cryptonote::is_v1_tx(cryptonote::blobdata_ref{(const char*)v.mv_data, v.mv_size});
}
enum { prune_mode_prune, prune_mode_update, prune_mode_check };
bool BlockchainLMDB::prune_worker(int mode, uint32_t pruning_seed)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
const uint32_t log_stripes = tools::get_pruning_log_stripes(pruning_seed);
if (log_stripes && log_stripes != CRYPTONOTE_PRUNING_LOG_STRIPES)
throw0(DB_ERROR("Pruning seed not in range"));
pruning_seed = tools::get_pruning_stripe(pruning_seed);
if (pruning_seed > (1ul << CRYPTONOTE_PRUNING_LOG_STRIPES))
throw0(DB_ERROR("Pruning seed not in range"));
check_open();
TIME_MEASURE_START(t);
size_t n_total_records = 0, n_prunable_records = 0, n_pruned_records = 0, commit_counter = 0;
uint64_t n_bytes = 0;
mdb_txn_safe txn;
auto result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
MDB_stat db_stats;
if ((result = mdb_stat(txn, m_txs_prunable, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_txs_prunable: ", result).c_str()));
const size_t pages0 = db_stats.ms_branch_pages + db_stats.ms_leaf_pages + db_stats.ms_overflow_pages;
MDB_val_str(k, "pruning_seed");
MDB_val v;
result = mdb_get(txn, m_properties, &k, &v);
bool prune_tip_table = false;
if (result == MDB_NOTFOUND)
{
// not pruned yet
if (mode != prune_mode_prune)
{
txn.abort();
TIME_MEASURE_FINISH(t);
MDEBUG("Pruning not enabled, nothing to do");
return true;
}
if (pruning_seed == 0)
pruning_seed = tools::get_random_stripe();
pruning_seed = tools::make_pruning_seed(pruning_seed, CRYPTONOTE_PRUNING_LOG_STRIPES);
v.mv_data = &pruning_seed;
v.mv_size = sizeof(pruning_seed);
result = mdb_put(txn, m_properties, &k, &v, 0);
if (result)
throw0(DB_ERROR("Failed to save pruning seed"));
prune_tip_table = false;
}
else if (result == 0)
{
// pruned already
if (v.mv_size != sizeof(uint32_t))
throw0(DB_ERROR("Failed to retrieve or create pruning seed: unexpected value size"));
const uint32_t data = *(const uint32_t*)v.mv_data;
if (pruning_seed == 0)
pruning_seed = tools::get_pruning_stripe(data);
if (tools::get_pruning_stripe(data) != pruning_seed)
throw0(DB_ERROR("Blockchain already pruned with different seed"));
if (tools::get_pruning_log_stripes(data) != CRYPTONOTE_PRUNING_LOG_STRIPES)
throw0(DB_ERROR("Blockchain already pruned with different base"));
pruning_seed = tools::make_pruning_seed(pruning_seed, CRYPTONOTE_PRUNING_LOG_STRIPES);
prune_tip_table = (mode == prune_mode_update);
}
else
{
throw0(DB_ERROR(lmdb_error("Failed to retrieve or create pruning seed: ", result).c_str()));
}
if (mode == prune_mode_check)
MINFO("Checking blockchain pruning...");
else
MINFO("Pruning blockchain...");
MDB_cursor *c_txs_pruned, *c_txs_prunable, *c_txs_prunable_tip;
result = mdb_cursor_open(txn, m_txs_pruned, &c_txs_pruned);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_pruned: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_prunable, &c_txs_prunable);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_prunable_tip, &c_txs_prunable_tip);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable_tip: ", result).c_str()));
const uint64_t blockchain_height = height();
if (prune_tip_table)
{
MDB_cursor_op op = MDB_FIRST;
while (1)
{
int ret = mdb_cursor_get(c_txs_prunable_tip, &k, &v, op);
op = MDB_NEXT;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw0(DB_ERROR(lmdb_error("Failed to enumerate transactions: ", ret).c_str()));
uint64_t block_height;
memcpy(&block_height, v.mv_data, sizeof(block_height));
if (block_height + CRYPTONOTE_PRUNING_TIP_BLOCKS < blockchain_height)
{
++n_total_records;
if (!tools::has_unpruned_block(block_height, blockchain_height, pruning_seed) && !is_v1_tx(c_txs_pruned, &k))
{
++n_prunable_records;
result = mdb_cursor_get(c_txs_prunable, &k, &v, MDB_SET);
if (result == MDB_NOTFOUND)
MDEBUG("Already pruned at height " << block_height << "/" << blockchain_height);
else if (result)
throw0(DB_ERROR(lmdb_error("Failed to find transaction prunable data: ", result).c_str()));
else
{
MDEBUG("Pruning at height " << block_height << "/" << blockchain_height);
++n_pruned_records;
++commit_counter;
n_bytes += k.mv_size + v.mv_size;
result = mdb_cursor_del(c_txs_prunable, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete transaction prunable data: ", result).c_str()));
}
}
result = mdb_cursor_del(c_txs_prunable_tip, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete transaction tip data: ", result).c_str()));
if (mode != prune_mode_check && commit_counter >= 4096)
{
MDEBUG("Committing txn at checkpoint...");
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_pruned, &c_txs_pruned);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_pruned: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_prunable, &c_txs_prunable);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_prunable_tip, &c_txs_prunable_tip);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable_tip: ", result).c_str()));
commit_counter = 0;
}
}
}
}
else
{
MDB_cursor *c_tx_indices;
result = mdb_cursor_open(txn, m_tx_indices, &c_tx_indices);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for tx_indices: ", result).c_str()));
MDB_cursor_op op = MDB_FIRST;
while (1)
{
int ret = mdb_cursor_get(c_tx_indices, &k, &v, op);
op = MDB_NEXT;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw0(DB_ERROR(lmdb_error("Failed to enumerate transactions: ", ret).c_str()));
++n_total_records;
//const txindex *ti = (const txindex *)v.mv_data;
txindex ti;
memcpy(&ti, v.mv_data, sizeof(ti));
const uint64_t block_height = ti.data.block_id;
if (block_height + CRYPTONOTE_PRUNING_TIP_BLOCKS >= blockchain_height)
{
MDB_val_set(kp, ti.data.tx_id);
MDB_val_set(vp, block_height);
if (mode == prune_mode_check)
{
result = mdb_cursor_get(c_txs_prunable_tip, &kp, &vp, MDB_SET);
if (result && result != MDB_NOTFOUND)
throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str()));
if (result == MDB_NOTFOUND)
MERROR("Transaction not found in prunable tip table for height " << block_height << "/" << blockchain_height <<
", seed " << epee::string_tools::to_string_hex(pruning_seed));
}
else
{
result = mdb_cursor_put(c_txs_prunable_tip, &kp, &vp, 0);
if (result && result != MDB_NOTFOUND)
throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str()));
}
}
MDB_val_set(kp, ti.data.tx_id);
if (!tools::has_unpruned_block(block_height, blockchain_height, pruning_seed) && !is_v1_tx(c_txs_pruned, &kp))
{
result = mdb_cursor_get(c_txs_prunable, &kp, &v, MDB_SET);
if (result && result != MDB_NOTFOUND)
throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str()));
if (mode == prune_mode_check)
{
if (result != MDB_NOTFOUND)
MERROR("Prunable data found for pruned height " << block_height << "/" << blockchain_height <<
", seed " << epee::string_tools::to_string_hex(pruning_seed));
}
else
{
++n_prunable_records;
if (result == MDB_NOTFOUND)
MDEBUG("Already pruned at height " << block_height << "/" << blockchain_height);
else
{
MDEBUG("Pruning at height " << block_height << "/" << blockchain_height);
++n_pruned_records;
n_bytes += kp.mv_size + v.mv_size;
result = mdb_cursor_del(c_txs_prunable, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete transaction prunable data: ", result).c_str()));
++commit_counter;
}
}
}
else
{
if (mode == prune_mode_check)
{
MDB_val_set(kp, ti.data.tx_id);
result = mdb_cursor_get(c_txs_prunable, &kp, &v, MDB_SET);
if (result && result != MDB_NOTFOUND)
throw0(DB_ERROR(lmdb_error("Error looking for transaction prunable data: ", result).c_str()));
if (result == MDB_NOTFOUND)
MERROR("Prunable data not found for unpruned height " << block_height << "/" << blockchain_height <<
", seed " << epee::string_tools::to_string_hex(pruning_seed));
}
}
if (mode != prune_mode_check && commit_counter >= 4096)
{
MDEBUG("Committing txn at checkpoint...");
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_pruned, &c_txs_pruned);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_pruned: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_prunable, &c_txs_prunable);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_prunable_tip, &c_txs_prunable_tip);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable_tip: ", result).c_str()));
result = mdb_cursor_open(txn, m_tx_indices, &c_tx_indices);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for tx_indices: ", result).c_str()));
MDB_val val;
val.mv_size = sizeof(ti);
val.mv_data = (void *)&ti;
result = mdb_cursor_get(c_tx_indices, (MDB_val*)&zerokval, &val, MDB_GET_BOTH);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to restore cursor for tx_indices: ", result).c_str()));
commit_counter = 0;
}
}
mdb_cursor_close(c_tx_indices);
}
if ((result = mdb_stat(txn, m_txs_prunable, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_txs_prunable: ", result).c_str()));
const size_t pages1 = db_stats.ms_branch_pages + db_stats.ms_leaf_pages + db_stats.ms_overflow_pages;
const size_t db_bytes = (pages0 - pages1) * db_stats.ms_psize;
mdb_cursor_close(c_txs_prunable_tip);
mdb_cursor_close(c_txs_prunable);
mdb_cursor_close(c_txs_pruned);
txn.commit();
TIME_MEASURE_FINISH(t);
MINFO((mode == prune_mode_check ? "Checked" : "Pruned") << " blockchain in " <<
t << " ms: " << (n_bytes/1024.0f/1024.0f) << " MB (" << db_bytes/1024.0f/1024.0f << " MB) pruned in " <<
n_pruned_records << " records (" << pages0 - pages1 << "/" << pages0 << " " << db_stats.ms_psize << " byte pages), " <<
n_prunable_records << "/" << n_total_records << " pruned records");
return true;
}
bool BlockchainLMDB::prune_blockchain(uint32_t pruning_seed)
{
return prune_worker(prune_mode_prune, pruning_seed);
}
bool BlockchainLMDB::update_pruning()
{
return prune_worker(prune_mode_update, 0);
}
bool BlockchainLMDB::check_pruning()
{
return prune_worker(prune_mode_check, 0);
}
bool BlockchainLMDB::for_all_txpool_txes(std::function<bool(const crypto::hash&, const txpool_tx_meta_t&, const cryptonote::blobdata_ref*)> f, bool include_blob, relay_category category) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(txpool_meta);
RCURSOR(txpool_blob);
MDB_val k;
MDB_val v;
bool ret = true;
MDB_cursor_op op = MDB_FIRST;
while (1)
{
int result = mdb_cursor_get(m_cur_txpool_meta, &k, &v, op);
op = MDB_NEXT;
if (result == MDB_NOTFOUND)
break;
if (result)
throw0(DB_ERROR(lmdb_error("Failed to enumerate txpool tx metadata: ", result).c_str()));
const crypto::hash txid = *(const crypto::hash*)k.mv_data;
const txpool_tx_meta_t &meta = *(const txpool_tx_meta_t*)v.mv_data;
if (!meta.matches(category))
continue;
cryptonote::blobdata_ref bd;
if (include_blob)
{
MDB_val b;
result = mdb_cursor_get(m_cur_txpool_blob, &k, &b, MDB_SET);
if (result == MDB_NOTFOUND)
throw0(DB_ERROR("Failed to find txpool tx blob to match metadata"));
if (result)
throw0(DB_ERROR(lmdb_error("Failed to enumerate txpool tx blob: ", result).c_str()));
bd = {reinterpret_cast<const char*>(b.mv_data), b.mv_size};
}
if (!f(txid, meta, &bd)) {
ret = false;
break;
}
}
TXN_POSTFIX_RDONLY();
return ret;
}
bool BlockchainLMDB::for_all_alt_blocks(std::function<bool(const crypto::hash&, const alt_block_data_t&, const cryptonote::blobdata_ref*)> f, bool include_blob) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(alt_blocks);
MDB_val k;
MDB_val v;
bool ret = true;
MDB_cursor_op op = MDB_FIRST;
while (1)
{
int result = mdb_cursor_get(m_cur_alt_blocks, &k, &v, op);
op = MDB_NEXT;
if (result == MDB_NOTFOUND)
break;
if (result)
throw0(DB_ERROR(lmdb_error("Failed to enumerate alt blocks: ", result).c_str()));
const crypto::hash &blkid = *(const crypto::hash*)k.mv_data;
if (v.mv_size < sizeof(alt_block_data_t))
throw0(DB_ERROR("alt_blocks record is too small"));
const alt_block_data_t *data = (const alt_block_data_t*)v.mv_data;
cryptonote::blobdata_ref bd;
if (include_blob)
{
bd = {reinterpret_cast<const char*>(v.mv_data) + sizeof(alt_block_data_t), v.mv_size - sizeof(alt_block_data_t)};
}
if (!f(blkid, *data, &bd)) {
ret = false;
break;
}
}
TXN_POSTFIX_RDONLY();
return ret;
}
bool BlockchainLMDB::block_exists(const crypto::hash& h, uint64_t *height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(block_heights);
bool ret = false;
MDB_val_set(key, h);
auto get_result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &key, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
{
LOG_PRINT_L3("Block with hash " << epee::string_tools::pod_to_hex(h) << " not found in db");
}
else if (get_result)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch block index from hash", get_result).c_str()));
else
{
if (height)
{
const blk_height *bhp = (const blk_height *)key.mv_data;
*height = bhp->bh_height;
}
ret = true;
}
TXN_POSTFIX_RDONLY();
return ret;
}
cryptonote::blobdata BlockchainLMDB::get_block_blob(const crypto::hash& h) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
return get_block_blob_from_height(get_block_height(h));
}
uint64_t BlockchainLMDB::get_block_height(const crypto::hash& h) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(block_heights);
MDB_val_set(key, h);
auto get_result = mdb_cursor_get(m_cur_block_heights, (MDB_val *)&zerokval, &key, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
throw1(BLOCK_DNE("Attempted to retrieve non-existent block height"));
else if (get_result)
throw0(DB_ERROR("Error attempting to retrieve a block height from the db"));
blk_height *bhp = (blk_height *)key.mv_data;
uint64_t ret = bhp->bh_height;
TXN_POSTFIX_RDONLY();
return ret;
}
block_header BlockchainLMDB::get_block_header(const crypto::hash& h) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
// block_header object is automatically cast from block object
return get_block(h);
}
cryptonote::blobdata BlockchainLMDB::get_block_blob_from_height(const uint64_t& height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(blocks);
MDB_val_copy<uint64_t> key(height);
MDB_val result;
auto get_result = mdb_cursor_get(m_cur_blocks, &key, &result, MDB_SET);
if (get_result == MDB_NOTFOUND)
{
throw0(BLOCK_DNE(std::string("Attempt to get block from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- block not in db").c_str()));
}
else if (get_result)
throw0(DB_ERROR("Error attempting to retrieve a block from the db"));
blobdata bd;
bd.assign(reinterpret_cast<char*>(result.mv_data), result.mv_size);
TXN_POSTFIX_RDONLY();
return bd;
}
uint64_t BlockchainLMDB::get_block_timestamp(const uint64_t& height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(block_info);
MDB_val_set(result, height);
auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
{
throw0(BLOCK_DNE(std::string("Attempt to get timestamp from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- timestamp not in db").c_str()));
}
else if (get_result)
throw0(DB_ERROR("Error attempting to retrieve a timestamp from the db"));
mdb_block_info *bi = (mdb_block_info *)result.mv_data;
uint64_t ret = bi->bi_timestamp;
TXN_POSTFIX_RDONLY();
return ret;
}
std::vector<uint64_t> BlockchainLMDB::get_block_cumulative_rct_outputs(const std::vector<uint64_t> &heights) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
std::vector<uint64_t> res;
int result;
if (heights.empty())
return {};
res.reserve(heights.size());
TXN_PREFIX_RDONLY();
RCURSOR(block_info);
MDB_stat db_stats;
if ((result = mdb_stat(m_txn, m_blocks, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
for (size_t i = 0; i < heights.size(); ++i)
if (heights[i] >= db_stats.ms_entries)
throw0(BLOCK_DNE(std::string("Attempt to get rct distribution from height " + std::to_string(heights[i]) + " failed -- block size not in db").c_str()));
MDB_val v;
uint64_t prev_height = heights[0];
uint64_t range_begin = 0, range_end = 0;
for (uint64_t height: heights)
{
if (height >= range_begin && height < range_end)
{
// nothing to do
}
else
{
if (height == prev_height + 1)
{
MDB_val k2;
result = mdb_cursor_get(m_cur_block_info, &k2, &v, MDB_NEXT_MULTIPLE);
range_begin = ((const mdb_block_info*)v.mv_data)->bi_height;
range_end = range_begin + v.mv_size / sizeof(mdb_block_info); // whole records please
if (height < range_begin || height >= range_end)
throw0(DB_ERROR(("Height " + std::to_string(height) + " not included in multuple record range: " + std::to_string(range_begin) + "-" + std::to_string(range_end)).c_str()));
}
else
{
v.mv_size = sizeof(uint64_t);
v.mv_data = (void*)&height;
result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
range_begin = height;
range_end = range_begin + 1;
}
if (result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve rct distribution from the db: ", result).c_str()));
}
const mdb_block_info *bi = ((const mdb_block_info *)v.mv_data) + (height - range_begin);
res.push_back(bi->bi_cum_rct);
prev_height = height;
}
TXN_POSTFIX_RDONLY();
return res;
}
uint64_t BlockchainLMDB::get_top_block_timestamp() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
uint64_t m_height = height();
// if no blocks, return 0
if (m_height == 0)
{
return 0;
}
return get_block_timestamp(m_height - 1);
}
size_t BlockchainLMDB::get_block_weight(const uint64_t& height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(block_info);
MDB_val_set(result, height);
auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
{
throw0(BLOCK_DNE(std::string("Attempt to get block size from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- block size not in db").c_str()));
}
else if (get_result)
throw0(DB_ERROR("Error attempting to retrieve a block size from the db"));
mdb_block_info *bi = (mdb_block_info *)result.mv_data;
size_t ret = bi->bi_weight;
TXN_POSTFIX_RDONLY();
return ret;
}
std::vector<uint64_t> BlockchainLMDB::get_block_info_64bit_fields(uint64_t start_height, size_t count, off_t offset) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(block_info);
const uint64_t h = height();
if (start_height >= h)
throw0(DB_ERROR(("Height " + std::to_string(start_height) + " not in blockchain").c_str()));
std::vector<uint64_t> ret;
ret.reserve(count);
MDB_val v;
uint64_t range_begin = 0, range_end = 0;
for (uint64_t height = start_height; height < h && count--; ++height)
{
if (height >= range_begin && height < range_end)
{
// nothing to do
}
else
{
int result = 0;
if (range_end > 0)
{
MDB_val k2;
result = mdb_cursor_get(m_cur_block_info, &k2, &v, MDB_NEXT_MULTIPLE);
range_begin = ((const mdb_block_info*)v.mv_data)->bi_height;
range_end = range_begin + v.mv_size / sizeof(mdb_block_info); // whole records please
if (height < range_begin || height >= range_end)
throw0(DB_ERROR(("Height " + std::to_string(height) + " not included in multiple record range: " + std::to_string(range_begin) + "-" + std::to_string(range_end)).c_str()));
}
else
{
v.mv_size = sizeof(uint64_t);
v.mv_data = (void*)&height;
result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
range_begin = height;
range_end = range_begin + 1;
}
if (result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve block_info from the db: ", result).c_str()));
}
const mdb_block_info *bi = ((const mdb_block_info *)v.mv_data) + (height - range_begin);
ret.push_back(*(const uint64_t*)(((const char*)bi) + offset));
}
TXN_POSTFIX_RDONLY();
return ret;
}
uint64_t BlockchainLMDB::get_max_block_size()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(properties)
MDB_val_str(k, "max_block_size");
MDB_val v;
int result = mdb_cursor_get(m_cur_properties, &k, &v, MDB_SET);
if (result == MDB_NOTFOUND)
return std::numeric_limits<uint64_t>::max();
if (result)
throw0(DB_ERROR(lmdb_error("Failed to retrieve max block size: ", result).c_str()));
if (v.mv_size != sizeof(uint64_t))
throw0(DB_ERROR("Failed to retrieve or create max block size: unexpected value size"));
uint64_t max_block_size;
memcpy(&max_block_size, v.mv_data, sizeof(max_block_size));
TXN_POSTFIX_RDONLY();
return max_block_size;
}
void BlockchainLMDB::add_max_block_size(uint64_t sz)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(properties)
MDB_val_str(k, "max_block_size");
MDB_val v;
int result = mdb_cursor_get(m_cur_properties, &k, &v, MDB_SET);
if (result && result != MDB_NOTFOUND)
throw0(DB_ERROR(lmdb_error("Failed to retrieve max block size: ", result).c_str()));
uint64_t max_block_size = 0;
if (result == 0)
{
if (v.mv_size != sizeof(uint64_t))
throw0(DB_ERROR("Failed to retrieve or create max block size: unexpected value size"));
memcpy(&max_block_size, v.mv_data, sizeof(max_block_size));
}
if (sz > max_block_size)
max_block_size = sz;
v.mv_data = (void*)&max_block_size;
v.mv_size = sizeof(max_block_size);
result = mdb_cursor_put(m_cur_properties, &k, &v, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to set max_block_size: ", result).c_str()));
}
std::vector<uint64_t> BlockchainLMDB::get_block_weights(uint64_t start_height, size_t count) const
{
return get_block_info_64bit_fields(start_height, count, offsetof(mdb_block_info, bi_weight));
}
std::vector<uint64_t> BlockchainLMDB::get_long_term_block_weights(uint64_t start_height, size_t count) const
{
return get_block_info_64bit_fields(start_height, count, offsetof(mdb_block_info, bi_long_term_block_weight));
}
difficulty_type BlockchainLMDB::get_block_cumulative_difficulty(const uint64_t& height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__ << " height: " << height);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(block_info);
MDB_val_set(result, height);
auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
{
throw0(BLOCK_DNE(std::string("Attempt to get cumulative difficulty from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- difficulty not in db").c_str()));
}
else if (get_result)
throw0(DB_ERROR("Error attempting to retrieve a cumulative difficulty from the db"));
mdb_block_info *bi = (mdb_block_info *)result.mv_data;
difficulty_type ret = bi->bi_diff_hi;
ret <<= 64;
ret |= bi->bi_diff_lo;
TXN_POSTFIX_RDONLY();
return ret;
}
difficulty_type BlockchainLMDB::get_block_difficulty(const uint64_t& height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
difficulty_type diff1 = 0;
difficulty_type diff2 = 0;
diff1 = get_block_cumulative_difficulty(height);
if (height != 0)
{
diff2 = get_block_cumulative_difficulty(height - 1);
}
return diff1 - diff2;
}
uint64_t BlockchainLMDB::get_block_already_generated_coins(const uint64_t& height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(block_info);
MDB_val_set(result, height);
auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
{
throw0(BLOCK_DNE(std::string("Attempt to get generated coins from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- block size not in db").c_str()));
}
else if (get_result)
throw0(DB_ERROR("Error attempting to retrieve a total generated coins from the db"));
mdb_block_info *bi = (mdb_block_info *)result.mv_data;
uint64_t ret = bi->bi_coins;
TXN_POSTFIX_RDONLY();
return ret;
}
uint64_t BlockchainLMDB::get_block_long_term_weight(const uint64_t& height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(block_info);
MDB_val_set(result, height);
auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
{
throw0(BLOCK_DNE(std::string("Attempt to get block long term weight from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- block info not in db").c_str()));
}
else if (get_result)
throw0(DB_ERROR("Error attempting to retrieve a long term block weight from the db"));
mdb_block_info *bi = (mdb_block_info *)result.mv_data;
uint64_t ret = bi->bi_long_term_block_weight;
TXN_POSTFIX_RDONLY();
return ret;
}
crypto::hash BlockchainLMDB::get_block_hash_from_height(const uint64_t& height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(block_info);
MDB_val_set(result, height);
auto get_result = mdb_cursor_get(m_cur_block_info, (MDB_val *)&zerokval, &result, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
{
throw0(BLOCK_DNE(std::string("Attempt to get hash from height ").append(boost::lexical_cast<std::string>(height)).append(" failed -- hash not in db").c_str()));
}
else if (get_result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve a block hash from the db: ", get_result).c_str()));
mdb_block_info *bi = (mdb_block_info *)result.mv_data;
crypto::hash ret = bi->bi_hash;
TXN_POSTFIX_RDONLY();
return ret;
}
std::vector<block> BlockchainLMDB::get_blocks_range(const uint64_t& h1, const uint64_t& h2) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
std::vector<block> v;
for (uint64_t height = h1; height <= h2; ++height)
{
v.push_back(get_block_from_height(height));
}
return v;
}
std::vector<crypto::hash> BlockchainLMDB::get_hashes_range(const uint64_t& h1, const uint64_t& h2) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
std::vector<crypto::hash> v;
for (uint64_t height = h1; height <= h2; ++height)
{
v.push_back(get_block_hash_from_height(height));
}
return v;
}
crypto::hash BlockchainLMDB::top_block_hash(uint64_t *block_height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
uint64_t m_height = height();
if (block_height)
*block_height = m_height - 1;
if (m_height != 0)
{
return get_block_hash_from_height(m_height - 1);
}
return null_hash;
}
block BlockchainLMDB::get_top_block() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
uint64_t m_height = height();
if (m_height != 0)
{
return get_block_from_height(m_height - 1);
}
block b;
return b;
}
uint64_t BlockchainLMDB::height() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
int result;
// get current height
MDB_stat db_stats;
if ((result = mdb_stat(m_txn, m_blocks, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
return db_stats.ms_entries;
}
uint64_t BlockchainLMDB::num_outputs() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
int result;
RCURSOR(output_txs)
uint64_t num = 0;
MDB_val k, v;
result = mdb_cursor_get(m_cur_output_txs, &k, &v, MDB_LAST);
if (result == MDB_NOTFOUND)
num = 0;
else if (result == 0)
num = 1 + ((const outtx*)v.mv_data)->output_id;
else
throw0(DB_ERROR(lmdb_error("Failed to query m_output_txs: ", result).c_str()));
return num;
}
bool BlockchainLMDB::tx_exists(const crypto::hash& h) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(tx_indices);
MDB_val_set(key, h);
bool tx_found = false;
TIME_MEASURE_START(time1);
auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &key, MDB_GET_BOTH);
if (get_result == 0)
tx_found = true;
else if (get_result != MDB_NOTFOUND)
throw0(DB_ERROR(lmdb_error(std::string("DB error attempting to fetch transaction index from hash ") + epee::string_tools::pod_to_hex(h) + ": ", get_result).c_str()));
TIME_MEASURE_FINISH(time1);
time_tx_exists += time1;
TXN_POSTFIX_RDONLY();
if (! tx_found)
{
LOG_PRINT_L1("transaction with hash " << epee::string_tools::pod_to_hex(h) << " not found in db");
return false;
}
return true;
}
bool BlockchainLMDB::tx_exists(const crypto::hash& h, uint64_t& tx_id) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(tx_indices);
MDB_val_set(v, h);
TIME_MEASURE_START(time1);
auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
TIME_MEASURE_FINISH(time1);
time_tx_exists += time1;
if (!get_result) {
txindex *tip = (txindex *)v.mv_data;
tx_id = tip->data.tx_id;
}
TXN_POSTFIX_RDONLY();
bool ret = false;
if (get_result == MDB_NOTFOUND)
{
LOG_PRINT_L1("transaction with hash " << epee::string_tools::pod_to_hex(h) << " not found in db");
}
else if (get_result)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch transaction from hash", get_result).c_str()));
else
ret = true;
return ret;
}
uint64_t BlockchainLMDB::get_tx_unlock_time(const crypto::hash& h) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(tx_indices);
MDB_val_set(v, h);
auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
throw1(TX_DNE(lmdb_error(std::string("tx data with hash ") + epee::string_tools::pod_to_hex(h) + " not found in db: ", get_result).c_str()));
else if (get_result)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx data from hash: ", get_result).c_str()));
txindex *tip = (txindex *)v.mv_data;
uint64_t ret = tip->data.unlock_time;
TXN_POSTFIX_RDONLY();
return ret;
}
bool BlockchainLMDB::get_tx_blob(const crypto::hash& h, cryptonote::blobdata &bd) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(tx_indices);
RCURSOR(txs_pruned);
RCURSOR(txs_prunable);
MDB_val_set(v, h);
MDB_val result0, result1;
auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (get_result == 0)
{
txindex *tip = (txindex *)v.mv_data;
MDB_val_set(val_tx_id, tip->data.tx_id);
get_result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &result0, MDB_SET);
if (get_result == 0)
{
get_result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, &result1, MDB_SET);
}
}
if (get_result == MDB_NOTFOUND)
return false;
else if (get_result)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx from hash", get_result).c_str()));
bd.assign(reinterpret_cast<char*>(result0.mv_data), result0.mv_size);
bd.append(reinterpret_cast<char*>(result1.mv_data), result1.mv_size);
TXN_POSTFIX_RDONLY();
return true;
}
bool BlockchainLMDB::get_pruned_tx_blob(const crypto::hash& h, cryptonote::blobdata &bd) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(tx_indices);
RCURSOR(txs_pruned);
MDB_val_set(v, h);
MDB_val result;
auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (get_result == 0)
{
txindex *tip = (txindex *)v.mv_data;
MDB_val_set(val_tx_id, tip->data.tx_id);
get_result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &result, MDB_SET);
}
if (get_result == MDB_NOTFOUND)
return false;
else if (get_result)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx from hash", get_result).c_str()));
bd.assign(reinterpret_cast<char*>(result.mv_data), result.mv_size);
TXN_POSTFIX_RDONLY();
return true;
}
bool BlockchainLMDB::get_pruned_tx_blobs_from(const crypto::hash& h, size_t count, std::vector<cryptonote::blobdata> &bd) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
if (!count)
return true;
TXN_PREFIX_RDONLY();
RCURSOR(tx_indices);
RCURSOR(txs_pruned);
bd.reserve(bd.size() + count);
MDB_val_set(v, h);
MDB_val result;
int res = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (res == MDB_NOTFOUND)
return false;
if (res)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx from hash", res).c_str()));
const txindex *tip = (const txindex *)v.mv_data;
const uint64_t id = tip->data.tx_id;
MDB_val_set(val_tx_id, id);
MDB_cursor_op op = MDB_SET;
while (count--)
{
res = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &result, op);
op = MDB_NEXT;
if (res == MDB_NOTFOUND)
return false;
if (res)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx blob", res).c_str()));
bd.emplace_back(reinterpret_cast<char*>(result.mv_data), result.mv_size);
}
TXN_POSTFIX_RDONLY();
return true;
}
bool BlockchainLMDB::get_blocks_from(uint64_t start_height, size_t min_block_count, size_t max_block_count, size_t max_tx_count, size_t max_size, std::vector<std::pair<std::pair<cryptonote::blobdata, crypto::hash>, std::vector<std::pair<crypto::hash, cryptonote::blobdata>>>>& blocks, bool pruned, bool skip_coinbase, bool get_miner_tx_hash) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(blocks);
RCURSOR(tx_indices);
RCURSOR(txs_pruned);
if (!pruned)
{
RCURSOR(txs_prunable);
}
blocks.reserve(std::min<size_t>(max_block_count, 10000)); // guard against very large max count if only checking bytes
const uint64_t blockchain_height = height();
uint64_t size = 0;
size_t num_txes = 0;
MDB_val_copy<uint64_t> key(start_height);
MDB_val k, v, val_tx_id;
uint64_t tx_id = ~0;
MDB_cursor_op op = MDB_SET;
for (uint64_t h = start_height; h < blockchain_height && blocks.size() < max_block_count && (size < max_size || blocks.size() < min_block_count); ++h)
{
MDB_cursor_op op = h == start_height ? MDB_SET : MDB_NEXT;
int result = mdb_cursor_get(m_cur_blocks, &key, &v, op);
if (result == MDB_NOTFOUND)
throw0(BLOCK_DNE(std::string("Attempt to get block from height ").append(boost::lexical_cast<std::string>(h)).append(" failed -- block not in db").c_str()));
else if (result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve a block from the db", result).c_str()));
blocks.resize(blocks.size() + 1);
auto ¤t_block = blocks.back();
current_block.first.first.assign(reinterpret_cast<char*>(v.mv_data), v.mv_size);
size += v.mv_size;
cryptonote::block b;
if (!parse_and_validate_block_from_blob(current_block.first.first, b))
throw0(DB_ERROR("Invalid block"));
current_block.first.second = get_miner_tx_hash ? cryptonote::get_transaction_hash(b.miner_tx) : crypto::null_hash;
// get the tx_id for the first tx (the first block's coinbase tx)
if (h == start_height)
{
crypto::hash hash = cryptonote::get_transaction_hash(b.miner_tx);
MDB_val_set(v, hash);
result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve block coinbase transaction from the db: ", result).c_str()));
const txindex *tip = (const txindex *)v.mv_data;
tx_id = tip->data.tx_id;
val_tx_id.mv_data = &tx_id;
val_tx_id.mv_size = sizeof(tx_id);
}
if (skip_coinbase)
{
result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &v, op);
if (result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve transaction data from the db: ", result).c_str()));
if (!pruned)
{
result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, &v, op);
if (result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve transaction data from the db: ", result).c_str()));
}
}
op = MDB_NEXT;
current_block.second.reserve(b.tx_hashes.size());
num_txes += b.tx_hashes.size() + (skip_coinbase ? 0 : 1);
for (const auto &tx_hash: b.tx_hashes)
{
// get pruned data
cryptonote::blobdata tx_blob;
result = mdb_cursor_get(m_cur_txs_pruned, &val_tx_id, &v, op);
if (result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve transaction data from the db: ", result).c_str()));
tx_blob.assign((const char*)v.mv_data, v.mv_size);
if (!pruned)
{
result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, &v, op);
if (result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve transaction data from the db: ", result).c_str()));
tx_blob.append(reinterpret_cast<const char*>(v.mv_data), v.mv_size);
}
current_block.second.push_back(std::make_pair(tx_hash, std::move(tx_blob)));
size += current_block.second.back().second.size();
}
if (blocks.size() >= min_block_count && num_txes >= max_tx_count)
break;
}
TXN_POSTFIX_RDONLY();
return true;
}
bool BlockchainLMDB::get_prunable_tx_blob(const crypto::hash& h, cryptonote::blobdata &bd) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(tx_indices);
RCURSOR(txs_prunable);
MDB_val_set(v, h);
MDB_val result;
auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (get_result == 0)
{
const txindex *tip = (const txindex *)v.mv_data;
MDB_val_set(val_tx_id, tip->data.tx_id);
get_result = mdb_cursor_get(m_cur_txs_prunable, &val_tx_id, &result, MDB_SET);
}
if (get_result == MDB_NOTFOUND)
return false;
else if (get_result)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx from hash", get_result).c_str()));
bd.assign(reinterpret_cast<char*>(result.mv_data), result.mv_size);
TXN_POSTFIX_RDONLY();
return true;
}
bool BlockchainLMDB::get_prunable_tx_hash(const crypto::hash& tx_hash, crypto::hash &prunable_hash) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(tx_indices);
RCURSOR(txs_prunable_hash);
MDB_val_set(v, tx_hash);
MDB_val result, val_tx_prunable_hash;
auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (get_result == 0)
{
txindex *tip = (txindex *)v.mv_data;
MDB_val_set(val_tx_id, tip->data.tx_id);
get_result = mdb_cursor_get(m_cur_txs_prunable_hash, &val_tx_id, &result, MDB_SET);
}
if (get_result == MDB_NOTFOUND)
return false;
else if (get_result)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx prunable hash from tx hash", get_result).c_str()));
prunable_hash = *(const crypto::hash*)result.mv_data;
TXN_POSTFIX_RDONLY();
return true;
}
uint64_t BlockchainLMDB::get_tx_count() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
int result;
MDB_stat db_stats;
if ((result = mdb_stat(m_txn, m_txs_pruned, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_txs_pruned: ", result).c_str()));
TXN_POSTFIX_RDONLY();
return db_stats.ms_entries;
}
std::vector<transaction> BlockchainLMDB::get_tx_list(const std::vector<crypto::hash>& hlist) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
std::vector<transaction> v;
for (auto& h : hlist)
{
v.push_back(get_tx(h));
}
return v;
}
uint64_t BlockchainLMDB::get_tx_block_height(const crypto::hash& h) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(tx_indices);
MDB_val_set(v, h);
auto get_result = mdb_cursor_get(m_cur_tx_indices, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
{
throw1(TX_DNE(std::string("tx_data_t with hash ").append(epee::string_tools::pod_to_hex(h)).append(" not found in db").c_str()));
}
else if (get_result)
throw0(DB_ERROR(lmdb_error("DB error attempting to fetch tx height from hash", get_result).c_str()));
txindex *tip = (txindex *)v.mv_data;
uint64_t ret = tip->data.block_id;
TXN_POSTFIX_RDONLY();
return ret;
}
uint64_t BlockchainLMDB::get_num_outputs(const uint64_t& amount) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(output_amounts);
MDB_val_copy<uint64_t> k(amount);
MDB_val v;
mdb_size_t num_elems = 0;
auto result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_SET);
if (result == MDB_SUCCESS)
{
mdb_cursor_count(m_cur_output_amounts, &num_elems);
}
else if (result != MDB_NOTFOUND)
throw0(DB_ERROR("DB error attempting to get number of outputs of an amount"));
TXN_POSTFIX_RDONLY();
return num_elems;
}
output_data_t BlockchainLMDB::get_output_key(const uint64_t& amount, const uint64_t& index, bool include_commitmemt) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(output_amounts);
MDB_val_set(k, amount);
MDB_val_set(v, index);
auto get_result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
throw1(OUTPUT_DNE(std::string("Attempting to get output pubkey by index, but key does not exist: amount " +
std::to_string(amount) + ", index " + std::to_string(index)).c_str()));
else if (get_result)
throw0(DB_ERROR("Error attempting to retrieve an output pubkey from the db"));
output_data_t ret;
if (amount == 0)
{
const outkey *okp = (const outkey *)v.mv_data;
ret = okp->data;
}
else
{
const pre_rct_outkey *okp = (const pre_rct_outkey *)v.mv_data;
memcpy(&ret, &okp->data, sizeof(pre_rct_output_data_t));
if (include_commitmemt)
ret.commitment = rct::zeroCommit(amount);
}
TXN_POSTFIX_RDONLY();
return ret;
}
tx_out_index BlockchainLMDB::get_output_tx_and_index_from_global(const uint64_t& output_id) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(output_txs);
MDB_val_set(v, output_id);
auto get_result = mdb_cursor_get(m_cur_output_txs, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
throw1(OUTPUT_DNE("output with given index not in db"));
else if (get_result)
throw0(DB_ERROR("DB error attempting to fetch output tx hash"));
outtx *ot = (outtx *)v.mv_data;
tx_out_index ret = tx_out_index(ot->tx_hash, ot->local_index);
TXN_POSTFIX_RDONLY();
return ret;
}
tx_out_index BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, const uint64_t& index) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
std::vector < uint64_t > offsets;
std::vector<tx_out_index> indices;
offsets.push_back(index);
get_output_tx_and_index(amount, offsets, indices);
if (!indices.size())
throw1(OUTPUT_DNE("Attempting to get an output index by amount and amount index, but amount not found"));
return indices[0];
}
std::vector<std::vector<uint64_t>> BlockchainLMDB::get_tx_amount_output_indices(uint64_t tx_id, size_t n_txes) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(tx_outputs);
MDB_val_set(k_tx_id, tx_id);
MDB_val v;
std::vector<std::vector<uint64_t>> amount_output_indices_set;
amount_output_indices_set.reserve(n_txes);
MDB_cursor_op op = MDB_SET;
while (n_txes-- > 0)
{
int result = mdb_cursor_get(m_cur_tx_outputs, &k_tx_id, &v, op);
if (result == MDB_NOTFOUND)
LOG_PRINT_L0("WARNING: Unexpected: tx has no amount indices stored in "
"tx_outputs, but it should have an empty entry even if it's a tx without "
"outputs");
else if (result)
throw0(DB_ERROR(lmdb_error("DB error attempting to get data for tx_outputs[tx_index]", result).c_str()));
op = MDB_NEXT;
const uint64_t* indices = (const uint64_t*)v.mv_data;
size_t num_outputs = v.mv_size / sizeof(uint64_t);
amount_output_indices_set.resize(amount_output_indices_set.size() + 1);
std::vector<uint64_t> &amount_output_indices = amount_output_indices_set.back();
amount_output_indices.reserve(num_outputs);
for (size_t i = 0; i < num_outputs; ++i)
{
amount_output_indices.push_back(indices[i]);
}
}
TXN_POSTFIX_RDONLY();
return amount_output_indices_set;
}
bool BlockchainLMDB::has_key_image(const crypto::key_image& img) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
bool ret;
TXN_PREFIX_RDONLY();
RCURSOR(spent_keys);
MDB_val k = {sizeof(img), (void *)&img};
ret = (mdb_cursor_get(m_cur_spent_keys, (MDB_val *)&zerokval, &k, MDB_GET_BOTH) == 0);
TXN_POSTFIX_RDONLY();
return ret;
}
bool BlockchainLMDB::for_all_key_images(std::function<bool(const crypto::key_image&)> f) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(spent_keys);
MDB_val k, v;
bool fret = true;
k = zerokval;
MDB_cursor_op op = MDB_FIRST;
while (1)
{
int ret = mdb_cursor_get(m_cur_spent_keys, &k, &v, op);
op = MDB_NEXT;
if (ret == MDB_NOTFOUND)
break;
if (ret < 0)
throw0(DB_ERROR("Failed to enumerate key images"));
const crypto::key_image k_image = *(const crypto::key_image*)v.mv_data;
if (!f(k_image)) {
fret = false;
break;
}
}
TXN_POSTFIX_RDONLY();
return fret;
}
bool BlockchainLMDB::for_blocks_range(const uint64_t& h1, const uint64_t& h2, std::function<bool(uint64_t, const crypto::hash&, const cryptonote::block&)> f) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(blocks);
MDB_val k;
MDB_val v;
bool fret = true;
MDB_cursor_op op;
if (h1)
{
k = MDB_val{sizeof(h1), (void*)&h1};
op = MDB_SET;
} else
{
op = MDB_FIRST;
}
while (1)
{
int ret = mdb_cursor_get(m_cur_blocks, &k, &v, op);
op = MDB_NEXT;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw0(DB_ERROR("Failed to enumerate blocks"));
uint64_t height = *(const uint64_t*)k.mv_data;
blobdata_ref bd{reinterpret_cast<char*>(v.mv_data), v.mv_size};
block b;
if (!parse_and_validate_block_from_blob(bd, b))
throw0(DB_ERROR("Failed to parse block from blob retrieved from the db"));
crypto::hash hash;
if (!get_block_hash(b, hash))
throw0(DB_ERROR("Failed to get block hash from blob retrieved from the db"));
if (!f(height, hash, b)) {
fret = false;
break;
}
if (height >= h2)
break;
}
TXN_POSTFIX_RDONLY();
return fret;
}
bool BlockchainLMDB::for_all_transactions(std::function<bool(const crypto::hash&, const cryptonote::transaction&)> f, bool pruned) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(txs_pruned);
RCURSOR(txs_prunable);
RCURSOR(tx_indices);
MDB_val k;
MDB_val v;
bool fret = true;
MDB_cursor_op op = MDB_FIRST;
while (1)
{
int ret = mdb_cursor_get(m_cur_tx_indices, &k, &v, op);
op = MDB_NEXT;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw0(DB_ERROR(lmdb_error("Failed to enumerate transactions: ", ret).c_str()));
txindex *ti = (txindex *)v.mv_data;
const crypto::hash hash = ti->key;
k.mv_data = (void *)&ti->data.tx_id;
k.mv_size = sizeof(ti->data.tx_id);
ret = mdb_cursor_get(m_cur_txs_pruned, &k, &v, MDB_SET);
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw0(DB_ERROR(lmdb_error("Failed to enumerate transactions: ", ret).c_str()));
transaction tx;
if (pruned)
{
blobdata_ref bd{reinterpret_cast<char*>(v.mv_data), v.mv_size};
if (!parse_and_validate_tx_base_from_blob(bd, tx))
throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db"));
}
else
{
blobdata bd;
bd.assign(reinterpret_cast<char*>(v.mv_data), v.mv_size);
ret = mdb_cursor_get(m_cur_txs_prunable, &k, &v, MDB_SET);
if (ret)
throw0(DB_ERROR(lmdb_error("Failed to get prunable tx data the db: ", ret).c_str()));
bd.append(reinterpret_cast<char*>(v.mv_data), v.mv_size);
if (!parse_and_validate_tx_from_blob(bd, tx))
throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db"));
}
if (!f(hash, tx)) {
fret = false;
break;
}
}
TXN_POSTFIX_RDONLY();
return fret;
}
bool BlockchainLMDB::for_all_outputs(std::function<bool(uint64_t amount, const crypto::hash &tx_hash, uint64_t height, size_t tx_idx)> f) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(output_amounts);
MDB_val k;
MDB_val v;
bool fret = true;
MDB_cursor_op op = MDB_FIRST;
while (1)
{
int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, op);
op = MDB_NEXT;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw0(DB_ERROR("Failed to enumerate outputs"));
uint64_t amount = *(const uint64_t*)k.mv_data;
outkey *ok = (outkey *)v.mv_data;
tx_out_index toi = get_output_tx_and_index_from_global(ok->output_id);
if (!f(amount, toi.first, ok->data.height, toi.second)) {
fret = false;
break;
}
}
TXN_POSTFIX_RDONLY();
return fret;
}
bool BlockchainLMDB::for_all_outputs(uint64_t amount, const std::function<bool(uint64_t height)> &f) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(output_amounts);
MDB_val_set(k, amount);
MDB_val v;
bool fret = true;
MDB_cursor_op op = MDB_SET;
while (1)
{
int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, op);
op = MDB_NEXT_DUP;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw0(DB_ERROR("Failed to enumerate outputs"));
uint64_t out_amount = *(const uint64_t*)k.mv_data;
if (amount != out_amount)
{
MERROR("Amount is not the expected amount");
fret = false;
break;
}
const outkey *ok = (const outkey *)v.mv_data;
if (!f(ok->data.height)) {
fret = false;
break;
}
}
TXN_POSTFIX_RDONLY();
return fret;
}
// batch_num_blocks: (optional) Used to check if resize needed before batch transaction starts.
bool BlockchainLMDB::batch_start(uint64_t batch_num_blocks, uint64_t batch_bytes)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
if (! m_batch_transactions)
throw0(DB_ERROR("batch transactions not enabled"));
if (m_batch_active)
return false;
if (m_write_batch_txn != nullptr)
return false;
if (m_write_txn)
throw0(DB_ERROR("batch transaction attempted, but m_write_txn already in use"));
check_open();
m_writer = boost::this_thread::get_id();
check_and_resize_for_batch(batch_num_blocks, batch_bytes);
m_write_batch_txn = new mdb_txn_safe();
// NOTE: need to make sure it's destroyed properly when done
if (auto mdb_res = lmdb_txn_begin(m_env, NULL, 0, *m_write_batch_txn))
{
delete m_write_batch_txn;
m_write_batch_txn = nullptr;
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", mdb_res).c_str()));
}
// indicates this transaction is for batch transactions, but not whether it's
// active
m_write_batch_txn->m_batch_txn = true;
m_write_txn = m_write_batch_txn;
m_batch_active = true;
memset(&m_wcursors, 0, sizeof(m_wcursors));
if (m_tinfo.get())
{
if (m_tinfo->m_ti_rflags.m_rf_txn)
mdb_txn_reset(m_tinfo->m_ti_rtxn);
memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
}
LOG_PRINT_L3("batch transaction: begin");
return true;
}
void BlockchainLMDB::batch_commit()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
if (! m_batch_transactions)
throw0(DB_ERROR("batch transactions not enabled"));
if (! m_batch_active)
throw1(DB_ERROR("batch transaction not in progress"));
if (m_write_batch_txn == nullptr)
throw1(DB_ERROR("batch transaction not in progress"));
if (m_writer != boost::this_thread::get_id())
throw1(DB_ERROR("batch transaction owned by other thread"));
check_open();
LOG_PRINT_L3("batch transaction: committing...");
TIME_MEASURE_START(time1);
m_write_txn->commit();
TIME_MEASURE_FINISH(time1);
time_commit1 += time1;
LOG_PRINT_L3("batch transaction: committed");
m_write_txn = nullptr;
delete m_write_batch_txn;
m_write_batch_txn = nullptr;
memset(&m_wcursors, 0, sizeof(m_wcursors));
}
void BlockchainLMDB::cleanup_batch()
{
// for destruction of batch transaction
m_write_txn = nullptr;
delete m_write_batch_txn;
m_write_batch_txn = nullptr;
m_batch_active = false;
memset(&m_wcursors, 0, sizeof(m_wcursors));
}
void BlockchainLMDB::batch_stop()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
if (! m_batch_transactions)
throw0(DB_ERROR("batch transactions not enabled"));
if (! m_batch_active)
throw1(DB_ERROR("batch transaction not in progress"));
if (m_write_batch_txn == nullptr)
throw1(DB_ERROR("batch transaction not in progress"));
if (m_writer != boost::this_thread::get_id())
throw1(DB_ERROR("batch transaction owned by other thread"));
check_open();
LOG_PRINT_L3("batch transaction: committing...");
TIME_MEASURE_START(time1);
try
{
m_write_txn->commit();
TIME_MEASURE_FINISH(time1);
time_commit1 += time1;
cleanup_batch();
}
catch (const std::exception &e)
{
cleanup_batch();
throw;
}
LOG_PRINT_L3("batch transaction: end");
}
void BlockchainLMDB::batch_abort()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
if (! m_batch_transactions)
throw0(DB_ERROR("batch transactions not enabled"));
if (! m_batch_active)
throw1(DB_ERROR("batch transaction not in progress"));
if (m_write_batch_txn == nullptr)
throw1(DB_ERROR("batch transaction not in progress"));
if (m_writer != boost::this_thread::get_id())
throw1(DB_ERROR("batch transaction owned by other thread"));
check_open();
// for destruction of batch transaction
m_write_txn = nullptr;
// explicitly call in case mdb_env_close() (BlockchainLMDB::close()) called before BlockchainLMDB destructor called.
m_write_batch_txn->abort();
delete m_write_batch_txn;
m_write_batch_txn = nullptr;
m_batch_active = false;
memset(&m_wcursors, 0, sizeof(m_wcursors));
LOG_PRINT_L3("batch transaction: aborted");
}
void BlockchainLMDB::set_batch_transactions(bool batch_transactions)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
if ((batch_transactions) && (m_batch_transactions))
{
MINFO("batch transaction mode already enabled, but asked to enable batch mode");
}
m_batch_transactions = batch_transactions;
MINFO("batch transactions " << (m_batch_transactions ? "enabled" : "disabled"));
}
// return true if we started the txn, false if already started
bool BlockchainLMDB::block_rtxn_start(MDB_txn **mtxn, mdb_txn_cursors **mcur) const
{
bool ret = false;
mdb_threadinfo *tinfo;
if (m_write_txn && m_writer == boost::this_thread::get_id()) {
*mtxn = m_write_txn->m_txn;
*mcur = (mdb_txn_cursors *)&m_wcursors;
return ret;
}
/* Check for existing info and force reset if env doesn't match -
* only happens if env was opened/closed multiple times in same process
*/
if (!(tinfo = m_tinfo.get()) || mdb_txn_env(tinfo->m_ti_rtxn) != m_env)
{
tinfo = new mdb_threadinfo;
m_tinfo.reset(tinfo);
memset(&tinfo->m_ti_rcursors, 0, sizeof(tinfo->m_ti_rcursors));
memset(&tinfo->m_ti_rflags, 0, sizeof(tinfo->m_ti_rflags));
if (auto mdb_res = lmdb_txn_begin(m_env, NULL, MDB_RDONLY, &tinfo->m_ti_rtxn))
throw0(DB_ERROR_TXN_START(lmdb_error("Failed to create a read transaction for the db: ", mdb_res).c_str()));
ret = true;
} else if (!tinfo->m_ti_rflags.m_rf_txn)
{
if (auto mdb_res = lmdb_txn_renew(tinfo->m_ti_rtxn))
throw0(DB_ERROR_TXN_START(lmdb_error("Failed to renew a read transaction for the db: ", mdb_res).c_str()));
ret = true;
}
if (ret)
tinfo->m_ti_rflags.m_rf_txn = true;
*mtxn = tinfo->m_ti_rtxn;
*mcur = &tinfo->m_ti_rcursors;
if (ret)
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
return ret;
}
void BlockchainLMDB::block_rtxn_stop() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
mdb_txn_reset(m_tinfo->m_ti_rtxn);
memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
}
bool BlockchainLMDB::block_rtxn_start() const
{
MDB_txn *mtxn;
mdb_txn_cursors *mcur;
return block_rtxn_start(&mtxn, &mcur);
}
void BlockchainLMDB::block_wtxn_start()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
// Distinguish the exceptions here from exceptions that would be thrown while
// using the txn and committing it.
//
// If an exception is thrown in this setup, we don't want the caller to catch
// it and proceed as if there were an existing write txn, such as trying to
// call block_txn_abort(). It also indicates a serious issue which will
// probably be thrown up another layer.
if (! m_batch_active && m_write_txn)
throw0(DB_ERROR_TXN_START((std::string("Attempted to start new write txn when write txn already exists in ")+__FUNCTION__).c_str()));
if (! m_batch_active)
{
m_writer = boost::this_thread::get_id();
m_write_txn = new mdb_txn_safe();
if (auto mdb_res = lmdb_txn_begin(m_env, NULL, 0, *m_write_txn))
{
delete m_write_txn;
m_write_txn = nullptr;
throw0(DB_ERROR_TXN_START(lmdb_error("Failed to create a transaction for the db: ", mdb_res).c_str()));
}
memset(&m_wcursors, 0, sizeof(m_wcursors));
if (m_tinfo.get())
{
if (m_tinfo->m_ti_rflags.m_rf_txn)
mdb_txn_reset(m_tinfo->m_ti_rtxn);
memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
}
} else if (m_writer != boost::this_thread::get_id())
throw0(DB_ERROR_TXN_START((std::string("Attempted to start new write txn when batch txn already exists in ")+__FUNCTION__).c_str()));
}
void BlockchainLMDB::block_wtxn_stop()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
if (!m_write_txn)
throw0(DB_ERROR_TXN_START((std::string("Attempted to stop write txn when no such txn exists in ")+__FUNCTION__).c_str()));
if (m_writer != boost::this_thread::get_id())
throw0(DB_ERROR_TXN_START((std::string("Attempted to stop write txn from the wrong thread in ")+__FUNCTION__).c_str()));
{
if (! m_batch_active)
{
TIME_MEASURE_START(time1);
m_write_txn->commit();
TIME_MEASURE_FINISH(time1);
time_commit1 += time1;
delete m_write_txn;
m_write_txn = nullptr;
memset(&m_wcursors, 0, sizeof(m_wcursors));
}
}
}
void BlockchainLMDB::block_wtxn_abort()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
if (!m_write_txn)
throw0(DB_ERROR_TXN_START((std::string("Attempted to abort write txn when no such txn exists in ")+__FUNCTION__).c_str()));
if (m_writer != boost::this_thread::get_id())
throw0(DB_ERROR_TXN_START((std::string("Attempted to abort write txn from the wrong thread in ")+__FUNCTION__).c_str()));
if (! m_batch_active)
{
delete m_write_txn;
m_write_txn = nullptr;
memset(&m_wcursors, 0, sizeof(m_wcursors));
}
}
void BlockchainLMDB::block_rtxn_abort() const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
mdb_txn_reset(m_tinfo->m_ti_rtxn);
memset(&m_tinfo->m_ti_rflags, 0, sizeof(m_tinfo->m_ti_rflags));
}
uint64_t BlockchainLMDB::add_block(const std::pair<block, blobdata>& blk, size_t block_weight, uint64_t long_term_block_weight, const difficulty_type& cumulative_difficulty, const uint64_t& coins_generated,
const std::vector<std::pair<transaction, blobdata>>& txs)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
uint64_t m_height = height();
if (m_height % 1024 == 0)
{
// for batch mode, DB resize check is done at start of batch transaction
if (! m_batch_active && need_resize())
{
LOG_PRINT_L0("LMDB memory map needs to be resized, doing that now.");
do_resize();
}
}
try
{
BlockchainDB::add_block(blk, block_weight, long_term_block_weight, cumulative_difficulty, coins_generated, txs);
}
catch (const DB_ERROR_TXN_START& e)
{
throw;
}
return ++m_height;
}
void BlockchainLMDB::pop_block(block& blk, std::vector<transaction>& txs)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
block_wtxn_start();
try
{
BlockchainDB::pop_block(blk, txs);
block_wtxn_stop();
}
catch (...)
{
block_wtxn_abort();
throw;
}
}
void BlockchainLMDB::get_output_tx_and_index_from_global(const std::vector<uint64_t> &global_indices,
std::vector<tx_out_index> &tx_out_indices) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
tx_out_indices.clear();
tx_out_indices.reserve(global_indices.size());
TXN_PREFIX_RDONLY();
RCURSOR(output_txs);
for (const uint64_t &output_id : global_indices)
{
MDB_val_set(v, output_id);
auto get_result = mdb_cursor_get(m_cur_output_txs, (MDB_val *)&zerokval, &v, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
throw1(OUTPUT_DNE("output with given index not in db"));
else if (get_result)
throw0(DB_ERROR("DB error attempting to fetch output tx hash"));
const outtx *ot = (const outtx *)v.mv_data;
tx_out_indices.push_back(tx_out_index(ot->tx_hash, ot->local_index));
}
TXN_POSTFIX_RDONLY();
}
void BlockchainLMDB::get_output_key(const epee::span<const uint64_t> &amounts, const std::vector<uint64_t> &offsets, std::vector<output_data_t> &outputs, bool allow_partial) const
{
if (amounts.size() != 1 && amounts.size() != offsets.size())
throw0(DB_ERROR("Invalid sizes of amounts and offets"));
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
TIME_MEASURE_START(db3);
check_open();
outputs.clear();
outputs.reserve(offsets.size());
TXN_PREFIX_RDONLY();
RCURSOR(output_amounts);
for (size_t i = 0; i < offsets.size(); ++i)
{
const uint64_t amount = amounts.size() == 1 ? amounts[0] : amounts[i];
MDB_val_set(k, amount);
MDB_val_set(v, offsets[i]);
auto get_result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
{
if (allow_partial)
{
MDEBUG("Partial result: " << outputs.size() << "/" << offsets.size());
break;
}
throw1(OUTPUT_DNE((std::string("Attempting to get output pubkey by global index (amount ") + boost::lexical_cast<std::string>(amount) + ", index " + boost::lexical_cast<std::string>(offsets[i]) + ", count " + boost::lexical_cast<std::string>(get_num_outputs(amount)) + "), but key does not exist (current height " + boost::lexical_cast<std::string>(height()) + ")").c_str()));
}
else if (get_result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve an output pubkey from the db", get_result).c_str()));
if (amount == 0)
{
const outkey *okp = (const outkey *)v.mv_data;
outputs.push_back(okp->data);
}
else
{
const pre_rct_outkey *okp = (const pre_rct_outkey *)v.mv_data;
outputs.resize(outputs.size() + 1);
output_data_t &data = outputs.back();
memcpy(&data, &okp->data, sizeof(pre_rct_output_data_t));
data.commitment = rct::zeroCommit(amount);
}
}
TXN_POSTFIX_RDONLY();
TIME_MEASURE_FINISH(db3);
LOG_PRINT_L3("db3: " << db3);
}
void BlockchainLMDB::get_output_tx_and_index(const uint64_t& amount, const std::vector<uint64_t> &offsets, std::vector<tx_out_index> &indices) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
indices.clear();
std::vector <uint64_t> tx_indices;
tx_indices.reserve(offsets.size());
TXN_PREFIX_RDONLY();
RCURSOR(output_amounts);
MDB_val_set(k, amount);
for (const uint64_t &index : offsets)
{
MDB_val_set(v, index);
auto get_result = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_GET_BOTH);
if (get_result == MDB_NOTFOUND)
throw1(OUTPUT_DNE("Attempting to get output by index, but key does not exist"));
else if (get_result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve an output from the db", get_result).c_str()));
const outkey *okp = (const outkey *)v.mv_data;
tx_indices.push_back(okp->output_id);
}
TIME_MEASURE_START(db3);
if(tx_indices.size() > 0)
{
get_output_tx_and_index_from_global(tx_indices, indices);
}
TIME_MEASURE_FINISH(db3);
LOG_PRINT_L3("db3: " << db3);
}
std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> BlockchainLMDB::get_output_histogram(const std::vector<uint64_t> &amounts, bool unlocked, uint64_t recent_cutoff, uint64_t min_count) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(output_amounts);
std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>> histogram;
MDB_val k;
MDB_val v;
if (amounts.empty())
{
MDB_cursor_op op = MDB_FIRST;
while (1)
{
int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, op);
op = MDB_NEXT_NODUP;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw0(DB_ERROR(lmdb_error("Failed to enumerate outputs: ", ret).c_str()));
mdb_size_t num_elems = 0;
mdb_cursor_count(m_cur_output_amounts, &num_elems);
uint64_t amount = *(const uint64_t*)k.mv_data;
if (num_elems >= min_count)
histogram[amount] = std::make_tuple(num_elems, 0, 0);
}
}
else
{
for (const auto &amount: amounts)
{
MDB_val_copy<uint64_t> k(amount);
int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, MDB_SET);
if (ret == MDB_NOTFOUND)
{
if (0 >= min_count)
histogram[amount] = std::make_tuple(0, 0, 0);
}
else if (ret == MDB_SUCCESS)
{
mdb_size_t num_elems = 0;
mdb_cursor_count(m_cur_output_amounts, &num_elems);
if (num_elems >= min_count)
histogram[amount] = std::make_tuple(num_elems, 0, 0);
}
else
{
throw0(DB_ERROR(lmdb_error("Failed to enumerate outputs: ", ret).c_str()));
}
}
}
if (unlocked || recent_cutoff > 0) {
const uint64_t blockchain_height = height();
for (std::map<uint64_t, std::tuple<uint64_t, uint64_t, uint64_t>>::iterator i = histogram.begin(); i != histogram.end(); ++i) {
uint64_t amount = i->first;
uint64_t num_elems = std::get<0>(i->second);
while (num_elems > 0) {
const tx_out_index toi = get_output_tx_and_index(amount, num_elems - 1);
const uint64_t height = get_tx_block_height(toi.first);
if (height + CRYPTONOTE_DEFAULT_TX_SPENDABLE_AGE <= blockchain_height)
break;
--num_elems;
}
// modifying second does not invalidate the iterator
std::get<1>(i->second) = num_elems;
if (recent_cutoff > 0)
{
uint64_t recent = 0;
while (num_elems > 0) {
const tx_out_index toi = get_output_tx_and_index(amount, num_elems - 1);
const uint64_t height = get_tx_block_height(toi.first);
const uint64_t ts = get_block_timestamp(height);
if (ts < recent_cutoff)
break;
--num_elems;
++recent;
}
// modifying second does not invalidate the iterator
std::get<2>(i->second) = recent;
}
}
}
TXN_POSTFIX_RDONLY();
return histogram;
}
bool BlockchainLMDB::get_output_distribution(uint64_t amount, uint64_t from_height, uint64_t to_height, std::vector<uint64_t> &distribution, uint64_t &base) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(output_amounts);
distribution.clear();
const uint64_t db_height = height();
if (from_height >= db_height)
return false;
distribution.resize(db_height - from_height, 0);
bool fret = true;
MDB_val_set(k, amount);
MDB_val v;
MDB_cursor_op op = MDB_SET;
base = 0;
while (1)
{
int ret = mdb_cursor_get(m_cur_output_amounts, &k, &v, op);
op = MDB_NEXT_DUP;
if (ret == MDB_NOTFOUND)
break;
if (ret)
throw0(DB_ERROR("Failed to enumerate outputs"));
const outkey *ok = (const outkey *)v.mv_data;
const uint64_t height = ok->data.height;
if (height >= from_height)
distribution[height - from_height]++;
else
base++;
if (to_height > 0 && height > to_height)
break;
}
distribution[0] += base;
for (size_t n = 1; n < distribution.size(); ++n)
distribution[n] += distribution[n - 1];
base = 0;
TXN_POSTFIX_RDONLY();
return true;
}
void BlockchainLMDB::check_hard_fork_info()
{
}
void BlockchainLMDB::drop_hard_fork_info()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX(0);
auto result = mdb_drop(*txn_ptr, m_hf_starting_heights, 1);
if (result)
throw1(DB_ERROR(lmdb_error("Error dropping hard fork starting heights db: ", result).c_str()));
result = mdb_drop(*txn_ptr, m_hf_versions, 1);
if (result)
throw1(DB_ERROR(lmdb_error("Error dropping hard fork versions db: ", result).c_str()));
TXN_POSTFIX_SUCCESS();
}
void BlockchainLMDB::set_hard_fork_version(uint64_t height, uint8_t version)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_BLOCK_PREFIX(0);
MDB_val_copy<uint64_t> val_key(height);
MDB_val_copy<uint8_t> val_value(version);
int result;
result = mdb_put(*txn_ptr, m_hf_versions, &val_key, &val_value, MDB_APPEND);
if (result == MDB_KEYEXIST)
result = mdb_put(*txn_ptr, m_hf_versions, &val_key, &val_value, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Error adding hard fork version to db transaction: ", result).c_str()));
TXN_BLOCK_POSTFIX_SUCCESS();
}
uint8_t BlockchainLMDB::get_hard_fork_version(uint64_t height) const
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(hf_versions);
MDB_val_copy<uint64_t> val_key(height);
MDB_val val_ret;
auto result = mdb_cursor_get(m_cur_hf_versions, &val_key, &val_ret, MDB_SET);
if (result == MDB_NOTFOUND || result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve a hard fork version at height " + boost::lexical_cast<std::string>(height) + " from the db: ", result).c_str()));
uint8_t ret = *(const uint8_t*)val_ret.mv_data;
TXN_POSTFIX_RDONLY();
return ret;
}
void BlockchainLMDB::add_alt_block(const crypto::hash &blkid, const cryptonote::alt_block_data_t &data, const cryptonote::blobdata_ref &blob)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(alt_blocks)
MDB_val k = {sizeof(blkid), (void *)&blkid};
const size_t val_size = sizeof(alt_block_data_t) + blob.size();
std::unique_ptr<char[]> val(new char[val_size]);
memcpy(val.get(), &data, sizeof(alt_block_data_t));
memcpy(val.get() + sizeof(alt_block_data_t), blob.data(), blob.size());
MDB_val v = {val_size, (void *)val.get()};
if (auto result = mdb_cursor_put(m_cur_alt_blocks, &k, &v, MDB_NODUPDATA)) {
if (result == MDB_KEYEXIST)
throw1(DB_ERROR("Attempting to add alternate block that's already in the db"));
else
throw1(DB_ERROR(lmdb_error("Error adding alternate block to db transaction: ", result).c_str()));
}
}
bool BlockchainLMDB::get_alt_block(const crypto::hash &blkid, alt_block_data_t *data, cryptonote::blobdata *blob)
{
LOG_PRINT_L3("BlockchainLMDB:: " << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(alt_blocks);
MDB_val_set(k, blkid);
MDB_val v;
int result = mdb_cursor_get(m_cur_alt_blocks, &k, &v, MDB_SET);
if (result == MDB_NOTFOUND)
return false;
if (result)
throw0(DB_ERROR(lmdb_error("Error attempting to retrieve alternate block " + epee::string_tools::pod_to_hex(blkid) + " from the db: ", result).c_str()));
if (v.mv_size < sizeof(alt_block_data_t))
throw0(DB_ERROR("Record size is less than expected"));
const alt_block_data_t *ptr = (const alt_block_data_t*)v.mv_data;
if (data)
*data = *ptr;
if (blob)
blob->assign((const char*)(ptr + 1), v.mv_size - sizeof(alt_block_data_t));
TXN_POSTFIX_RDONLY();
return true;
}
void BlockchainLMDB::remove_alt_block(const crypto::hash &blkid)
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
mdb_txn_cursors *m_cursors = &m_wcursors;
CURSOR(alt_blocks)
MDB_val k = {sizeof(blkid), (void *)&blkid};
MDB_val v;
int result = mdb_cursor_get(m_cur_alt_blocks, &k, &v, MDB_SET);
if (result)
throw0(DB_ERROR(lmdb_error("Error locating alternate block " + epee::string_tools::pod_to_hex(blkid) + " in the db: ", result).c_str()));
result = mdb_cursor_del(m_cur_alt_blocks, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Error deleting alternate block " + epee::string_tools::pod_to_hex(blkid) + " from the db: ", result).c_str()));
}
uint64_t BlockchainLMDB::get_alt_block_count()
{
LOG_PRINT_L3("BlockchainLMDB:: " << __func__);
check_open();
TXN_PREFIX_RDONLY();
RCURSOR(alt_blocks);
MDB_stat db_stats;
int result = mdb_stat(m_txn, m_alt_blocks, &db_stats);
uint64_t count = 0;
if (result != MDB_NOTFOUND)
{
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query m_alt_blocks: ", result).c_str()));
count = db_stats.ms_entries;
}
TXN_POSTFIX_RDONLY();
return count;
}
void BlockchainLMDB::drop_alt_blocks()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
check_open();
TXN_PREFIX(0);
auto result = mdb_drop(*txn_ptr, m_alt_blocks, 0);
if (result)
throw1(DB_ERROR(lmdb_error("Error dropping alternative blocks: ", result).c_str()));
TXN_POSTFIX_SUCCESS();
}
bool BlockchainLMDB::is_read_only() const
{
unsigned int flags;
auto result = mdb_env_get_flags(m_env, &flags);
if (result)
throw0(DB_ERROR(lmdb_error("Error getting database environment info: ", result).c_str()));
if (flags & MDB_RDONLY)
return true;
return false;
}
uint64_t BlockchainLMDB::get_database_size() const
{
uint64_t size = 0;
boost::filesystem::path datafile(m_folder);
datafile /= CRYPTONOTE_BLOCKCHAINDATA_FILENAME;
if (!epee::file_io_utils::get_file_size(datafile.string(), size))
size = 0;
return size;
}
void BlockchainLMDB::fixup()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
// Always call parent as well
BlockchainDB::fixup();
}
#define RENAME_DB(name) do { \
char n2[] = name; \
MDB_dbi tdbi; \
n2[sizeof(n2)-2]--; \
/* play some games to put (name) on a writable page */ \
result = mdb_dbi_open(txn, n2, MDB_CREATE, &tdbi); \
if (result) \
throw0(DB_ERROR(lmdb_error("Failed to create " + std::string(n2) + ": ", result).c_str())); \
result = mdb_drop(txn, tdbi, 1); \
if (result) \
throw0(DB_ERROR(lmdb_error("Failed to delete " + std::string(n2) + ": ", result).c_str())); \
k.mv_data = (void *)name; \
k.mv_size = sizeof(name)-1; \
result = mdb_cursor_open(txn, 1, &c_cur); \
if (result) \
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for " name ": ", result).c_str())); \
result = mdb_cursor_get(c_cur, &k, NULL, MDB_SET_KEY); \
if (result) \
throw0(DB_ERROR(lmdb_error("Failed to get DB record for " name ": ", result).c_str())); \
ptr = (char *)k.mv_data; \
ptr[sizeof(name)-2]++; } while(0)
#define LOGIF(y) if (ELPP->vRegistry()->allowed(y, "global"))
void BlockchainLMDB::migrate_0_1()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
uint64_t i, z, m_height;
int result;
mdb_txn_safe txn(false);
MDB_val k, v;
char *ptr;
MGINFO_YELLOW("Migrating blockchain from DB version 0 to 1 - this may take a while:");
MINFO("updating blocks, hf_versions, outputs, txs, and spent_keys tables...");
do {
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
MDB_stat db_stats;
if ((result = mdb_stat(txn, m_blocks, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
m_height = db_stats.ms_entries;
MINFO("Total number of blocks: " << m_height);
MINFO("block migration will update block_heights, block_info, and hf_versions...");
MINFO("migrating block_heights:");
MDB_dbi o_heights;
unsigned int flags;
result = mdb_dbi_flags(txn, m_block_heights, &flags);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to retrieve block_heights flags: ", result).c_str()));
/* if the flags are what we expect, this table has already been migrated */
if ((flags & (MDB_INTEGERKEY|MDB_DUPSORT|MDB_DUPFIXED)) == (MDB_INTEGERKEY|MDB_DUPSORT|MDB_DUPFIXED)) {
txn.abort();
LOG_PRINT_L1(" block_heights already migrated");
break;
}
/* the block_heights table name is the same but the old version and new version
* have incompatible DB flags. Create a new table with the right flags. We want
* the name to be similar to the old name so that it will occupy the same location
* in the DB.
*/
o_heights = m_block_heights;
lmdb_db_open(txn, "block_heightr", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_heights, "Failed to open db handle for block_heightr");
mdb_set_dupsort(txn, m_block_heights, compare_hash32);
MDB_cursor *c_old, *c_cur;
blk_height bh;
MDB_val_set(nv, bh);
/* old table was k(hash), v(height).
* new table is DUPFIXED, k(zeroval), v{hash, height}.
*/
i = 0;
z = m_height;
while(1) {
if (!(i % 2000)) {
if (i) {
LOGIF(el::Level::Info) {
std::cout << i << " / " << z << " \r" << std::flush;
}
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
}
result = mdb_cursor_open(txn, m_block_heights, &c_cur);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_heightr: ", result).c_str()));
result = mdb_cursor_open(txn, o_heights, &c_old);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_heights: ", result).c_str()));
if (!i) {
MDB_stat ms;
result = mdb_stat(txn, m_block_heights, &ms);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query block_heights table: ", result).c_str()));
i = ms.ms_entries;
}
}
result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
if (result == MDB_NOTFOUND) {
txn.commit();
break;
}
else if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from block_heights: ", result).c_str()));
bh.bh_hash = *(crypto::hash *)k.mv_data;
bh.bh_height = *(uint64_t *)v.mv_data;
result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to put a record into block_heightr: ", result).c_str()));
/* we delete the old records immediately, so the overall DB and mapsize should not grow.
* This is a little slower than just letting mdb_drop() delete it all at the end, but
* it saves a significant amount of disk space.
*/
result = mdb_cursor_del(c_old, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_heights: ", result).c_str()));
i++;
}
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
/* Delete the old table */
result = mdb_drop(txn, o_heights, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete old block_heights table: ", result).c_str()));
RENAME_DB("block_heightr");
/* close and reopen to get old dbi slot back */
mdb_dbi_close(m_env, m_block_heights);
lmdb_db_open(txn, "block_heights", MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED, m_block_heights, "Failed to open db handle for block_heights");
mdb_set_dupsort(txn, m_block_heights, compare_hash32);
txn.commit();
} while(0);
/* old tables are k(height), v(value).
* new table is DUPFIXED, k(zeroval), v{height, values...}.
*/
do {
LOG_PRINT_L1("migrating block info:");
MDB_dbi coins;
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_dbi_open(txn, "block_coins", 0, &coins);
if (result == MDB_NOTFOUND) {
txn.abort();
LOG_PRINT_L1(" block_info already migrated");
break;
}
MDB_dbi diffs, hashes, sizes, timestamps;
mdb_block_info_1 bi;
MDB_val_set(nv, bi);
lmdb_db_open(txn, "block_diffs", 0, diffs, "Failed to open db handle for block_diffs");
lmdb_db_open(txn, "block_hashes", 0, hashes, "Failed to open db handle for block_hashes");
lmdb_db_open(txn, "block_sizes", 0, sizes, "Failed to open db handle for block_sizes");
lmdb_db_open(txn, "block_timestamps", 0, timestamps, "Failed to open db handle for block_timestamps");
MDB_cursor *c_cur, *c_coins, *c_diffs, *c_hashes, *c_sizes, *c_timestamps;
i = 0;
z = m_height;
while(1) {
MDB_val k, v;
if (!(i % 2000)) {
if (i) {
LOGIF(el::Level::Info) {
std::cout << i << " / " << z << " \r" << std::flush;
}
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
}
result = mdb_cursor_open(txn, m_block_info, &c_cur);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_info: ", result).c_str()));
result = mdb_cursor_open(txn, coins, &c_coins);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_coins: ", result).c_str()));
result = mdb_cursor_open(txn, diffs, &c_diffs);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_diffs: ", result).c_str()));
result = mdb_cursor_open(txn, hashes, &c_hashes);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_hashes: ", result).c_str()));
result = mdb_cursor_open(txn, sizes, &c_sizes);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_coins: ", result).c_str()));
result = mdb_cursor_open(txn, timestamps, &c_timestamps);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_timestamps: ", result).c_str()));
if (!i) {
MDB_stat ms;
result = mdb_stat(txn, m_block_info, &ms);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query block_info table: ", result).c_str()));
i = ms.ms_entries;
}
}
result = mdb_cursor_get(c_coins, &k, &v, MDB_NEXT);
if (result == MDB_NOTFOUND) {
break;
} else if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from block_coins: ", result).c_str()));
bi.bi_height = *(uint64_t *)k.mv_data;
bi.bi_coins = *(uint64_t *)v.mv_data;
result = mdb_cursor_get(c_diffs, &k, &v, MDB_NEXT);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from block_diffs: ", result).c_str()));
bi.bi_diff = *(uint64_t *)v.mv_data;
result = mdb_cursor_get(c_hashes, &k, &v, MDB_NEXT);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from block_hashes: ", result).c_str()));
bi.bi_hash = *(crypto::hash *)v.mv_data;
result = mdb_cursor_get(c_sizes, &k, &v, MDB_NEXT);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from block_sizes: ", result).c_str()));
if (v.mv_size == sizeof(uint32_t))
bi.bi_weight = *(uint32_t *)v.mv_data;
else
bi.bi_weight = *(uint64_t *)v.mv_data; // this is a 32/64 compat bug in version 0
result = mdb_cursor_get(c_timestamps, &k, &v, MDB_NEXT);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from block_timestamps: ", result).c_str()));
bi.bi_timestamp = *(uint64_t *)v.mv_data;
result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to put a record into block_info: ", result).c_str()));
result = mdb_cursor_del(c_coins, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_coins: ", result).c_str()));
result = mdb_cursor_del(c_diffs, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_diffs: ", result).c_str()));
result = mdb_cursor_del(c_hashes, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_hashes: ", result).c_str()));
result = mdb_cursor_del(c_sizes, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_sizes: ", result).c_str()));
result = mdb_cursor_del(c_timestamps, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_timestamps: ", result).c_str()));
i++;
}
mdb_cursor_close(c_timestamps);
mdb_cursor_close(c_sizes);
mdb_cursor_close(c_hashes);
mdb_cursor_close(c_diffs);
mdb_cursor_close(c_coins);
result = mdb_drop(txn, timestamps, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete block_timestamps from the db: ", result).c_str()));
result = mdb_drop(txn, sizes, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete block_sizes from the db: ", result).c_str()));
result = mdb_drop(txn, hashes, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete block_hashes from the db: ", result).c_str()));
result = mdb_drop(txn, diffs, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete block_diffs from the db: ", result).c_str()));
result = mdb_drop(txn, coins, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete block_coins from the db: ", result).c_str()));
txn.commit();
} while(0);
do {
LOG_PRINT_L1("migrating hf_versions:");
MDB_dbi o_hfv;
unsigned int flags;
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_dbi_flags(txn, m_hf_versions, &flags);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to retrieve hf_versions flags: ", result).c_str()));
/* if the flags are what we expect, this table has already been migrated */
if (flags & MDB_INTEGERKEY) {
txn.abort();
LOG_PRINT_L1(" hf_versions already migrated");
break;
}
/* the hf_versions table name is the same but the old version and new version
* have incompatible DB flags. Create a new table with the right flags.
*/
o_hfv = m_hf_versions;
lmdb_db_open(txn, "hf_versionr", MDB_INTEGERKEY | MDB_CREATE, m_hf_versions, "Failed to open db handle for hf_versionr");
MDB_cursor *c_old, *c_cur;
i = 0;
z = m_height;
while(1) {
if (!(i % 2000)) {
if (i) {
LOGIF(el::Level::Info) {
std::cout << i << " / " << z << " \r" << std::flush;
}
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
}
result = mdb_cursor_open(txn, m_hf_versions, &c_cur);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for spent_keyr: ", result).c_str()));
result = mdb_cursor_open(txn, o_hfv, &c_old);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for spent_keys: ", result).c_str()));
if (!i) {
MDB_stat ms;
result = mdb_stat(txn, m_hf_versions, &ms);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query hf_versions table: ", result).c_str()));
i = ms.ms_entries;
}
}
result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
if (result == MDB_NOTFOUND) {
txn.commit();
break;
}
else if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from hf_versions: ", result).c_str()));
result = mdb_cursor_put(c_cur, &k, &v, MDB_APPEND);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to put a record into hf_versionr: ", result).c_str()));
result = mdb_cursor_del(c_old, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from hf_versions: ", result).c_str()));
i++;
}
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
/* Delete the old table */
result = mdb_drop(txn, o_hfv, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete old hf_versions table: ", result).c_str()));
RENAME_DB("hf_versionr");
mdb_dbi_close(m_env, m_hf_versions);
lmdb_db_open(txn, "hf_versions", MDB_INTEGERKEY, m_hf_versions, "Failed to open db handle for hf_versions");
txn.commit();
} while(0);
do {
LOG_PRINT_L1("deleting old indices:");
/* Delete all other tables, we're just going to recreate them */
MDB_dbi dbi;
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_dbi_open(txn, "tx_unlocks", 0, &dbi);
if (result == MDB_NOTFOUND) {
txn.abort();
LOG_PRINT_L1(" old indices already deleted");
break;
}
txn.abort();
#define DELETE_DB(x) do { \
LOG_PRINT_L1(" " x ":"); \
result = mdb_txn_begin(m_env, NULL, 0, txn); \
if (result) \
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str())); \
result = mdb_dbi_open(txn, x, 0, &dbi); \
if (!result) { \
result = mdb_drop(txn, dbi, 1); \
if (result) \
throw0(DB_ERROR(lmdb_error("Failed to delete " x ": ", result).c_str())); \
txn.commit(); \
} } while(0)
DELETE_DB("tx_heights");
DELETE_DB("output_txs");
DELETE_DB("output_indices");
DELETE_DB("output_keys");
DELETE_DB("spent_keys");
DELETE_DB("output_amounts");
DELETE_DB("tx_outputs");
DELETE_DB("tx_unlocks");
/* reopen new DBs with correct flags */
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
lmdb_db_open(txn, LMDB_OUTPUT_TXS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_output_txs, "Failed to open db handle for m_output_txs");
mdb_set_dupsort(txn, m_output_txs, compare_uint64);
lmdb_db_open(txn, LMDB_TX_OUTPUTS, MDB_INTEGERKEY | MDB_CREATE, m_tx_outputs, "Failed to open db handle for m_tx_outputs");
lmdb_db_open(txn, LMDB_SPENT_KEYS, MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_spent_keys, "Failed to open db handle for m_spent_keys");
mdb_set_dupsort(txn, m_spent_keys, compare_hash32);
lmdb_db_open(txn, LMDB_OUTPUT_AMOUNTS, MDB_INTEGERKEY | MDB_DUPSORT | MDB_DUPFIXED | MDB_CREATE, m_output_amounts, "Failed to open db handle for m_output_amounts");
mdb_set_dupsort(txn, m_output_amounts, compare_uint64);
txn.commit();
} while(0);
do {
LOG_PRINT_L1("migrating txs and outputs:");
unsigned int flags;
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_dbi_flags(txn, m_txs, &flags);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to retrieve txs flags: ", result).c_str()));
/* if the flags are what we expect, this table has already been migrated */
if (flags & MDB_INTEGERKEY) {
txn.abort();
LOG_PRINT_L1(" txs already migrated");
break;
}
MDB_dbi o_txs;
blobdata_ref bd;
block b;
MDB_val hk;
o_txs = m_txs;
mdb_set_compare(txn, o_txs, compare_hash32);
lmdb_db_open(txn, "txr", MDB_INTEGERKEY | MDB_CREATE, m_txs, "Failed to open db handle for txr");
txn.commit();
MDB_cursor *c_blocks, *c_txs, *c_props, *c_cur;
i = 0;
z = m_height;
hk.mv_size = sizeof(crypto::hash);
set_batch_transactions(true);
batch_start(1000);
txn.m_txn = m_write_txn->m_txn;
m_height = 0;
while(1) {
if (!(i % 1000)) {
if (i) {
LOGIF(el::Level::Info) {
std::cout << i << " / " << z << " \r" << std::flush;
}
MDB_val_set(pk, "txblk");
MDB_val_set(pv, m_height);
result = mdb_cursor_put(c_props, &pk, &pv, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to update txblk property: ", result).c_str()));
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
m_write_txn->m_txn = txn.m_txn;
m_write_batch_txn->m_txn = txn.m_txn;
memset(&m_wcursors, 0, sizeof(m_wcursors));
}
result = mdb_cursor_open(txn, m_blocks, &c_blocks);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for blocks: ", result).c_str()));
result = mdb_cursor_open(txn, m_properties, &c_props);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for properties: ", result).c_str()));
result = mdb_cursor_open(txn, o_txs, &c_txs);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs: ", result).c_str()));
if (!i) {
MDB_stat ms;
result = mdb_stat(txn, m_txs, &ms);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query txs table: ", result).c_str()));
i = ms.ms_entries;
if (i) {
MDB_val_set(pk, "txblk");
result = mdb_cursor_get(c_props, &pk, &k, MDB_SET);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from properties: ", result).c_str()));
m_height = *(uint64_t *)k.mv_data;
}
}
if (i) {
result = mdb_cursor_get(c_blocks, &k, &v, MDB_SET);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from blocks: ", result).c_str()));
}
}
result = mdb_cursor_get(c_blocks, &k, &v, MDB_NEXT);
if (result == MDB_NOTFOUND) {
MDB_val_set(pk, "txblk");
result = mdb_cursor_get(c_props, &pk, &v, MDB_SET);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from props: ", result).c_str()));
result = mdb_cursor_del(c_props, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from props: ", result).c_str()));
batch_stop();
break;
} else if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from blocks: ", result).c_str()));
bd = {reinterpret_cast<char*>(v.mv_data), v.mv_size};
if (!parse_and_validate_block_from_blob(bd, b))
throw0(DB_ERROR("Failed to parse block from blob retrieved from the db"));
add_transaction(null_hash, std::make_pair(b.miner_tx, tx_to_blob(b.miner_tx)));
for (unsigned int j = 0; j<b.tx_hashes.size(); j++) {
transaction tx;
hk.mv_data = &b.tx_hashes[j];
result = mdb_cursor_get(c_txs, &hk, &v, MDB_SET);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to get record from txs: ", result).c_str()));
bd = {reinterpret_cast<char*>(v.mv_data), v.mv_size};
if (!parse_and_validate_tx_from_blob(bd, tx))
throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db"));
add_transaction(null_hash, std::make_pair(std::move(tx), bd), &b.tx_hashes[j]);
result = mdb_cursor_del(c_txs, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to get record from txs: ", result).c_str()));
}
i++;
m_height = i;
}
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_drop(txn, o_txs, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete txs from the db: ", result).c_str()));
RENAME_DB("txr");
mdb_dbi_close(m_env, m_txs);
lmdb_db_open(txn, "txs", MDB_INTEGERKEY, m_txs, "Failed to open db handle for txs");
txn.commit();
} while(0);
uint32_t version = 1;
v.mv_data = (void *)&version;
v.mv_size = sizeof(version);
MDB_val_str(vk, "version");
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_put(txn, m_properties, &vk, &v, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
txn.commit();
}
void BlockchainLMDB::migrate_1_2()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
uint64_t i, z;
int result;
mdb_txn_safe txn(false);
MDB_val k, v;
char *ptr;
MGINFO_YELLOW("Migrating blockchain from DB version 1 to 2 - this may take a while:");
MINFO("updating txs_pruned and txs_prunable tables...");
do {
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
MDB_stat db_stats_txs;
MDB_stat db_stats_txs_pruned;
MDB_stat db_stats_txs_prunable;
MDB_stat db_stats_txs_prunable_hash;
if ((result = mdb_stat(txn, m_txs, &db_stats_txs)))
throw0(DB_ERROR(lmdb_error("Failed to query m_txs: ", result).c_str()));
if ((result = mdb_stat(txn, m_txs_pruned, &db_stats_txs_pruned)))
throw0(DB_ERROR(lmdb_error("Failed to query m_txs_pruned: ", result).c_str()));
if ((result = mdb_stat(txn, m_txs_prunable, &db_stats_txs_prunable)))
throw0(DB_ERROR(lmdb_error("Failed to query m_txs_prunable: ", result).c_str()));
if ((result = mdb_stat(txn, m_txs_prunable_hash, &db_stats_txs_prunable_hash)))
throw0(DB_ERROR(lmdb_error("Failed to query m_txs_prunable_hash: ", result).c_str()));
if (db_stats_txs_pruned.ms_entries != db_stats_txs_prunable.ms_entries)
throw0(DB_ERROR("Mismatched sizes for txs_pruned and txs_prunable"));
if (db_stats_txs_pruned.ms_entries == db_stats_txs.ms_entries)
{
txn.commit();
MINFO("txs already migrated");
break;
}
MINFO("updating txs tables:");
MDB_cursor *c_old, *c_cur0, *c_cur1, *c_cur2;
i = 0;
while(1) {
if (!(i % 1000)) {
if (i) {
result = mdb_stat(txn, m_txs, &db_stats_txs);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query m_txs: ", result).c_str()));
LOGIF(el::Level::Info) {
std::cout << i << " / " << (i + db_stats_txs.ms_entries) << " \r" << std::flush;
}
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
}
result = mdb_cursor_open(txn, m_txs_pruned, &c_cur0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_pruned: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_prunable, &c_cur1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs_prunable_hash, &c_cur2);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs_prunable_hash: ", result).c_str()));
result = mdb_cursor_open(txn, m_txs, &c_old);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for txs: ", result).c_str()));
if (!i) {
i = db_stats_txs_pruned.ms_entries;
}
}
MDB_val_set(k, i);
result = mdb_cursor_get(c_old, &k, &v, MDB_SET);
if (result == MDB_NOTFOUND) {
txn.commit();
break;
}
else if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from txs: ", result).c_str()));
cryptonote::blobdata bd{reinterpret_cast<char*>(v.mv_data), v.mv_size};
transaction tx;
if (!parse_and_validate_tx_from_blob(bd, tx))
throw0(DB_ERROR("Failed to parse tx from blob retrieved from the db"));
std::stringstream ss;
binary_archive<true> ba(ss);
bool r = tx.serialize_base(ba);
if (!r)
throw0(DB_ERROR("Failed to serialize pruned tx"));
std::string pruned = ss.str();
if (pruned.size() > bd.size())
throw0(DB_ERROR("Pruned tx is larger than raw tx"));
if (memcmp(pruned.data(), bd.data(), pruned.size()))
throw0(DB_ERROR("Pruned tx is not a prefix of the raw tx"));
MDB_val nv;
nv.mv_data = (void*)pruned.data();
nv.mv_size = pruned.size();
result = mdb_cursor_put(c_cur0, (MDB_val *)&k, &nv, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to put a record into txs_pruned: ", result).c_str()));
nv.mv_data = (void*)(bd.data() + pruned.size());
nv.mv_size = bd.size() - pruned.size();
result = mdb_cursor_put(c_cur1, (MDB_val *)&k, &nv, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to put a record into txs_prunable: ", result).c_str()));
if (tx.version > 1)
{
crypto::hash prunable_hash = get_transaction_prunable_hash(tx);
MDB_val_set(val_prunable_hash, prunable_hash);
result = mdb_cursor_put(c_cur2, (MDB_val *)&k, &val_prunable_hash, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to put a record into txs_prunable_hash: ", result).c_str()));
}
result = mdb_cursor_del(c_old, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from txs: ", result).c_str()));
i++;
}
} while(0);
uint32_t version = 2;
v.mv_data = (void *)&version;
v.mv_size = sizeof(version);
MDB_val_str(vk, "version");
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_put(txn, m_properties, &vk, &v, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
txn.commit();
}
void BlockchainLMDB::migrate_2_3()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
uint64_t i;
int result;
mdb_txn_safe txn(false);
MDB_val k, v;
char *ptr;
MGINFO_YELLOW("Migrating blockchain from DB version 2 to 3 - this may take a while:");
do {
LOG_PRINT_L1("migrating block info:");
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
MDB_stat db_stats;
if ((result = mdb_stat(txn, m_blocks, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
const uint64_t blockchain_height = db_stats.ms_entries;
MDEBUG("enumerating rct outputs...");
std::vector<uint64_t> distribution(blockchain_height, 0);
bool r = for_all_outputs(0, [&](uint64_t height) {
if (height >= blockchain_height)
{
MERROR("Output found claiming height >= blockchain height");
return false;
}
distribution[height]++;
return true;
});
if (!r)
throw0(DB_ERROR("Failed to build rct output distribution"));
for (size_t i = 1; i < distribution.size(); ++i)
distribution[i] += distribution[i - 1];
/* the block_info table name is the same but the old version and new version
* have incompatible data. Create a new table. We want the name to be similar
* to the old name so that it will occupy the same location in the DB.
*/
MDB_dbi o_block_info = m_block_info;
lmdb_db_open(txn, "block_infn", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
mdb_set_dupsort(txn, m_block_info, compare_uint64);
MDB_cursor *c_old, *c_cur;
i = 0;
while(1) {
if (!(i % 1000)) {
if (i) {
LOGIF(el::Level::Info) {
std::cout << i << " / " << blockchain_height << " \r" << std::flush;
}
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
}
result = mdb_cursor_open(txn, m_block_info, &c_cur);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_infn: ", result).c_str()));
result = mdb_cursor_open(txn, o_block_info, &c_old);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_info: ", result).c_str()));
if (!i) {
MDB_stat db_stat;
result = mdb_stat(txn, m_block_info, &db_stats);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query m_block_info: ", result).c_str()));
i = db_stats.ms_entries;
}
}
result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
if (result == MDB_NOTFOUND) {
txn.commit();
break;
}
else if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from block_info: ", result).c_str()));
const mdb_block_info_1 *bi_old = (const mdb_block_info_1*)v.mv_data;
mdb_block_info_2 bi;
bi.bi_height = bi_old->bi_height;
bi.bi_timestamp = bi_old->bi_timestamp;
bi.bi_coins = bi_old->bi_coins;
bi.bi_weight = bi_old->bi_weight;
bi.bi_diff = bi_old->bi_diff;
bi.bi_hash = bi_old->bi_hash;
if (bi_old->bi_height >= distribution.size())
throw0(DB_ERROR("Bad height in block_info record"));
bi.bi_cum_rct = distribution[bi_old->bi_height];
MDB_val_set(nv, bi);
result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to put a record into block_infn: ", result).c_str()));
/* we delete the old records immediately, so the overall DB and mapsize should not grow.
* This is a little slower than just letting mdb_drop() delete it all at the end, but
* it saves a significant amount of disk space.
*/
result = mdb_cursor_del(c_old, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_info: ", result).c_str()));
i++;
}
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
/* Delete the old table */
result = mdb_drop(txn, o_block_info, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete old block_info table: ", result).c_str()));
RENAME_DB("block_infn");
mdb_dbi_close(m_env, m_block_info);
lmdb_db_open(txn, "block_info", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
mdb_set_dupsort(txn, m_block_info, compare_uint64);
txn.commit();
} while(0);
uint32_t version = 3;
v.mv_data = (void *)&version;
v.mv_size = sizeof(version);
MDB_val_str(vk, "version");
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_put(txn, m_properties, &vk, &v, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
txn.commit();
}
void BlockchainLMDB::migrate_3_4()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
uint64_t i;
int result;
mdb_txn_safe txn(false);
MDB_val k, v;
char *ptr;
bool past_long_term_weight = false;
MGINFO_YELLOW("Migrating blockchain from DB version 3 to 4 - this may take a while:");
do {
LOG_PRINT_L1("migrating block info:");
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
MDB_stat db_stats;
if ((result = mdb_stat(txn, m_blocks, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
const uint64_t blockchain_height = db_stats.ms_entries;
boost::circular_buffer<uint64_t> long_term_block_weights(CRYPTONOTE_LONG_TERM_BLOCK_WEIGHT_WINDOW_SIZE);
/* the block_info table name is the same but the old version and new version
* have incompatible data. Create a new table. We want the name to be similar
* to the old name so that it will occupy the same location in the DB.
*/
MDB_dbi o_block_info = m_block_info;
lmdb_db_open(txn, "block_infn", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
mdb_set_dupsort(txn, m_block_info, compare_uint64);
MDB_cursor *c_blocks;
result = mdb_cursor_open(txn, m_blocks, &c_blocks);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for blocks: ", result).c_str()));
MDB_cursor *c_old, *c_cur;
i = 0;
while(1) {
if (!(i % 1000)) {
if (i) {
LOGIF(el::Level::Info) {
std::cout << i << " / " << blockchain_height << " \r" << std::flush;
}
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
}
result = mdb_cursor_open(txn, m_block_info, &c_cur);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_infn: ", result).c_str()));
result = mdb_cursor_open(txn, o_block_info, &c_old);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_info: ", result).c_str()));
result = mdb_cursor_open(txn, m_blocks, &c_blocks);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for blocks: ", result).c_str()));
if (!i) {
MDB_stat db_stat;
result = mdb_stat(txn, m_block_info, &db_stats);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query m_block_info: ", result).c_str()));
i = db_stats.ms_entries;
}
}
result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
if (result == MDB_NOTFOUND) {
txn.commit();
break;
}
else if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from block_info: ", result).c_str()));
const mdb_block_info_2 *bi_old = (const mdb_block_info_2*)v.mv_data;
mdb_block_info_3 bi;
bi.bi_height = bi_old->bi_height;
bi.bi_timestamp = bi_old->bi_timestamp;
bi.bi_coins = bi_old->bi_coins;
bi.bi_weight = bi_old->bi_weight;
bi.bi_diff = bi_old->bi_diff;
bi.bi_hash = bi_old->bi_hash;
bi.bi_cum_rct = bi_old->bi_cum_rct;
// get block major version to determine which rule is in place
if (!past_long_term_weight)
{
MDB_val_copy<uint64_t> kb(bi.bi_height);
MDB_val vb;
result = mdb_cursor_get(c_blocks, &kb, &vb, MDB_SET);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
if (vb.mv_size == 0)
throw0(DB_ERROR("Invalid data from m_blocks"));
const uint8_t block_major_version = *((const uint8_t*)vb.mv_data);
if (block_major_version >= HF_VERSION_LONG_TERM_BLOCK_WEIGHT)
past_long_term_weight = true;
}
uint64_t long_term_block_weight;
if (past_long_term_weight)
{
std::vector<uint64_t> weights(long_term_block_weights.begin(), long_term_block_weights.end());
uint64_t long_term_effective_block_median_weight = std::max<uint64_t>(CRYPTONOTE_BLOCK_GRANTED_FULL_REWARD_ZONE, epee::misc_utils::median(weights));
long_term_block_weight = std::min<uint64_t>(bi.bi_weight, long_term_effective_block_median_weight + long_term_effective_block_median_weight * 2 / 5);
}
else
{
long_term_block_weight = bi.bi_weight;
}
long_term_block_weights.push_back(long_term_block_weight);
bi.bi_long_term_block_weight = long_term_block_weight;
MDB_val_set(nv, bi);
result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to put a record into block_infn: ", result).c_str()));
/* we delete the old records immediately, so the overall DB and mapsize should not grow.
* This is a little slower than just letting mdb_drop() delete it all at the end, but
* it saves a significant amount of disk space.
*/
result = mdb_cursor_del(c_old, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_info: ", result).c_str()));
i++;
}
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
/* Delete the old table */
result = mdb_drop(txn, o_block_info, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete old block_info table: ", result).c_str()));
RENAME_DB("block_infn");
mdb_dbi_close(m_env, m_block_info);
lmdb_db_open(txn, "block_info", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
mdb_set_dupsort(txn, m_block_info, compare_uint64);
txn.commit();
} while(0);
uint32_t version = 4;
v.mv_data = (void *)&version;
v.mv_size = sizeof(version);
MDB_val_str(vk, "version");
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_put(txn, m_properties, &vk, &v, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
txn.commit();
}
void BlockchainLMDB::migrate_4_5()
{
LOG_PRINT_L3("BlockchainLMDB::" << __func__);
uint64_t i;
int result;
mdb_txn_safe txn(false);
MDB_val k, v;
char *ptr;
MGINFO_YELLOW("Migrating blockchain from DB version 4 to 5 - this may take a while:");
do {
LOG_PRINT_L1("migrating block info:");
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
MDB_stat db_stats;
if ((result = mdb_stat(txn, m_blocks, &db_stats)))
throw0(DB_ERROR(lmdb_error("Failed to query m_blocks: ", result).c_str()));
const uint64_t blockchain_height = db_stats.ms_entries;
/* the block_info table name is the same but the old version and new version
* have incompatible data. Create a new table. We want the name to be similar
* to the old name so that it will occupy the same location in the DB.
*/
MDB_dbi o_block_info = m_block_info;
lmdb_db_open(txn, "block_infn", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
mdb_set_dupsort(txn, m_block_info, compare_uint64);
MDB_cursor *c_blocks;
result = mdb_cursor_open(txn, m_blocks, &c_blocks);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for blocks: ", result).c_str()));
MDB_cursor *c_old, *c_cur;
i = 0;
while(1) {
if (!(i % 1000)) {
if (i) {
LOGIF(el::Level::Info) {
std::cout << i << " / " << blockchain_height << " \r" << std::flush;
}
txn.commit();
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
}
result = mdb_cursor_open(txn, m_block_info, &c_cur);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_infn: ", result).c_str()));
result = mdb_cursor_open(txn, o_block_info, &c_old);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to open a cursor for block_info: ", result).c_str()));
if (!i) {
MDB_stat db_stat;
result = mdb_stat(txn, m_block_info, &db_stats);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to query m_block_info: ", result).c_str()));
i = db_stats.ms_entries;
}
}
result = mdb_cursor_get(c_old, &k, &v, MDB_NEXT);
if (result == MDB_NOTFOUND) {
txn.commit();
break;
}
else if (result)
throw0(DB_ERROR(lmdb_error("Failed to get a record from block_info: ", result).c_str()));
const mdb_block_info_3 *bi_old = (const mdb_block_info_3*)v.mv_data;
mdb_block_info_4 bi;
bi.bi_height = bi_old->bi_height;
bi.bi_timestamp = bi_old->bi_timestamp;
bi.bi_coins = bi_old->bi_coins;
bi.bi_weight = bi_old->bi_weight;
bi.bi_diff_lo = bi_old->bi_diff;
bi.bi_diff_hi = 0;
bi.bi_hash = bi_old->bi_hash;
bi.bi_cum_rct = bi_old->bi_cum_rct;
bi.bi_long_term_block_weight = bi_old->bi_long_term_block_weight;
MDB_val_set(nv, bi);
result = mdb_cursor_put(c_cur, (MDB_val *)&zerokval, &nv, MDB_APPENDDUP);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to put a record into block_infn: ", result).c_str()));
/* we delete the old records immediately, so the overall DB and mapsize should not grow.
* This is a little slower than just letting mdb_drop() delete it all at the end, but
* it saves a significant amount of disk space.
*/
result = mdb_cursor_del(c_old, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete a record from block_info: ", result).c_str()));
i++;
}
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
/* Delete the old table */
result = mdb_drop(txn, o_block_info, 1);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to delete old block_info table: ", result).c_str()));
RENAME_DB("block_infn");
mdb_dbi_close(m_env, m_block_info);
lmdb_db_open(txn, "block_info", MDB_INTEGERKEY | MDB_CREATE | MDB_DUPSORT | MDB_DUPFIXED, m_block_info, "Failed to open db handle for block_infn");
mdb_set_dupsort(txn, m_block_info, compare_uint64);
txn.commit();
} while(0);
uint32_t version = 5;
v.mv_data = (void *)&version;
v.mv_size = sizeof(version);
MDB_val_str(vk, "version");
result = mdb_txn_begin(m_env, NULL, 0, txn);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to create a transaction for the db: ", result).c_str()));
result = mdb_put(txn, m_properties, &vk, &v, 0);
if (result)
throw0(DB_ERROR(lmdb_error("Failed to update version for the db: ", result).c_str()));
txn.commit();
}
void BlockchainLMDB::migrate(const uint32_t oldversion)
{
if (oldversion < 1)
migrate_0_1();
if (oldversion < 2)
migrate_1_2();
if (oldversion < 3)
migrate_2_3();
if (oldversion < 4)
migrate_3_4();
if (oldversion < 5)
migrate_4_5();
}
} // namespace cryptonote
|
ebc1afa8df012d2b74b85bd011de78262bea6114 | 9a32178d3c2fdf377d84f65b55989264e67f40e9 | /2002/ALL VC SAMPLES/MFC/internet/StockTicker/containermfc/containerMFCView.h | 843140a09db2d8c28c7f058583ac912325ccdff3 | [] | no_license | philipwolfe/Samples | 5e5cc1376575ac6361b62a3554c98626f153b694 | 7eb703287a6d07596a141c4557f271efe6c1666f | refs/heads/master | 2021-12-25T12:52:52.616313 | 2021-12-19T04:26:29 | 2021-12-19T04:26:29 | 250,445,305 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,890 | h | containerMFCView.h | // containerMFCView.h : interface of the CContainerMFCView class
//
// This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
#if !defined(AFX_CONTAINERMFCVIEW_H__925782CF_9815_11D0_944C_00A0C903487E__INCLUDED_)
#define AFX_CONTAINERMFCVIEW_H__925782CF_9815_11D0_944C_00A0C903487E__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "_stocktickerctrl.h"
class CContainerMFCCntrItem;
class CContainerMFCView : public CView
{
protected: // create from serialization only
CContainerMFCView();
DECLARE_DYNCREATE(CContainerMFCView)
// Attributes
public:
CContainerMFCDoc* GetDocument();
// m_pSelection holds the selection to the current CContainerMFCCntrItem.
// For many applications, such a member variable isn't adequate to
// represent a selection, such as a multiple selection or a selection
// of objects that are not CContainerMFCCntrItem objects. This selection
// mechanism is provided just to help you get started.
// TODO: replace this selection mechanism with one appropriate to your app.
CContainerMFCCntrItem* m_pSelection;
// Operations
public:
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CContainerMFCView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual void Serialize(CArchive& ar);
protected:
virtual void OnInitialUpdate(); // called first time after construct
virtual BOOL IsSelected(const CObject* pDocItem) const;// Container support
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CContainerMFCView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CContainerMFCView)
afx_msg void OnDestroy();
afx_msg void OnSetFocus(CWnd* pOldWnd);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnInsertObject();
afx_msg void OnCancelEditCntr();
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in containerMFCView.cpp
inline CContainerMFCDoc* CContainerMFCView::GetDocument()
{ return (CContainerMFCDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_CONTAINERMFCVIEW_H__925782CF_9815_11D0_944C_00A0C903487E__INCLUDED_)
|
9e0af2f650bf2b7057de274837f7a159deb65a15 | 1828d7dd7783c256a87eba166a0bae16b9e1a559 | /FOR/c/Pares1al1000.cpp | 9c3cefbeb4dc93278dc9076a302827366821f91b | [] | no_license | juandiegorb/TallerNo3 | e7aa6bdab925c730906429c0533f6b63fad55d8b | 754c2e7989966a4a968eb19898750caa779d7c8c | refs/heads/master | 2020-03-26T17:34:46.777210 | 2018-08-23T00:01:47 | 2018-08-23T00:01:47 | 145,169,189 | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 346 | cpp | Pares1al1000.cpp | /*
*Programa: Pares entre el 1 y el 1000
*Fecha: 21 de Agosto del 2018
*Elaborado por: Juan Diego Rios Ballesteros
*/
#include <stdio.h>
//función principal
int main(int argc, char *argv[]) {
//Variables
int i;
// ciclo para tomar multiplos de 4
for(i = 1; i <= 1000; i++){
if(i % 2 == 0){
printf("%d\n", i);
}
}
return 0;
}
|
c71d491744d5fb45a5e09b73441266e4a3f57d19 | 9fd16b8b69f2ad2cf849d0ae9a10851fa29f301a | /Classes/main.cpp | f69565fd31b40678a0f22b48cf3340fccb1ebb0e | [] | no_license | sungincho02/A4541 | c16d12fba5bec64e1247e798a5ad7694ce31ccc8 | a6ce3bc45c6276967bb70f156940305c88959a03 | refs/heads/master | 2023-02-27T14:02:53.392343 | 2021-02-08T15:47:29 | 2021-02-08T15:47:29 | 295,785,636 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,481 | cpp | main.cpp | /*
* Project: Classes
* Author: Sungin Cho
* Date: 10/19/20
* Instructor: Jason Galbraith
* Description: This is a program for managing a list of 3 types of digital media
*/
#include <iostream>
#include <cstring>
#include <vector>
#include <limits>
#include <typeinfo>
#include <algorithm>
#include "Videogame.h"
#include "Music.h"
#include "Movie.h"
using namespace std;
// global variables
vector<Media*> list;
char dtitle[99];
int dyear;
//function prototypes
void addVG();
void addMusic();
void addMovie();
void search();
void print(Media* media);
void del();
bool titleMatch(Media* media);
bool yearMatch(Media* media);
int main() {
bool quit = false;
char input[99];
// setting precision for ratings
cout.setf(ios::fixed, ios::floatfield);
cout.setf(ios::showpoint);
cout.precision(1);
while (!quit) {
// prompt for a user command and resolve
cout << "\nEnter a command" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (strcmp(input, "ADD") == 0) {
// prompt for the type of digital media
cout << "\nChoose a digital media you want to add:\n1) Video Game\n2) Music\n3) Movie" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (strcmp(input, "1") == 0) {
addVG();
}
else if (strcmp(input, "2") == 0) {
addMusic();
}
else if (strcmp(input, "3") == 0) {
addMovie();
}
else {
cout << "Invalid command" << endl;
}
}
else if (strcmp(input, "SEARCH") == 0) {
search();
}
else if (strcmp(input, "DELETE") == 0) {
del();
}
else if (strcmp(input, "QUIT") == 0) {
quit = true;
}
else {
cout << "Invalid command" << endl;
}
}
return 0;
}
// Add a new Videogame to the list
void addVG() {
char title[99];
int year;
char publisher[99];
float rating;
// prompt for the video game details
cout << "\nTitle:" << endl;
cin.get(title, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Year:" << endl;
cin >> year;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Publisher:" << endl;
cin.get(publisher, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Rating;" << endl;
cin >> rating;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// create new Videogame and add to the list
Media* nmedia = new Videogame(title, year, publisher, rating);
list.push_back(nmedia);
cout << "Video game added" << endl;
}
// Add a new Music to the list
void addMusic() {
char title[99];
int year;
char artist[99];
int duration;
char publisher[99];
// prompt for the music details
cout << "\nTitle:" << endl;
cin.get(title, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Year:" << endl;
cin >> year;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Artist:" << endl;
cin.get(artist, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Duration:" << endl;
cin >> duration;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Publisher:" << endl;
cin.get(publisher, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// create new Music and add to the list
Media* nmedia = new Music(title, year, artist, duration, publisher);
list.push_back(nmedia);
cout << "Music added" << endl;
}
// Add a new Movie to the list
void addMovie() {
char title[99];
int year;
char director[99];
int duration;
float rating;
// prompt for the movie details
cout << "\nTitle:" << endl;
cin.get(title, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Year:" << endl;
cin >> year;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Director:" << endl;
cin.get(director, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Duration:" << endl;
cin >> duration;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Rating;" << endl;
cin >> rating;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
// create a new Movie and add to the list
Media* nmedia = new Movie(title, year, director, duration, rating);
list.push_back(nmedia);
cout << "Movie added" << endl;
}
// search for digital media in the list with title or year
void search() {
char input[99];
bool nf = true;
// prompt for search type
cout << "\nSearch with:\n1) Title\n2) Year" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (strcmp(input, "1") == 0) {
// print all digital media with matching title
cout << "\nEnter the title:" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int i = 0; i < list.size(); i++) {
if (strcmp(list.at(i)->getTitle(), input) == 0) {
print(list.at(i));
nf = false;
}
}
// notify user if none of them matched
if (nf) {
cout << "There's no digital media with that title" << endl;
}
}
else if (strcmp(input, "2") == 0) {
int syear;
// print all digital media with matching year
cout << "\nEnter the year:" << endl;
cin >> syear;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
for (int i = 0; i < list.size(); i++) {
if (list.at(i)->getYear() == syear) {
print(list.at(i));
nf = false;
}
}
// notify user if none of them matched
if (nf) {
cout << "There's no digital media from that year" << endl;
}
}
else {
cout << "Invalid command" << endl;
}
}
// print out details of given digital media
void print(Media* media) {
// check for the type and print its details
if (typeid(*media) == typeid(Videogame)) {
Videogame* ptr = (Videogame*)media;
cout << "\nType: Video Game" << "\nTitle: " << ptr->getTitle() << "\nYear: " << ptr->getYear() << "\nPublisher: " << ptr->getPublisher() << "\nRating: " << ptr->getRating() << endl;
}
else if (typeid(*media) == typeid(Music)) {
Music* ptr = (Music*)media;
cout << "\nType: Music" << "\nTitle: " << ptr->getTitle() << "\nYear: " << ptr->getYear() << "\nArtist: " << ptr->getArtist() << "\nDuration: " << ptr->getDuration() << "m" << "\nPublisher: " << ptr->getPublisher() << endl;
}
else if (typeid(*media) == typeid(Movie)) {
Movie* ptr = (Movie*)media;
cout << "\nType: Movie" << "\nTitle: " << ptr->getTitle() << "\nYear: " << ptr->getYear() << "\nDirector: " << ptr->getDirector() << "\nDuration: " << ptr->getDuration() << "m" << "\nRating: " << ptr->getRating() << endl;
}
}
// search & delete digital media
void del() {
char input[99];
bool nf = true;
// search for digital media to delete
cout << "\nSearch with:\n1) Title\n2) Year" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if (strcmp(input, "1") == 0) {
// search and print result
cout << "\nEnter the title:" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
strcpy(dtitle, input);
for (int i = 0; i < list.size(); i++) {
if (strcmp(list.at(i)->getTitle(), input) == 0) {
print(list.at(i));
nf = false;
}
}
if (nf) {
cout << "There's no digital media with that title" << endl;
}
else {
// ask for confirmation
cout << "\nDelete these items? [Y/N]" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
while (strcmp(input, "Y") != 0 && strcmp(input, "N") != 0) {
cout << "Please answer with a \"Y\" or \"N\"" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (strcmp(input, "Y") == 0) {
// delete all digital media with matching title
list.erase(remove_if(list.begin(), list.end(), titleMatch), list.end());
cout << "Items deleted" << endl;
}
else {
// terminate deletion
cout << "Deletion terminated" << endl;
}
}
}
else if (strcmp(input, "2") == 0) {
int syear;
// search and print result
cout << "\nEnter the year:" << endl;
cin >> syear;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
dyear = syear;
for (int i = 0; i < list.size(); i++) {
if (list.at(i)->getYear() == syear) {
print(list.at(i));
nf = false;
}
}
if (nf) {
cout << "There's no digital media from that year" << endl;
}
else {
// ask for confirmation
cout << "\nDelete these items? [Y/N]" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
while (strcmp(input, "Y") != 0 && strcmp(input, "N") != 0) {
cout << "Please answer with a \"Y\" or \"N\"" << endl;
cin.get(input, 99);
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (strcmp(input, "Y") == 0) {
// delete all digital media with matching title
list.erase(remove_if(list.begin(), list.end(), yearMatch), list.end());
cout << "Items deleted" << endl;
}
else {
// terminate deletion
cout << "Deletion terminated" << endl;
}
}
}
else {
cout << "Invalid command" << endl;
}
}
// check for title match
bool titleMatch(Media* media) {
return (strcmp(media->getTitle(), dtitle) == 0);
}
// check for year match
bool yearMatch(Media* media) {
return (media->getYear() == dyear);
}
|
bd3a00fced93254c17d5a405500698991a50f0c8 | ef174be2e2f91bf336bfbc0b09899f2211e63561 | /Source/Headers/Reporter.h | 99013221ce1232188c8ce92de6ee2e407ffcd139 | [
"MIT"
] | permissive | lukemetz/cedarCPP | b3ed99280abb942329affa9d9804417dee5f4240 | 175d8ee112efa148617f0840a078c2cdf082b1c6 | refs/heads/master | 2021-01-15T22:58:05.123521 | 2013-07-05T19:02:42 | 2013-07-05T19:02:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,173 | h | Reporter.h | #pragma once
#include "Spec.h"
#include <exception>
#include "SpecException.h"
namespace cedar
{
class Reporter
{
public:
virtual void successTest()
{
successTests += 1;
std::cout << ".";
}
virtual void failTest(std::vector<std::string> location, SpecException &e)
{
failTests += 1;
std::cout << "F";
failureMessages.push_back(formatFailMessage(location, e));
}
virtual void endTests()
{
std::cout << std::endl << successTests << " Passed "
<< failTests << " Failed" <<std::endl;
for (auto message : failureMessages) {
std::cout << message;
}
}
std::string formatFailMessage(std::vector<std::string> location, SpecException &e)
{
std::stringstream stream;
stream << e.fileName << ":" << e.lineNumber << " ";
auto it = location.begin();
for (; it != location.end()-1; it++) {
stream << *it<< ">";
}
stream << *it << "\n";
stream << "\t" << e.error << "\n";
return stream.str();
}
private:
std::vector<std::string> failureMessages;
int successTests = 0;
int failTests = 0;
};
};
|
2fe8c61c343cc139b7b3f12552ac596e15e45565 | 952c325ae2117316f4368c9a3ee31ef8748d7fbc | /source/Analysis.cpp | f92c0bd430e8bd9eb496bb1ee1b3bb541726bc23 | [] | no_license | dlont/jetdis | fc2e966a59533835cd9d113c34116eca3616cc9d | f37570b956cbdaf0da8c8516fc463795c2d5b752 | refs/heads/master | 2021-01-19T19:37:40.273363 | 2013-12-09T13:12:52 | 2013-12-09T13:12:52 | 15,046,379 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,235 | cpp | Analysis.cpp | #include "Analysis.h"
#include "TChain.h"
#include "TEntryList.h"
#include "TEventList.h"
#include <iostream>
#include <vector>
#include <utility>
#include <fstream>
#define STOP_CODE -7
using namespace std;
class Analysis;
//!Default constructor
Analysis::Analysis() {}
//!Constructor with initialisation
Analysis::Analysis( TChain *ch) : fChain(ch),
fHistogramFileName("histogram.root"),
fOutputFileName("output.root"),
fEvenListFileName("event_list.txt"),
fReportPeriod(1000)
{ ; }
//!Default destructor
Analysis::~Analysis()
{
Finalize();
}
int Analysis::Finalize()
{
WriteEventList();
WriteHistograms();
WriteOutput();
return 0;
}
int Analysis::SetReport( unsigned int i = 10)
{
fReportPeriod = i;
return 0;
}
//!Runs events processing
int Analysis::Run( Long64_t Nevents)
{
if ( Nevents < 0) Nevents = fChain->GetEntriesFast();
cout << "Run " << Nevents << " to process" << endl;
for ( unsigned long int i = 0; i < Nevents; i++)
{
if( fOrangeTree -> LoadTree( i ) < 0 ) break;
if( i%fReportPeriod == 0 ) Report(i);
fOrangeTree->GetEntry(i);
if( Event(i) == STOP_CODE ) break;
}
return 0;
}
int Analysis::SetFilteringMode( bool isFiltering)
{
fIsFiltering = isFiltering;
//cout<<"SetFilteringMode "<<endl;
return 0;
}
//!Pushes one entry for small tree file of selected events
int Analysis::SetPassed( Long64_t EntryNumber, Long64_t RunNumber, Long64_t EventNumber)
{
if( fOutTree)
{
fEventList -> Enter( EntryNumber);
}
if( RunNumber > 0) PushRunEvent( RunNumber, EventNumber);
return 0;
}
//!Push one element to the event list, which will be written to the file
int Analysis::PushRunEvent( Long64_t RunNumber, Long64_t EventNumber)
{
fRunEventList.push_back( make_pair(RunNumber, EventNumber));
//cout<<"PushRunEvent "<< RunNumber <<"\t"<<EventNumber<<endl;
return 0;
}
//!Sets name of the file, in which histograms will be written
int Analysis::SetHistogramFile( const char* file_name)
{
fHistogramFileName = file_name;
return 0;
}
//!Sets name of the file, in which histograms will be written
int Analysis::SetHistogramFile( const string file_name)
{
fHistogramFileName = file_name;
return 0;
}
//!Set name of the file with tree of selected events
int Analysis::SetOutputFile( const string file_name)
{
fOutputFileName = file_name;
return 0;
}
//!Set name of the file with tree of selected events
int Analysis::SetOutputFile( const char* file_name)
{
fOutputFileName = file_name;
return 0;
}
//!Set name of the event list file
int Analysis::SetEvenListFile( const string file_name)
{
fEvenListFileName = file_name;
return 0;
}
//!Set name of the event list file
int Analysis::SetEvenListFile( const char* file_name)
{
fEvenListFileName = file_name;
return 0;
}
//!Set programm settings, that were read from xml
int Analysis::SetSettings( Settings* settings)
{
fSettings = settings;
return 0;
}
//!Write histograms to the file
int Analysis::WriteHistograms()
{
HistFile->cd();
HistFile->Write();
HistFile->Close();
delete HistFile;
return 0;
}
//!Write selected events to the smaller tree file
int Analysis::WriteOutput()
{
if ( fIsFiltering)
{
cout<<"Loading trees"<<endl;
//attach event list to the chain
fChain->SetEventList( fEventList);
//Create output file
TFile *OutFile = new TFile(fOutputFileName.c_str(),"RECREATE");
fOutTree = fChain->CopyTree( "");
// fOutTree->Print();
/* if( fNtupleArray->GetSize() != 0)
{
OutFile->cd();
TIter next( fNtupleArray);
TObject *obj;
while( obj = next())
{
obj->Write();
}
}
*/
OutFile->Write();
OutFile->Close();
delete OutFile;
delete fEventList;
}
return 0;
}
//!Write selected events to the file
int Analysis::WriteEventList()
{
//If list is not empty continue
if ( fRunEventList.size() == 0) return 1;
//Open output file
ofstream out_file(fEvenListFileName.c_str());
//Write list to the file
for( unsigned int k = 0; k < fRunEventList.size(); k++) {
out_file << fRunEventList[k].first<<"\t"
<< fRunEventList[k].second<< endl;
}
//Close output file
out_file.close();
return 0;
}
|
0700405eb074d67bd16069243800255e95d309cf | 02d2343755b3172278bbe16de8e783459550e630 | /abc108/a/main.cpp | 432b59d937ea73606e5acede7e371d9e936b7633 | [] | no_license | naototazumi/AtCoder | 415f2860f65caef7d30d26c4599339ddbe596213 | ede6d13db5d92778237f3481b9cd313465f31047 | refs/heads/master | 2022-04-14T11:33:47.069504 | 2020-04-20T09:29:04 | 2020-04-20T09:29:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 373 | cpp | main.cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define INF 99999999
#define rep(i, n) for(int i = 0; i < (int)(n); i++)
#define all(x) (x).begin(),(x).end()
int main()
{
int K;
cin >> K;
ll ans = 0;
for(int i = 1;i <= K;i++) if(i%2==0) ans++;
if(K%2==0) cout << ans * ans << endl;
else cout << ans * (ans + 1) << endl;
}
|
6734ed5fc032c950966467f3105e8ddfa39805b9 | 1b9484f051414df045b4be62d44b2e095ba5a71f | /include/ofp/yaml/ymptablestats.h | c5c89a010b50c1dbe23399f78ee0b63eec591090 | [
"MIT"
] | permissive | byllyfish/oftr | be1ad64864e56911e669849b4a40a2ef29e2ba3e | 5368b65d17d57286412478adcea84371ef5e4fc4 | refs/heads/master | 2022-02-17T15:37:56.907140 | 2022-02-01T04:24:44 | 2022-02-01T04:24:44 | 13,504,446 | 1 | 1 | MIT | 2022-02-01T04:24:44 | 2013-10-11T16:59:19 | C++ | UTF-8 | C++ | false | false | 1,352 | h | ymptablestats.h | // Copyright (c) 2015-2018 William W. Fisher (at gmail dot com)
// This file is distributed under the MIT License.
#ifndef OFP_YAML_YMPTABLESTATS_H_
#define OFP_YAML_YMPTABLESTATS_H_
#include "ofp/mptablestats.h"
namespace llvm {
namespace yaml {
template <>
struct MappingTraits<ofp::MPTableStats> {
static void mapping(IO &io, ofp::MPTableStats &body) {
io.mapRequired("table_id", body.tableId_);
io.mapOptional("name", body.name_);
io.mapOptional("wildcards", body.wildcards_);
io.mapOptional("max_entries", body.maxEntries_);
io.mapRequired("active_count", body.activeCount_);
io.mapRequired("lookup_count", body.lookupCount_);
io.mapRequired("matched_count", body.matchedCount_);
}
};
template <>
struct MappingTraits<ofp::MPTableStatsBuilder> {
static void mapping(IO &io, ofp::MPTableStatsBuilder &msg) {
io.mapRequired("table_id", msg.msg_.tableId_);
io.mapOptional("name", msg.msg_.name_);
io.mapOptional("wildcards", msg.msg_.wildcards_, ofp::Big32{});
io.mapOptional("max_entries", msg.msg_.maxEntries_, ofp::Big32{});
io.mapRequired("active_count", msg.msg_.activeCount_);
io.mapRequired("lookup_count", msg.msg_.lookupCount_);
io.mapRequired("matched_count", msg.msg_.matchedCount_);
}
};
} // namespace yaml
} // namespace llvm
#endif // OFP_YAML_YMPTABLESTATS_H_
|
f069ceacdc00b7d1c5bd39c47109ea3403287f81 | a33377b85c802259b690630cdb04246d6cd2c3d2 | /include/VectorIterator.tpp | df7f311208c03fdcefc5040d3b923be96bbf0afa | [] | no_license | CezaraDulceac/PracticaArobs | e9b5a743f85ed85d0c9dc63f51bf5a6452a8da64 | 0d42d94b327b91c1ae9ae4dc66d91ab38650e7b5 | refs/heads/master | 2022-11-30T20:31:30.378029 | 2020-08-09T21:24:31 | 2020-08-09T21:24:31 | 278,343,209 | 0 | 1 | null | 2020-08-04T09:08:53 | 2020-07-09T11:15:02 | C++ | UTF-8 | C++ | false | false | 1,593 | tpp | VectorIterator.tpp | #include "VectorIterator.hpp"
#include <iostream>
template <typename T>
VectorIterator<T>::VectorIterator(T* value):m_value(value){}
template <typename T>
VectorIterator<T>::VectorIterator(const VectorIterator& rhs):m_value(rhs.m_value){}
template <typename T>
VectorIterator<T>& VectorIterator<T>::operator=(const VectorIterator& rhs)
{
m_value = rhs.m_value;
return *this;
}
template <typename T>
bool VectorIterator<T>::operator!=(const VectorIterator& rhs)
{
return m_value != rhs.m_value;
}
template <typename T>
bool VectorIterator<T>::operator<(const VectorIterator& rhs)
{
return m_value < rhs.m_value;
}
template <typename T>
VectorIterator<T>& VectorIterator<T>::operator++()
{
++m_value;
return *this;
}
template <typename T>
VectorIterator<T>& VectorIterator<T>::operator--()
{
--m_value;
return *this;
}
template <typename T>
VectorIterator<T>& VectorIterator<T>::operator+=(std::size_t difference)
{
m_value += difference;
return *this;
}
template <typename T>
VectorIterator<T>& VectorIterator<T>::operator-=(std::size_t difference)
{
m_value -= difference;
return *this;
}
template <typename T>
VectorIterator<T> VectorIterator<T>::operator+(std::size_t difference)
{
VectorIterator<T> it(0);
it.m_value = m_value + difference;
return it;
}
template <typename T>
VectorIterator<T> VectorIterator<T>::operator-(std::size_t difference)
{
VectorIterator<T> it(0);
it.m_value = m_value - difference;
return it;
}
template <typename T>
T& VectorIterator<T>::operator*()
{
return *m_value;
}
|
7a7b927efc9af0810faa37832c3f2ec3af98cbb2 | 22efccb00473119295dc665039f1ff7500f1991b | /src/interface/determine_cell_is_pure.cpp | 18eb5cb057f1a13b59eda3d2a5190594de8f50e7 | [] | no_license | chennipman/MCLS | 7fc62b6920901a2cbb3eb60e6863bb743e87ebca | ae7e89e707cce7b525621d580ea7375c617ca5a8 | refs/heads/master | 2021-01-10T18:51:45.993314 | 2014-08-29T18:07:28 | 2014-08-29T18:07:28 | 16,737,066 | 1 | 0 | null | 2014-08-05T12:49:52 | 2014-02-11T16:27:17 | C++ | UTF-8 | C++ | false | false | 7,357 | cpp | determine_cell_is_pure.cpp | #include "../headers/array.h"
#include<cstdlib>
#include<iostream>
#include<math.h>
/********************************************************************************/
/********************************************************************************/
/* Function to establish the validity of the volume of fluid field */
/* method. */
/* */
/* Programmer : Duncan van der Heul */
/* Date : 10-03-2013 */
/* Update : */
/********************************************************************************/
/* Notes */
/* Check for cells with volume of fluid outside the */
/* interval [-eps,1+eps] , with eps the volume of fluid tolerance */
/* and 'vapor' cells. */
/* */
/* */
/* */
/********************************************************************************/
EXPORT int determine_cell_is_pure(
Array3<double> level_set, // level set field
// mass conserving
int i_index, // i-index of cell to be analyzed
int j_index, // j-index of cell to be analyzed
int k_index, // k-index of cell to be analyzed
int number_primary_cells_i, // number of primary (pressure) cells in x1 direction
int number_primary_cells_j, // number of primary (pressure) cells in x2 direction
int number_primary_cells_k // number of primary (pressure) cells in x3 direction
)
{
const int number_indices_neighbours_2D=4; // number of neigbouring cells
// to consider, two dimensional cases
const int number_indices_neighbours_3D=14; // number of neighbouring cells
// to consider, three dimensional case
int number_indices_neighbours; // actual number of neigbouring
// cells to consider, after the dimension
// of the problem has been determined
int sign_of_centerpoint; // sign of level set field at the point
// under consideration
int sign_of_this_point; // sign of level set field at the neighbouring point
// under consideration
int neighbour_index;
int index_set_neighbours[number_indices_neighbours_3D][3];// set of all index shifts to neighbouring
// points to consider
int pure_cell=1; //=1, cell is a pure cell,=0 cell is a vapor cell
/* compute the index-set of neighbours for a vapor cell */
/* compute how many cells are in the index set */
if( number_primary_cells_i==1 || number_primary_cells_j==1 || number_primary_cells_k==1)
{
/* 2-D case */
number_indices_neighbours=number_indices_neighbours_2D;
if(number_primary_cells_i==1)
{
/* 2_D case, constant i_index */
/* set up the default table and copy */
int table[number_indices_neighbours_3D][3]=
{
{ 0,-1, -1}, // 1
{ 0,-1, 1}, // 2
{ 0, 1, -1}, // 3
{ 0, 1, 1}, // 4
{ 0, 0, 0}, // 5
{ 0, 0, 0}, // 6
{ 0, 0, 0}, // 7
{ 0, 0, 0}, // 8
{ 0, 0, 0}, // 9
{ 0, 0, 0}, //10
{ 0, 0, 0}, //11
{ 0, 0, 0}, //12
{ 0, 0, 0}, //13
{ 0, 0, 0} //14
};
std::copy(table[0], table[0]+3*number_indices_neighbours_3D, index_set_neighbours[0]);
}
else
{
if(number_primary_cells_j==1)
{
/* 2_D case, constant j_index */
/* set up the default table and copy */
int table[number_indices_neighbours_3D][3]=
{
{ -1, 0,-1},// 1
{ -1, 0, 1},// 2
{ 1, 0,-1},// 3
{ 1, 0, 1},// 4
{ 0, 0, 0},// 5
{ 0, 0, 0},// 6
{ 0, 0, 0},// 7
{ 0, 0, 0},// 8
{ 0, 0, 0},// 9
{ 0, 0, 0},//10
{ 0, 0, 0},//11
{ 0, 0, 0},//12
{ 0, 0, 0},//13
{ 0, 0, 0} //14
};
std::copy(table[0], table[0]+3*number_indices_neighbours_3D, index_set_neighbours[0]);
}
else
{
/* 2_D case, constant k_index */
/* set up the default table and copy */
int table[number_indices_neighbours_3D][3]=
{
{-1, -1, 0},// 1
{-1, 1, 0},// 2
{ 1, -1, 0},// 3
{ 1, 1, 0},// 4
{ 0, 0, 0},// 5
{ 0, 0, 0},// 6
{ 0, 0, 0},// 7
{ 0, 0, 0},// 8
{ 0, 0, 0},// 9
{ 0, 0, 0},//10
{ 0, 0, 0},//11
{ 0, 0, 0},//12
{ 0, 0, 0},//13
{ 0, 0, 0} //14
};
std::copy(table[0], table[0]+3*number_indices_neighbours_3D, index_set_neighbours[0]);
}
}
}
else
{
/* 3-D case */
/* set up the default table and copy */
number_indices_neighbours=number_indices_neighbours_3D;
int table[number_indices_neighbours_3D][3]=
{
{1, 1, 1},// 1
{1, -1, 1},// 2
{-1, 1, 1},// 3
{-1, -1, 1},// 4
{ 1, 1, -1},// 5
{ 1, -1, -1},// 6
{-1, 1, -1},// 7
{-1, -1, -1},// 8
{ 1, 0, 0},// 9
{ -1, 0, 0},//10
{ 0, 1, 0},//11
{ 0, -1, 0},//12
{ 0, 0, 1},//13
{ 0, 0, -1} //14
};
std::copy(table[0], table[0]+3*number_indices_neighbours_3D, index_set_neighbours[0]);
}
/* determine the sign of the level set field at the center point */
sign_of_centerpoint=(int) round(sign(1.0,level_set[i_index][j_index][k_index]));
/* loop over all neighbours in the index set, and compare signs */
for(neighbour_index=0;neighbour_index<number_indices_neighbours;neighbour_index++)
{
int neighbour_index_i=i_index+index_set_neighbours[neighbour_index][0];
int neighbour_index_j=j_index+index_set_neighbours[neighbour_index][1];
int neighbour_index_k=k_index+index_set_neighbours[neighbour_index][2];
sign_of_this_point=
(int) round(sign(1.0,
level_set[neighbour_index_i][neighbour_index_j][neighbour_index_k]));
if(sign_of_centerpoint!=sign_of_this_point)
{
pure_cell=0;
break;
}
}
return pure_cell;
}
|
674895d7b0024d8a0893ba75938716764ad702de | 9a94e85ef2820d626cd76123b9aa49190c991003 | /HSPF_MRO_ANDR/build/Android/Release/app/src/main/jni/_root.HSMRO_DropdownOption_BorderColor_Property.cpp | bea0b12fac57f1f7a337e5544300a313db79faaa | [] | no_license | jaypk-104/FUSE | 448db1717a29052f7b551390322a6167dfea34cd | 0464afa07998eea8de081526a9337bd9af42dcf3 | refs/heads/master | 2023-03-13T14:32:43.855977 | 2021-03-18T01:57:10 | 2021-03-18T01:57:10 | 348,617,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,750 | cpp | _root.HSMRO_DropdownOption_BorderColor_Property.cpp | // This file was generated based on '.uno/ux15/HS MRO.unoproj.g.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#include <_root.DropdownOption.h>
#include <_root.HSMRO_DropdownOption_BorderColor_Property.h>
#include <Uno.Bool.h>
#include <Uno.UX.IPropertyListener.h>
#include <Uno.UX.PropertyObject.h>
#include <Uno.UX.Selector.h>
static uType* TYPES[1];
namespace g{
// internal sealed class HSMRO_DropdownOption_BorderColor_Property
// {
static void HSMRO_DropdownOption_BorderColor_Property_build(uType* type)
{
::TYPES[0] = ::g::DropdownOption_typeof();
type->SetBase(::g::Uno::UX::Property1_typeof()->MakeType(::g::Fuse::Drawing::Brush_typeof(), NULL));
type->SetFields(1,
::TYPES[0/*DropdownOption*/], offsetof(HSMRO_DropdownOption_BorderColor_Property, _obj), uFieldFlagsWeak);
}
::g::Uno::UX::Property1_type* HSMRO_DropdownOption_BorderColor_Property_typeof()
{
static uSStrong< ::g::Uno::UX::Property1_type*> type;
if (type != NULL) return type;
uTypeOptions options;
options.BaseDefinition = ::g::Uno::UX::Property1_typeof();
options.FieldCount = 2;
options.ObjectSize = sizeof(HSMRO_DropdownOption_BorderColor_Property);
options.TypeSize = sizeof(::g::Uno::UX::Property1_type);
type = (::g::Uno::UX::Property1_type*)uClassType::New("HSMRO_DropdownOption_BorderColor_Property", options);
type->fp_build_ = HSMRO_DropdownOption_BorderColor_Property_build;
type->fp_Get1 = (void(*)(::g::Uno::UX::Property1*, ::g::Uno::UX::PropertyObject*, uTRef))HSMRO_DropdownOption_BorderColor_Property__Get1_fn;
type->fp_get_Object = (void(*)(::g::Uno::UX::Property*, ::g::Uno::UX::PropertyObject**))HSMRO_DropdownOption_BorderColor_Property__get_Object_fn;
type->fp_Set1 = (void(*)(::g::Uno::UX::Property1*, ::g::Uno::UX::PropertyObject*, void*, uObject*))HSMRO_DropdownOption_BorderColor_Property__Set1_fn;
type->fp_get_SupportsOriginSetter = (void(*)(::g::Uno::UX::PropertyAccessor*, bool*))HSMRO_DropdownOption_BorderColor_Property__get_SupportsOriginSetter_fn;
return type;
}
// public HSMRO_DropdownOption_BorderColor_Property(DropdownOption obj, Uno.UX.Selector name)
void HSMRO_DropdownOption_BorderColor_Property__ctor_3_fn(HSMRO_DropdownOption_BorderColor_Property* __this, ::g::DropdownOption* obj, ::g::Uno::UX::Selector* name)
{
__this->ctor_3(obj, *name);
}
// public override sealed Fuse.Drawing.Brush Get(Uno.UX.PropertyObject obj)
void HSMRO_DropdownOption_BorderColor_Property__Get1_fn(HSMRO_DropdownOption_BorderColor_Property* __this, ::g::Uno::UX::PropertyObject* obj, ::g::Fuse::Drawing::Brush** __retval)
{
return *__retval = uPtr(uCast< ::g::DropdownOption*>(obj, ::TYPES[0/*DropdownOption*/]))->BorderColor(), void();
}
// public HSMRO_DropdownOption_BorderColor_Property New(DropdownOption obj, Uno.UX.Selector name)
void HSMRO_DropdownOption_BorderColor_Property__New1_fn(::g::DropdownOption* obj, ::g::Uno::UX::Selector* name, HSMRO_DropdownOption_BorderColor_Property** __retval)
{
*__retval = HSMRO_DropdownOption_BorderColor_Property::New1(obj, *name);
}
// public override sealed Uno.UX.PropertyObject get_Object()
void HSMRO_DropdownOption_BorderColor_Property__get_Object_fn(HSMRO_DropdownOption_BorderColor_Property* __this, ::g::Uno::UX::PropertyObject** __retval)
{
return *__retval = __this->_obj, void();
}
// public override sealed void Set(Uno.UX.PropertyObject obj, Fuse.Drawing.Brush v, Uno.UX.IPropertyListener origin)
void HSMRO_DropdownOption_BorderColor_Property__Set1_fn(HSMRO_DropdownOption_BorderColor_Property* __this, ::g::Uno::UX::PropertyObject* obj, ::g::Fuse::Drawing::Brush* v, uObject* origin)
{
uPtr(uCast< ::g::DropdownOption*>(obj, ::TYPES[0/*DropdownOption*/]))->SetBorderColor(v, origin);
}
// public override sealed bool get_SupportsOriginSetter()
void HSMRO_DropdownOption_BorderColor_Property__get_SupportsOriginSetter_fn(HSMRO_DropdownOption_BorderColor_Property* __this, bool* __retval)
{
return *__retval = true, void();
}
// public HSMRO_DropdownOption_BorderColor_Property(DropdownOption obj, Uno.UX.Selector name) [instance]
void HSMRO_DropdownOption_BorderColor_Property::ctor_3(::g::DropdownOption* obj, ::g::Uno::UX::Selector name)
{
ctor_2(name);
_obj = obj;
}
// public HSMRO_DropdownOption_BorderColor_Property New(DropdownOption obj, Uno.UX.Selector name) [static]
HSMRO_DropdownOption_BorderColor_Property* HSMRO_DropdownOption_BorderColor_Property::New1(::g::DropdownOption* obj, ::g::Uno::UX::Selector name)
{
HSMRO_DropdownOption_BorderColor_Property* obj1 = (HSMRO_DropdownOption_BorderColor_Property*)uNew(HSMRO_DropdownOption_BorderColor_Property_typeof());
obj1->ctor_3(obj, name);
return obj1;
}
// }
} // ::g
|
f92e2dfec38cb32a013b7bef636bcb72182d8528 | 80ebe41d667deb94da96585525e4b4f4638476cd | /BattleCityApp/BattleCityApp/animation.h | ed83ed7548db0fcea46fe680ad1085e1f008a756 | [] | no_license | HelgeID/BattleCityApp | 0a1f6a4ff4ebc00424923eaf843ecfadd291d215 | c9d74b1a6816d031ffd55c93410eb91ccc5a66e6 | refs/heads/master | 2020-06-28T22:41:40.067080 | 2019-07-31T08:00:00 | 2019-10-13T20:19:27 | 199,274,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,349 | h | animation.h | //FINAL
#ifndef ANIMATION_H
#define ANIMATION_H
#include <SFML\Graphics.hpp>
/////////////////////////////////////////////////////////////////////
// class Animation
/////////////////////////////////////////////////////////////////////
class Animation
{
private:
const sf::Texture* ptrTexture;
std::vector<sf::IntRect> frames;
public:
Animation();
void AddFrame(sf::IntRect);
void DelHeadFrame();
void SetTexture(const sf::Texture&);
const sf::Texture* GetTexture() const;
std::size_t GetSize() const;
const sf::IntRect& GetFrame(std::size_t) const;
};
inline Animation::Animation() : ptrTexture(NULL)
{
}
inline void Animation::AddFrame(sf::IntRect rect)
{
frames.push_back(rect);
return;
}
inline void Animation::DelHeadFrame()
{
frames.erase(frames.begin());
return;
}
inline void Animation::SetTexture(const sf::Texture& texture)
{
ptrTexture = &texture;
return;
}
inline const sf::Texture* Animation::GetTexture() const
{
return ptrTexture;
}
inline std::size_t Animation::GetSize() const
{
return frames.size();
}
inline const sf::IntRect& Animation::GetFrame(std::size_t num) const
{
return frames[num];
}
/////////////////////////////////////////////////////////////////////
// class AnimatedObject
/////////////////////////////////////////////////////////////////////
class AnimatedObject : public sf::Drawable, public sf::Transformable
{
private:
const Animation* animation;
sf::Time frameTime, currentTime;
std::size_t currentFrame;
bool isPaused;
bool isLooped;
const sf::Texture* ptrTexture;
sf::Vertex vertices[4];
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
public:
explicit AnimatedObject(
sf::Time frameTime = sf::seconds(0.2f),
bool paused = false,
bool looped = true
);
void SetAnimation(const Animation&);
void SetFrameTime(sf::Time);
void PlayAnimation();
void PlayAnimation(const Animation&);
void PauseAnimation();
void StopAnimation();
void SetLooped(bool);
void SetColor(const sf::Color&);
const Animation* GetAnimation() const;
sf::FloatRect GetLocalBounds() const;
sf::FloatRect GetGlobalBounds() const;
bool IsLooped() const;
bool IsPlaying() const;
sf::Time GetFrameTime() const;
void SetFrame(std::size_t, bool);
std::size_t GetCurrentFrame() const;
void Update(sf::Time);
};
inline AnimatedObject::AnimatedObject(sf::Time frameTime, bool paused, bool looped) :
animation(NULL), frameTime(frameTime), currentFrame(0), isPaused(paused), isLooped(looped), ptrTexture(NULL)
{
}
inline void AnimatedObject::SetAnimation(const Animation& animation)
{
this->animation = &animation;
ptrTexture = this->animation->GetTexture();
currentFrame = 0;
SetFrame(currentFrame, true);
return;
}
inline void AnimatedObject::SetFrameTime(sf::Time time)
{
frameTime = time;
return;
}
inline void AnimatedObject::PlayAnimation()
{
isPaused = false;
return;
}
inline void AnimatedObject::PlayAnimation(const Animation& animation)
{
if (GetAnimation() != &animation)
SetAnimation(animation);
PlayAnimation();
return;
}
inline void AnimatedObject::PauseAnimation()
{
isPaused = true;
return;
}
inline void AnimatedObject::StopAnimation()
{
isPaused = true;
currentFrame = 0;
SetFrame(currentFrame, true);
return;
}
inline void AnimatedObject::SetLooped(bool looped)
{
isLooped = looped;
return;
}
inline void AnimatedObject::SetColor(const sf::Color& color)
{
//Update the vertices' color
vertices[0].color = color;
vertices[1].color = color;
vertices[2].color = color;
vertices[3].color = color;
return;
}
inline const Animation* AnimatedObject::GetAnimation() const
{
return animation;
}
inline sf::FloatRect AnimatedObject::GetLocalBounds() const
{
sf::IntRect rect = animation->GetFrame(currentFrame);
float width = static_cast<float>(std::abs(rect.width));
float height = static_cast<float>(std::abs(rect.height));
return sf::FloatRect(0.f, 0.f, width, height);
}
inline sf::FloatRect AnimatedObject::GetGlobalBounds() const
{
return getTransform().transformRect(GetLocalBounds());
}
inline bool AnimatedObject::IsLooped() const
{
return isLooped;
}
inline bool AnimatedObject::IsPlaying() const
{
return !isPaused;
}
inline sf::Time AnimatedObject::GetFrameTime() const
{
return frameTime;
}
inline void AnimatedObject::SetFrame(std::size_t newFrame, bool resetTime)
{
if (animation) {
//calculate new vertex positions and texture coordiantes
sf::IntRect rect = animation->GetFrame(newFrame);
vertices[0].position = sf::Vector2f(0.f, 0.f);
vertices[1].position = sf::Vector2f(0.f, static_cast<float>(rect.height));
vertices[2].position = sf::Vector2f(static_cast<float>(rect.width), static_cast<float>(rect.height));
vertices[3].position = sf::Vector2f(static_cast<float>(rect.width), 0.f);
float left = static_cast<float>(rect.left) + 0.0001f;
float right = left + static_cast<float>(rect.width);
float top = static_cast<float>(rect.top);
float bottom = top + static_cast<float>(rect.height);
vertices[0].texCoords = sf::Vector2f(left, top);
vertices[1].texCoords = sf::Vector2f(left, bottom);
vertices[2].texCoords = sf::Vector2f(right, bottom);
vertices[3].texCoords = sf::Vector2f(right, top);
}
if (resetTime)
currentTime = sf::Time::Zero;
return;
}
inline std::size_t AnimatedObject::GetCurrentFrame() const
{
return currentFrame;
}
inline void AnimatedObject::Update(sf::Time deltaTime)
{
//if not paused and we have a valid animation
if (!isPaused && animation) {
//add delta time
currentTime += deltaTime;
//if current time is bigger then the frame time advance one frame
if (currentTime >= frameTime) {
//reset time, but keep the remainder
currentTime = sf::microseconds(currentTime.asMicroseconds() % frameTime.asMicroseconds());
//get next Frame index
if (currentFrame + 1 < animation->GetSize())
currentFrame++;
else {
//animation has ended
currentFrame = 0; //reset to start
if (!isLooped)
isPaused = true;
}
//set the current frame, not reseting the time
SetFrame(currentFrame, false);
}
}
return;
}
inline void AnimatedObject::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
if (animation && ptrTexture) {
states.transform *= getTransform();
states.texture = ptrTexture;
target.draw(vertices, 4, sf::Quads, states);
}
return;
}
#endif
|
d7fc92573f14a8fb5fbf03488c2e7657ae069a8e | 667b7f0280f01aa18cbaa3666f4a319f2deb63de | /AC Circuit Final Version/AC Circuit Project Final Version/AC Circuit Project Final Version/ComponentLibraryCreator.h | 7b180e75e5a8f3575a5f191cea28e7ce788f0946 | [] | no_license | lgaidoni/OOP-AC | ba620c5aaf701bec11c1ec01ec4f13f81eda1eb8 | 048818de05b0d7f4fb6bb106b84aa2ec8471795d | refs/heads/master | 2020-05-02T07:18:33.962773 | 2019-03-26T15:33:18 | 2019-03-26T15:33:18 | 177,814,362 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 517 | h | ComponentLibraryCreator.h | #pragma once
//Normal includes
#include <iostream>
#include <sstream>
#include <vector>
#include <iomanip>
//User defined headers
#include "CircuitObject.h"
#include "UserInputFunctions.h"
#include "Resistor.h"
#include "Capacitor.h"
#include "Inductor.h"
#include "Options.h"
//Using the standard namespace
using namespace std;
//Function to create the component library, given options
vector<circuitObject*> createComponentsLibrary(options options);
//Function returns the components vector |
db791ba184483831ba2aef0593c44dd8bdb8e8f8 | be486f49b047e76af9442fa53b1f14eaafc2874d | /baekjoon/1377 버블 소트/file.cpp | 589174fbe48bc271f9f2831381ea59e3fa412f1e | [] | no_license | kkbwilldo/all-problems | d2703d0e68c27dafa7232ccda43a867b36416ce0 | b4388e5f884d6a8d5e59e4243c587695587aae30 | refs/heads/master | 2023-01-21T22:55:18.236572 | 2020-12-05T06:37:55 | 2020-12-05T06:37:55 | 248,887,553 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 553 | cpp | file.cpp | #include <iostream>
#define endl '\n'
using namespace std;
const int MAX=500010;
int num;
int a[MAX];
void BubbleSort(){
bool change=false;
for(int i=1;i<num;i++){
change=false;
for(int j=1;j<=num-i;j++){
if(a[j]>a[j+1]){
change=true;
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
}
if(!change){
cout<<i<<endl;
break;
}
}
}
}
int main ()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
freopen("input.txt","r",stdin);
cin>>num;
for(int i=1;i<=num;i++) cin>>a[i];
BubbleSort();
return 0;
}
|
36035125af9fee822148f3200f96382c3a23fed8 | 1463abcfbe949dcf409613518ea8fc0815499b7b | /sprout/weed/traits/type/is_string.hpp | b12d4ce9e1b45452ad32e46a669e7475f0bde133 | [
"BSL-1.0"
] | permissive | osyo-manga/Sprout | d445c0d2e59a2e32f91c03fceb35958dcfb2c0ce | 8885b115f739ef255530f772067475d3bc0dcef7 | refs/heads/master | 2021-01-18T11:58:21.604326 | 2013-04-09T10:27:06 | 2013-04-09T10:27:06 | 4,191,046 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 987 | hpp | is_string.hpp | #ifndef SPROUT_WEED_TRAITS_TYPE_IS_STRING_HPP
#define SPROUT_WEED_TRAITS_TYPE_IS_STRING_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/string.hpp>
namespace sprout {
namespace weed {
namespace traits {
//
// is_string
//
template<typename T>
struct is_string
: public std::false_type
{};
template<typename T>
struct is_string<T const>
: public sprout::weed::traits::is_string<T>
{};
template<typename T>
struct is_string<T volatile>
: public sprout::weed::traits::is_string<T>
{};
template<typename T>
struct is_string<T const volatile>
: public sprout::weed::traits::is_string<T>
{};
template<typename T, std::size_t N, typename Traits>
struct is_string<sprout::basic_string<T, N, Traits> >
: public std::true_type
{};
} // namespace traits
} // namespace weed
} // namespace sprout
#endif // #ifndef SPROUT_WEED_TRAITS_TYPE_IS_STRING_HPP
|
48f14bf5250e4fa47a335c27f2f1fc4cdf81da00 | 4af8cc30af42a826608222883b1c55e4c8a6b8f7 | /prj/GooseBerry/src/GB_Color.cc | 4b5aa7077f51ddbb3a7bc5a49681513680bf1946 | [] | no_license | ManicPumpkin/Project-O.R.B.S. | 98154d5a1da5cf6912931460964b9094a1079c88 | 162ff4171231d25062dad8349d402e3d1a1695f0 | refs/heads/master | 2021-01-21T08:05:31.515159 | 2016-11-21T01:39:05 | 2016-11-21T01:39:05 | 15,568,394 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,533 | cc | GB_Color.cc | /**
@file GB_Color.cpp
@brief Implements GB_Color methods
@author drubner
@date 2013-08-28
**/
//==================================================================
// Include
//==================================================================
#include "GB_Color.h"
//==================================================================
/**
@fn GB_Color :: GooseBerry::GB_Color()
@brief Standardconstructor
**/
//==================================================================
GB_Color :: GB_Color()
{
}
//==================================================================
/**
@fn GB_Color(float r, float g, float b)
@brief Enhanced constructor
**/
//==================================================================
GB_Color :: GB_Color(float r, float g, float b)
{
this->r = r;
this->g = g;
this->b = b;
this->a = 1.0f;
}
//==================================================================
/**
@fn GB_Color(float r, float g, float b, float a)
@brief Enhanced constructor
**/
//==================================================================
GB_Color :: GB_Color(float r, float g, float b, float a)
{
this->r = r;
this->g = g;
this->b = b;
this->a = a;
}
//==================================================================
/**
@fn GB_Color :: GB_Color(float * colors)
@brief Enhanced constructor
**/
//==================================================================
GB_Color :: GB_Color(float * colors)
{
this->r = colors[0];
this->g = colors[1];
this->b = colors[2];
this->a = colors[3];
} |
824462930b5c5796eaacc29db9ab2d04de2f185d | 306232bfafeb2b88e353c4ffa7fd9946654b15d8 | /Engine/Engine/GlobalRenderingParams.cpp | 12e0e4793538e0703ff8e14615bd7499e269bf6b | [
"Zlib"
] | permissive | Aloalo/Trayc | 35b9f1161e64d84e1ac35df0f03b46422af2b9a5 | 048e36934b1b4dc87449feaf6f89b0161b2d08af | refs/heads/master | 2020-04-12T02:22:36.696046 | 2019-06-01T11:38:09 | 2019-06-01T11:38:09 | 26,697,097 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 176 | cpp | GlobalRenderingParams.cpp | #include <Engine/Engine/GlobalRenderingParams.h>
namespace engine
{
int GetMRTIdx(TextureType type)
{
return type - TextureType::CT_MAT_TEXTURE_TYPES;
}
}
|
13706ecce68614814e5c0cea54283f18de6ae4fb | e2a5a93292d5a61c9a8622576cb1a56a71caf8cd | /data/maps/ArtisanCave_B1F/scripts.inc | ac16e4227293c7c8818aeb54df25f966c6158abf | [] | no_license | BelialClover/pokeemerald_rowe | d9b918ff034ee7d0f7255403840e916029c00623 | 752638c80d7157cf380520f605d8e617cbeaa218 | refs/heads/master | 2023-07-28T21:38:02.770418 | 2021-09-28T21:56:22 | 2021-09-28T21:56:22 | 398,417,858 | 3 | 0 | null | 2021-08-22T12:15:41 | 2021-08-20T22:57:10 | Assembly | UTF-8 | C++ | false | false | 1,264 | inc | scripts.inc | ArtisanCave_B1F_MapScripts:: @ 823AFAD
map_script MAP_SCRIPT_ON_TRANSITION, ArtisanCave_B1F_OnTransition
.byte 0
ArtisanCave_B1F_OnTransition: @ 823AFB3
setflag FLAG_LANDMARK_ARTISAN_CAVE
end
ArtisanCave_B1F_EventScript_Latios::
lock
faceplayer
waitse
playmoncry SPECIES_LATIOS, 2
delay 40
waitmoncry
setwildbattle SPECIES_LATIOS, 70, ITEM_NONE
setflag FLAG_SYS_CTRL_OBJ_DELETE
special StartRegiBattle
waitstate
clearflag FLAG_SYS_CTRL_OBJ_DELETE
specialvar VAR_RESULT, GetBattleOutcome
compare VAR_RESULT, B_OUTCOME_CAUGHT
goto_if_eq ArtisanCave_B1F_EventScript_CaughtLatios
compare VAR_RESULT, B_OUTCOME_WON
goto_if_eq ArtisanCave_B1F_EventScript_DefeatedLatios
compare VAR_RESULT, B_OUTCOME_RAN
goto_if_eq ArtisanCave_B1F_EventScript_RanFromLatios
compare VAR_RESULT, B_OUTCOME_PLAYER_TELEPORTED
goto_if_eq ArtisanCave_B1F_EventScript_RanFromLatios
setflag FLAG_UNUSED_0x274
release
end
ArtisanCave_B1F_EventScript_CaughtLatios::
setflag FLAG_UNUSED_0x274
goto Common_EventScript_RemoveStaticPokemon
end
ArtisanCave_B1F_EventScript_DefeatedLatios::
goto Common_EventScript_RemoveStaticPokemon
end
ArtisanCave_B1F_EventScript_RanFromLatios::
setvar VAR_0x8004, SPECIES_LATIOS
goto Common_EventScript_LegendaryFlewAway
end
|
bcb06b3a083582b95af036d80a470bdd215030bf | d2847848e1decbb8076345ebcc71223edf47ac80 | /askap/scimath/fitting/GenericNormalEquations.h | fd8304c9e5b3a047e2b31a52134f6a0579fa4aaa | [
"MIT"
] | permissive | lao19881213/base-scimath | fd274a76ea386fb3f659666812b1ab522ad3bc65 | bfbe6b01be130d83f116c11f48189062782ced35 | refs/heads/main | 2023-05-31T03:23:03.407735 | 2021-06-12T06:38:52 | 2021-06-12T06:38:52 | 376,219,225 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,172 | h | GenericNormalEquations.h | /// @file
/// @brief Normal equations without any approximation
/// @details There are two kinds of normal equations currently supported. The
/// first one is a generic case, where the full normal matrix is retained. It
/// is used for calibration. The second one is intended for imaging, where we
/// can't afford to keep the whole normal matrix. In the latter approach, the
/// matrix is approximated by a sum of diagonal and shift invariant matrices.
/// This class represents the generic case, where no approximation to the normal
/// matrix is done.
///
/// @copyright (c) 2007 CSIRO
/// Australia Telescope National Facility (ATNF)
/// Commonwealth Scientific and Industrial Research Organisation (CSIRO)
/// PO Box 76, Epping NSW 1710, Australia
/// atnf-enquiries@csiro.au
///
/// This file is part of the ASKAP software distribution.
///
/// The ASKAP software distribution is free software: you can redistribute it
/// and/or modify it under the terms of the GNU General Public License as
/// published by the Free Software Foundation; either version 2 of the License,
/// or (at your option) any later version.
///
/// This program is distributed in the hope that it will be useful,
/// but WITHOUT ANY WARRANTY; without even the implied warranty of
/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
/// GNU General Public License for more details.
///
/// You should have received a copy of the GNU General Public License
/// along with this program; if not, write to the Free Software
/// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
///
/// @author Max Voronkov <maxim.voronkov@csiro.au>
/// @author Vitaliy Ogarko <vogarko@gmail.com>
///
#ifndef GENERIC_NORMAL_EQUATIONS_H
#define GENERIC_NORMAL_EQUATIONS_H
// casa includes
#include <casacore/casa/Arrays/Matrix.h>
#include <casacore/casa/Arrays/Vector.h>
#include <casacore/casa/Arrays/Array.h>
// own includes
#include <askap/scimath/fitting/INormalEquations.h>
#include <askap/scimath/fitting/ComplexDiffMatrix.h>
#include <askap/scimath/fitting/PolXProducts.h>
#include <askap/scimath/fitting/Params.h>
// std includes
#include <map>
#include <string>
namespace askap {
namespace scimath {
// forward declarations
class DesignMatrix;
/// @brief Normal equations without any approximation
/// @details There are two kinds of normal equations currently supported. The
/// first one is a generic case, where the full normal matrix is retained. It
/// is used for calibration. The second one is intended for imaging, where we
/// can't afford to keep the whole normal matrix. In this approach, the matrix
/// is approximated by a sum of diagonal and shift invariant matrices. This
/// class represents the generic case, where no approximation to the normal
/// matrix is done.
/// @ingroup fitting
struct GenericNormalEquations : public INormalEquations {
/// @brief a default constructor
/// @details It creates an empty normal equations class
GenericNormalEquations();
/// @brief copy constructor
/// @details It is required because this class has non-trivial types (std containers
/// of casa containers)
/// @param[in] src other class
GenericNormalEquations(const GenericNormalEquations &src);
/// @brief assignment operator
/// @details It is required because this class has non-trivial types (std containers
/// of casa containers)
/// @param[in] src other class
/// @return reference to this object
GenericNormalEquations& operator=(const GenericNormalEquations &src);
/// @brief constructor from a design matrix
/// @details This version of the constructor is equivalent to an
/// empty constructor plus a call to add method with the given
/// design matrix
/// @param[in] dm Design matrix to use
explicit GenericNormalEquations(const DesignMatrix& dm);
/// @brief reset the normal equation object
/// @details After a call to this method the object has the same pristine
/// state as immediately after creation with the default constructor
virtual void reset();
/// @brief Clone this into a shared pointer
/// @details "Virtual constructor" - creates a copy of this object. Derived
/// classes must override this method to instantiate the object of a proper
/// type.
/// @return shared pointer on INormalEquation class
virtual GenericNormalEquations::ShPtr clone() const;
/// @brief Merge these normal equations with another
/// @details Combining two normal equations depends on the actual class type
/// (different work is required for a full matrix and for an approximation).
/// This method must be overriden in the derived classes for correct
/// implementation.
/// This means that we just add
/// @param[in] src an object to get the normal equations from
virtual void merge(const INormalEquations& src);
/// @brief Add a design matrix to the normal equations
/// @details This method computes the contribution to the normal matrix
/// using a given design matrix and adds it.
/// @param[in] dm Design matrix to use
void add(const DesignMatrix& dm);
/// @brief add special type of design equations formed as a matrix product
/// @details This method adds design equations formed by a product of
/// a certain CompleDiffMatrix and a vector. It is equivalent to adding a design
/// matrix formed from the result of this product. However, bypassing design
/// matrix allows to delay calculation of contributions to the normal matrix and
/// use buffer cross terms (between model and measured visibilities, which are
/// expected to be a part of the vector cdm is multiplied to) separately. This
/// is used for pre-averaging (or pre-summing to be exact) calibration. The
/// cross-products of visibilities are tracked using the PolXProduct object
/// @param[in] cdm matrix with derivatives and values (to be multiplied to a
/// vector represented by cross-products given in the second parameter). Should be
/// a square matrix of npol x npol size.
/// @param[in] pxp cross-products (model by measured and model by model, where
/// measured is the vector cdm is multiplied to).
void add(const ComplexDiffMatrix &cdm, const PolXProducts &pxp);
/// @brief add normal matrix for a given parameter
/// @details This means that the cross terms between parameters
/// are excluded. However the terms inside a parameter are retained.
/// @param[in] name Name of the parameter
/// @param[in] normalmatrix Normal Matrix for this parameter
/// @param[in] datavector Data vector for this parameter
void add(const string& name, const casacore::Matrix<double>& normalmatrix,
const casacore::Vector<double>& datavector);
/// @brief normal equations for given parameters
/// @details In the current framework, parameters are essentially
/// vectors, not scalars. Each element of such vector is treated
/// independently (but only vector as a whole can be fixed). As a
/// result any element of the normal matrix is another matrix for
/// all non-scalar parameters. For scalar parameters each such
/// matrix has a shape of [1,1].
/// @param[in] par1 the name of the first parameter
/// @param[in] par2 the name of the second parameter
/// @return one element of the sparse normal matrix (a dense matrix)
virtual const casacore::Matrix<double>& normalMatrix(const std::string &par1,
const std::string &par2) const;
/// @brief Returns iterator to the beginning of normal matrix row, defined by input parameter.
/// @param[in] par the name of the parameter describing the matrix row
std::map<string, casa::Matrix<double> >::const_iterator getNormalMatrixRowBegin(const std::string &par) const;
/// @brief Returns iterator to the end of normal matrix row, defined by input parameter.
/// @details It is used together with getNormalMatrixRowBegin() to iterate through the (sparse) matrix elements.
/// @param[in] par the name of the parameter describing the matrix row
std::map<string, casa::Matrix<double> >::const_iterator getNormalMatrixRowEnd(const std::string &par) const;
/// @brief Returns the number of (scalar) elements in the normal matrix.
/// @details This should be close to the number of non zero elements,
/// depending if the elements-matrices (casa::Matrix) have non diagonal nonzero elements (or leakages).
size_t getNumberElements() const;
/// @brief data vector for a given parameter
/// @details In the current framework, parameters are essentially
/// vectors, not scalars. Each element of such vector is treated
/// independently (but only vector as a whole can be fixed). As a
/// result any element of the normal matrix as well as an element of the
/// data vector are, in general, matrices, not scalar. For the scalar
/// parameter each element of data vector is a vector of unit length.
/// @param[in] par the name of the parameter of interest
/// @return one element of the sparse data vector (a dense vector)
virtual const casacore::Vector<double>& dataVector(const std::string &par) const;
/// @brief write the object to a blob stream
/// @param[in] os the output stream
virtual void writeToBlob(LOFAR::BlobOStream& os) const;
/// @brief read the object from a blob stream
/// @param[in] is the input stream
/// @note Not sure whether the parameter should be made const or not
virtual void readFromBlob(LOFAR::BlobIStream& is);
/// @brief obtain all parameters dealt with by these normal equations
/// @details Normal equations provide constraints for a number of
/// parameters (i.e. unknowns of these equations). This method returns
/// a vector with the string names of all parameters mentioned in the
/// normal equations represented by the given object.
/// @return a vector listing the names of all parameters (unknowns of these equations)
/// @note if ASKAP_DEBUG is set some extra checks on consistency of these
/// equations are done
virtual std::vector<std::string> unknowns() const;
/// @brief obtain reference to metadata
/// @details It is handy to have key=value type metadata transported along with the
/// normal equations. The main applications are the metadata for calibration parameters
/// (i.e. time the solution corresponds to) and parameters which could assist merging of
/// the normal equations in a more intelligent way in the imaging case. At this stage,
/// calibration is the main driver. Therefore, this data field and handling methods are
/// implemented only for GenericNormalEquations. We could move this up in the hierarchy
/// and even expose access methods via the main interface.
/// @return reference to metadata
inline Params& metadata() { return itsMetadata;}
/// @brief obtain const reference to metadata
/// @details This is a const version of the metadata() method
/// @return const reference to metadata
inline const Params& metadata() const { return itsMetadata; }
protected:
/// @brief map of matrices (data element of each row map)
typedef std::map<std::string, casacore::Matrix<double> > MapOfMatrices;
/// @brief map of vectors (data vectors for all parameters)
typedef std::map<std::string, casacore::Vector<double> > MapOfVectors;
/// @brief Add one parameter from another normal equations class
/// @details This helper method is used in merging of two normal equations.
/// It processes just one parameter.
/// @param[in] par name of the parameter to copy
/// @param[in] src an object to get the normal equations from
/// @note This helper method works with instances of this class only (as
/// only then it knows how the actual normal matrix is handled). One could
/// have a general code which would work for every possible normal equation,
/// but in some cases it would be very inefficient. Therefore, the decision
/// has been made to throw an exception if incompatible operation is requested
/// and add the code to handle this situation later, if it appears to be
/// necessary.
void mergeParameter(const std::string &par, const GenericNormalEquations& src);
/// @brief Add/update one parameter using given matrix and data vector
/// @details This helper method is the main workhorse used in merging two
/// normal equations, adding an independent parameter or a design matrix.
/// The normal matrix to be integrated with this class is given in the form
/// of map of matrices (effectively a sparse matrix). Each element of the map
/// corresponds to a cross- or parallel term in the normal equations. Data
/// vector is given simply as a casacore::Vector, rather than the map of vectors,
/// because only one parameter is concerned here. If a parameter with the given
/// name doesn't exist, the method adds it to both normal matrix and data vector,
/// populating correctly all required cross-terms with 0-matrices of an
/// appropriate shape.
/// @param[in] par name of the parameter to work with
/// @param[in] inNM input normal matrix
/// @param[in] inDV input data vector
void addParameter(const std::string &par, const MapOfMatrices &inNM,
const casa::Vector<double>& inDV);
/// @brief Add/update one parameter to/in sparse matrix, using given matrix and data vector.
/// @details Similar to addParameter, but does not initialize the full matrix.
/// Instead, only elements (cross-terms) used in calculations get initialized,
/// essentially allowing for building a sparse matrix.
/// @param[in] par name of the parameter to work with
/// @param[in] inNM input normal matrix
/// @param[in] inDV input data vector
void addParameterSparsely(const std::string &par, const MapOfMatrices &inNM,
const casa::Vector<double>& inDV);
/// @brief extract dimension of a parameter from the given row
/// @details This helper method analyses the matrices stored in the supplied
/// map (effectively a row of a sparse matrix) and extracts the dimension of
/// the parameter this row corresponds to. If compiled with ASKAP_DEBUG,
/// this method does an additional consistency check that all elements of
/// the sparse matrix give the same dimension (number of rows is the same for
/// all elements).
/// @param[in] nmRow a row of the sparse normal matrix to work with
/// @return dimension of the corresponding parameter
static casa::uInt parameterDimension(const MapOfMatrices &nmRow);
/// @brief Calculate an element of A^tA
/// @details Each element of a sparse normal matrix is also a matrix
/// in general. However, due to some limitations of CASA operators, a
/// separate treatment is required for degenerate cases. This method
/// calculates an element of the normal matrix (effectively an element of
/// a product of A transposed and A, where A is the whole design matrix)
/// @param[in] matrix1 the first element of a sparse normal matrix
/// @param[in] matrix2 the second element of a sparse normal matrix
/// @return a product of matrix1 transposed to matrix2
static casacore::Matrix<double> nmElement(const casacore::Matrix<double> &matrix1,
const casacore::Matrix<double> &matrix2);
/// @brief Calculate an element of A^tB
/// @details Each element of a sparse normal matrix is also a matrix
/// in general. However, due to some limitations of CASA operators, a
/// separate treatment is required for degenerate cases. This method
/// calculates an element of the right-hand side of the normal equation
/// (effectively an element of a product of A transposed and the data
/// vector, where A is the whole design matrix)
/// @param[in] dm an element of the design matrix
/// @param[in] dv an element of the data vector
/// @return element of the right-hand side of the normal equations
static casa::Vector<double> dvElement(const casa::Matrix<double> &dm,
const casa::Vector<double> &dv);
/// @brief Extract derivatives from design matrix
/// @details This method extracts an appropriate derivative matrix
/// from the given design matrix. Effectively, it implements
/// dm.derivative(par)[dataPoint] with some additional validity checks
/// @param[in] dm Design matrix to work with
/// @param[in] par parameter name of interest
/// @param[in] dataPoint a sequence number of the data point, for which
/// the derivatives are returned
/// @return matrix of derivatives
static const casacore::Matrix<double>& extractDerivatives(const DesignMatrix &dm,
const std::string &par, casacore::uInt dataPoint);
private:
// Adding the data vector for a parameter.
void addDataVector(const std::string &par, const casa::Vector<double>& inDV);
/// @brief test that all matrix elements are zero
/// @details This is a helper method to test all matrix elements
/// @param[in] matrix matrix to test
/// @return true if all elements are zero
static bool allMatrixElementsAreZeros(const casa::Matrix<double>& matrix);
/// @brief normal matrix
/// @details Normal matrices stored as a map or maps of Matrixes -
/// it's really just a big matrix.
std::map<string, MapOfMatrices> itsNormalMatrix;
/// @brief the data vectors
/// @details This parameter may eventually go a level up in the class
/// hierarchy
MapOfVectors itsDataVector;
/// @brief metadata
/// @details It is handy to have key=value type metadata transported along with the
/// normal equations. The main applications are the metadata for calibration parameters
/// (i.e. time the solution corresponds to) and parameters which could assist merging of
/// the normal equations in a more intelligent way in the imaging case. At this stage,
/// calibration is the main driver. Therefore, this data field and handling methods are
/// implemented only for GenericNormalEquations. We could move this up in the hierarchy
/// and even expose access methods via the main interface.
Params itsMetadata;
};
} // namespace scimath
} // namespace askap
#endif // #ifndef GENERIC_NORMAL_EQUATIONS_H
|
9522b7b63f2fd754e2436be5442a08505e8145dc | 735a7df620232d87a54c4e53c86ea8d0c07b6afa | /Concurso_3/A.cpp | ff8357ef8dc7dee99c60417e96d667fba385cb9e | [] | no_license | DanielCuSanchez/vjudge-ejercicios-algoritmos | 7916026b66932a9649c310a34093265558aa167a | 097e768f4d29f98807f28f06defa64e8d5e7f77c | refs/heads/master | 2023-05-28T11:53:41.266514 | 2021-06-10T15:00:05 | 2021-06-10T15:00:05 | 361,593,680 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 519 | cpp | A.cpp | /*
Daniel Cu Sanchez
A01703613
*/
//A - Problem 160A
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int numberOfCoins, a[100], sum = 0, ans = 0, counter = 0;
cin >> numberOfCoins;
for (int i = 0; i < numberOfCoins; i++)
{
cin >> a[i];
}
sort(a, a + numberOfCoins);
for (int i = 0; i < numberOfCoins; i++)
{
sum += a[i];
}
sum = sum / 2;
while (ans <= sum)
{
++counter;
ans += a[numberOfCoins - counter];
}
cout << counter;
return 0;
} |
32de6bdfdf641fd6a958cae16c4b83d983267df4 | eb95a186af602d623b73a20b8d29d16789036a77 | /Game/MyProject/Game/BasicMenu/FirstMenu.cpp | cdac323f61b6dbc35d4ff8f375339b39b28f6108 | [] | no_license | sabauandrei98/RacingGame | edd89aaf1ef19ee2cd146d3311b963e52eb7676a | f225936370db3872f7a8e2dd45f1152dd4b85f98 | refs/heads/master | 2020-05-04T07:32:24.919402 | 2019-05-23T13:40:22 | 2019-05-23T13:40:22 | 179,030,272 | 0 | 0 | null | 2019-05-23T13:40:23 | 2019-04-02T08:12:43 | C++ | UTF-8 | C++ | false | false | 2,885 | cpp | FirstMenu.cpp | //-------------------------------------------------------------------------------
//-- FirstMenu.cpp --------------------------------------------------------------
//-------------------------------------------------------------------------------
#include "FirstMenu.hpp"
//-------------------------------------------------------------------------------
// PUBLIC METHODS
//-------------------------------------------------------------------------------
//-------------------------------------------------------------------------------
// @FirstMenu::FirstMenu()
//-------------------------------------------------------------------------------
FirstMenu::FirstMenu()
{
MeshManager meshManager;
std::shared_ptr<Camera> camera=std::make_shared<Camera>(45.0, 0.1, 100.0, 1280, 720);
camera->setLookAt({0.f, 0.f, 0.f });
camera->setPosition({0,-25,0});
camera->setRotation({0,0,1});
menu=std::make_shared<SceneGraph>();
std::shared_ptr<SceneNode> root=std::make_shared<SceneNode>("rootFirstMenu");
std::vector<std::string> uniforms;
uniforms.push_back("mTexture");
std::shared_ptr<SceneNode> testQuad=HelperManager::BuildTexturedQuad("test",HelperManager::CreateMeshInstance(meshManager.GetMesh("quad"),uniforms,"../../Game/BasicMenu/Shaders/AlphaChanger"),"../../Game/BasicMenu/Resources/test.tga");
std::shared_ptr<SceneNode> gameQuad=HelperManager::BuildTexturedQuad("game",HelperManager::CreateMeshInstance(meshManager.GetMesh("quad"),uniforms,"../../Game/BasicMenu/Shaders/AlphaChanger"),"../../Game/BasicMenu/Resources/game.tga");
std::shared_ptr<SceneNode> exitQuad=HelperManager::BuildTexturedQuad("exitFirst",HelperManager::CreateMeshInstance(meshManager.GetMesh("quad"),uniforms,"../../Game/BasicMenu/Shaders/AlphaChanger"),"../../Game/BasicMenu/Resources/exit.tga");
testQuad->setLocalTransform(IvVector3{-4,0,0}, IvVector3{0,4.72,1}, IvVector3{4,4,5});
gameQuad->setLocalTransform(IvVector3{4,0,0}, IvVector3{0,4.72,1}, IvVector3{4,4,5});
exitQuad->setLocalTransform(IvVector3{14,0,-5}, IvVector3{0,4.72,1}, IvVector3{4,5,4});
std::shared_ptr<CameraSceneNode> cameraSceneNode=std::make_shared<CameraSceneNode>("camera",camera);
menu->setRoot(root);
menu->getRoot()->addChild(testQuad);
menu->getRoot()->addChild(gameQuad);
menu->getRoot()->addChild(exitQuad);
menu->getRoot()->addChild(cameraSceneNode);
menu->setCamera(camera);
}
//-------------------------------------------------------------------------------
// @FirstMenu::~FirstMenu()
//-------------------------------------------------------------------------------
FirstMenu::~FirstMenu()
{
}
//-------------------------------------------------------------------------------
// PRIVATE METHODS
//-------------------------------------------------------------------------------
|
01dad2f9073b30807498b246b257956b744b65a9 | f821e756a85def979302e35053b8584ccb511edf | /Ejercicio 3.ino | 53e3f6a890fdfd668e04379c59de1d8983a623ae | [] | no_license | PalomaPavoni/Desaf-o-27-de-mayo | d9ba9659e16b7dbd3d5a09ea9b81b6500325b546 | 14541f45f7e730f11288bacdd3ad3790a01779da | refs/heads/main | 2023-05-14T03:38:34.785058 | 2021-06-02T19:18:22 | 2021-06-02T19:18:22 | 371,829,998 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 247 | ino | Ejercicio 3.ino | void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.println("funcionamiento ok.");
delay(1000);
}
void serialEvent(){
String lectura = Serial.readString();
if(lectura.equals("hola")){
Serial.println("full picado pa");
}
}
|
5df4b5fb9e6e327c221e992605676b6870749928 | c279a2fcb56de70f5cac2c8e890f155e177e676e | /Source/Plugins/SubsystemPlugins/BladeUI/header/interface/IUISystem.h | bf6a7b5821a80a49328ef5e56b106b53d002b005 | [
"MIT"
] | permissive | crazii/blade | b4abacdf36677e41382e95f0eec27d3d3baa20b5 | 7670a6bdf48b91c5e2dd2acd09fb644587407f03 | refs/heads/master | 2021-06-06T08:41:55.603532 | 2021-05-20T11:50:11 | 2021-05-20T11:50:11 | 160,147,322 | 161 | 34 | NOASSERTION | 2019-01-18T03:36:11 | 2018-12-03T07:07:28 | C++ | UTF-8 | C++ | false | false | 570 | h | IUISystem.h | /********************************************************************
created: 2010/04/29
filename: IUISystem.h
author: Crazii
purpose:
*********************************************************************/
#ifndef __Blade_IUISystem_h__
#define __Blade_IUISystem_h__
#include <BladeUI.h>
#include <interface/public/ui/IUIService.h>
#include <interface/public/ISubsystem.h>
namespace Blade
{
class IUISystem : public ISubsystem, public IUIService
{
public:
virtual ~IUISystem() {}
};//class IUISystem
}//namespace Blade
#endif //__Blade_IUISystem_h__ |
34c9084ddc89d70d02ecdce04e9687ca47573f4a | 8a4401e9985a059aff8aa8eab1dd8564d5e7409c | /SpaceInvadersWindows/BulletConstructor.h | e9890b4afb534bdc95407c8a301bf11c9cb6d703 | [] | no_license | DanOpdyke/Game-Engine-Windows | 0ecf3971aab53623185e66fc5aa36fadc93b344c | 229aae4ff98dec49687a176ac875716133c55ee6 | refs/heads/master | 2021-01-25T08:42:19.173022 | 2015-10-13T01:10:54 | 2015-10-13T01:10:54 | 42,748,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 357 | h | BulletConstructor.h | #pragma once
#include "GameObjectConstructor.h"
namespace SI
{
class BulletConstructor :
public GameObjectConstructor
{
public:
BulletConstructor();
~BulletConstructor();
// Inherited via GameObjectConstructor
GameObject & configureObject(RenderSystem & renderSystem, LevelInputHandler & inputHandler, GameObject & object) override;
};
}
|
89c5633d6114ebed2b31f3b2b127377debfe9381 | de4cf9d9c6a0e799bbf4d596ad2b81f4d673dafd | /chat.cpp | 2dd7d1431bf8463bf9e0b891b69c1aecfe6e23a3 | [] | no_license | samuraiexx/ChatP2P_UDP | e8521625240d50cca3732a764c7ddd57eaac35aa | e5e6b891721482e6a2888a6215ce387ce470c631 | refs/heads/master | 2021-07-14T14:28:02.597413 | 2017-10-14T16:00:05 | 2017-10-14T16:00:05 | 105,715,973 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,833 | cpp | chat.cpp | #include <iostream>
#include <vector>
#include <stdlib.h>
#include <string>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <thread>
#include <iomanip>
#include <sstream>
#include <mutex>
#include <queue>
#include <unistd.h>
#include <sys/fcntl.h>
using namespace std;
#define BUFFERSIZE 2048
string to_hex_string( const unsigned int i ) {
std::stringstream s;
s << "0x" << setfill('0') << setw(2) << hex << i;
return s.str();
}
class ChatHandler{
mutex qMu;
priority_queue<string, vector<string>, greater<string>> queued_msgs; // true for messages false for confirmations
string last_confirmed;
bool on;
friend class Client;
friend class Server;
};
class Client{
protected:
char buffer[BUFFERSIZE];
int send_s; //socket for send and receive
struct sockaddr_in localAddr, remoteAddr, fromAddr;
int count;
socklen_t addr_size;
ChatHandler* handler;
public:
Client(int remote_port, string ip, ChatHandler &chandler){
handler = &chandler;
count = 0;
handler->on = true;
addr_size = sizeof fromAddr;
if((send_s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
throw string("Socket creation failed");
memset(&localAddr, 0, sizeof(localAddr));
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(0);
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
if(bind(send_s, (struct sockaddr*) &localAddr, sizeof(localAddr)) < 0)
throw string("Bind failed1");
if(fcntl(send_s, F_SETFL, O_NONBLOCK) < 0)
throw string("Failed to set socket to non-blocking.");
memset(&remoteAddr, 0, sizeof(remoteAddr));
remoteAddr.sin_family = AF_INET;
remoteAddr.sin_port = htons(remote_port);
if(inet_pton(AF_INET, ip.c_str(), &remoteAddr.sin_addr) <= 0)
throw "Invalid Adress";
}
void client_thread(){
while(handler->on) if(handler->queued_msgs.size()) {
unique_lock<mutex> locker(handler->qMu);
string msg = handler->queued_msgs.top(); handler->queued_msgs.pop();
locker.unlock();
string pkt = msg.substr(0, 4);
if(pkt.compare(to_hex_string(0))){ //if its a message, not a confirmation
while(handler->last_confirmed.compare(pkt) != 0) {
locker.lock();
string top;
while(handler->queued_msgs.size() && (top = handler->queued_msgs.top()).substr(0, 4).compare(to_hex_string(0)))
sendto(send_s, top.c_str(), top.size() + 1, 0,
(struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
locker.unlock();
sendto(send_s, msg.c_str(), msg.size() + 1, 0,
(struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
}
} else { //its is a confirmation
sendto(send_s, msg.c_str(), msg.size() + 1, 0,
(struct sockaddr*) &remoteAddr, sizeof(remoteAddr));
}
}
}
void turn_off(){ handler->on = false; }
void send(string msg) {
if(msg == "EXIT")
throw string("Chat has ended.");
while(handler->queued_msgs.size() > 0 && count == 255); //Id reset, must wait the queue
if(count == 255) count = 0;
lock_guard<mutex> locker(handler->qMu);
handler->queued_msgs.push(to_hex_string(++count) + msg);
}
};
class Server{
protected:
char buffer[BUFFERSIZE];
int send_s, receive_s; //socket for send and receive
struct sockaddr_in localAddr, remoteAddr, fromAddr;
socklen_t addr_size;
string last_readed;
ChatHandler* handler;
public:
Server(int local_port, ChatHandler &chandler){
handler = &chandler;
handler->on = true;
addr_size = sizeof fromAddr;
if((receive_s = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
throw string("Socket creation failed");
memset(&localAddr, 0, sizeof(localAddr));
localAddr.sin_family = AF_INET;
localAddr.sin_addr.s_addr = htonl(INADDR_ANY);
localAddr.sin_port = htons(local_port);
if(bind(receive_s, (struct sockaddr*) &localAddr, sizeof(localAddr)) < 0)
throw string("Bind failed4");
if(fcntl(receive_s, F_SETFL, O_NONBLOCK) < 0)
throw string("Failed to set socket to non-blocking.");
}
void turn_off() { handler->on = false; }
void server_thread(){
while(handler->on){
if(recvfrom(receive_s, buffer, BUFFERSIZE, 0, (struct sockaddr*)&fromAddr, &addr_size) < 4) continue;
string msg(buffer);
string pkt = msg.substr(0, 4);
msg = msg.substr(4);
if(pkt.compare(to_hex_string(0)) == 0) //confirmation message, update last packet received
handler->last_confirmed = msg;
else {
if(pkt.compare(last_readed)) cout << "\t\t\t\t\t" << msg << endl, last_readed = pkt;
unique_lock<mutex> locker(handler->qMu);
handler->queued_msgs.push(to_hex_string(0) + pkt);
locker.unlock();
}
}
}
};
int main(){
try{
string msg, dest_ip;
int port_in, port_out;
cout << "Escolha uma porta para enviar mensagens: ";
cin >> port_out;
cout << "Escolha uma porta para receber mensagens: ";
cin >> port_in;
cout << "Insira o IP do destino: ";
cin >> dest_ip;
getline(cin, msg);
cout << "Conversa iniciada." << endl;
ChatHandler cHandler;
Client clt(port_out, dest_ip, cHandler);
Server svr(port_in, cHandler);
thread client(&Client::client_thread, &clt);
thread server(&Server::server_thread, &svr);
try{
while(getline(cin, msg)) clt.send(msg);
} catch(string s){
cout << s << endl;
clt.turn_off();
svr.turn_off();
client.join();
server.join();
}
} catch(string s){
cout << s << endl;
}
}
|
76c86af1d2381f01839af6ad5e21392ab598f8d8 | cc13cce6c2c03b8a9c776a16dbd2dd3206cb03f6 | /user/WBC_Controller/WBC_States/Bounding/CtrlSet/KinBoundingAux.cpp | cacfbeb51c951e9bd586cae6f575f94e07f811a8 | [
"MIT"
] | permissive | alexhaislip/mit_mini_cheetah | fd91667ffd3324ee68da0b3003ffed3d8ea23bed | 4c3d6f9f34598b3e139bb30f4389d0c3b6b6fe74 | refs/heads/master | 2023-02-10T17:29:57.050879 | 2021-01-14T01:35:22 | 2021-01-14T01:35:22 | 470,216,254 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,434 | cpp | KinBoundingAux.cpp | #include "KinBoundingCtrl.hpp"
#include <WBC_States/Cheetah_DynaCtrl_Definition.h>
#include <WBC_States/Bounding/TaskSet/BodyRyRzTask.hpp>
#include <WBC_States/Bounding/TaskSet/BodyXYTask.hpp>
#include <WBC_States/Bounding/TaskSet/LocalHeadPosTask.hpp>
#include <WBC_States/Bounding/TaskSet/LocalPosTask.hpp>
#include <WBC_States/Bounding/TaskSet/LocalRollTask.hpp>
#include <WBC_States/Bounding/TaskSet/LocalTailPosTask.hpp>
#include <WBC_States/StateProvider.hpp>
#include <WBC_States/common/ContactSet/SingleContact.hpp>
#include <WBC_States/common/TaskSet/BodyOriTask.hpp>
#include <WBC_States/common/TaskSet/JPosTask.hpp>
#include <Utilities/save_file.h>
#include <ParamHandler/ParamHandler.hpp>
#include <WBC/WBIC/WBIC.hpp>
#include <WBC/WBLC/KinWBC.hpp>
#include <WBC_States/Bounding/BoundingTest.hpp>
template <typename T>
void KinBoundingCtrl<T>::FirstVisit() {
_qdot_pre_queue.push(_sp->_Qdot);
T apex = _total_mass * 9.81 * (_swing_time + _nominal_stance_time) /
(2. * 2.0 * 0.7 * _nominal_stance_time);
_front_z_impulse.setCurve(apex, _nominal_stance_time);
_hind_z_impulse.setCurve(apex, _nominal_stance_time);
_nominal_gait_period = _swing_time + _nominal_stance_time;
_front_swing_time = _nominal_gait_period / 2. - 2. * Test<T>::dt;
_front_previous_stance = _nominal_stance_time;
_front_previous_swing = _swing_time;
_front_current_stance = _nominal_stance_time;
_hind_previous_stance = _nominal_stance_time;
_hind_previous_swing = _swing_time;
_hind_current_stance = _nominal_stance_time;
_aerial_duration = 0.;
_ini_fr = Ctrl::_robot_sys->_pGC[linkID::FR] -
Ctrl::_robot_sys->_pGC[linkID::FR_abd];
_ini_fl = Ctrl::_robot_sys->_pGC[linkID::FL] -
Ctrl::_robot_sys->_pGC[linkID::FL_abd];
_fin_fr = _ini_fr + _bounding_test->_body_vel * _nominal_stance_time / 2.;
_fin_fl = _ini_fl + _bounding_test->_body_vel * _nominal_stance_time / 2.;
_ini_hr = Ctrl::_robot_sys->_pGC[linkID::HR] -
Ctrl::_robot_sys->_pGC[linkID::HR_abd];
_ini_hl = Ctrl::_robot_sys->_pGC[linkID::HL] -
Ctrl::_robot_sys->_pGC[linkID::HL_abd];
_fin_hr = _ini_hr + _bounding_test->_body_vel * _nominal_stance_time / 2.;
_fin_hl = _ini_hl + _bounding_test->_body_vel * _nominal_stance_time / 2.;
_front_start_time = _sp->_curr_time;
_hind_start_time = _sp->_curr_time;
_ctrl_start_time = _sp->_curr_time;
_ini_front_body = 0.5 * Ctrl::_robot_sys->_pGC[linkID::FR_abd] +
0.5 * Ctrl::_robot_sys->_pGC[linkID::FL_abd] -
0.5 * Ctrl::_robot_sys->_pGC[linkID::FR] -
0.5 * Ctrl::_robot_sys->_pGC[linkID::FL];
_ini_hind_body = 0.5 * Ctrl::_robot_sys->_pGC[linkID::HR_abd] +
0.5 * Ctrl::_robot_sys->_pGC[linkID::HL_abd] -
0.5 * Ctrl::_robot_sys->_pGC[linkID::HR] -
0.5 * Ctrl::_robot_sys->_pGC[linkID::HL];
}
template <typename T>
void KinBoundingCtrl<T>::_contact_update() {
typename std::vector<ContactSpec<T> *>::iterator iter =
Ctrl::_contact_list.begin();
while (iter < Ctrl::_contact_list.end()) {
(*iter)->UpdateContactSpec();
++iter;
}
iter = _kin_contact_list.begin();
while (iter < _kin_contact_list.end()) {
(*iter)->UpdateContactSpec();
++iter;
}
}
///////////////////////////////////////////////////////////////////////////////
// PARAMETER setup
///////////////////////////////////////////////////////////////////////////////
template <typename T>
void KinBoundingCtrl<T>::CtrlInitialization(const std::string &category_name) {
_param_handler->getValue<T>(category_name, "K_time", _K_time);
_param_handler->getValue<T>(category_name, "K_pitch", _K_pitch);
_param_handler->getValue<T>(category_name, "impact_amp", _impact_amp);
_param_handler->getValue<T>(category_name, "front_foot_offset",
_front_foot_offset);
_param_handler->getValue<T>(category_name, "hind_foot_offset",
_hind_foot_offset);
_param_handler->getValue<T>(category_name, "swing_height", _swing_height);
_param_handler->getValue<T>(category_name, "contact_vel_threshold",
_contact_vel_threshold);
_param_handler->getValue<T>(category_name, "total_mass", _total_mass);
_param_handler->getValue<T>(category_name, "step_length_limit",
_step_length_lim);
_param_handler->getValue<T>(category_name, "step_width", _step_width);
}
template <typename T>
void KinBoundingCtrl<T>::SetTestParameter(const std::string &test_file) {
_param_handler = new ParamHandler(test_file);
std::vector<T> tmp_vec;
if (!_param_handler->getValue<T>("leg_height", _target_leg_height)) {
printf("[BoundingInitiate] No leg height\n");
}
_param_handler->getValue<T>("swing_time", _swing_time);
_param_handler->getValue<T>("default_stance_time", _nominal_stance_time);
_param_handler->getValue<T>("bounding_time", _end_time);
_param_handler->getVector<T>("Kp_ryrz", tmp_vec);
for (size_t i(0); i < tmp_vec.size(); ++i) {
((BodyRyRzTask<T> *)_body_ryrz_task)->_Kp[i] = tmp_vec[i];
}
_param_handler->getVector<T>("Kd_ryrz", tmp_vec);
for (size_t i(0); i < tmp_vec.size(); ++i) {
((BodyRyRzTask<T> *)_body_ryrz_task)->_Kd[i] = tmp_vec[i];
}
// Head Pos
_param_handler->getVector<T>("Kp_head", tmp_vec);
for (size_t i(0); i < tmp_vec.size(); ++i) {
((LocalHeadPosTask<T> *)_local_head_pos_task)->_Kp[i] = tmp_vec[i];
}
_param_handler->getVector<T>("Kd_head", tmp_vec);
for (size_t i(0); i < tmp_vec.size(); ++i) {
((LocalHeadPosTask<T> *)_local_head_pos_task)->_Kd[i] = tmp_vec[i];
}
// Tail Pos
_param_handler->getVector<T>("Kp_tail", tmp_vec);
for (size_t i(0); i < tmp_vec.size(); ++i) {
((LocalTailPosTask<T> *)_local_tail_pos_task)->_Kp[i] = tmp_vec[i];
}
_param_handler->getVector<T>("Kd_tail", tmp_vec);
for (size_t i(0); i < tmp_vec.size(); ++i) {
((LocalTailPosTask<T> *)_local_tail_pos_task)->_Kd[i] = tmp_vec[i];
}
// Local Roll
T tmp_value;
_param_handler->getValue<T>("Kp_roll", tmp_value);
((LocalRollTask<T> *)_local_roll_task)->_Kp[0] = tmp_value;
_param_handler->getValue<T>("Kd_roll", tmp_value);
((LocalRollTask<T> *)_local_roll_task)->_Kd[0] = tmp_value;
// Joint level feedback gain
_param_handler->getVector<T>("Kp_joint", _Kp_joint);
_param_handler->getVector<T>("Kd_joint", _Kd_joint);
}
template <typename T>
void KinBoundingCtrl<T>::LastVisit() {}
template <typename T>
bool KinBoundingCtrl<T>::EndOfPhase() {
if (_sp->_mode == 12) {
_bounding_test->_stop = true;
return true;
}
if(_jump_signal && _b_jump_initiation){
_jump_signal = false;
_b_jump_initiation = false;
return true;
}
return false;
}
template <typename T>
KinBoundingCtrl<T>::~KinBoundingCtrl() {
delete _kin_wbc;
delete _wbic;
delete _wbic_data;
delete _param_handler;
typename std::vector<Task<T> *>::iterator iter = Ctrl::_task_list.begin();
while (iter < Ctrl::_task_list.end()) {
delete (*iter);
++iter;
}
Ctrl::_task_list.clear();
typename std::vector<ContactSpec<T> *>::iterator iter2 =
Ctrl::_contact_list.begin();
while (iter2 < Ctrl::_contact_list.end()) {
delete (*iter2);
++iter2;
}
Ctrl::_contact_list.clear();
}
///////////////////////////////////////////////////////////////////////////////
// DATA save
///////////////////////////////////////////////////////////////////////////////
template <typename T>
void KinBoundingCtrl<T>::_lcm_data_sending() {
_wbc_data_lcm.contact_est[0] = _b_front_contact_est;
_wbc_data_lcm.contact_est[1] = _b_hind_contact_est;
for (size_t i(0); i < cheetah::num_act_joint; ++i) {
_wbc_data_lcm.jpos_cmd[i] = _des_jpos[i];
_wbc_data_lcm.jvel_cmd[i] = _des_jvel[i];
_wbc_data_lcm.jacc_cmd[i] = _des_jacc[i];
}
_wbc_data_lcm.body_ori[3] = Ctrl::_robot_sys->_state.bodyOrientation[3];
for (size_t i(0); i < 3; ++i) {
_wbc_data_lcm.body_ori[i] = Ctrl::_robot_sys->_state.bodyOrientation[i];
_wbc_data_lcm.body_ang_vel[i] = Ctrl::_robot_sys->_state.bodyVelocity[i];
_wbc_data_lcm.fr_foot_pos_cmd[i] = _fr_foot_pos[i];
_wbc_data_lcm.fl_foot_pos_cmd[i] = _fl_foot_pos[i];
_wbc_data_lcm.hr_foot_pos_cmd[i] = _hr_foot_pos[i];
_wbc_data_lcm.hl_foot_pos_cmd[i] = _hl_foot_pos[i];
_wbc_data_lcm.fr_foot_vel_cmd[i] = _fr_foot_vel[i];
_wbc_data_lcm.fl_foot_vel_cmd[i] = _fl_foot_vel[i];
_wbc_data_lcm.hr_foot_vel_cmd[i] = _hr_foot_vel[i];
_wbc_data_lcm.hl_foot_vel_cmd[i] = _hl_foot_vel[i];
_wbc_data_lcm.fr_foot_local_pos[i] =
_fr_foot_pos[i] - _fr_foot_local_task->getPosError()[i];
_wbc_data_lcm.fl_foot_local_pos[i] =
_fl_foot_pos[i] - _fl_foot_local_task->getPosError()[i];
_wbc_data_lcm.hr_foot_local_pos[i] =
_hr_foot_pos[i] - _hr_foot_local_task->getPosError()[i];
_wbc_data_lcm.hl_foot_local_pos[i] =
_hl_foot_pos[i] - _hl_foot_local_task->getPosError()[i];
_wbc_data_lcm.fr_foot_local_vel[i] =
(Ctrl::_robot_sys->_vGC[linkID::FR])[i] -
(Ctrl::_robot_sys->_vGC[linkID::FR_abd])[i];
_wbc_data_lcm.fl_foot_local_vel[i] =
(Ctrl::_robot_sys->_vGC[linkID::FL])[i] -
(Ctrl::_robot_sys->_vGC[linkID::FL_abd])[i];
_wbc_data_lcm.hr_foot_local_vel[i] =
(Ctrl::_robot_sys->_vGC[linkID::HR])[i] -
(Ctrl::_robot_sys->_vGC[linkID::HR_abd])[i];
_wbc_data_lcm.hl_foot_local_vel[i] =
(Ctrl::_robot_sys->_vGC[linkID::HL])[i] -
(Ctrl::_robot_sys->_vGC[linkID::HL_abd])[i];
if ((!_b_front_swing) && (!_b_hind_swing)) {
_wbc_data_lcm.fr_Fr_des[i] = _fr_contact->getRFDesired()[i];
_wbc_data_lcm.fl_Fr_des[i] = _fl_contact->getRFDesired()[i];
_wbc_data_lcm.hr_Fr_des[i] = _hr_contact->getRFDesired()[i];
_wbc_data_lcm.hl_Fr_des[i] = _hl_contact->getRFDesired()[i];
_wbc_data_lcm.fr_Fr[i] = _wbic_data->_Fr[i];
_wbc_data_lcm.fl_Fr[i] = _wbic_data->_Fr[i + 3];
_wbc_data_lcm.hr_Fr[i] = _wbic_data->_Fr[i + 6];
_wbc_data_lcm.hl_Fr[i] = _wbic_data->_Fr[i + 9];
} else if ((!_b_front_swing)) {
_wbc_data_lcm.fr_Fr_des[i] = _fr_contact->getRFDesired()[i];
_wbc_data_lcm.fl_Fr_des[i] = _fl_contact->getRFDesired()[i];
_wbc_data_lcm.fr_Fr[i] = _wbic_data->_Fr[i];
_wbc_data_lcm.fl_Fr[i] = _wbic_data->_Fr[i + 3];
} else if ((!_b_hind_swing)) {
_wbc_data_lcm.hr_Fr_des[i] = _hr_contact->getRFDesired()[i];
_wbc_data_lcm.hl_Fr_des[i] = _hl_contact->getRFDesired()[i];
_wbc_data_lcm.hr_Fr[i] = _wbic_data->_Fr[i];
_wbc_data_lcm.hl_Fr[i] = _wbic_data->_Fr[i + 3];
}
}
_wbcLCM.publish("wbc_lcm_data", &_wbc_data_lcm);
}
template <typename T>
void KinBoundingCtrl<T>::_save_file() {
saveValue(Ctrl::_state_machine_time, _folder_name, "time");
saveValue(_b_hind_contact, _folder_name, "hind_contact");
saveValue(_b_front_contact, _folder_name, "front_contact");
saveValue(_b_front_contact_est, _folder_name, "front_contact_est");
saveValue(_b_hind_contact_est, _folder_name, "hind_contact_est");
saveVector(_fr_foot_pos, _folder_name, "fr_foot_pos_cmd");
saveVector(_fr_foot_vel, _folder_name, "fr_foot_vel_cmd");
saveVector(_fr_foot_acc, _folder_name, "fr_foot_acc_cmd");
saveVector(_fl_foot_pos, _folder_name, "fl_foot_pos_cmd");
saveVector(_fl_foot_vel, _folder_name, "fl_foot_vel_cmd");
saveVector(_fl_foot_acc, _folder_name, "fl_foot_acc_cmd");
saveVector(_hr_foot_pos, _folder_name, "hr_foot_pos_cmd");
saveVector(_hr_foot_vel, _folder_name, "hr_foot_vel_cmd");
saveVector(_hr_foot_acc, _folder_name, "hr_foot_acc_cmd");
saveVector(_hl_foot_pos, _folder_name, "hl_foot_pos_cmd");
saveVector(_hl_foot_vel, _folder_name, "hl_foot_vel_cmd");
saveVector(_hl_foot_acc, _folder_name, "hl_foot_acc_cmd");
saveVector(_fr_foot_local_task->getPosError(), _folder_name, "fr_foot_err");
saveVector(_fl_foot_local_task->getPosError(), _folder_name, "fl_foot_err");
saveVector(_hr_foot_local_task->getPosError(), _folder_name, "hr_foot_err");
saveVector(_hl_foot_local_task->getPosError(), _folder_name, "hl_foot_err");
saveVector(_des_jpos, _folder_name, "jpos_cmd");
saveVector(_des_jvel, _folder_name, "jvel_cmd");
saveVector(_des_jacc, _folder_name, "jacc_cmd");
saveVector(_sp->_Q, _folder_name, "config");
saveVector(_sp->_Qdot, _folder_name, "qdot");
_Fr_des = DVec<T>::Zero(12);
_Fr_result = DVec<T>::Zero(12);
if ((!_b_front_swing) && (!_b_hind_swing)) { // Full Stance
_Fr_des.head(3) = _fr_contact->getRFDesired();
_Fr_des.segment(3, 3) = _fl_contact->getRFDesired();
_Fr_des.segment(6, 3) = _hr_contact->getRFDesired();
_Fr_des.segment(9, 3) = _hl_contact->getRFDesired();
_Fr_result = _wbic_data->_Fr;
} else if (!_b_front_swing) { // Front Stance
_Fr_des.head(3) = _fr_contact->getRFDesired();
_Fr_des.segment(3, 3) = _fl_contact->getRFDesired();
_Fr_result.head(6) = _wbic_data->_Fr;
} else if (!_b_hind_swing) { // Hind Stance
_Fr_des.segment(6, 3) = _hr_contact->getRFDesired();
_Fr_des.segment(9, 3) = _hl_contact->getRFDesired();
_Fr_result.tail(6) = _wbic_data->_Fr;
}
saveVector(_Fr_des, _folder_name, "Fr_des");
saveVector(_Fr_result, _folder_name, "Fr_result");
}
template class KinBoundingCtrl<double>;
template class KinBoundingCtrl<float>;
|
754067e8697986f0217ca0a3c0986b7a93d4cdd4 | c6847d62a4a35906bff53522bf3f20f8a6753c4c | /Flag.cpp | 8e1804ea14b61659ae739bbdc7ba45d6e197d9c3 | [] | no_license | alizare1/super-mario | bd70394a4fd960a1d4836d5de639187e4feec900 | 4846eb67e39a8635a5fed5d1d9cf1f2a86c5391e | refs/heads/master | 2021-06-12T20:17:52.808853 | 2021-05-30T06:31:58 | 2021-05-30T06:31:58 | 198,785,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 796 | cpp | Flag.cpp | #include "Flag.h"
Flag::Flag(Point headPos, int _height)
:position(headPos, BLOCK_SIZE, _height * BLOCK_SIZE),
height(_height) {}
void Flag::draw(Window* win, int winOffset) {
drawHead(win, winOffset);
if (height > 1)
drawBody(win, winOffset);
}
void Flag::drawHead(Window* win, int winOffset) {
win->draw_img(
FLAG_HEAD_PNG,
Rectangle(position.x - winOffset, position.y,
BLOCK_SIZE, BLOCK_SIZE)
);
}
void Flag::drawBody(Window* win, int winOffset) {
for (int i = 1; i < height; i++) {
win->draw_img(
FLAG_BODY_PNG,
Rectangle(position.x - winOffset, position.y + i * BLOCK_SIZE,
BLOCK_SIZE, BLOCK_SIZE)
);
}
}
Rectangle* Flag::getPositionPointer() {
return &position;
}
|
67f6748eb2ab8013c243e1ad28ffdc4213ddce4a | c6c9555e656c801ae580443260d6e01cdd6f8f01 | /cppitertools/permutations.hpp | 1d0e4442988af8057d2e9cd8e4a3e788a4514df1 | [
"BSD-2-Clause"
] | permissive | caomw/imageTriangulator | eabb5207b753262981a41207cf31d33ab30e07de | d2166f72eb7b5ff14f8a9ef3c3717d9d4f47bff6 | refs/heads/master | 2021-01-21T16:53:29.497463 | 2014-06-10T01:14:11 | 2014-06-10T01:14:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,180 | hpp | permutations.hpp | #ifndef PERMUTATIONS_HPP
#define PERMUTATIONS_HPP
#include "iterator_range.hpp"
#include <algorithm>
#include <initializer_list>
#include <vector>
namespace iter {
template <typename Container>
struct permutation_iter;
template <typename Container>
iterator_range<permutation_iter<Container>>
permutations (const Container & container) {
return iterator_range<permutation_iter<Container>>(
permutation_iter<Container>(container),
permutation_iter<Container>());
}
//since initializer_list doesn't have bidir iters this is a hack
//to get it to work by using a vector in its place
template <typename T>
iterator_range<permutation_iter<std::vector<T>>>
permutations (std::initializer_list<T> && container) {
std::vector<T> begin(std::begin(container),std::end(container));
return {permutation_iter<std::vector<T>>(container),
permutation_iter<std::vector<T>>()};
}
template <typename Container>
struct permutation_iter
{
Container container;
using Iterator = decltype(std::begin(container));
bool is_not_last = true;
permutation_iter(){}
permutation_iter(const Container & c) : container(c)
{
//sort first so you can get every permutation
std::sort(std::begin(container),std::end(container));
}
const Container & operator*()
{
return container;
}
permutation_iter & operator++() {
is_not_last = std::next_permutation(std::begin(container),std::end(container));
return *this;
}
bool operator!=(const permutation_iter &) {
return is_not_last;
}
};
}
namespace std {
template <typename Container>
struct iterator_traits<iter::permutation_iter<Container>> {
using difference_type = ptrdiff_t;
using iterator_category = input_iterator_tag;
};
}
#endif //PERMUTATIONS_HPP
|
afb9f018e5d2ea5f6fdfabdf445a0c04b19bcf03 | 5f6e42e41b04b369c1fe1c046cbe9d8c5fba3080 | /Software Projects/Implementation of a UML Class Application/Circle.cpp | 6bbaabfea993a87ab7911d0837fa57eacf6d52ad | [] | no_license | hshahzada/engineering-projects | e242dbe9515116b0c0746e5e9a7bfa24de0ca424 | 976a86e787182988fd374544b6ee89c93f571c78 | refs/heads/main | 2023-09-02T23:27:02.592600 | 2021-11-22T21:30:07 | 2021-11-22T21:30:07 | 430,847,048 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 281 | cpp | Circle.cpp | #include "Circle.h"
Circle::Circle(string color, double radius) : Shape(color), radius(radius) {
};
void Circle::print() {
double area = 3.14 * radius * radius;
cout << "Circle R=" << radius << ", area=" << area << ", " << getColor() << endl;
};
Circle::~Circle() {
};
|
dff12415a3e702262ae34a3f719420258de8e241 | a1e9b5703039e08f153c4c129d106abcc37778c2 | /上传版本/初赛/4_26/main.cpp | 4b6d6b267f1b962abfe0cb56cb1a162af8139f51 | [] | no_license | baoyi84930/HuaWeiCodeCraft2020 | d59c099e2d9480806a7277ef4dd7b45ca4002448 | 51c96eae8bf7df26b6c43e25ffd2f70486f99923 | refs/heads/master | 2022-07-12T22:07:19.533983 | 2020-05-16T17:14:47 | 2020-05-16T17:14:47 | 264,480,799 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,854 | cpp | main.cpp | #include <bits/stdc++.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
using namespace std;
struct Node{
string s;
int length;
Node(string s,int length) : s(s) ,length(length){}
bool operator<(Node &node) const {
if (length != node.length)
return length < node.length;
for (int i = 0; i < length; i++) {
if (s[i] != node.s[i])
return s[i] < node.s[i];
}
return 0;
}
bool operator==(Node &node) const {
if (length != node.length)
return false;
for (int i = 0; i < length; i++) {
if (s[i] != node.s[i])
return false;
}
return true;
}
};
#define TEST
int threadnum = 4;
vector<int> all_loops;
typedef unsigned int ui;
vector<array<string, 5>> Ans;
class Solution {
public:
vector<vector<int>> G, GF;
unordered_map<string, int> idHash; // sorted id to 0...n
vector<Node> ids; // 0...n to sorted id
vector<Node> inputs; // u-v pairs
vector<bool> vis, able4;
unordered_map<int, vector<array<int, 2>>> p4;
int nodeCnt;
int loops;
void operator()(int threadId) {
vis = vector<bool>(nodeCnt, false);
int path[7];
able4 = vector<bool>(nodeCnt, false);
for (int i = threadId; i < nodeCnt; i += threadnum) {
// cout << threadId << endl;
if (!G[i].empty()) {
prepare(i);
if (p4.size() == 0) {
continue;
}
dfs(i,i,1,path);
p4.clear();
able4 = vis;
}
}
all_loops[threadId] = loops;
}
void parseInput(string &testFile) {
struct stat file;
int f = open("/data/test_data.txt", O_RDONLY);
fstat(f,&file);
long long len = file.st_size;
char* buf = new char[len];
read(f,&buf[0],len);
char *data=new char[len];
strncpy(data,buf,len);
int num=0;
int index=0;
for (int i = 0; i < len; i++)
{
if(data[i]==',' || data[i]=='\n'){
num++;
if(num%3!=0){
data[i]='\0';
inputs.push_back(Node(&data[index],i-index));
}
index = i+1;
}
}
close(f);
}
void constructGraph() {
auto tmp = inputs;
sort(tmp.begin(), tmp.end());
tmp.erase(unique(tmp.begin(), tmp.end()), tmp.end());
ids = tmp;
nodeCnt = 0;
for (Node &n : tmp) {
idHash[n.s] = nodeCnt++;
}
int sz = inputs.size();
G = vector<vector<int>>(nodeCnt);
GF = vector<vector<int>>(nodeCnt);
for (int i = 0; i < sz; i += 2) {
int u = idHash[inputs[i].s], v = idHash[inputs[i + 1].s];
G[u].push_back(v);
GF[v].push_back(u);
}
// 测试 char* to sort 映射是否正常
// cout << nodeCnt << endl;
// cout << idHash[tmp[nodeCnt-1].s] << endl;
for (int i = 0; i < nodeCnt; i++) {
sort(G[i].begin(), G[i].end());
sort(GF[i].begin(), GF[i].end());
}
loops = 0;
}
void backhome(int head, int cur, int depth, int *path) {
path[depth - 1] = cur;
string tmp = "";
for (int i = 0; i < depth; i++) {
tmp.append(ids[path[i]].s + ",");
}
for (array<int, 2> &u : p4[cur]) {
if (!vis[u[0]] && !vis[u[1]]) {
Ans[head][depth - 1].append(tmp);
Ans[head][depth - 1].append(ids[u[0]].s + ",");
Ans[head][depth - 1].append(ids[u[1]].s + "\n");
loops++;
}
}
}
void dfs(int head, int cur, int depth, int *path) {
if (depth == 5) {
return;
}
vis[cur] = true;
path[depth - 1] = cur;
for (int &v : G[cur]) {
// 剪枝
if (v <= head || vis[v]) {
continue;
}
if (able4[v] && depth < 5) {
backhome(head, v, depth + 1, path);
}
dfs(head, v, depth + 1, path);
}
vis[cur] = false;
}
void prepare(int i) {
array<int, 2> temp2;
vector<array<int,2>> depth3;
string ans3="";
string head = ids[i].s + ",";
string one=head;
for (int &v : GF[i]) {
temp2[1] = v;
if (v > i) {
for (int &u : GF[v]) {
if (u > i) {
temp2[0] = u;
for (int &w : GF[u]) {
if(w!=v){
//构成三环
if(w==i){
depth3.push_back(temp2);
loops++;
}
else if (w > i) {
p4[w].push_back(temp2);
able4[w] = true;
sort(p4[w].begin(), p4[w].end());
}
}
}
}
}
}
}
// Ans[i][0].append(ans3);
sort(depth3.begin(),depth3.end());
for (array<int,2> &u:depth3)
{
Ans[i][0].append(head);
Ans[i][0].append(ids[u[0]].s+",");
Ans[i][0].append(ids[u[1]].s + "\n");
}
}
/*
fwrite 逐行写
*/
void save() {
// FILE *file = fopen("output.txt", "w");
FILE *file = fopen("/projects/student/result.txt", "w");
for (int &u : all_loops) {
loops += u;
}
fprintf(file, "%d\n", loops);
for (int i = 0; i < 5; i++) {
for (int k = 0; k < nodeCnt; k++) {
fwrite(Ans[k][i].c_str(), 1, Ans[k][i].length(), file);
}
}
fflush(file);
fclose(file);
}
};
int main() {
extern vector<array<string, 5>> Ans;
extern vector<int> all_loops;
// string testFile = "test_data.txt";
string testFile = "/data/test_data.txt";
Solution solution;
vector<thread> threadname;
solution.parseInput(testFile);
solution.constructGraph();
Ans = vector<array<string, 5>>(solution.nodeCnt);
all_loops = vector<int>(threadnum, 0);
for (int i = 0; i < threadnum; i++) {
thread mythread(solution, i);
threadname.push_back(move(mythread));
}
for (int i = 0; i < threadnum; i++) {
threadname[i].join();
}
solution.save();
return 0;
} |
e2aa233243382eccf120520339a235b3279af0ff | 4f870ad0794d9e9e550a5ed38aec5941eebcd463 | /Samples/LibTest/TestCases/CollectionTest.cpp | 27d67fb76fbf10cb6002685d991bc417e10b0231 | [] | no_license | Hongtae/DKTools_Legacy | 5d2efccad15ee1523c2c8e6d7828743aac1bf1d3 | 17c989695c8dac89b2b246fa61d1d37fce4f48ae | refs/heads/master | 2020-04-09T15:31:51.512556 | 2015-02-21T04:05:03 | 2015-02-21T04:05:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,440 | cpp | CollectionTest.cpp | #include "../TestCase.h"
struct CollectionTest : public TestCase
{
bool EnumFuncArrayAndSet(const int& a)
{
DKLog("[%s] value=%d\n", DKLIB_FUNCTION_NAME, a);
return true;
}
bool EnumFuncPair(const DKMap<int,int>::Pair& p)
{
DKLog("[%s] key=%d, value=%d\n", DKLIB_FUNCTION_NAME, p.key, p.value);
return true;
}
void EnumTest(size_t count)
{
DKArray<int> arrayItems;
DKOrderedArray<int> orderedItems;
DKMap<int, int> mapItems;
DKSet<int> setItems;
DKQueue<int> queueItems;
arrayItems.Reserve(count);
orderedItems.Reserve(count);
DKLog("Generating %d itmes\n", count);
for (unsigned int i = 0; i < count; i++)
{
//int v = DKRandom();
int v = i;
arrayItems.Add(v);
orderedItems.Insert(v);
mapItems.Insert(v, v);
setItems.Insert(v);
queueItems.PushBack(v);
}
arrayItems.EnumerateBackward([this](int a){ this->EnumFuncArrayAndSet(a); });
orderedItems.EnumerateBackward([this](int a){ this->EnumFuncArrayAndSet(a); });
mapItems.EnumerateBackward([this](DKMap<int, int>::Pair& a){ this->EnumFuncPair(a); });
setItems.EnumerateBackward([this](int a){ this->EnumFuncArrayAndSet(a); });
queueItems.EnumerateBackward([this](int a){ this->EnumFuncArrayAndSet(a); });
}
void TimeTest(size_t count)
{
DKArray<int> items;
items.Reserve(count);
DKLog("Generating %d itmes\n", count);
for (unsigned int i = 0; i < count; i++)
items.Add(DKRandom());
DKTimer timer;
{
DKLog("Insert %d items in DKArray\n", count);
DKArray<int> collection;
timer.Reset();
for (unsigned int i = 0; i < items.Count(); i++)
{
collection.Add(items.Value(i));
collection.Sort(0, collection.Count(), DKArraySortAscending<int>);
}
DKLog("Insert %d items in DKArray = %f\n", collection.Count(), timer.Elapsed());
}
{
DKLog("Insert %d items in DKSortedArray\n", count);
DKOrderedArray<int> collection;
timer.Reset();
for (unsigned int i = 0; i < items.Count(); i++)
collection.Insert(items.Value(i));
DKLog("Insert %d items in DKSortedArray = %f\n", collection.Count(), timer.Elapsed());
}
{
DKLog("Insert %d items in DKSet\n", count);
DKSet<int> collection;
timer.Reset();
for (unsigned int i = 0; i < items.Count(); i++)
collection.Insert(items.Value(i));
DKLog("Insert %d items in DKSet = %f\n", collection.Count(), timer.Elapsed());
}
}
void RunTest()
{
EnumTest(3);
TimeTest(1000);
}
} collectionTest;
|
b643dee36201b0e652fef98cdaea41bcdd01fc62 | 2124d0b0d00c3038924f5d2ad3fe14b35a1b8644 | /source/MagFieldManager/include/UniformFieldCreator.hh | 0a5c0b94984a2f97eec712c79cbf891c0bc28f73 | [] | no_license | arceciemat/GAMOS | 2f3059e8b0992e217aaf98b8591ef725ad654763 | 7db8bd6d1846733387b6cc946945f0821567662b | refs/heads/master | 2023-07-08T13:31:01.021905 | 2023-06-26T10:57:43 | 2023-06-26T10:57:43 | 21,818,258 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 945 | hh | UniformFieldCreator.hh | ///////////////////////////////////////////////////////////
/////////Code developed by SpaceIt GmbH, Bern Switzerland
/////////For the Space european Agency
/////////First Author :L. Desorgher
///////////////////////////////////////////////////////////
#ifndef UniformFieldCreator_HH
#define UniformFieldCreator_HH 1
#include"globals.hh"
#include"G4ios.hh"
#include"ParametrizedFieldCreator.hh"
class G4UIcmdWith3VectorAndUnit;
class G4UIdirectory;
class UniformFieldCreator : public ParametrizedFieldCreator
{
public:
UniformFieldCreator();
~UniformFieldCreator();
public: //methods
virtual void CreateMacroCommands(G4String cmd_dir_name, G4UImessenger* aMessenger);
G4bool DefineParameters(G4UIcommand* aCmd , G4String parameter_string);
virtual G4MagneticField* CreateNewField();
private:
G4UIcmdWith3VectorAndUnit* theCmd;
G4UIdirectory* UniformFieldDir;
G4ThreeVector B_vec;
} ;
#endif
|
e5fd43a0e9722b62118c46a3c1e5502427e3e47b | 281c2763051432271b132499702860bd2b3f5ffa | /Volume_21/2190_Angel_Stairs.cpp | 59c6a20efb1ae5c38f891a3986192931a0c8923b | [
"Apache-2.0"
] | permissive | dtbinh/AOJ | 27c95c32a829adbee37431e6e5f510723992fe45 | f4fc75717e67b85977f5ba0ccf9e823762e44a45 | refs/heads/master | 2021-01-24T23:42:46.858379 | 2015-05-25T17:05:03 | 2015-05-25T17:05:03 | 36,429,163 | 1 | 0 | null | 2015-05-28T09:46:45 | 2015-05-28T09:46:44 | null | UTF-8 | C++ | false | false | 2,001 | cpp | 2190_Angel_Stairs.cpp | #define _USE_MATH_DEFINES
#define INF 0x3f3f3f3f
#include <iostream>
#include <cstdio>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cctype>
#include <utility>
using namespace std;
typedef long long ll;
typedef pair <int,int> P;
typedef pair <int,P> PP;
static const double EPS = 1e-8;
static const int tx[] = {0,1,0,-1};
static const int ty[] = {-1,0,1,0};
map<string,int> note2idx;
const static int idx2dist[] = {1,-1,-2};
const static int offset[] = {11,0,1};
vector<int> stair;
vector<int> song;
bool dfs(int note_pos,int stair_pos){
if(note_pos == -1 && stair_pos == -1){
return true;
}
else if(stair_pos < 0 || note_pos < 0) return false;
bool res = false;
for(int i = 0; i < 3; i++){
if(song[note_pos] != (stair[stair_pos] + offset[i]) % 12) continue;
int next = stair_pos + idx2dist[i];
res |= dfs(note_pos - 1,next);
}
return res;
}
int main(){
int total_test_cases;
note2idx["C"] = 0;
note2idx["C#"] = 1;
note2idx["D"] = 2;
note2idx["D#"] = 3;
note2idx["E"] = 4;
note2idx["F"] = 5;
note2idx["F#"] = 6;
note2idx["G"] = 7;
note2idx["G#"] = 8;
note2idx["A"] = 9;
note2idx["A#"] = 10;
note2idx["B"] = 11;
while(~scanf("%d",&total_test_cases)){
for(int test_i = 0; test_i < total_test_cases; test_i++){
stair.clear();
song.clear();
int num_of_steps;
int song_length;
scanf("%d %d",&num_of_steps,&song_length);
for(int i = 0; i < num_of_steps; i++){
string note;
cin >> note;
stair.push_back(note2idx[note]);
}
for(int i = 0; i < song_length; i++){
string note;
cin >> note;
song.push_back(note2idx[note]);
}
printf("%s\n",(dfs(song.size()-1,stair.size()-2)
|| dfs(song.size()-1,stair.size()-1))
? "Yes" : "No");
}
}
}
|
a150b26830117b03f6c2aee6438bf57ffec1de32 | a92237bd9b14f588b9fdae06f60ddca998f504c3 | /src/pieces/King.h | 18b14622543af8445c241896f1e893d348a300d0 | [] | no_license | darrian12/Chess | 2149c132fb962d8c486251d3f02c12135d8052f6 | 13ef6491d5832540132d1f310881a424c5287cbe | refs/heads/main | 2023-02-24T23:19:25.336811 | 2021-01-31T22:10:27 | 2021-01-31T22:10:27 | 334,757,171 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 164 | h | King.h | #pragma once
#include "Piece.h"
class King : public Piece
{
public:
King(int tile, COLOR color);
~King();
void SetupMoves() override;
private:
};
|
bd5472abbdb5400d32704cea4f5815df3200999f | d3fcfcc53ac6a18ed64debb8264a4bab9ed56d53 | /guidance-sdk/demo/obstacle_bypass/balance_strategy/src/dji_sdk_node.cpp | 32e2c03e2efb5ce75b4e30e795d2765f693e7b17 | [] | no_license | Foyoung-com/fy-cv-guidance | 0907e7166249d881b0e8d8175dce4b8fffecc36a | 6216cf79f082e16ea0615c05a55d0dab8e41fba0 | refs/heads/master | 2021-01-11T19:01:53.569499 | 2017-04-02T10:05:35 | 2017-04-02T10:05:35 | 79,295,736 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,570 | cpp | dji_sdk_node.cpp | /*
============================================================================
Name : dji_sdk_node.cpp
Author : Mario Chris
Description : Obstacle Avoidance
============================================================================
*/
/* System */
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sys/time.h>
#include <unistd.h>
/* Onboard */
#include "DJI_Codec.h"
#include "DJI_Link.h"
#include "DJI_App.h"
#include "DJI_API.h"
#include "DJI_Type.h"
#include "DJI_Flight.h"
#include "DJI_HardDriver.h"
#include "DJI_HardDriver_Manifold.h"
/* Guidance */
#include "opencv2/video/tracking.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/opencv.hpp"
#include "DJI_guidance.h"
#include "DJI_utility.h"
#include "imagetransfer.h"
#include "usb_transfer.h"
using namespace cv;
using namespace std;
using namespace DJI;
using namespace DJI::onboardSDK;
/* additional includes */
#include <string.h>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <ctime>
#include <math.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <pthread.h>
#include <thread>
HardDriver_Manifold* m_hd;
CoreAPI *coreAPI;
Flight *flight;
ActivateData user_act_data;
BroadcastData bc_data;
int ret;
/* roslaunch parameters */
std::string serial_name;
unsigned int baud_rate;
int app_id;
int app_api_level;
int app_version;
char app_key[65];
string enc_key;
pthread_t m_recvTid;
/* parameter */
#define WIDTH 320
#define HEIGHT 240
#define IMAGE_SIZE (HEIGHT * WIDTH)
#define VBUS e_vbus1
#define RETURN_IF_ERR(err_code) { if( err_code ){ release_transfer(); printf( "error code:%d,%s %d\n", err_code, __FILE__, __LINE__ );}}
/* guidance */
int err_code;
Mat g_greyscale_image_left=Mat::zeros(HEIGHT, WIDTH, CV_8UC1);
Mat g_greyscale_image_right=Mat::zeros(HEIGHT, WIDTH, CV_8UC1);
int iter = 0;
DJI_lock g_lock;
DJI_event g_event;
// Shi-Tomasi
#define MIN_CORNERS (uint) 15
#define CORNER_THRESHOLD (uint) 95
#define MAX_CORNERS (uint) 100
#define QUALITY_LEVEL (double) 0.01
#define MIN_DISTANCE (double) 1
// Lucas-Kanade
int frame_num = 0;
vector<Point2f> prevleftpts, prevrightpts;
Mat prevleftimg, prevrightimg;
#define OF_MARGIN (double) 0.5 // 2 optical flow values considered different if their difference exceeds this margin
bool l_kpt_regen = true;
bool r_kpt_regen = true;
// control
#define CMD_FLAG 0x4A // control horizontal/vertical velocity in body frame and yaw rate in ground frame
#define FWD (double) 0.5 // constant horizontal velocity
#define TURN (double) 10 // constant yaw rate
#define ALT (double) 0.01 // constant vertical velocity
double l_fwd = FWD; // left image forward control
double l_turn = 0; // left image turn control
double l_alt = 0; // left image altitude control
double r_fwd = FWD; // right image forward control
double r_turn = 0; // right image turn control
double r_alt = 0; // right image altitude control
double turn_prev = 0; // previous yaw for weighted camera observation
int guidance_callback(int data_type, int data_len, char *content)
{
g_lock.enter();
if (e_image == data_type && NULL != content)
{
printf("image data...................\n");
image_data data;
memcpy( (char*)&data, content, sizeof(data) );
printf( "frame index:%d,stamp:%d\n", data.frame_index, data.time_stamp );
for ( int d = 0; d < CAMERA_PAIR_NUM; ++d )
{
if ( data.m_greyscale_image_left[d] )
{
memcpy( g_greyscale_image_left.data, data.m_greyscale_image_left[d], IMAGE_SIZE );//maybe select too many image so just overwrite it
// control text
string ctrl_text = "";
// potential obstacle display
vector<Point2f> kpts;
vector<double> kpt_of;
double left_avg, right_avg, up_avg, down_avg;
/* Lucas-Kanade */
if(prevleftpts.size() < MIN_CORNERS)
{
// control decision
ctrl_text = "STOP MOVING";
l_fwd = 0;
l_turn = 0;
l_alt = 0;
}
else if(frame_num > 0)
{
vector<Point2f> LKleftpts;
vector<uchar> status;
vector<float> err;
vector<Mat> prevleftpyr;
buildOpticalFlowPyramid(prevleftimg, prevleftpyr, Size(21, 21), 3);
vector<Mat> currleftpyr;
buildOpticalFlowPyramid(g_greyscale_image_left, currleftpyr, Size(21, 21), 3);
calcOpticalFlowPyrLK(prevleftpyr, currleftpyr, prevleftpts, LKleftpts, status, err, Size(21, 21), 3, TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), OPTFLOW_LK_GET_MIN_EIGENVALS);
// control decision
ctrl_text = "GO";
double left_of_x = 0, left_of_y = 0, right_of_x = 0, right_of_y = 0, up_of_x = 0, up_of_y = 0, down_of_x = 0, down_of_y = 0;
int left_count = 0, right_count = 0, up_count = 0, down_count = 0;
for(size_t i = 0; i < LKleftpts.size(); i++)
{
if(LKleftpts[i].x >= 0 && LKleftpts[i].x <= WIDTH && LKleftpts[i].y >= 0 && LKleftpts[i].y <= HEIGHT)
{
if(LKleftpts[i].x < (double)WIDTH/2.0)
{
left_of_x += LKleftpts[i].x - prevleftpts[i].x;
left_of_y += LKleftpts[i].y - prevleftpts[i].y;
left_count++;
}
else
{
right_of_x += LKleftpts[i].x - prevleftpts[i].x;
right_of_y += LKleftpts[i].y - prevleftpts[i].y;
right_count++;
}
if(LKleftpts[i].y < (double)HEIGHT/2.0)
{
up_of_x += LKleftpts[i].x - prevleftpts[i].x;
up_of_y += LKleftpts[i].y - prevleftpts[i].y;
up_count++;
}
else
{
down_of_x += LKleftpts[i].x - prevleftpts[i].x;
down_of_y += LKleftpts[i].y - prevleftpts[i].y;
down_count++;
}
kpts.push_back(LKleftpts[i]);
kpt_of.push_back(pow(pow(LKleftpts[i].x - prevleftpts[i].x, 2) + pow(LKleftpts[i].y - prevleftpts[i].y, 2), 0.5));
}
}
left_of_x /= (double)left_count;
left_of_y /= (double)left_count;
double left_of = pow(pow(left_of_x, 2) + pow(left_of_y, 2), 0.5);
right_of_x /= (double)right_count;
right_of_y /= (double)right_count;
double right_of = pow(pow(right_of_x, 2) + pow(right_of_y, 2), 0.5);
up_of_x /= (double)up_count;
up_of_y /= (double)up_count;
double up_of = pow(pow(up_of_x, 2) + pow(up_of_y, 2), 0.5);
down_of_x /= (double)down_count;
down_of_y /= (double)down_count;
double down_of = pow(pow(down_of_x, 2) + pow(down_of_y, 2), 0.5);
// move away from high image section optical flow
l_fwd = FWD;
double turn_prev = l_turn;
double alt_prev = l_alt;
l_turn = 0;
l_alt = 0;
if(1.0 - right_of/left_of > OF_MARGIN)
{
ctrl_text += " RIGHT";
if(turn_prev > 0) l_turn = (1 + (left_of - right_of)/(left_of + right_of))*turn_prev;
else l_turn = TURN;
}
else if(1.0 - left_of/right_of > OF_MARGIN)
{
ctrl_text += " LEFT";
if(turn_prev < 0) l_turn = (1 + (right_of - left_of)/(right_of + left_of))*turn_prev;
else l_turn = -1.0*TURN;
}
if(1.0 - down_of/up_of > OF_MARGIN)
{
ctrl_text += " DOWN";
if(alt_prev < 0) l_alt = (1 + (up_of - down_of)/(up_of + down_of))*alt_prev;
else l_alt = -1.0*ALT;
}
else if(1.0 - up_of/down_of > OF_MARGIN)
{
ctrl_text += " UP";
if(alt_prev > 0) l_alt = (1 + (down_of - up_of)/(down_of + up_of))*alt_prev;
else l_alt = ALT;
}
if(ctrl_text.compare("GO") == 0) ctrl_text += " STRAIGHT";
left_avg = left_of;
right_avg = right_of;
up_avg = up_of;
down_avg = down_of;
}
/* Shi-Tomasi */
vector<Point2f> left_corners;
if(frame_num > 0)
{
if(kpts.size() >= CORNER_THRESHOLD)
{
left_corners.assign(kpts.begin(), kpts.end()); // retain previously tracked keypoints
l_kpt_regen = false;
}
else
{
goodFeaturesToTrack(g_greyscale_image_left, left_corners, MAX_CORNERS, QUALITY_LEVEL, MIN_DISTANCE); // generate new keypoints
l_kpt_regen = true;
}
}
// allow for color overlaid on greyscale image
Mat left_rgb(g_greyscale_image_left.size(), CV_8UC3);
cvtColor(g_greyscale_image_left, left_rgb, CV_GRAY2RGB);
// keypoints display
for(size_t i = 0; i < left_corners.size(); i++)
{
circle(left_rgb, left_corners[i], 4, Scalar(255, 0, 0), -1);
}
g_greyscale_image_left.copyTo(prevleftimg);
prevleftpts.assign(left_corners.begin(), left_corners.end());
// potential obstacle display
for(size_t i = 0; i < kpts.size(); i++)
{
bool draw_obstacle = false;
if(kpts[i].x < (double)WIDTH/2.0)
{
if(1.0 - right_avg/kpt_of[i] > OF_MARGIN) draw_obstacle = true;
}
else
{
if(1.0 - left_avg/kpt_of[i] > OF_MARGIN) draw_obstacle = true;
}
if(kpts[i].y < (double)HEIGHT/2.0)
{
if(1.0 - down_avg/kpt_of[i] > OF_MARGIN) draw_obstacle = true;
}
else
{
if(1.0 - up_avg/kpt_of[i] > OF_MARGIN) draw_obstacle = true;
}
if(draw_obstacle) rectangle(left_rgb, Point2f(kpts[i].x - 5, kpts[i].y - 5), Point2f(kpts[i].x + 5, kpts[i].y + 5), Scalar(0, 0, 255), -1);
}
// control display
putText(left_rgb, ctrl_text, Point2f(10, HEIGHT - 10), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 255, 0), 3, 3);
imshow("left", left_rgb);
moveWindow("left", 0, 0);
}
if ( data.m_greyscale_image_right[d] )
{
memcpy( g_greyscale_image_right.data, data.m_greyscale_image_right[d], IMAGE_SIZE );
// control text
string ctrl_text = "";
// potential obstacle display
vector<Point2f> kpts;
vector<double> kpt_of;
double left_avg, right_avg, up_avg, down_avg;
/* Lucas-Kanade */
if(prevrightpts.size() < MIN_CORNERS)
{
// control decision
ctrl_text = "STOP MOVING";
r_fwd = 0;
r_turn = 0;
r_alt = 0;
}
else if(frame_num > 0)
{
vector<Point2f> LKrightpts;
vector<uchar> status;
vector<float> err;
vector<Mat> prevrightpyr;
buildOpticalFlowPyramid(prevrightimg, prevrightpyr, Size(21, 21), 3);
vector<Mat> currrightpyr;
buildOpticalFlowPyramid(g_greyscale_image_right, currrightpyr, Size(21, 21), 3);
calcOpticalFlowPyrLK(prevrightpyr, currrightpyr, prevrightpts, LKrightpts, status, err, Size(21, 21), 3, TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), OPTFLOW_LK_GET_MIN_EIGENVALS);
// control decision
ctrl_text = "GO";
double left_of_x = 0, left_of_y = 0, right_of_x = 0, right_of_y = 0, up_of_x = 0, up_of_y = 0, down_of_x = 0, down_of_y = 0;
int left_count = 0, right_count = 0, up_count = 0, down_count = 0;
for(size_t i = 0; i < LKrightpts.size(); i++)
{
if(LKrightpts[i].x >= 0 && LKrightpts[i].x <= WIDTH && LKrightpts[i].y >= 0 && LKrightpts[i].y <= HEIGHT)
{
if(LKrightpts[i].x < (double)WIDTH/2.0)
{
left_of_x += LKrightpts[i].x - prevrightpts[i].x;
left_of_y += LKrightpts[i].y - prevrightpts[i].y;
left_count++;
}
else
{
right_of_x += LKrightpts[i].x - prevrightpts[i].x;
right_of_y += LKrightpts[i].y - prevrightpts[i].y;
right_count++;
}
if(LKrightpts[i].y < (double)HEIGHT/2.0)
{
up_of_x += LKrightpts[i].x - prevrightpts[i].x;
up_of_y += LKrightpts[i].y - prevrightpts[i].y;
up_count++;
}
else
{
down_of_x += LKrightpts[i].x - prevrightpts[i].x;
down_of_y += LKrightpts[i].y - prevrightpts[i].y;
down_count++;
}
kpts.push_back(LKrightpts[i]);
kpt_of.push_back(pow(pow(LKrightpts[i].x - prevrightpts[i].x, 2) + pow(LKrightpts[i].y - prevrightpts[i].y, 2), 0.5));
}
}
left_of_x /= (double)left_count;
left_of_y /= (double)left_count;
double left_of = pow(pow(left_of_x, 2) + pow(left_of_y, 2), 0.5);
right_of_x /= (double)right_count;
right_of_y /= (double)right_count;
double right_of = pow(pow(right_of_x, 2) + pow(right_of_y, 2), 0.5);
up_of_x /= (double)up_count;
up_of_y /= (double)up_count;
double up_of = pow(pow(up_of_x, 2) + pow(up_of_y, 2), 0.5);
down_of_x /= (double)down_count;
down_of_y /= (double)down_count;
double down_of = pow(pow(down_of_x, 2) + pow(down_of_y, 2), 0.5);
// move away from high image section optical flow
r_fwd = FWD;
double turn_prev = r_turn;
double alt_prev = r_alt;
r_turn = 0;
r_alt = 0;
if(1.0 - right_of/left_of > OF_MARGIN)
{
ctrl_text += " RIGHT";
if(turn_prev > 0) r_turn = (1 + (left_of - right_of)/(left_of + right_of))*turn_prev;
else r_turn = TURN;
}
else if(1.0 - left_of/right_of > OF_MARGIN)
{
ctrl_text += " LEFT";
if(turn_prev < 0) r_turn = (1 + (right_of - left_of)/(right_of + left_of))*turn_prev;
else r_turn = -1.0*TURN;
}
if(1.0 - down_of/up_of > OF_MARGIN)
{
ctrl_text += " DOWN";
if(alt_prev < 0) r_alt = (1 + (up_of - down_of)/(up_of + down_of))*alt_prev;
else r_alt = -1.0*ALT;
}
else if(1.0 - up_of/down_of > OF_MARGIN)
{
ctrl_text += " UP";
if(alt_prev > 0) r_alt = (1 + (down_of - up_of)/(down_of + up_of))*alt_prev;
else r_alt = ALT;
}
if(ctrl_text.compare("GO") == 0) ctrl_text += " STRAIGHT";
left_avg = left_of;
right_avg = right_of;
up_avg = up_of;
down_avg = down_of;
}
/* Shi-Tomasi */
vector<Point2f> right_corners;
if(frame_num > 0)
{
if(kpts.size() >= CORNER_THRESHOLD)
{
right_corners.assign(kpts.begin(), kpts.end()); // retain previously tracked keypoints
r_kpt_regen = false;
}
else
{
goodFeaturesToTrack(g_greyscale_image_right, right_corners, MAX_CORNERS, QUALITY_LEVEL, MIN_DISTANCE); // generate new keypoints
r_kpt_regen = true;
}
}
// allow for color overlaid on greyscale image
Mat right_rgb(g_greyscale_image_right.size(), CV_8UC3);
cvtColor(g_greyscale_image_right, right_rgb, CV_GRAY2RGB);
// keypoints display
for(size_t i = 0; i < right_corners.size(); i++)
{
circle(right_rgb, right_corners[i], 4, Scalar(255, 0, 0), -1);
}
g_greyscale_image_right.copyTo(prevrightimg);
prevrightpts.assign(right_corners.begin(), right_corners.end());
// potential obstacle display
for(size_t i = 0; i < kpts.size(); i++)
{
bool draw_obstacle = false;
if(kpts[i].x < (double)WIDTH/2.0)
{
if(1.0 - right_avg/kpt_of[i] > OF_MARGIN) draw_obstacle = true;
}
else
{
if(1.0 - left_avg/kpt_of[i] > OF_MARGIN) draw_obstacle = true;
}
if(kpts[i].y < (double)HEIGHT/2.0)
{
if(1.0 - down_avg/kpt_of[i] > OF_MARGIN) draw_obstacle = true;
}
else
{
if(1.0 - up_avg/kpt_of[i] > OF_MARGIN) draw_obstacle = true;
}
if(draw_obstacle) rectangle(right_rgb, Point2f(kpts[i].x - 5, kpts[i].y - 5), Point2f(kpts[i].x + 5, kpts[i].y + 5), Scalar(0, 0, 255), -1);
}
// control display
putText(right_rgb, ctrl_text, Point2f(10, HEIGHT - 10), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 255, 0), 3, 3);
imshow("right", right_rgb);
moveWindow("right", 500, 0);
frame_num++;
}
}
waitKey(1);
// maneuver
//if(ctrl_strat != NONE)
//{
double x = (l_fwd + r_fwd)/2.0;
double y = 0;
double z = (l_alt + r_alt)/2.0;
#ifdef NO_ALT_CTRL
z = 0;
#endif
double yaw = (l_turn + r_turn)/2.0;
flight->control(CMD_FLAG, x, y, z, yaw);
//}
}
g_lock.leave();
g_event.set_DJI_event();
return 0;
}
void run() {
/* Request Control */
coreAPI->setControl(1);
/* Takeoff */
usleep(2000000);// wait for 2 seconds
flight->task(Flight::TASK_TAKEOFF);
printf("\nTaking off...\n");
/* Maneuvering and avoiding obstacles */
usleep(1000000); // wait for 1 second
printf("\nBeginning Obstacle Avoidance...\n");
err_code = start_transfer(); // start guidance data collection
RETURN_IF_ERR( err_code );
/* Landing */
getchar(); // press key to begin autonomous mode
printf("\nEnding Obstacle Avoidance...\n");
err_code = stop_transfer(); // stop guidance
RETURN_IF_ERR( err_code );
bc_data = coreAPI->getBroadcastData();
printf("\nLanding...\n");
flight->task(Flight::TASK_LANDING); // land
usleep(1000000);
/* Release Control */
coreAPI->setControl(0);
}
void* APIRecvThread(void* param) {
CoreAPI* p_coreAPI = (CoreAPI*)param;
while(true) {
p_coreAPI->readPoll();
p_coreAPI->sendPoll();
usleep(1000);
}
return nullptr;
}
int main (int argc, char** argv)
{
/* OnboardSDK Initialization */
printf("Test SDK Protocol demo\n");
serial_name = std::string("/dev/ttyTHS1");
baud_rate = 230400;
app_id = 1027749;
app_api_level = 2;
app_version = 1;
enc_key = std::string("5de4dfff4bea190522bd6d9bb7da434a213c5e30611a8d5f01c8ed1146e1712a");
user_act_data.ID = app_id;
user_act_data.version = (uint32_t)0x03010a00;// M100
user_act_data.encKey = app_key;
strcpy(user_act_data.encKey, enc_key.c_str());
printf("=================================================\n");
printf("app id: %d\n", user_act_data.ID);
printf("app version: 0x0%X\n", user_act_data.version);
printf("app key: %s\n", user_act_data.encKey);
printf("=================================================\n");
m_hd = new HardDriver_Manifold(serial_name, baud_rate);
m_hd->init();
coreAPI = new CoreAPI( (HardDriver*)m_hd );
coreAPI->setVersion(user_act_data.version);
ret = pthread_create(&m_recvTid, 0, APIRecvThread, (void *)coreAPI);
if(0 != ret)
cout << "Cannot create new thread for readPoll!"<< endl;
else
cout << "Succeed to create thread for readPoll"<< endl;
coreAPI->activate(&user_act_data,NULL);
flight = new Flight(coreAPI);
/* Guidance */
reset_config();
err_code = init_transfer();
RETURN_IF_ERR( err_code );
err_code = select_greyscale_image( VBUS, true );
RETURN_IF_ERR( err_code );
err_code = select_greyscale_image( VBUS, false );
RETURN_IF_ERR( err_code );
err_code = set_sdk_event_handler( guidance_callback ); // set guidance callback
RETURN_IF_ERR( err_code );
/* Mission */
printf("\nRunning Mission...\n");
run();
//make sure the ack packet from GUIDANCE is received
sleep( 1000000 );
err_code = release_transfer();
RETURN_IF_ERR( err_code );
return 0;
}
|
34573ddd34892fce2fa853985adcc66e8efe01f0 | 64f873f96cb17bd57f83ae6e7116a1f7da6a47a5 | /CoordinateMappingBasics-D2D/include/glprint.hpp | e9b514996f94dddee6efb80ee210a02a3ad7ece3 | [] | no_license | miftahulbagusp/Virtual-shoes-try-on | 9932b370b0c82c0bbf9931b436de5d5393136b27 | 61a363a41231b8536c61935f9c4840a67deb1850 | refs/heads/master | 2022-01-07T03:40:39.635421 | 2019-04-28T11:37:02 | 2019-04-28T11:37:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,287 | hpp | glprint.hpp |
#ifndef __GL_PRINT__
#define __GL_PRINT__
#include <stdio.h>
#include <string>
#include <windows.h>
#include <time.h>
#include <math.h>
#include <gl/glut.h>
#define GP_MAX_CHAR 128
#ifndef GP_PI
#define GP_PI 3.1415926535f
#endif
#define GP_ENG ANSI_CHARSET
#define GP_CHS GB2312_CHARSET
#define GP_CHT DEFAULT_CHARSET
/* font
_______________________________________________________________*/
// set font type
void glFont ( int size, int char_set, const char *font_family );
// print english string
void glPrint ( const char *string );
// print integer number
void glPrint ( int integer );
// print chinese string
void glPrintCT ( const char *string );
/* draw
_______________________________________________________________*/
void glCircle ( float radius, int edge_number );
void glEllipse ( float x_axis, float y_axis, int edge_number );
/* fps
_______________________________________________________________*/
class glFPS
{
public:
glFPS( void );
~glFPS( void );
int Get( void );
int Size( void ) { return size; }
bool Size( int font_size );
int Lang( void ) { return lang; }
void Lang( int font_lang );
char *Font( void ) { return font; }
void Font( const std::string string );
protected:
int fps, frame;
clock_t lastTime, currentTime;
int size;
std::string font_s;
char *font;
int lang;
};
/*===============================================================
Do
===============================================================*/
/*
/* font
_______________________________________________________________*/
void glFont( int _size, int _char, const char *_font )
{
HFONT font = CreateFontA( _size, 0, 0, 0, FW_MEDIUM, 0, 0, 0, _char,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH | FF_SWISS, _font );
HFONT lastFont = (HFONT)SelectObject( wglGetCurrentDC(), font );
DeleteObject( lastFont );
}
void glPrint( const char *_string )
{
bool firstCall = true;
static GLuint lists;
if( firstCall )
{
firstCall = false;
lists = glGenLists( GP_MAX_CHAR );
wglUseFontBitmaps( wglGetCurrentDC(), 0, GP_MAX_CHAR, lists );
}
for( ; _string[0] != '\0'; _string++ )
glCallList( lists + _string[0] );
}
void glPrint( int _integer )
{
char c[1];
sprintf_s( c, sizeof(int), "%d", _integer );
glPrint( c );
}
void glPrintCT( const char *_string )
{
int leng, i;
const char *ptrc = _string;
wchar_t *wstring, *ptrw;
HDC hDC = wglGetCurrentDC();
GLuint list = glGenLists( 1 );
leng = 0;
for( ; ptrc[0] != '\0'; ptrc++, leng++ )
if( IsDBCSLeadByte( ptrc[0] ) )
ptrc++;
wstring = (wchar_t*)malloc( ( leng + 1 )*sizeof(wchar_t) );
MultiByteToWideChar( CP_ACP, MB_PRECOMPOSED, _string, -1, wstring, leng );
wstring[leng] = L'\0';
ptrw = wstring;
for( i = 0; i < leng; i++, ptrw++ )
{
wglUseFontBitmapsW( hDC, ptrw[0], 1, list );
glCallList( list );
}
free( wstring );
glDeleteLists( list, 1 );
}
/*
/* draw
_______________________________________________________________*/
void glCircle( float _radius, int _edge_number )
{
float temp, mult = 2*GP_PI/_edge_number;
glBegin( GL_LINE_LOOP );
for( int i = 0; i < _edge_number; i++ )
{
temp = i*mult;
glVertex3f( _radius*cosf( temp ), _radius*sinf( temp ), 0.f );
}
glEnd();
}
void glEllipse( float _x_length, float _y_length, int _edge_number )
{
float temp, mult = 2*GP_PI/_edge_number;
glBegin( GL_LINE_LOOP );
for( int i = 0; i < _edge_number; i++ )
{
temp = i*mult;
glVertex3f( _x_length*cosf( temp ), _y_length*sinf( temp ), 0.f );
}
glEnd();
}
/*
/* fps
_______________________________________________________________*/
#pragma region :: CLASS : FPS ::
glFPS::glFPS( void )
{
size = 30;
lang = GP_CHT;
font_s = "Fixedsys";
font = &font_s[0];
fps = 0;
frame = 0;
lastTime = clock();
}
glFPS::~glFPS( void )
{
}
int glFPS::Get( void )
{
frame++;
currentTime = clock();
if( currentTime - lastTime > CLOCKS_PER_SEC )
{
fps = frame;
lastTime = currentTime;
frame = 0;
}
return fps;
}
bool glFPS::Size( int _size )
{
if( _size <= 0 )
return false;
size = _size;
return true;
}
void glFPS::Lang( int _lang )
{
lang = _lang;
}
void glFPS::Font( const std::string _string )
{
font_s = _string;
}
#pragma endregion
#endif |
351d843138d8e75de551c7a3d3257c9e9c3af573 | 63e690e784aab87672dc80f9166f3fabca952063 | /Item.hpp | a015c0551576f1c0be73e5ea533f73c4352fad5f | [] | no_license | JohnYoon13/textAdventureGame | a95ee16ec781b19ce7162093b73857caffa32f86 | b376aee9223ab36b7d70635c0b4c0e1befd980af | refs/heads/master | 2021-05-12T15:40:45.090323 | 2018-01-10T17:48:48 | 2018-01-10T17:48:48 | 116,990,424 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 497 | hpp | Item.hpp | /************************************************************************
** Author: John Yoon
** Description: Item [Interface] - The class that represents the items
that Mr. Incredible can collect during his adventure.
************************************************************************/
#ifndef ITEM_HPP
#define ITEM_HPP
#include <string>
#include <iostream>
using std::string;
class Item
{
protected:
string item;
public:
Item();
Item(string item1);
void getItem();
};
#endif |
fc71983d9d1004744e7aba951d5679ff550daf25 | cfc37564b429df991a362da0e625f898cad74d33 | /client.cpp | 955574a3925ae4056e12048fcaaa382acf10d294 | [] | no_license | heweisheng/learn | eeeb8057beafc50dc6e9b09b42f1df96bb8e00ae | 7664c055fbebf0d8a46af2d0356c940c6ce2337e | refs/heads/master | 2020-04-06T14:27:37.007214 | 2019-11-14T13:24:55 | 2019-11-14T13:24:55 | 157,541,765 | 2 | 0 | null | null | null | null | GB18030 | C++ | false | false | 648 | cpp | client.cpp | #include"block.h"
#include"Socket_TCP.h"
typedef struct//不考虑主机字节序问题
{
int size;
char *buff;
}buff;
int main()
{
Tcp_client cli("127.0.0.1", 43491,0);
int fd = cli.Connect();
if (fd == -1)
ERR_EXIT("ser");
buff send;
while (true)
{
char *str = new char[1000];
scanf("%s", str);
send.size = strlen(str);
send.buff = str;
try
{
int ret = Writes(fd, &send.size, sizeof(int));
if(ret==-1)
{
throw"ser close";
}
ret = Writes(fd, send.buff, send.size);
if(ret==-1)
{
throw "ser close";
}
delete[]send.buff;
}
catch (char *str)
{
printf("%s\n", str);
break;
}
}
} |
70f448660644720ab313a6d727963223afab5650 | 3a785d999582988111f553aa3dc24c038842fd9c | /src/Diff2D/prob.cpp | f57b7a653e984dcc4d076e6f2500229bb3ec7a9f | [] | no_license | chuck1/Diffusion2D | 17ea84a80ca7f788d9a5ac28c516f8bbada78a9d | 173dbb0bbd5f9a06d11704ce3209091a446409da | refs/heads/master | 2016-09-06T05:36:39.147113 | 2014-12-05T20:25:56 | 2014-12-05T20:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,529 | cpp | prob.cpp | #define _POSIX_SOURCE
#include <sys/stat.h>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <Diff2D/config.hpp>
#include <Diff2D/face.hpp>
#include <Diff2D/prob.hpp>
#include <Diff2D/util.hpp>
#define REPLACE_MIN(x,y) if(y < x) x = y;
#define REPLACE_MAX(x,y) if(y > x) x = y;
Prob::Prob(
std::string name,
std::vector< math::array<real,1> > x,
std::vector< math::array<size_t,1> > nx,
int it_max_inner,
int it_max_outer):
it_max_inner_(it_max_inner),
it_max_outer_(it_max_outer)
{
name_ = name;
x_ = x;
nx_ = nx;
equs_ = {};
//signal.signal(signal.SIGINT, self)
}
Equation_Prob_s Prob::create_equation(std::string name, real k, real alpha, real alpha_source) {
auto e = std::make_shared<Equation_Prob>(shared_from_this(), name, k, alpha, alpha_source);
equs_[name] = e;
return e;
}
Patch_Group_s Prob::create_patch_group(std::string name, std::map<std::string, real> v_0, std::map<std::string, real> S, point v_0_point) {
auto g = std::make_shared<Patch_Group>(shared_from_this(), name, v_0, S, v_0_point);
patch_groups_.push_back(g);
return g;
}
/*def __call__(signal, frame) {
print "saving"
//save()
sys.exit(0)
}*/
real Prob::max(std::string const & equ_name) const {
real T = -1E37;
for(auto f : faces()) {
auto e = f->equs_[equ_name];
T = std::max(e->max(), T);
}
return T;
}
real Prob::min(std::string const & equ_name) const {
real v = 1E37;
for(auto f : faces()) {
auto e = f->equs_[equ_name];
v = std::min(e->min(), v);
}
return v;
}
real Prob::grad_max(std::string const & equ_name) const {
real v = -1E37;
for(auto f : faces()) {
auto e = f->equs_[equ_name];
v = std::max(e->grad_max(), v);
}
return v;
}
real Prob::grad_min(std::string const & equ_name) const {
real v = 1E37;
for(auto f : faces()) {
auto e = f->equs_[equ_name];
v = std::min(e->grad_min(), v);
}
return v;
}
// value manipulation
void Prob::value_add(std::string const & equ_name, math::array<real,2> const & v) {
for(auto f : faces()) {
auto equ = f->equs_[equ_name];
equ->v_->add_self(v);
}
}
void Prob::value_add(std::string const & equ_name, real const & v) {
for(auto f : faces()) {
auto equ = f->equs_[equ_name];
equ->v_->add_self(v);
}
}
void Prob::value_clamp_per_group(std::string const & name, real a, real const & b) {
for(auto g : patch_groups_) {
g->value_clamp(name,a,b);
}
}
void Prob::value_normalize(std::string const & equ_name) {
for(auto g : patch_groups_) {
// max value in patch group
real v_max = -1E37;
for(auto p : g->patches_) {
real p_v_max = p->max(equ_name);
//print "patch max value",p_v_max
v_max = std::max(v_max, p_v_max);
//print "max value",v_max
// normalize
for(auto p : g->patches_) {
for(auto f : *(p->faces_)) {
auto equ = f->equs_[equ_name];
equ->v_->divide_self(v_max);
}
}
}
}
}
void Prob::copy_value_to_source(std::string equ_name_from, std::string equ_name_to) {
Equation_s e1;
Equation_s e2;
for(auto f : faces()) {
e1 = f->equs_[equ_name_from];
e2 = f->equs_[equ_name_to];
}
std::vector<size_t> s1;
for(auto a : e1->v_->shape()) {
s1.push_back(a-2);
}
auto s2 = e2->s_->shape();
if(s1 == s2) {
e2->s_ = e1->v_->sub({0,0},{-2,-2});
} else {
//print s1, s2;
throw 0;//raise ValueError('size mismatch')
}
}
std::vector<Face_s> Prob::faces() const {
std::vector<Face_s> ret;
for(auto g : patch_groups_) {
for(auto p : g->patches_) {
for(auto f : *(p->faces_)) {
ret.push_back(f);
}
}
}
return ret;
}
// solving
int Prob::solve(std::string name, real cond, size_t it_outer, real R_outer) {
return solve_serial(name, cond, it_outer, R_outer);
}
int Prob::solve_serial(std::string name, real cond_inner, size_t it_outer, real R_outer) {
real cond_grad_inner = -1E-9;
/** @todo move this to class variable to avoid excess alloc!*/
auto R = math::make_zeros<real,1>({it_max_inner_});
real nR = 0;
size_t it = 0;
for(; it < it_max_inner_; ++it) {
nR = 0;
for(auto face : faces()) {
nR = std::max(face->step(name, it_outer), nR);
face->send(name);
}
for(auto face : faces()) {
face->recv(name);
}
IF(std::isnan(nR)) {
//LOG(gal::log::lg, info, critical) << "nan" << GAL_LOG_ENDLINE;
throw 0;
}
IF(std::isinf(nR)) {
//LOG(gal::log::lg, info, critical) << "nan" << GAL_LOG_ENDLINE;
throw 0;
}
R->get(it) = nR;
real grad = R->fda_1_back(it, 1.0);
real grad2 = R->fda_2_back(it, 1.0);
LOG(lg, info, info) << std::scientific
<< std::setw(4) << name
<< std::setw(6) << it_outer
<< std::setw(16) << R_outer
<< std::setw(6) << it
<< std::setw(16) << nR
<< std::setw(16) << grad
<< std::setw(16) << grad2;
if((grad <= 0) && (grad > cond_grad_inner)) {
LOG(lg, info, info) << "break inner because residual gradient < " << std::scientific << cond_grad_inner;
break;
}
if(nR < cond_inner) {
LOG(lg, info, info) << "break inner because residual < " << std::scientific << cond_inner;
break;
}
}
return it;
}
int Prob::solve_outer_group(
std::string const & ename,
real cond_outer,
real cond_inner,
std::shared_ptr<Patch_Group> group) {
real cond_upper_outer = 1E4;
real R_outer = 1.0;
// iterate
size_t it_outer = 0;
solve(ename, cond_inner, it_outer, R_outer);
it_outer++;
for(; it_outer < it_max_outer_; ++it_outer) {
// reset source =======================
R_outer = group->reset_s(it_outer, ename);
// solve inner ========================
solve(ename, cond_inner, it_outer, R_outer);
LOG(lg, info, info)
<< std::setw(6) << it_outer
<< std::setw(16) << R_outer;
if(std::isnan(R_outer)) {
throw 0;//raise ValueError('nan')
}
if(R_outer < cond_outer) {
//LOG(gal::log::lg, info, info) << "break outer because residual < " << std::scientific << cond_outer << std::endl;
// callback good break
// fill S with final value
real S = group->S_[ename]->get(it_outer-1);
group->S_[ename]->ones();
group->S_[ename]->multiply_self(S);
// fill v_0_history with final value
real v_0 = group->v_0_history_[ename]->get(it_outer-1);
group->v_0_history_[ename]->ones();
group->v_0_history_[ename]->multiply_self(v_0);
/// @todo put in Patch_Group equation data class
group->flag_ |= Patch_Group::flags::SOURCE_SOLVED;
break;
}
if(R_outer > cond_upper_outer) {
//LOG(gal::log::lg, info, info) << "kill because outer residual > " << std::scientific << cond_upper_outer << std::endl;
throw 0;
}
}
return it_outer;
}
void Prob::solve2(std::string ename, real cond_outer, real cond_inner) {
//real R_outer = 1.0;
// run at least twice
size_t it3 = 0;
size_t it3_stop = 5;
while(1) {
for(auto g : patch_groups_) {
solve_outer_group(ename, cond_outer, cond_inner, g);
}
real R3_max = -1E35;
real R3 = 0;
for(auto g : patch_groups_) {
R3 = g->get_value_of_interest_residual(ename);
R3_max = std::max(R3_max, R3);
std::cout << "group '" << g->name_ << "' residual = " << R3 << std::endl;
}
if(R3 < cond_outer) {
LOG(lg, info, info) << "break loop 3 because residual < " << std::scientific << cond_outer;
break;
}
if(it3 == (it3_stop-1)) {
LOG(lg, info, info) << "break loop 3 because it3 == " << std::scientific << it3_stop;
break;
}
it3++;
}
}
void Prob::save() {
std::ofstream ofs;
ofs.open("case_" + name_, std::ofstream::out);
//pickle.dump(f)
}
void Prob::connection_info() const {
for(auto g : patch_groups_) {
for(auto p : g->patches_) {
p->connection_info();
}
}
}
void Prob::value_stats(std::string const & name) const {
size_t col = 16;
std::cout
<< std::setw(col*4) << std::setfill(' ') << " "
<< std::setw(col) << "min"
<< std::setw(col) << "max"
<< std::endl;
for(auto g : patch_groups_) {
print_row(col, "group", ("'" + g->name_ + "'"), " ", " ", g->min(name), g->max(name));
for(auto p : g->patches_) {
std::cout
<< std::setw(col*2) << " "
<< std::setw(col) << "patch"
<< std::setw(col) << ("'" + p->name_ + "'")
<< std::setw(col) << p->min(name)
<< std::setw(col) << p->max(name)<< std::endl;
}
}
// value of interest
print_row(16, "group", "target", "value", "error");
for(auto g : patch_groups_) {
real target, value, error;
g->get_value_of_interest(name, target, value, error);
print_row(16, ("'" + g->name_ + "'"), target, value, error);
}
}
void Prob::write(std::string equ_name, std::string filename_post) {
/*if(not os.path.exists(directory)) {
os.makedirs(directory)
}*/
std::ofstream ofs;
ofs.open("prof_" + name_ + "_" + equ_name + filename_post + ".prof", std::ofstream::trunc);
if(!ofs.is_open()) {
LOG(lg, info, warning) << "file stream not open";
return;
}
std::vector<real> x;// = np.zeros(0);
std::vector<real> y;// = np.zeros(0);
std::vector<real> z;// = np.zeros(0);
std::vector<real> w;// = np.zeros(0);
for(auto g : patch_groups_) {
//print g
//g->write(equ_name, ofs);
for(auto f : g->faces()) {
auto grid = f->grid(equ_name);
//X,Y,Z,W = f.grid(equ_name);
auto Xr = grid.X[f->glo_to_loc2(1).i]->ravel();
auto Yr = grid.X[f->glo_to_loc2(2).i]->ravel();
auto Zr = grid.X[f->glo_to_loc2(3).i]->ravel();
auto Wr = grid.W->ravel();
x.insert(x.end(), Xr.begin(), Xr.end());
y.insert(y.end(), Yr.begin(), Yr.end());
z.insert(z.end(), Zr.begin(), Zr.end());
w.insert(w.end(), Wr.begin(), Wr.end());
}
}
std::string name = "prof_" + name_ + "_" + equ_name;
int n = x.size();
LOG(lg, info, info)
<< "writing " << n << " points";
ofs << "((" << name << " point " << n << ")\n";
ofs << "(x\n";
write_vec(ofs, x);
ofs << ")\n";
ofs << "(y\n";
write_vec(ofs, y);
ofs << ")\n";
ofs << "(z\n";
write_vec(ofs, z);
ofs << ")\n";
ofs << "(w\n";
write_vec(ofs, w);
ofs << ")\n";
ofs << ")\n";
}
void Prob::write_binary(std::string ename) {
for(auto g : patch_groups_) {
//print g
g->write_binary(ename);
}
}
std::string Prob::mkdir(std::string const & ename) const {
std::string dir1 = "output";
std::string dir2 = dir1 + "/" + name_;
std::string dir3 = dir2 + "/" + ename;
// create folders
auto lmkdir = [] (std::string const & dir) {
struct stat sb;
if(stat(dir.c_str(), &sb) == 0 && S_ISDIR(sb.st_mode)) {
} else {
if(::mkdir(dir.c_str(), S_IRWXU|S_IRGRP|S_IXGRP) != 0) {
perror("mkdir error:");
return;
}
}
};
lmkdir(dir1);
lmkdir(dir2);
lmkdir(dir3);
return dir3;
}
|
54fa8d36fc7020d09d5382e833cb67f9ff061487 | fd24837a20e4e6e37d5f9bebb3873f7010edee3e | /matrix4.cpp | 93439eeca4de950af857f363dd5ca643bedcf142 | [] | no_license | rafaelsales/CG_Camera | 5ad22423a7a4bc94473c2c65018c007d769b4614 | fb89bd3f352dd9806916e8c9378386c924714e3f | refs/heads/master | 2020-04-07T14:30:07.690842 | 2011-11-17T01:19:13 | 2011-11-17T01:19:13 | 2,780,329 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,977 | cpp | matrix4.cpp | #include <GL/gl.h>
#include <math.h>
#include "matrix4.h"
#include "vector3.h"
#include "point3.h"
Matrix4::Matrix4() {
// Inicializa como identidade:
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (i == j) {
(*this)(i,j) = 1.0;
} else {
(*this)(i,j) = 0.0;
}
}
}
}
Matrix4::~Matrix4(){
}
Matrix4 Matrix4::operator+(const Matrix4 & other) const {
Matrix4 newMatrix;
for (int k = 0; k < 4 * 4; k++) {
newMatrix.matrix[k] = this->matrix[k] + other.matrix[k];
}
return newMatrix;
}
Matrix4 Matrix4::operator-(const Matrix4 & other) const {
Matrix4 newMatrix;
for (int k = 0; k < 4 * 4; k++) {
newMatrix.matrix[k] = this->matrix[k] - other.matrix[k];
}
return newMatrix;
}
Matrix4 Matrix4::operator*(const Matrix4 & other) const {
Matrix4 newMatrix;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
newMatrix(i,j) = 0.0;
for (int k = 0; k < 4; k++) {
newMatrix(i,j) += (*this)(i,k) * other(k,j);
}
}
}
return newMatrix;
}
Vector3 Matrix4::operator*(const Vector3 & vector) const {
float newVector[3] = {0.0, 0.0, 0.0};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
newVector[i] += (*this)(i,j) * vector(j);
}
newVector[i] += (*this)(i,3);
}
return Vector3(newVector[0], newVector[1], newVector[2]);
}
Point3 Matrix4::operator*(const Point3 & point) const {
float newPoint[3] = {0.0, 0.0, 0.0};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
newPoint[i] += (*this)(i,j) * point(j);
}
newPoint[i] += (*this)(i,3);
}
return Point3(newPoint[0], newPoint[1], newPoint[2]);
}
/*
Próximo operador permite:
Matrix4 m;
m(0,0) = 10;
*/
float& Matrix4::operator()(unsigned int row, unsigned int column) {
return this->matrix[4 * row + column];
}
const float& Matrix4::operator()(unsigned int row, unsigned int column) const {
return this->matrix[4 * row + column];
}
/* Multiplica a matriz atual do OpenGL com a matriz atual usando glMultMatrix() */
void Matrix4::applyGL() const {
glMultMatrixf(this->matrix);
}
Matrix4 Matrix4::rotationMatrix(float angle, Vector3 axis) {
//Q = w + u * sin(angle)
//w = cos(angle)
//u é o vetor normalizado do eixo de rotação:
//u = (axis_x, axis_y, axis_z)
//Normaliza o eixo e multiplica pelo seno do ângulo:
axis = sin(angle) * axis.normalize();
float x = axis.x, x2 = x * x;
float y = axis.y, y2 = y * y;
float z = axis.z, z2 = z * z;
float w = cos(angle), w2 = w * w;
//Matrix de rotação do quatérnio:
Matrix4 rotationMatrix;
rotationMatrix(0,0) = w2 + x2 - y2 - z2;
rotationMatrix(0,1) = 2 * x * y - 2 * w * z;
rotationMatrix(0,2) = 2 * x * z + 2 * w * y;
rotationMatrix(0,3) = 0.0;
rotationMatrix(1,0) = 2 * x * y + 2 * w * z;
rotationMatrix(1,1) = w2 - x2 + y2 - z2;
rotationMatrix(1,2) = 2 * y * z - 2 * w * x;
rotationMatrix(1,3) = 0.0;
rotationMatrix(2,0) = 2 * x * z - 2 * w * y;
rotationMatrix(2,1) = 2 * y * z + 2 * w * x;
rotationMatrix(2,2) = w2 - x2 - y2 + z2;
rotationMatrix(2,3) = 0.0;
rotationMatrix(3,0) = 0.0;
rotationMatrix(3,1) = 0.0;
rotationMatrix(3,2) = 0.0;
rotationMatrix(3,3) = w2 + x2 + y2 + z2;
//Para rotacionar, basta multiplicar rotationMatrix * Vector3
return rotationMatrix;
}
Matrix4 Matrix4::translationMatrix(Vector3 displacement) {
Matrix4 translationMatrix;
for (int i = 0; i < 3; i++) {
translationMatrix(i, 3) = displacement(i);
}
return translationMatrix;
}
Matrix4 Matrix4::scaleMatrix(float x, float y, float z) {
Matrix4 scaleMatrix;
scaleMatrix(0,0) = x;
scaleMatrix(1,1) = y;
scaleMatrix(2,2) = z;
return scaleMatrix;
}
|
ee613df7ff0ac1882c3ad24005fa8c2fca0e61ce | fe17aed136b0981e530922104325e6d8dfcc21e6 | /src/Image/EquivalenceTable.h | bc8026ba6792df1a9d4da3775f66c8e6a0bceea8 | [] | no_license | mohammadalihedayat/Digital-Image-Processing-and-Computer-Vision | 2226e09255890ea91193831176778865714b0187 | e4c1cbe24678475a8caaed3bf1630b13e5b36083 | refs/heads/master | 2021-06-07T00:49:42.152424 | 2016-09-17T00:35:44 | 2016-09-17T00:35:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,847 | h | EquivalenceTable.h | /*
* Copyright (c) 2004,2005,2008 Clemson University.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or (at
* your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __BLEPO_EQUIVALENCE_TABLE_H__
#define __BLEPO_EQUIVALENCE_TABLE_H__
//#include "ImageAlgorithms.h"
//#include "Utilities/Math.h"
#include <vector>
namespace blepo {
/**
Equivalence table for connected components. Equivalences are stored in a directional
fashion, with labels with higher numbers always pointing to labels with lower numbers.
Helpful description of algorithm can be found at http://en.wikipedia.org/wiki/Disjoint-set_data_structure
@author Stan Birchfield (STB)
*/
class EquivalenceTable
{
public:
EquivalenceTable() {}
/// Call this whenever two labels have been found to be equivalent
void AddEquivalence(int label1, int label2)
{
if (label1 == label2) return;
int a = GetEquivalentLabelRecursive( label1 );
int b = GetEquivalentLabelRecursive( label2 );
if (a == b) return;
else if (a > b) { EnsureAllocated(a); m_table[a] = b; }
else { EnsureAllocated(b); m_table[b] = a; }
}
/// traverse links; after this step each label either points to itself
/// or points to another label that points to itself
void TraverseLinks()
{
for (int i = 0 ; i < (int) m_table.size() ; i++)
{
m_table[i] = GetEquivalentLabelRecursive( m_table[i] );
}
}
/// Condense table by removing gaps.
/// After calling this function, the labels are sequential: 0, 1, 2, ...
/// Returns the number of labels (i.e., the maximum label + 1)
int RemoveGaps()
{
int next = 0;
for (int a = 0 ; a < (int) m_table.size() ; a++)
{
int b = m_table[a];
m_table[a] = (a == b) ? next++ : m_table[b];
}
return next;
}
/// Return the equivalent label.
/// Call TraverseLinks() before calling this function.
int GetEquivalentLabel(int label) const
{
assert( label >= 0 );
return (label < (int) m_table.size()) ? m_table[label] : label;
}
/// Ensure that table is initialized at least up to and including 'label'
void EnsureAllocated(int label)
{
assert( label >= 0 );
int n = (int) m_table.size();
for (int i=n ; i<=label ; i++) m_table.push_back(i);
}
/// Return the smallest equivalent label, recursively
int GetEquivalentLabelRecursive(int label) const
{
assert( label >= 0 );
// cast away constness so that internal data structure can be updated for efficiency
EquivalenceTable* me = (const_cast<EquivalenceTable*>(this));
me->EnsureAllocated( label );
if (label == m_table[label]) return label;
else
{
me->m_table[label] = GetEquivalentLabelRecursive( m_table[label] );
return m_table[label];
}
}
private:
std::vector<int> m_table;
};
/*
// This code works, but is not as simple as it could be. -- STB 9/1/08
class EquivalenceTable
{
public:
EquivalenceTable() {}
/// Call this whenever two labels have been found to be equivalent
void AddEquivalence(int label1, int label2)
{
if (label1 == label2) return;
// sort labels
int a = blepo_ex::Max(label1, label2);
int b = blepo_ex::Min(label1, label2);
// allocate memory if needed, and initialize m_table[i] = i
EnsureAllocated(a);
// add equivalence;
// if 'a' already pointed to another label higher than 'b', then recurse
int a_equiv = m_table[a];
m_table[a] = blepo_ex::Min(a_equiv, b);
if (a_equiv != a) AddEquivalence(a_equiv, b);
}
/// traverse links; after this step each label either points to itself
/// or points to another label that points to itself
void TraverseLinks()
{
for (int i=0 ; i<(int)m_table.size() ; i++)
{
m_table[i] = GetEquivalentLabelRecursive(m_table[i]);
}
}
/// Condense table by removing gaps.
/// After calling this function, the labels are sequential: 0, 1, 2, ...
/// Returns the number of labels (i.e., the maximum label + 1)
int RemoveGaps()
{
int next = 0;
for (int a = 0 ; a < (int)m_table.size() ; a++)
{
int b = m_table[a];
m_table[a] = (a == b) ? next++ : m_table[b];
}
return next;
}
/// Return the equivalent label.
/// Call TraverseLinks() before calling this function.
int GetEquivalentLabel(int label) const
{
assert( label >= 0 );
return (label < (int) m_table.size()) ? m_table[label] : label;
}
/// Ensure that table is initialized at least up to and including 'label'
void EnsureAllocated(int label)
{
int n = m_table.size();
for (int i=n ; i<=label ; i++) m_table.push_back(i);
}
/// Return the smallest equivalent label, recursively
int GetEquivalentLabelRecursive(int label) const
{
assert( label >= 0 );
int a = (label < (int) m_table.size()) ? m_table[label] : label;
return (a == label) ? a : GetEquivalentLabelRecursive(a);
}
private:
std::vector<int> m_table;
};
*/
}; // end namespace blepo
#endif // __BLEPO_EQUIVALENCE_TABLE_H__
|
fae40d94de4cbfcf06ded16f597c43b421daa182 | 200e2fabc88dd03edeb1446c4be7f709a0328f3f | /learnCppProject/LearnCppProject/LearnOpenGL/src/ModelFileHelper.cpp | b93aabd127eef05d6b24dd10c7d81b9be90338ff | [] | no_license | wangtianhang/LearnCpp | 9d5c5b21e4fea0364398b846ee29d1a634258ee7 | eb7934a7d5e203024364c3a7d9f63c50ef505401 | refs/heads/master | 2020-06-18T17:22:57.462292 | 2019-11-22T06:14:30 | 2019-11-22T06:14:30 | 196,380,109 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 20,169 | cpp | ModelFileHelper.cpp | #pragma once
//#include <iostream>
//#include <string>
#include <fstream>
#include<sstream>
#include <assimp/Importer.hpp>
#include <assimp/scene.h>
#include <assimp/postprocess.h>
#include "./DebugMemory.h"
#include "./ModelFileHelper.h"
#include "./GUtil.h"
#include "./Learn3D/MathHelper.h"
/*
*/
extern MeshFliter GetMeshFilter(std::vector<Vector3> vertices,
std::vector<Vector3> normals,
std::vector<GLuint> indexs)
{
MeshFliter ret;
ret.m_frontFace = GL_CW;
ret.m_bigIndex = true;
GLfloat * vertex_positions = new GLfloat[vertices.size() * 3];
GLuint * vertex_indices = new GLuint[indexs.size()];
GLfloat * vertex_normals = new GLfloat[normals.size() * 3];
for (int i = 0; i < vertices.size(); ++i)
{
vertex_positions[i * 3] = vertices[i].x;
vertex_positions[i * 3 + 1] = vertices[i].y;
vertex_positions[i * 3 + 2] = vertices[i].z;
}
for (int i = 0; i < indexs.size(); ++i)
{
vertex_indices[i] = indexs[i];
}
for (int i = 0; i < normals.size(); ++i)
{
vertex_normals[i * 3] = normals[i].x;
vertex_normals[i * 3 + 1] = normals[i].y;
vertex_normals[i * 3 + 2] = normals[i].z;
}
int size_vertex_positions = vertices.size() * 3 * 4;
int size_vertex_indices = indexs.size() * 4;
ret.drawVerticesCount = indexs.size();
int size_vertex_normals = normals.size() * 3 * 4;
//GLuint vao = 0;
glGenVertexArrays(1, &ret.m_vao);
glBindVertexArray(ret.m_vao);
glGenBuffers(1, &ret.m_positionVBO);
glBindBuffer(GL_ARRAY_BUFFER, ret.m_positionVBO);
glBufferData(GL_ARRAY_BUFFER,
size_vertex_positions,
vertex_positions,
GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(0);
glGenBuffers(1, &ret.m_normalVBO);
glBindBuffer(GL_ARRAY_BUFFER, ret.m_normalVBO);
glBufferData(GL_ARRAY_BUFFER,
size_vertex_normals,
vertex_normals,
GL_STATIC_DRAW);
glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, NULL);
glEnableVertexAttribArray(3);
glGenBuffers(1, &ret.m_indexVBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ret.m_indexVBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
size_vertex_indices,
vertex_indices,
GL_STATIC_DRAW);
delete vertex_positions;
delete vertex_indices;
delete vertex_normals;
return ret;
}
#pragma region boneAnimation
Matrix4x4 Convert(aiMatrix4x4 offset)
{
Matrix4x4 ret;
ret.m00 = offset.a1;
ret.m01 = offset.a2;
ret.m02 = offset.a3;
ret.m03 = offset.a4;
ret.m10 = offset.b1;
ret.m11 = offset.b2;
ret.m12 = offset.b3;
ret.m13 = offset.b4;
ret.m20 = offset.c1;
ret.m21 = offset.c2;
ret.m22 = offset.c3;
ret.m23 = offset.c4;
ret.m30 = offset.d1;
ret.m31 = offset.d2;
ret.m32 = offset.d3;
ret.m33 = offset.d4;
return ret;
}
Transform * processHierarchyTransform(const aiNode * aiNolde, std::vector<Transform *> & boneTransformVec)
{
Transform * transform = new Transform();
transform->m_name = std::string(aiNolde->mName.C_Str());
Matrix4x4 localToWorldMatrix = Convert(aiNolde->mTransformation);
// if (transform->m_name == "Bip001 Pelvis")
// {
// int test = 0;
// GUtil::Log(transform->m_name + " origin matrix \n" + localToWorldMatrix.ToString());
// Quaternion qua = MathHelper::GetRotation(localToWorldMatrix);
// GUtil::Log("euler1 " + qua.eulerAngles().toString());
//GUtil::Log("euler2 " + dxQua.eulerAngles().toString());
// Matrix4x4 src = localToWorldMatrix;
// Matrix4x4 des = src;
// des.m01 = -src.m01;
// des.m02 = -src.m02;
// des.m02 = -src.m03;
//
// des.m10 = -src.m10;
//
// des.m20 = -src.m20;
// des.m23 = -src.m23;
//
// Matrix4x4 x = des * src.inverse();
// GUtil::Log(transform->m_name + " x matrix \n" + x.ToString());
// GUtil::Log(MathHelper::GetPosition(x).toString());
// GUtil::Log(MathHelper::GetRotation(x).eulerAngles().toString());
// GUtil::Log(MathHelper::GetScale(x).toString());
// }
// 下面这两处很奇怪 不知道为何需要转一下
bool copyUnity = false;
Vector3 pos = MathHelper::GetPosition(localToWorldMatrix);
if (copyUnity)
{
pos.x = -pos.x;
pos.z = -pos.z;
}
transform->SetLocalPosition(pos);
Vector3 euler = MathHelper::GetRotation(localToWorldMatrix).eulerAngles();
if (copyUnity)
{
euler.x = -euler.x;
euler.z = -euler.z;
}
transform->SetLocalEulerAngles(euler);
Vector3 scale = MathHelper::GetScale(localToWorldMatrix);
transform->SetLocalScale(scale);
// if (transform->m_name == "Bip001 Pelvis")
// {
// int test = 0;
// }
for (unsigned int i = 0; i < aiNolde->mNumChildren; i++)
{
Transform * childTrans = processHierarchyTransform(aiNolde->mChildren[i], boneTransformVec);
Vector3 cacheLocalPos = childTrans->GetLocalPosition();
Vector3 cacheLocalEuler = childTrans->GetLocalEulerAngles();
Vector3 cacheLocalScale = childTrans->GetLocalScale();
childTrans->SetParent(transform);
childTrans->SetLocalPosition(cacheLocalPos);
childTrans->SetLocalEulerAngles(cacheLocalEuler);
childTrans->SetLocalScale(cacheLocalScale);
}
boneTransformVec.push_back(transform);
return transform;
}
const aiNode * FindNode(const aiNode * node, aiString nodeName)
{
if (node->mName == nodeName)
{
return node;
}
else
{
for (unsigned int i = 0; i < node->mNumChildren; i++)
{
const aiNode * childNode = FindNode(node->mChildren[i], nodeName);
if (childNode != nullptr)
{
return childNode;
}
}
return nullptr;
}
}
// Vector3 Convert(aiVector3D tmp)
// {
// return Vector3(tmp.x, tmp.y, tmp.z);
// }
//
// Quaternion Convert(aiQuaternion tmp)
// {
// return Quaternion(tmp.x, tmp.y, tmp.z, tmp.w);
// }
// Vector3 Convert(aiVector3D tmp)
// {
// return Vector3(tmp.x, tmp.y, tmp.z);
// }
//
// Quaternion Convert(aiQuaternion tmp)
// {
// return Quaternion(tmp.x, tmp.y, tmp.z, tmp.w);
// }
VectorKey Covnert2(aiVectorKey key)
{
VectorKey ret;
ret.mTime = key.mTime;
ret.mValue = Vector3(key.mValue.x, key.mValue.y, key.mValue.z);
return ret;
}
QuatKey Convert3(aiQuatKey key)
{
QuatKey ret;
ret.mTime = key.mTime;
ret.mValue = Quaternion(key.mValue.x, key.mValue.y, key.mValue.z, key.mValue.w);
return ret;
}
void processBoneAnimation(std::vector<std::string> & boneNameVec, const aiScene *scene, aiAnimation *animation, BoneAnimation * boneAnimation)
{
const aiNode * bone001 = FindNode(scene->mRootNode, aiString("Bone001"));
// Matrix4x4 localToWorldMatrix = Convert(bone001->mTransformation);
// GUtil::Log("Bone001 origin matrix " + localToWorldMatrix.ToString());
// GUtil::Log(MathHelper::GetPosition(localToWorldMatrix).toString());
// GUtil::Log(MathHelper::GetRotation(localToWorldMatrix).eulerAngles().toString());
// GUtil::Log(MathHelper::GetScale(localToWorldMatrix).toString());
const aiNode * bip001Node = FindNode(scene->mRootNode, aiString(animation->mChannels[0]->mNodeName));
std::vector<Transform *> fullBoneTransformVec;
Transform * bip001Transform = processHierarchyTransform(bip001Node, fullBoneTransformVec);
bool debug = true;
if (debug)
{
// todo Bone001 的parent还有好几层。。从父节点感觉可以读取出旋转和缩放数据
Transform * bone001 = new Transform;
bone001->m_name = "Bone001";
bone001->SetLocalEulerAngles(Vector3(0, 270, 180));
bone001->SetLocalScale(Vector3(0.05256505f, 0.05256505f, 0.05256505f));
Vector3 cacheLocalPos = bip001Transform->GetLocalPosition();
Vector3 cacheLocalEuler = bip001Transform->GetLocalEulerAngles();
Vector3 cacheLocalScale = bip001Transform->GetLocalScale();
bip001Transform->SetParent(bone001);
bip001Transform->SetLocalPosition(cacheLocalPos);
bip001Transform->SetLocalEulerAngles(cacheLocalEuler);
bip001Transform->SetLocalScale(cacheLocalScale);
fullBoneTransformVec.push_back(bone001);
}
for (int i = 0; i < boneNameVec.size(); ++i)
{
for (int j = 0; j < fullBoneTransformVec.size(); ++j)
{
if (fullBoneTransformVec[j]->m_name == boneNameVec[i])
{
boneAnimation->m_boneTransformVec.push_back(fullBoneTransformVec[j]);
break;
}
}
}
std::vector<Transform *> allAnimationTransformVec;
for (int j = 0; j < animation->mNumChannels; ++j)
{
for (int i = 0; i < fullBoneTransformVec.size(); ++i)
{
if (animation->mChannels[j]->mNodeName == aiString(fullBoneTransformVec[i]->m_name.c_str()))
{
allAnimationTransformVec.push_back(fullBoneTransformVec[i]);
aiNodeAnim * nodeAnim = animation->mChannels[j];
ChannelFrameData * data = new ChannelFrameData();
for (int i = 0; i < nodeAnim->mNumPositionKeys; ++i)
{
data->m_posKeyVec.push_back(Covnert2(nodeAnim->mPositionKeys[i]));
}
for (int i = 0; i < nodeAnim->mNumRotationKeys; ++i)
{
data->m_quaKeyVec.push_back(Convert3(nodeAnim->mRotationKeys[i]));
}
for (int i = 0; i < nodeAnim->mNumScalingKeys; ++i)
{
data->m_scaleVec.push_back(Covnert2(nodeAnim->mScalingKeys[i]));
}
boneAnimation->m_channelVec.push_back(data);
break;
}
}
}
//boneAnimation->m_boneTransformVec = boneTransformVec;
boneAnimation->m_allHierarchyTransformVec = fullBoneTransformVec;
boneAnimation->m_fullAnimTransformVec = allAnimationTransformVec;
// if (false)
// {
// for (int i = 0; i < fullBoneTransformVec.size(); ++i)
// {
// Transform * iter = fullBoneTransformVec[i];
// if (iter->m_name == "Bone001"
// || iter->m_name == "Bip001"
// || iter->m_name == "Bip001 Pelvis"
// || iter->m_name == "Bip001 Spine")
// {
// if (iter->m_name == "Bone001")
// {
// int test = 0;
// }
// if (iter->m_name == "Bip001")
// {
// int test = 0;
// }
// if (iter->m_name == "Bip001 Pelvis")
// {
// int test = 0;
// }
// GUtil::Log(iter->m_name + " localpos " + iter->GetLocalPosition().toString() +
// " localeuler " + iter->GetLocalEulerAngles().toString() +
// " localScale " + iter->GetLocalScale().toString() +
// " worldPos " + iter->GetPosition().toString() +
// " worldEuler " + iter->GetEulerAngles().toString() +
// " worldScale " + iter->GetLossyScale().toString());
// }
// }
// }
// for (int i = 0; i < boneTransformVec.size(); ++i)
// {
// Transform * iter = boneTransformVec[i];
// {
// // GUtil::Log(iter->m_name + " localpos " + iter->GetLocalPosition().toString() +
// // " localeuler " + iter->GetLocalEulerAngles().toString() +
// // " worldPos " + iter->GetPosition().toString() +
// // " worldEuler " + iter->GetEulerAngles().toString() +
// // " worldScale " + iter->GetLossyScale().toString());
// }
// }
//aiQuaternion key = animVec[0]->mRotationKeys[0].mValue;
//Quaternion bip001Qua = Quaternion(key.x, key.y, key.z, key.w);
//GUtil::Log("bip001 euler " + bip001Qua.eulerAngles().toString());
}
void processMesh(aiMesh *mesh, const aiScene *scene, bool inverseZ, bool readBone, MeshFliter & meshFilter, BoneAnimation * pBoneAnimation)
{
std::vector<Vector3> vertices;
std::vector<GLuint> indices;
//std::vector<Texture> textures;
std::vector<Vector3> normals;
Matrix4x4 inverseMat = Matrix4x4::TRS(Vector3::zero(), Quaternion::Euler(Vector3(0, 180, 0)), Vector3::one());
for (unsigned int i = 0; i < mesh->mNumVertices; i++)
{
Vector3 vertex;
// 处理顶点位置、法线和纹理坐标
vertex.x = mesh->mVertices[i].x;
vertex.y = mesh->mVertices[i].y;
vertex.z = mesh->mVertices[i].z;
if (inverseZ)
{
vertex = inverseMat.MultiplyPoint(vertex);
}
vertices.push_back(vertex);
Vector3 normal;
normal.x = mesh->mNormals[i].x;
normal.y = mesh->mNormals[i].y;
normal.z = mesh->mNormals[i].z;
if (inverseZ)
{
normal = inverseMat.MultiplyVector(normal);
}
normals.push_back(normal);
}
for (unsigned int i = 0; i < mesh->mNumFaces; i++)
{
aiFace face = mesh->mFaces[i];
for (unsigned int j = 0; j < face.mNumIndices; j++)
indices.push_back(face.mIndices[j]);
}
//===================解析骨骼和骨骼动画=======================
if (!readBone)
{
meshFilter = GetMeshFilter(vertices, normals, indices);
return;
}
if (mesh->mNumBones == 0)
{
return;
}
//meshFilter.m_vertices = vertices;
std::vector<BoneWeight> boneWeights;
for (int i = 0; i < vertices.size(); ++i)
{
boneWeights.push_back(BoneWeight());
}
//meshFilter.m_normals = normals;
std::vector<std::string> boneNameVec;
//int numBones = mesh->mNumBones;
std::vector<Matrix4x4> bindPoses;
for (int i = 0; i < mesh->mNumBones; ++i)
{
aiBone * bone = mesh->mBones[i];
Matrix4x4 bindPose = Convert(bone->mOffsetMatrix);
bindPoses.push_back(bindPose);
boneNameVec.push_back(bone->mName.C_Str());
for (int j = 0; j < bone->mNumWeights; ++j)
{
aiVertexWeight weight = bone->mWeights[j];
boneWeights[weight.mVertexId].AddWeight(i, weight.mWeight);
}
}
if (scene->mNumAnimations > 0)
{
aiAnimation * animation = scene->mAnimations[0];
pBoneAnimation->m_framePerSecond = animation->mTicksPerSecond;
pBoneAnimation->m_totalFrame = animation->mDuration;
// for (int i = 0; i < animation->mNumChannels; ++i)
// {
// //aiNodeAnim * anim = animation->mChannels[0];
// //int test = 0;
// aiNodeAnim * anim = animation->mChannels[i];
// }
processBoneAnimation(boneNameVec, scene, animation, pBoneAnimation);
}
//=====================测试静态骨骼数据====================
// GUtil::Log("vertexCount " + vertices.size());
// std::string vertexData;
// for (int i = 0; i < 100; ++i)
// {
// vertexData += vertices[i].toString() + "\n";
// }
// GUtil::Log("vertexData \n" + vertexData);
//
// std::vector<Matrix4x4> vertexToModel;
// for (int i = 0; i < boneNameVec.size(); ++i)
// {
// Matrix4x4 mat = boneAnimation->m_boneTransformVec[i]->GetLocalToWorldMatrix() * bindPoses[i];
// vertexToModel.push_back(mat);
// }
// std::vector<Vector3> posVertices;
// for (int i = 0; i < vertices.size(); ++i)
// {
// Vector3 iter = vertices[i];
// BoneWeight weight = boneWeights[i];
// Matrix4x4 mat0 = vertexToModel[weight.m_index0];
// Matrix4x4 mat1 = vertexToModel[weight.m_index1];
// Matrix4x4 mat2 = vertexToModel[weight.m_index2];
// Matrix4x4 mat3 = vertexToModel[weight.m_index3];
// Vector3 newPos = mat0.MultiplyPoint(iter) * weight.m_weight0 +
// mat1.MultiplyPoint(iter) * weight.m_weight1 +
// mat2.MultiplyPoint(iter) * weight.m_weight2 +
// mat3.MultiplyPoint(iter) * weight.m_weight3;
// posVertices.push_back(newPos);
// }
//===========================================
meshFilter = GetMeshFilter(vertices, normals, indices);
meshFilter.m_vertices = vertices;
meshFilter.m_normals = normals;
meshFilter.m_bindPoses = bindPoses;
meshFilter.m_boneWeights = boneWeights;
//meshFilter = GetMeshFilter(posVertices, normals, indices);
}
#pragma endregion
void processNode(aiNode *node, const aiScene *scene, bool readBone, std::vector<MeshFliter>& meshFilterVec, std::vector<BoneAnimation *> & boneAnimationVec, bool inverseZ)
{
// 处理节点所有的网格(如果有的话)
for (unsigned int i = 0; i < node->mNumMeshes; i++)
{
aiMesh *mesh = scene->mMeshes[node->mMeshes[i]];
MeshFliter meshFilter;
BoneAnimation * boneAnimation = new BoneAnimation();
processMesh(mesh, scene, inverseZ, readBone, meshFilter, boneAnimation);
meshFilterVec.push_back(meshFilter);
boneAnimationVec.push_back(boneAnimation);
}
// 接下来对它的子节点重复这一过程
for (unsigned int i = 0; i < node->mNumChildren; i++)
{
processNode(node->mChildren[i], scene, readBone, meshFilterVec, boneAnimationVec, inverseZ);
}
}
bool ModelFileHelper::loadMeshAsVAO(std::string path, std::vector<MeshFliter> & ret, bool inverseZ)
{
std::vector<BoneAnimation *> boneAnimation;
return loadBoneAnimation(path, ret, boneAnimation, inverseZ, false);
}
bool ModelFileHelper::loadBoneAnimation(std::string path, std::vector<MeshFliter> & ret, std::vector<BoneAnimation *> & boneAnimation, bool inverseZ /*= true*/, bool readBone)
{
Assimp::Importer import;
const aiScene *scene = import.ReadFile(path, aiProcessPreset_TargetRealtime_Quality | aiProcess_ConvertToLeftHanded);
if (!scene || scene->mFlags & AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode)
{
GUtil::Log(std::string("ERROR::ASSIMP::") + import.GetErrorString());
return false;
}
std::string directory = path.substr(0, path.find_last_of('/'));
//std::vector<MeshFliter> meshFilterVec;
processNode(scene->mRootNode, scene, readBone, ret, boneAnimation, inverseZ);
import.FreeScene();
return true;
}
// void ObjFileHelper::load_obj(const char* filename, std::vector<Vector3> &vertices, std::vector<Vector3> &normals, std::vector<GLuint> &elements)
// {
// using namespace std;
// ifstream in(filename, ios::in);
// if (!in)
// {
// cerr << "Cannot open " << filename << endl; exit(1);
// }
//
// string line;
// while (getline(in, line))
// {
// if (line.substr(0, 2) == "v ")
// {
// istringstream s(line.substr(2));
// Vector3 v;
// s >> v.x;
// s >> v.y;
// s >> v.z;
// vertices.push_back(v);
// }
// else if (line.substr(0, 2) == "f ")
// {
// istringstream s(line.substr(2));
// GLushort a, b, c;
// s >> a;
// s >> b;
// s >> c;
// a--;
// b--;
// c--;
// elements.push_back(a); elements.push_back(b); elements.push_back(c);
// }
// else if (line[0] == '#')
// {
// // ignoring this line
// }
// else
// {
// // ignoring this line
// }
// }
//
// // 3dmax 为右手坐标系 需要转换下坐标
// // for (int i = 0; i < vertices.size(); ++i)
// // {
// // Vector3 iter = vertices[i];
// // iter.x = -iter.x;
// // vertices[i] = iter;
// // }
//
// normals.resize(vertices.size(), Vector3(0.0, 0.0, 0.0));
// for (int i = 0; i < elements.size(); i += 3)
// {
// GLuint ia = elements[i];
// GLuint ib = elements[i + 1];
// GLuint ic = elements[i + 2];
// Vector3 v1 = vertices[ia];
// Vector3 v2 = vertices[ib];
// Vector3 v3 = vertices[ic];
// Vector3 normal = Vector3::Normalize(Vector3::Cross(
// v2 - v1,
// v3 - v1));
// normals[ia] = normals[ib] = normals[ic] = normal;
// }
//
// }
// MeshFliter ObjFileHelper::loadObjAsVAO2(const char* filename)
// {
// MeshFliter ret;
// ret.m_frontFace = GL_CW;
//
// std::vector<Vector3> vertices;
// std::vector<Vector3> normals;
// std::vector<GLuint> indexs;
// load_obj(filename, vertices, normals, indexs);
// GLfloat * vertex_positions = new GLfloat[vertices.size() * 3];
// GLuint * vertex_indices = new GLuint[indexs.size()];
// GLfloat * vertex_normals = new GLfloat[normals.size() * 3];
//
// for (int i = 0; i < vertices.size(); ++i)
// {
// vertex_positions[i * 3] = vertices[i].x;
// vertex_positions[i * 3 + 1] = vertices[i].y;
// vertex_positions[i * 3 + 2] = vertices[i].z;
// }
//
// for (int i = 0; i < indexs.size(); ++i)
// {
// vertex_indices[i] = indexs[i];
// }
//
// for (int i = 0; i < normals.size(); ++i)
// {
// vertex_normals[i * 3] = normals[i].x;
// vertex_normals[i * 3 + 1] = normals[i].y;
// vertex_normals[i * 3 + 2] = normals[i].z;
// }
//
// int size_vertex_positions = vertices.size() * 3 * 4;
// int size_vertex_indices = indexs.size() * 4;
// ret.drawVerticesCount = indexs.size();
// int size_vertex_normals = normals.size() * 3 * 4;
//
// //GLuint vao = 0;
// glGenVertexArrays(1, &ret.m_vao);
// glBindVertexArray(ret.m_vao);
//
// glGenBuffers(1, &ret.m_positionVBO);
// glBindBuffer(GL_ARRAY_BUFFER, ret.m_positionVBO);
// glBufferData(GL_ARRAY_BUFFER,
// size_vertex_positions,
// vertex_positions,
// GL_STATIC_DRAW);
// glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
// glEnableVertexAttribArray(0);
//
// glGenBuffers(1, &ret.m_normalVBO);
// glBindBuffer(GL_ARRAY_BUFFER, ret.m_normalVBO);
// glBufferData(GL_ARRAY_BUFFER,
// size_vertex_normals,
// vertex_normals,
// GL_STATIC_DRAW);
// glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, 0, NULL);
// glEnableVertexAttribArray(3);
//
// glGenBuffers(1, &ret.m_indexVBO);
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ret.m_indexVBO);
// glBufferData(GL_ELEMENT_ARRAY_BUFFER,
// size_vertex_indices,
// vertex_indices,
// GL_STATIC_DRAW);
//
// return ret;
// }
|
4b6f508119e1030979edfc3be01f38aab2851e70 | eae8c2b8970210ef5e3b25bfb77d703818b351c1 | /Common/SafeQueue.h | 8a5f864408f105faa7c7052a5d4fc0b56c728ee4 | [] | no_license | fpusderkis/TP-Final-Taller-I | 62f971d025c544953d341e711fa448341cd1719a | d30301a96fea7ba641574112e39646211924db49 | refs/heads/master | 2022-01-19T23:00:49.506962 | 2019-06-26T02:49:01 | 2019-06-26T02:49:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 992 | h | SafeQueue.h | #ifndef PORTAL_PROTECTEDQUEUE_H
#define PORTAL_PROTECTEDQUEUE_H
#include <condition_variable>
#include <queue>
#include <memory>
#include <Common/ProtocolTranslator/ProtocolDTO.h>
#include <iostream>
// Monitor de la cola, responsable de agregar los elementos e
// interpretar los mismos controlando los posibles threads a traves de
// condition variable
template <class T>
class SafeQueue {
std::queue<T> _queue;
std::mutex _m;
public:
// Agrega un elemento a la cola
void push(T new_data) {
std::lock_guard<std::mutex> lock(_m);
this->_queue.push(std::move(new_data));
}
// Retorna un elemento de la cola y lo quita.
// Retorna nullptr en caso que la cola este vacia
T getTopAndPop() {
std::lock_guard<std::mutex> lock(_m);
T aux = nullptr;
if (!this->_queue.empty()) {
aux = _queue.front();
this->_queue.pop();
}
return aux;
}
};
#endif //PORTAL_PROTECTEDQUEUE_H
|
5d30e49d195720af99c50b0cc535696a8412f6c6 | 3b4af5aca9761277fdf82efe3e2462ff7b0a4e9c | /SCar-ESB32_code/Bluetooth.ino | ecfe5371542a30432d1157a80ca1b2482b8d6459 | [] | no_license | mohamedotaki/S-Car | 490d1224d9c2a2e4c81988c09aea1def939a004b | 99dedc4d9df7753890dcf2de04b8cb0d2a4d08dc | refs/heads/main | 2023-05-15T04:43:19.598914 | 2021-05-19T16:18:10 | 2021-05-19T16:18:10 | 309,731,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,905 | ino | Bluetooth.ino | void bluetooth() {
if (SerialBT.available()) {
switch (SerialBT.read()) {
// user is in control car activity start sending sensors value to the app
case 'C': {
//set all the bits to high
Serial.println("in control car activity start sending sensors vlaue");
vTaskResume( ultrasonicTaskHandle );
xEventGroupSetBits(xEventGroup, allSensorBits | sendSensorsValueBit);
}
// turn left received from user
case 'L':
Serial.println("turning left");
BTSteering = BTSteering + 100;
if (BTSteering >= 1900) {
BTSteering = 1900;
}
writeServo(BTSteering);
break;
//Turn right received from user
case 'R':
Serial.println("turning Right");
BTSteering = BTSteering - 100;
if (BTSteering <= 1100) {
BTSteering = 1100;
}
writeServo(BTSteering);
break;
//go forward or increase the speed
case 'F':
Serial.println("forward");
motorF(forwardSpeed);
break;
//Reverse or increase the speed
case 'B':
Serial.println("reverse");
motorS();
motorR(reversingSpeed);
break;
// Stop motor
case 'S':
Serial.println("stop");
xEventGroupClearBits(xEventGroup, allFeatureBits);
motorS();
break;
// Activate parking assist
case 'P':
xEventGroupSetBits(xEventGroup, parkingAssistBit );
break;
case 'j':
Serial.println("Wifi");
break;
// Stpe sending sensors value to to app and suspend the ultrasonic task
case 'E':
xEventGroupClearBits(xEventGroup, allSensorBits | sendSensorsValueBit);
vTaskSuspend(ultrasonicTaskHandle);
break;
case 'W':
// scan the available wifi and send to the app
scanNetworks();
break;
case 'O':
// get user input from the app
getWifiDetailsFromApp();
break;
case 1:
// get user input from the app
Serial.println(readBTInput());
break;
case 'A':
xEventGroupSetBits(xEventGroup, autonomousDrivingBit );
break;
} // end of BT read
}
} // end of BT function
void sendSensorsValue() {
// send sensors value to the app using bluetooth
uint8_t a[9] = {highByte(f), lowByte(f), highByte(b), lowByte(b), highByte(rfs), lowByte(rfs), highByte(r), lowByte(r), 'x'};
SerialBT.write(a, 9);
}
void callback(esp_spp_cb_event_t event, esp_spp_cb_param_t *param) {
if (event == ESP_SPP_SRV_OPEN_EVT) {
Serial.println("Client Connected");
// vTaskResume( checkUserHandle);
}
}
String readBTInput() {
BTDataInput = "";
byte b;
while (true) {
b = SerialBT.read();
if (b == 4) {
break;
}
BTDataInput += (char) b;
}
return BTDataInput;
}
|
0d38d76b2574d8dd24a2c9efb40f63a1f8666dfe | 8a4d44fb90eab0a9875a4f3d02efd9c4a6a52a9e | /src/memalloc/tests/memory_test.cpp | 1e99dff44ebabdac593a48b8ab202d2925e440b1 | [
"MIT"
] | permissive | vasil-sd/engineering-sw-hw-model-checking-letures | 7e2a89900099a1af6b1b2f9ab1b7a9d41ef79014 | b6aaa096eb033670a5643cc5ae1d5b63798e38f0 | refs/heads/master | 2023-04-06T14:23:53.391411 | 2021-04-19T06:26:36 | 2021-04-19T06:26:36 | 293,767,366 | 20 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,128 | cpp | memory_test.cpp | #include "memory.h"
#include <iostream>
#include <cstddef>
#include <vector>
static const size_t pool_size = 65536;
static char mempool[pool_size];
static Memory mem{mempool, &mempool[pool_size]};
void Test() {
struct Something {
int a;
int b;
};
std::cout << "Initial: " << std::endl << mem << std::endl;
auto alloc = mem.allocator<Something>();
{
std::vector<Something, decltype(alloc)> vec(alloc);
std::cout << "vector created: " << std::endl << mem << std::endl;
for(int a=0; a<100; ++a) {
vec.emplace_back(Something{a,a});
}
std::cout << "vector populated: " << std::endl << mem << std::endl;
for(int a=0; a<70; ++a) {
vec.pop_back();
}
std::cout << "some elements are removed from vector : " << std::endl << mem << std::endl;
vec.shrink_to_fit();
std::cout << "vector was shrinked: " << std::endl << mem << std::endl;
}
std::cout << "vector destroyed: " << std::endl << mem << std::endl;
}
int main(int argc, char** argv) {
Test();
return 0;
}
|
861678c6de9eea25cafd2bb00cf64a3e74a29daf | c0f2c548fa1c0fb50a2b612f11ef6b9d264e429f | /socket/DefaultClientSocket.h | 8fe4aaebe5bf38f16ec66d084b16cbd1aee676f6 | [] | no_license | zcj6758/TCP_Nat_Traversal | f76985fca0fce685ff6b63f2ee70fe54ce24e603 | 588b6339a38cb53fde323beb1fcb3740e19532dc | refs/heads/master | 2023-03-18T04:57:55.514076 | 2018-06-27T05:14:00 | 2018-06-27T05:14:00 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,772 | h | DefaultClientSocket.h | #ifndef DEFAULT_CLIENT_SOCKET_H
#define DEFAULT_CLIENT_SOCKET_H
#include "../include/socket/ClientSocket.h"
#include "DefaultSocket.h"
LIB_BEGIN
#define DEFAULT_READ_BYTE 512
class DefaultClientSocket : public ClientSocket
{
public:
DefaultClientSocket() :m_bHasConnect(false) { }
explicit DefaultClientSocket(int socket); // Review: 本来想写成protected的,但是这样得申明DefaultServerSocket是它的友元,想想还是这么处理吧
DefaultClientSocket(int socket,const ip_type& addr,port_type port);
virtual bool open() { return m_socket.open(); }
virtual bool close();
virtual bool isOpen() const { return m_socket.isOpen(); }
virtual bool bind(port_type port) { return m_socket.bind("",port); }
virtual bool bind(const ip_type& addr, port_type port) { return m_socket.bind(addr,port); }
virtual bool isBound() const { return m_socket.isBound(); }
virtual std::string read(int read_bype = DEFAULT_READ_BYTE); // 默认读取 512 个字节
virtual size_t write(const char*);
virtual bool connect(const char*, port_type, size_t time = (size_t)(-1));
virtual bool isConnected() const { return m_bHasConnect; }
virtual bool setNonBlock(bool flag = true);
virtual port_type getPort() const { return m_socket._port(); }
virtual ip_type getAddr() const { return m_socket._addr(); }
virtual port_type getPeerPort() const;
virtual ip_type getPeerAddr() const;
public:
int _getfd(){ return m_socket._socket(); } // 提供给 NatTraversalClient 的特殊函数
void _invalid(){ m_socket.invalid(); }
protected:
size_t _getMaxTryTime() const { return 5; }
size_t _getSleepTime() const { return 1 * 1000000; }
protected:
DefaultSocket m_socket;
bool m_bHasConnect;
};
LIB_END
#endif
|
cd2fb2cea10f59ac829fc93ab350bf34b4188608 | caaa22d93fa1fc79fe2f68fa54b9c7650a774644 | /02-Number Theory/extended_gcd.cpp | 6c9c6d4876d2c5fa1d7cd17d27e86489e9386ddd | [] | no_license | soumilk/Algorithms_and_Their_Techniques | 6b9575d0bd589a13b44ca082580f317641bc4163 | 49a658a0e8eb55e4d4c50a17f5b83dc719da0611 | refs/heads/master | 2020-04-18T06:32:12.755468 | 2020-02-03T08:46:30 | 2020-02-03T08:46:30 | 167,324,935 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 691 | cpp | extended_gcd.cpp | //
// Created by soumil on 8/17/2019.
//
/*
* This is the program in which we will extend the implementation of the euclid's GCD
* The problem is to find out the x and y which satisfies the equation :
Ax + By =GCD(A,B)
*/
#include<iostream>
using namespace std;
int x,y,gcd;
void extended_gcd(int a,int b)
{
if (b==0)
{
x=1;
y=0;
gcd=a;
return ;
}
extended_gcd(b,a%b);
int cx,cy;
cx=y;
cy=x-(a/b)*y;
x=cx;
y=cy;
}
int main()
{
cout<<"Provide the input for A abd B in Ax + By =GCD(A,B)"<<endl;
int a,b;
cin>>a>>b;
extended_gcd(a,b);
cout<<"x :"<<x<<"\t"<<"y :"<<y<<endl;
return 0;
}
|
793c7e423406e0b167d1d6419aa19a826b0dfdbf | e9a8cc296c3defae37471477270dbe9c2a434327 | /Zeiterfassungssystem/Zeiterfassungssystem/Kalender.cpp | 7cc3106bc77a0d5f77aba84dea05f294b570b13f | [] | no_license | Toniaaaa/Arbeitszeitenerfassungssystem | cd0eefdb08fb43223878d5c2405e7cc659d64039 | 99c93074e9b86b53e8a920525a874114f8537494 | refs/heads/master | 2020-03-27T09:01:34.789403 | 2018-11-15T18:58:48 | 2018-11-15T18:58:48 | 146,307,738 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,201 | cpp | Kalender.cpp | #include "Kalender.h"
Kalender::Kalender()
{
}
Kalender::~Kalender()
{
}
//Kalenderwoche eines Tages berechnen
Int32 Kalender::berechneKW(DateTime^ tag)
{
//"Kultur" wird auf deutsch gestellt
CultureInfo^ meinCI = gcnew CultureInfo("de");
//Ein Kalender nach deutschem (mitteleuropäischem) Standard wird erstellt
Calendar^ meinKalender = meinCI->Calendar;
//Die Regel, nach der Kalenderwochen gezählt werden, wird so eingestellt, dass die KW1 mit dem ersten Kalendertag beginnt
CalendarWeekRule^ meineCWR = meinCI->DateTimeFormat->CalendarWeekRule;
//Der Erste Wochentag wird als Montag gesetzt
DayOfWeek^ meinErsterWochentag = meinCI->DateTimeFormat->FirstDayOfWeek;
//Die KW des übergebenen Tages wird berechnet und zurückgegeben
return meinKalender->GetWeekOfYear(*tag, *meineCWR, *meinErsterWochentag);
}
//Gibt den ersten Tag dieser Kalenderwoche zurück
DateTime^ Kalender::ersterTagDieserWoche()
{
//Wenn heute Montag ist, wird heute als erster Tag dieser Woche gesetzt
DateTime^ tag = DateTime::Now.Date;
//Ansonsten wird nach dem ersten Montag in der Vergangenheit gesucht
while (tag->DayOfWeek != DayOfWeek::Monday) {
tag = tag->AddDays(-1.0);
}
return tag;
} |
997a6e799aad48905a5633974133976a1a06d738 | b4e7a8d779d813c5e6b229ed3aad0afb6c015f0b | /tcbdb/TcbDB.hpp | 2b145375238d5608e8b8ba4f3da701ff006071a5 | [] | no_license | yangjietadie/db | 2b9c7ba963827812b62ae023311b0965911c3dd5 | cfefa3c84fff1336304a68187f9f22408a3ba4ce | refs/heads/master | 2023-07-14T13:21:49.820343 | 2021-08-17T09:15:43 | 2021-08-17T09:15:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,749 | hpp | TcbDB.hpp | /*
** Copyright (C) 2015 Wang Yaofu
** All rights reserved.
**
**Author:Wang Yaofu voipman@qq.com
**Description: The header file of class TcbDB.
*/
#pragma once
#include <stdint.h>
#include <string>
#include <vector>
#include <tcbdb.h>
// START_NAMESPACE
struct Options {
int32_t membersOfLeaf = { 1024 };
int32_t membersOfNonLeaf = { 2048 };
int32_t elementsOfArray = { 50000000 };
int8_t apow = { 8 };
int8_t fpow = { 10 };
int8_t opts = { BDBTLARGE };
// maximum number of leaf nodes to be cached.
int32_t maxNumOfLeaf = { 1048576 };
// the size of the extra mapped memory
int32_t extraMemorySize = { 1024 };
};
class TcbDB {
public:
enum Status {
OK,
FAILED
};
explicit TcbDB();
virtual ~TcbDB();
void setOption(const Options& opt);
int open(const std::string& db);
// Store record into a B+ tree database object.
int put(const std::string& key, const std::string& value);
// Store records into a B+ tree database object with allowing duplication of keys.
int multiPut(const std::string& key, const std::vector<std::string>& values);
// Store int record into a B+ tree database object.
int putInt(const std::string& key, int value);
// Store double record into a B+ tree database object.
int putDouble(const std::string& key, double value);
// Store a record into a B+ tree database object with allowing duplication of keys.
int putDup(const std::string& key, const std::string& value);
// Retrieve a record in a B+ tree database object.
int get(const std::string& key, std::string& value);
// Retrieve records in a B+ tree database object.
int multiGet(const std::string& beginKey,
const std::string& endKey, int limits,
std::vector<std::string>& values);
// Get forward matching keys in a B+ tree database object.
int getPrefix(const std::string& key, int limits,
std::vector<std::string>& values);
// Remove records of a B+ tree database object.
int del(const std::string& key);
// Concatenate a value at the end of the existing record in a B+ tree database object.
int append(const std::string& key, const std::string& value);
// Get the number of records of a B+ tree database object.
uint64_t keyCounts();
// Get the size of the database file of a B+ tree database object.
uint64_t dbSize();
// Get the number of records corresponding a string key in a B + tree database object.
int numOfKey(const std::string& key);
// Get the number of records corresponding a key in a B+ tree database object.
int valueSizeOfKey(const std::string& key);
// Retrieve records in a B+ tree database object.
int valuesOfKey(const std::string& key, std::vector<std::string>& values);
// Synchronize updated contents of a B+ tree database object with the file and the device.
int save();
// Remove all records of a B+ tree database object.
int destory();
// Optimize the file of a B+ tree database object.
int optimize(const Options& opt);
// Copy the database file of a B+ tree database object.
int copy(const std::string& toDbPath);
// Begin the transaction of a B+ tree database object.
int startTransaction();
// Abort the transaction of a B+ tree database object.
int rollback();
// Commit the transaction of a B+ tree database object.
int commit();
// Get the file path of a B+ tree database object.
std::string dbPath();
TCBDB* getTcbDbRawPtr() {
return tcbdb_;
}
private:
void TCLIST2vector(TCLIST* rets, std::vector<std::string>* values);
private:
// tcbdb pointer.
TCBDB *tcbdb_;
Options options_;
};
// END_NAMESPACE
|
eb089b96fc8c153323a4118831950a461a079b4a | 866bc8ae07353f7fdf21a2a2ebbf29fc1307c59e | /Client/EquipBar.cpp | 276b93196424ddce4d4c9f459e014b3c5665d95e | [] | no_license | kdd6826/TalseWeaver11 | d0aa78d804f3daf264c35ca1e80d39f0b1950711 | 7d6955869e9a87d44f5918de60f50924ddd7183b | refs/heads/master | 2022-12-17T09:31:09.025516 | 2020-09-17T16:47:00 | 2020-09-17T16:47:00 | 296,386,972 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,096 | cpp | EquipBar.cpp | #include "stdafx.h"
#include "EquipBar.h"
#include "Monster.h"
#include "KeyManager.h"
CEquipBar::CEquipBar()
{
m_ObjId = OBJ::OBJ_BUTTON;
ZeroMemory(&m_tFrame, sizeof(FRAME));
}
CEquipBar::~CEquipBar()
{
Release_GameObject();
}
HRESULT CEquipBar::Ready_GameObject()
{
m_tInfo.vPos = { 790.f, 150.f, 0.f };
m_tInfo.vSize = { 1.f, 1.f, 0.f };
//////
m_tInfo.vDir = { 1.f,1.f,0.f };
m_tInfo.vLook = { 1.f, 0.f, 0.f };
//////
m_szFrameKey = L"EquipBarUp";
m_tFrame = { 0,1 };
return S_OK;
}
int CEquipBar::Update_GameObject()
{
return OBJ_NOEVENT;
}
void CEquipBar::LateUpdate_GameObject()
{
}
void CEquipBar::Render_GameObject()
{
pTexInfo = CTexture_Manager::Get_Instance()->Get_TexInfo(L"UI", m_szFrameKey, 0);
if (nullptr == pTexInfo)
return;
m_tInfo.vRealSize = { float(pTexInfo->tImageInfo.Width), float(pTexInfo->tImageInfo.Height), 0.f };
_vec3 vCenter = { _float(pTexInfo->tImageInfo.Width >> 1), _float(pTexInfo->tImageInfo.Height >> 1) , 0.f };
_matrix matScale, matTrans, matWorld;
D3DXMatrixScaling(&matScale, m_tInfo.vSize.x, m_tInfo.vSize.y, 0.f);
D3DXMatrixTranslation(&matTrans, m_tInfo.vPos.x, m_tInfo.vPos.y, 0.f);
matWorld = matScale * matTrans;
CGraphic_Device::Get_Instance()->Get_Sprite()->SetTransform(&matWorld);
CGraphic_Device::Get_Instance()->Get_Sprite()->Draw(pTexInfo->pTexture, nullptr, &vCenter, nullptr, D3DCOLOR_ARGB(255, 255, 255, 255));
}
void CEquipBar::Release_GameObject()
{
}
void CEquipBar::OnCollision(CGameObject* _TargetObj)
{
switch (_TargetObj->GetObjId()) {
case OBJ::OBJ_MONSTER:
{
CMonster* tempCollision = dynamic_cast<CMonster*>(_TargetObj);
if (tempCollision)
{
/*m_SP -= 1;*/
}
}
}
}
CGameObject* CEquipBar::Create(LPVOID* pArg)
{
CGameObject* pInstnace = new CEquipBar;
if (FAILED(pInstnace->Ready_GameObject()))
return nullptr;
return pInstnace;
}
CGameObject * CEquipBar::Create(_vec3 vpos)
{
CGameObject* pInstnace = new CEquipBar;
if (FAILED(pInstnace->Ready_GameObject()))
return nullptr;
pInstnace->SetPos(vpos);
pInstnace->SetFirstPos(vpos);
return pInstnace;
}
|
116dd94aec65fa03a271beae499832de87ff32ac | 4b54f8a04a140ff4e043b7286cad71a00dd762ff | /list-entry.cpp | 48ee9f4b6bb8d974f049faf244403e0c4c015eca | [] | no_license | saji-spoon/SM-Tapu-RNGTool | 5e39fe93b5134565c6ad660771b67186ccfd75d5 | 6f3e10cfb47011620bc7ae41534f828925375449 | refs/heads/master | 2021-01-11T15:04:00.292028 | 2017-03-16T13:47:47 | 2017-03-16T13:47:47 | 80,290,783 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 548 | cpp | list-entry.cpp | #include"list.hpp"
int main(int argc, char* argv[])
{
if(argc < 2 || strlen(argv[1]) < 8)
{
printf("Usage: %s 1234FEDC\n", argv[0]);
printf("Seed(32 bit) is required.\n");
return 1;
}
uint32_t seed;
std::stringstream ss;
ss << argv[1];
ss >> std::hex >> seed;
auto rd = getRandDataList(seed, 1000);
saveFile(rd);
auto pkst = getPokeStatusList(rd, rd.size());
saveFile(pkst);
printf("Lists created. See ./lists/\n");
return 0;
}
|
64c9ccf24e530261ac171c6176aba2abd63a8ddd | 85fad9c15ca51e3cf79df91f87860ff2ac3643b7 | /Source/DTD/Private/CreepBase.cpp | ecb9f81d69a9fc021f89332585516c962389e1cb | [] | no_license | zlurker/DTD | c9499010eb6b4c3d8a21e6b930d03c5350a03d1a | e9fbd908b697cbd3d174631a6b43c840868899fb | refs/heads/master | 2021-04-17T12:11:57.133334 | 2020-07-05T08:54:53 | 2020-07-05T08:54:53 | 249,444,591 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 608 | cpp | CreepBase.cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "CreepBase.h"
// Sets default values
ACreepBase::ACreepBase()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ACreepBase::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ACreepBase::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
void ACreepBase::ModifyHealth(float value) {
health -= value;
if (health <= 0)
Destroy();
}
|
fb4cc91ddbbfc0598e6a15449701f12328ae5378 | b86811b16c3a7b916943f654eabfd3502689804a | /DiscRoomTA/Perdio.h | 8e7f1d1a6902ec91b1aeddc148f2fff438235cfd | [] | no_license | ShoLee01/DiscRoom-en-Windows-Form | 36c43eea9d446a74d7ce84d79dc3b05199ee8214 | c47a3fbbcd36b0247997b9e770f301fabbed2056 | refs/heads/master | 2023-01-15T13:35:12.508521 | 2020-10-27T17:37:47 | 2020-10-27T17:37:47 | 307,779,168 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,541 | h | Perdio.h | #pragma once
namespace DiscRoomTA {
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
/// <summary>
/// Summary for Perdio
/// </summary>
public ref class Perdio : public System::Windows::Forms::Form
{
public:
Perdio(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Perdio()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ lblTitulo;
protected:
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Perdio::typeid));
this->lblTitulo = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// lblTitulo
//
this->lblTitulo->AutoSize = true;
this->lblTitulo->BackColor = System::Drawing::SystemColors::WindowText;
this->lblTitulo->Font = (gcnew System::Drawing::Font(L"OCR A Extended", 72, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point,
static_cast<System::Byte>(0)));
this->lblTitulo->ForeColor = System::Drawing::SystemColors::ControlLightLight;
this->lblTitulo->Location = System::Drawing::Point(28, 43);
this->lblTitulo->Name = L"lblTitulo";
this->lblTitulo->Size = System::Drawing::Size(632, 99);
this->lblTitulo->TabIndex = 1;
this->lblTitulo->Text = L"GAME OVER!";
//
// Perdio
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->BackgroundImage = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"$this.BackgroundImage")));
this->BackgroundImageLayout = System::Windows::Forms::ImageLayout::Stretch;
this->ClientSize = System::Drawing::Size(684, 461);
this->Controls->Add(this->lblTitulo);
this->Name = L"Perdio";
this->Text = L"DiscRoom";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
};
}
|
a6578a0efc809cb62bfb0e32b45a7681a34790f4 | e396342013eb72e56ab526b2f43f8377e5846d7d | /cpp/json_client/main.cpp | c5659c6debfbde55e0113db1ca42dfb85c9696a1 | [
"MIT"
] | permissive | AtsushiSakai/JSONServerAndClient | e7f4099b60be3ecb5d31ee30a14fc6dd95fe4946 | a7e7cea92616c7e42d46d198f8276aa6c1c50b49 | refs/heads/master | 2021-06-03T17:17:31.921829 | 2020-10-10T05:24:27 | 2020-10-10T05:24:27 | 134,957,224 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | cpp | main.cpp | //
// Json http client in C++
//
// Author: Atsushi Sakai
//
#include <iostream>
#include "../cpp-httplib/httplib.h"
#include "../json/single_include/nlohmann/json.hpp"
using namespace std;
using json = nlohmann::json;
string get_server_ip(){
string SERVER_IP="localhost";
char* env_SERVER_IP = getenv("SERVER_IP");
if (env_SERVER_IP != NULL){
SERVER_IP=string(env_SERVER_IP);
}
return SERVER_IP;
}
int main(void){
cout<<"c++ Json client start !!"<<endl;
// Create request json
map<string, string> c_map { {"Name", "request_from_cpp_client"},
{"Test", "test"} };
json j_map(c_map);
string sjson = j_map.dump();
cout << "Request:" << endl;
cout << sjson << endl;
string SERVER_IP = get_server_ip();
httplib::Client cli(SERVER_IP.c_str(), 8000);
auto res = cli.Post("/", sjson, "application/json");
if (res && res->status == 200) {
cout << "Response:" << endl;
auto jres = json::parse(res->body);
for (json::iterator it = jres.begin(); it != jres.end(); ++it) {
cout << it.key() << " : " << it.value() << endl;
}
}
}
|
aecb87795f360289e2c74c499ec7c3fecf1068ad | b7a451237b0bd17285cb62a1027c5833d4113049 | /ClientConEventos/Excepciones/ExcepcionConPos.h | 261b9208edaa752e47731bf36795deb29f78650c | [] | no_license | diegobalestieri/MicroMachines | 422ae10239810a8b579e0ee2f3698d1e6cefea03 | 5dfce6270da1625f6699091eb5bc0539ab6bd281 | refs/heads/master | 2023-04-22T19:35:21.407078 | 2020-08-07T01:48:23 | 2020-08-07T01:48:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 712 | h | ExcepcionConPos.h | //
// Created by diego on 22/10/19.
//
#ifndef OPENGLTEST_EXCEPCIONCONPOS_H
#define OPENGLTEST_EXCEPCIONCONPOS_H
#include <stdexcept>
class ExcepcionConPos : public std::runtime_error {
private:
static std::string crearMensaje(const char* archivo, int linea, std::string& mensaje){
std::string falla("Error: " + mensaje);
falla.append(" en el archivo: ");
falla.append(archivo);
falla.append(" en la linea: ");
falla.append(std::to_string(linea));
return falla;
}
public:
ExcepcionConPos(const char* archivo, int linea, std::string mensaje) : std::runtime_error(crearMensaje(archivo, linea, mensaje)) {}
};
#endif //OPENGLTEST_EXCEPCIONCONPOS_H
|
2632573611a3d3a3a6e415dd641c3faf2be04845 | 0d22d5f5dbdb31c03d99a1f8b19589007a8823fb | /Practica4/display.cpp | 108b400d2dcb4297a8325aa7fd9126ece89ce24f | [] | no_license | Jaimee007/practicas_info | 42d77ae240d4ba1aa08aab73b22ba9576dff2cce | 3634e91a94626277e81c0fc6b75945b47841261e | refs/heads/main | 2023-02-20T05:23:54.296169 | 2021-01-22T10:04:00 | 2021-01-22T10:04:00 | 314,552,515 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 176 | cpp | display.cpp | #include "display.h"
Display::Display(){}
Display::Display(const string &name): Device(name){}
void Display::process(const string &data) const{
cout << data << endl;
}
|
1f842f1b819d4116c2c58cd8e9e07589966e69cd | 60946db12ed31b7cd43b6d89fe02fa4f72a6cb63 | /A2-Class/dateType.h | ac47d1ecce355464d26d771667baeb4382005159 | [] | no_license | metaknighttu/homework | 75edddadc0f81ab6d74fa879fbe869872e00d2fb | 585d0e84f154623e281039eb4e2b0fbdef542813 | refs/heads/master | 2020-09-23T09:40:00.229236 | 2019-12-02T21:17:32 | 2019-12-02T21:17:32 | 225,468,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | h | dateType.h | #ifndef DATETYPE_H
#define DATETYPE_H
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
class dateType
{
public:
void setDate(int month, int day, int year);
//Function to set the date.
//Postcondition: dateMonth = month; dateay = day;
// dateYear = year;
///GETTERS/// - Each returns its respective variable
int getDay() const;
int getMonth() const;
int getYear() const;
void printDate(dateType) const;
//Function to output the date in the form mm-dd-yyyy.
dateType(int month = 1, int day = 1, int year = 1111);
//Full Constructor to set the date
//The member variables dateMonth, dateDay, and dateYear
//are set according to the parameters.
//Postcondition: dMonth = month; dDay = day; dYear = year;
//If no values are specified, the default
//values are used to initialize the member
//variables.Composition (Aggregation) | 775
private:
int dateMonth; //variable to store the month
int dateDay; //variable to store the day
int dateYear; //variable to store the year
};
#endif |
9c8743aeae5c6683f2a1f9dcef99f73a41307298 | 3fd87fa4b5c921d71b9f4b3c20c2ec710a285d54 | /src/landmark_point_3d.h | 1c0926463fc934ce098dc7547bafe1634844592a | [] | no_license | mshicom/wolf | 8358bf5f84376a9f80b25c5cff8cf8a82f5d1d91 | 1d21ba4a2c72dcdc4347d91071f570beaadd3a29 | refs/heads/master | 2020-12-24T06:06:53.465173 | 2016-09-19T07:26:02 | 2016-09-19T07:26:02 | 73,229,005 | 0 | 0 | null | 2016-11-08T21:34:42 | 2016-11-08T21:34:41 | null | UTF-8 | C++ | false | false | 1,049 | h | landmark_point_3d.h | #ifndef LANDMARK_POINT_3D_H
#define LANDMARK_POINT_3D_H
//Wolf includes
#include "landmark_base.h"
//OpenCV includes
#include "opencv2/features2d/features2d.hpp"
// Std includes
namespace wolf {
class LandmarkPoint3D : public LandmarkBase
{
protected:
cv::Mat descriptor_;
Eigen::Vector3s position_;
public:
LandmarkPoint3D(StateBlock* _p_ptr, StateBlock* _o_ptr, Eigen::Vector3s _position, cv::Mat _2D_descriptor);
virtual ~LandmarkPoint3D();
const Eigen::Vector3s& getPosition() const;
void setPosition(const Eigen::Vector3s & _pos)
{
position_ = _pos;
}
const cv::Mat& getDescriptor() const;
void setDescriptor(const cv::Mat& _descriptor)
{
descriptor_ = _descriptor;
}
};
inline const Eigen::Vector3s& LandmarkPoint3D::getPosition() const
{
return position_;
}
inline const cv::Mat& LandmarkPoint3D::getDescriptor() const
{
return descriptor_;
}
} // namespace wolf
#endif // LANDMARK_POINT_3D_H
|
d18f659ea3af7e666f8027392d2106c992c446ab | 905ad4b5c16b1dc0bfed6d3156c14f5e62ce5d27 | /Ejercicio 02.cpp | 2037b801fc268e19bd7eeaba4aee8be9bcdb4aa2 | [] | no_license | yordysantos/Practica-1---CC2 | 37e5092daf74e4373694e4f6ea196fcbe1aa7502 | 024479885b1445d70c9dfea3f56a74b7f1a85248 | refs/heads/master | 2020-03-09T12:44:31.483685 | 2018-04-13T16:24:41 | 2018-04-13T16:24:41 | 128,793,085 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 469 | cpp | Ejercicio 02.cpp | #include <iostream>
using namespace std;
int sumare(int a[],int n)
{
if(n==0)
{
return 0;
}
else
{
return a[n-1]+sumare(a,--n);
}
}
int sumai(int a[],int n)
{
int sum=0;
for(int i=0;i<n;i++)
{
sum=sum+a[i];
}
return sum;
}
int main(){
int n;
cout<<"Longitud: ";
cin>>n;
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"Suma Recursiva: "<<sumare(a,n)<<endl;
cout<<"Suma Iterativa: "<<sumai(a,n)<<endl;
}
|
393fc3908cd6af41bbf66e3bc24e65e68e6b803f | 1ca288c3f3c54db93fe4828214a81f6687105a1e | /src/test/thinblock_data_tests.cpp | 681f4d7f67dc1b9aa2e44f80e8c586961dc3a913 | [
"MIT"
] | permissive | BitcoinUnlimited/BitcoinUnlimited | 489c91a9184bdbad3824a2ce3126d2e9c0786e5d | 05de381c02eb4bfca94957733acadfa217527f25 | refs/heads/release | 2023-06-01T08:11:18.920865 | 2021-03-29T15:58:02 | 2021-03-29T15:58:02 | 18,613,259 | 546 | 301 | MIT | 2021-01-04T01:05:24 | 2014-04-09T21:03:00 | C++ | UTF-8 | C++ | false | false | 3,609 | cpp | thinblock_data_tests.cpp | // Copyright (c) 2013-2015 The Bitcoin Core developers
// Copyright (c) 2015-2019 The Bitcoin Unlimited developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "blockrelay/thinblock.h"
#include "blockrelay/blockrelay_common.h"
#include "net.h"
#include "test/test_bitcoin.h"
#include <assert.h>
#include <boost/range/irange.hpp>
#include <boost/test/unit_test.hpp>
#include <limits>
#include <string>
#include <vector>
using namespace std;
class TestTBD : public CThinBlockData
{
protected:
virtual int64_t getTimeForStats() { return times[min(times_idx++, times.size() - 1)]; }
vector<int64_t> times;
size_t times_idx;
public:
TestTBD(const vector<int64_t> &_times)
{
assert(_times.size() > 0);
times = _times;
times_idx = 0;
}
void resetTimeIdx() { times_idx = 0; }
};
BOOST_FIXTURE_TEST_SUITE(thinblock_data_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(test_thinblockdata_stats1)
{
vector<int64_t> times1(1000); // minutes
for (uint32_t i = 0; i < times1.size(); i++)
{
times1[i] = 1000 * 60 * i;
}
{
TestTBD tbd(times1);
// exercise summary methods on empty arrays to make sure they don't fail
// in weird ways
tbd.ToString();
tbd.InBoundPercentToString();
tbd.OutBoundPercentToString();
tbd.InBoundBloomFiltersToString();
tbd.OutBoundBloomFiltersToString();
tbd.ResponseTimeToString();
tbd.ValidationTimeToString();
tbd.ReRequestedTxToString();
tbd.MempoolLimiterBytesSavedToString();
}
{
TestTBD tbd(times1);
for (int64_t i : boost::irange(0, 100))
tbd.UpdateInBound(i, 3 * i);
string res = tbd.InBoundPercentToString();
BOOST_CHECK_MESSAGE(res.find("66.7%") != string::npos, "InBoundPercentToString() is " << res);
}
{
TestTBD tbd(times1);
for (int64_t i : boost::irange(0, 100))
tbd.UpdateOutBound(i, 3 * i);
string res = tbd.OutBoundPercentToString();
BOOST_CHECK_MESSAGE(res.find("66.7%") != string::npos, "OutBoundPercentToString() is " << res);
}
{
TestTBD tbd(times1);
for (int64_t i : boost::irange(0, 100))
tbd.UpdateInBoundBloomFilter(1000 * i);
string res = tbd.InBoundBloomFiltersToString();
BOOST_CHECK_MESSAGE(res.find("49.50KB") != string::npos, "InBoundBloomFiltersToString() is " << res);
}
{
TestTBD tbd(times1);
for (int64_t i : boost::irange(0, 100))
tbd.UpdateOutBoundBloomFilter(1000 * i);
string res = tbd.OutBoundBloomFiltersToString();
BOOST_CHECK_MESSAGE(res.find("49.50KB") != string::npos, "OutBoundBloomFiltersToString() is " << res);
}
// FIXME: check others somehow that depend on chain sync state
{
TestTBD tbd(times1);
for (int64_t i : boost::irange(0, 100))
tbd.UpdateInBoundReRequestedTx(1000 * i);
string res = tbd.ReRequestedTxToString();
BOOST_CHECK_MESSAGE(res.find(":100") != string::npos, "ReRequestedTxToString() is " << res);
}
{
TestTBD tbd(times1);
for (int64_t i : boost::irange(0, 100))
tbd.UpdateMempoolLimiterBytesSaved(1000 * i);
string res = tbd.MempoolLimiterBytesSavedToString();
BOOST_CHECK_MESSAGE(res.find("4.95MB") != string::npos, "MempoolLimiterBytesSavedToString() is " << res);
}
}
BOOST_AUTO_TEST_SUITE_END()
|
0f9b6621beb0693c01786c7387c23398e707c281 | dd656493066344e70123776c2cc31dd13f31c1d8 | /MITK/BlueBerry/Bundles/org.blueberry.ui/src/tweaklets/berryWorkbenchPageTweaklet.h | 9cf9f808ef1fa4407e7f14876bdeb9b4d6752074 | [] | no_license | david-guerrero/MITK | e9832b830cbcdd94030d2969aaed45da841ffc8c | e5fbc9993f7a7032fc936f29bc59ca296b4945ce | refs/heads/master | 2020-04-24T19:08:37.405353 | 2011-11-13T22:25:21 | 2011-11-13T22:25:21 | 2,372,730 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,389 | h | berryWorkbenchPageTweaklet.h | /*=========================================================================
Program: BlueBerry Platform
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef BERRYWORKBENCHPAGETWEAKLET_H_
#define BERRYWORKBENCHPAGETWEAKLET_H_
#include "../internal/berryTweaklets.h"
#include "../berryIWorkbenchPage.h"
namespace berry
{
struct BERRY_UI WorkbenchPageTweaklet
{
static Tweaklets::TweakKey<WorkbenchPageTweaklet> KEY;
virtual void* CreateClientComposite(void* pageControl) = 0;
virtual void* CreatePaneControl(void* parent) = 0;
virtual Object::Pointer CreateStatusPart(void* parent, const std::string& title, const std::string& msg) = 0;
virtual IEditorPart::Pointer CreateErrorEditorPart(const std::string& partName, const std::string& msg) = 0;
};
}
Q_DECLARE_INTERFACE(berry::WorkbenchPageTweaklet, "org.blueberry.WorkbenchPageTweaklet")
#endif /* BERRYWORKBENCHPAGETWEAKLET_H_ */
|
2ad825f1bbc7d5776632b996fb83ad1ee6e2d23c | 1e785b0c901087910c07b64b5161984863c4887c | /MCAD/include/MdCmds.h | b5ea6b506ac6b678aa0309b9e4ff2fea75e691da | [] | no_license | pinery2004/mcad01s | 487eee3e27945d83540a0548777ca6f58d1ff33d | 1b01c200aefc8cd89c958bd42df3900250c6827d | refs/heads/master | 2022-07-18T23:49:10.011615 | 2020-05-20T03:38:59 | 2020-05-20T03:39:13 | 265,440,358 | 0 | 1 | null | null | null | null | ISO-8859-1 | C++ | false | false | 16,931 | h | MdCmds.h | /* F:\BLD\PRJ\LIB\CMDS\CMDS.H
* Copyright (C) 1997-1998 Visio Corporation. All rights reserved.
*
* Abstract
*
* <TODO : Add Abstract here>
*
*/
#pragma once
#include "MCad.h"
#include <time.h>
#include <limits.h>
#ifdef DLL_EXPORT_CMDS
#undef DLL_EXPORT_CMDS
#endif
#ifdef DLL_EXPORT_CMDS_DO
#pragma message( "<<< MdCmdsEdll_EXport >>>")
#define DLL_EXPORT_CMDS __declspec( dllexport)
#else
#ifdef DLL_NO_IMPORT_SUB_DO
#define DLL_EXPORT_CMDS
#else
// #pragma message( "=== MdCmdsEdll_IMport ===")
#define DLL_EXPORT_CMDS __declspec( dllimport)
#endif
#endif
#define IC_MCADBUF 256
//********************************************************************************
// These are the defines for our prompts to the user when **
// something they are trying to do won't work. **
// They are used with cmd_ErrorPrompt in cmds11.cpp **
// Look there for a sensible grouping, and to see what they do. **
//********************************************************************************
#define CMD_ERR_YESNO 700
#define CMD_ERR_TRYAGAIN 701
#define CMD_ERR_NOENT 702
#define CMD_ERR_NOCONTINUE 703
#define CMD_ERR_NOUNERASE 704
#define CMD_ERR_NOUNDO 705
#define CMD_ERR_NOMOREUNDO 706
#define CMD_ERR_ENTTYPE 707
#define CMD_ERR_SELECTION 708
#define CMD_ERR_LINEAR 709
#define CMD_ERR_LINE 710
#define CMD_ERR_POLYLINE 711
#define CMD_ERR_2DPOLYLINE 712
#define CMD_ERR_ARC 713
#define CMD_ERR_CIRCLE 714
#define CMD_ERR_COLORS 715
#define CMD_ERR_POLYSIDES 716
#define CMD_ERR_DIVSEGS 717
#define CMD_ERR_SEGSKWORD 718
#define CMD_ERR_NUMERIC 719
#define CMD_ERR_NONZERO 720
#define CMD_ERR_POSITIVE 721
#define CMD_ERR_POSNOZERO 722
#define CMD_ERR_KWORD 723
#define CMD_ERR_PT 724
#define CMD_ERR_PTKWORD 725
#define CMD_ERR_2DPT 726
#define CMD_ERR_2DPTKWORD 727
#define CMD_ERR_ANG2NDPT 728
#define CMD_ERR_ANG2NDPTKWORD 729
#define CMD_ERR_ANG2PTS 730
#define CMD_ERR_DIST 731
#define CMD_ERR_DIST2PTS 732
#define CMD_ERR_DIST2PTSKWORD 733
#define CMD_ERR_DIST2NDPT 734
#define CMD_ERR_DIST2NDPTKWORD 735
#define CMD_ERR_RADDCIRC 736
#define CMD_ERR_TEXTNAME 737
#define CMD_ERR_BLOCKNAME 738
#define CMD_ERR_FINDBLOCK 739
#define CMD_ERR_LTYPENAME 740
#define CMD_ERR_FINDLTYPE 741
#define CMD_ERR_FINDLAYER 742
#define CMD_ERR_NULLTAG 743
#define CMD_ERR_ELEVDIFFZ 744
#define CMD_ERR_OBLIQUELG 745
#define CMD_ERR_CANTCLOSE 746
#define CMD_ERR_NOCIRCLE 747
#define CMD_ERR_BADDATA 748
#define CMD_ERR_REMOVEEED 749
#define CMD_ERR_UPDATEENT 750
#define CMD_ERR_CREATEENT 751
#define CMD_ERR_CREATEATTDEF 752
#define CMD_ERR_CREATETEXT 753
#define CMD_ERR_CREATEDONUT 754
#define CMD_ERR_MOREMEM 756
#define CMD_ERR_FINDUCS 757
#define CMD_ERR_DASHDOT 758
#define CMD_ERR_LTYPEPAT 759
#define CMD_ERR_NOSAVEDVIEWS 760
#define CMD_ERR_NAMETOOLONG 761
#define CMD_ERR_NOPAPERVIEW 762
#define CMD_ERR_COLOR1255 763
#define CMD_ERR_COLOR0255 764
#define CMD_ERR_COLOR1256 765
#define CMD_ERR_COLOR0256 766
#define CMD_ERR_SNAPTARGET 767
#define CMD_ERR_CHAMNONPOLY 768
#define CMD_ERR_CHAM3DPOLY 769
#define CMD_ERR_CHAMDIFFPOLY 770
#define CMD_ERR_CHAMNONLINEAR 771
#define CMD_ERR_CHAMNOLENGTH 772
#define CMD_ERR_CHAMPARALLEL 773
#define CMD_ERR_CHAM2LINEAR 774
#define CMD_ERR_FILPOLYSEGS 775
#define CMD_ERR_FILNOTPOSS 776
#define CMD_ERR_FILCLOSEFAR 777
#define CMD_ERR_FILTOOCLOSE 778
#define CMD_ERR_FILNOLENGTH 779
#define CMD_ERR_FILRADIUSLG 780
#define CMD_ERR_NOINTERSECT 781
#define CMD_ERR_BREAKENT 782
#define CMD_ERR_BREAKBLOCK 783
#define CMD_ERR_MODENT 784
#define CMD_ERR_CANTGETDATA 785
#define CMD_ERR_CREATELINE 786
#define CMD_ERR_BREAKDISTINCT 787
#define CMD_ERR_CHAMDISTLG1 788
#define CMD_ERR_CHAMANGLE 789
#define CMD_ERR_EXTENDENT 790
#define CMD_ERR_CLOSEARC 791
#define CMD_ERR_UNRECOGSNAP 792
#define CMD_ERR_UNRECOGVAR 793
#define CMD_ERR_NUMRANGE 794
#define CMD_ERR_FILDIFFPOLY 795
#define CMD_ERR_GPS 796
#define CMD_ERR_FINDHELP 797
#define CMD_ERR_FINDTEXT 798
#define CMD_ERR_GETDWGNAME 799
#define CMD_ERR_OPENDWG 800
#define CMD_ERR_UNRECOGCMD 801
#define CMD_ERR_NODYNZOOM 802
#define CMD_ERR_DEFBLOCK 803
#define CMD_ERR_BUILDENT 804
#define CMD_ERR_CANTRENAME 805
#define CMD_ERR_RESERVEDBLOCK 806
#define CMD_ERR_NOMODELVIEW 807
#define CMD_ERR_UNITTYPE 808
#define CMD_ERR_DECIMALS 809
#define CMD_ERR_DENOMINATOR 810
#define CMD_ERR_NOTATABLET 811
#define CMD_ERR_OPENGLCHOOSE 812
#define CMD_ERR_OPENGLSET 813
#define CMD_ERR_UNTERMINATED 814
#define CMD_ERR_NUMTWO2DPT 815
#define CMD_ERR_LOADDIALOG 816
#define CMD_ERR_HATCHEXPPREV 817
#define CMD_ERR_NOPATTERNS 818
#define CMD_ERR_FINDPATTERN 819
#define CMD_ERR_MIXCLOSEOPEN 820
#define CMD_ERR_2PTSURFACE 821
#define CMD_ERR_NOUCSDEFS 822
#define CMD_ERR_DELETEUCS 823
#define CMD_ERR_SAVEUCS 824
#define CMD_ERR_FINDSNAP 825
#define CMD_ERR_DIFFPTS 826
#define CMD_ERR_NOPLANES 827
#define CMD_ERR_ONSAMELINE 828
#define CMD_ERR_MESHSIZE 829
#define CMD_ERR_OFFSMALLRAD 830
#define CMD_ERR_OFFZEROLEN 831
#define CMD_ERR_PEDITPFACE 832
#define CMD_ERR_CLOSEDPLINE 833
#define CMD_ERR_CLOSEDMPLINE 834
#define CMD_ERR_CLOSEDNPLINE 835
#define CMD_ERR_NOTCLOSEDPLINE 836
// #define CMD_ERR_NOTCLOSEDMPLINE NOT USED
#define CMD_ERR_NOTCLOSEDNPLINE 837
#define CMD_ERR_JOINCLOSEDPLINE 838
// #define CMD_ERR_BEGOFPLINE NOT USED
// #define CMD_ERR_ENDOFPLINE NOT USED
#define CMD_ERR_BREAKDELETE 841
#define CMD_ERR_COINCVERPTS 842
// #define CMD_ERR_COINCENDPTS 843 Not used yet, but Rick suggested that I will need it
#define CMD_ERR_LENGTHENENT 843
#define CMD_ERR_LENCLOSEPOLY 844
#define CMD_ERR_LENBYANG 845
#define CMD_ERR_LENBYDIST 846
#define CMD_ERR_LENBYDYNPT 847
#define CMD_ERR_ARCSIZE 848
#define CMD_ERR_BADENTNAME 849
#define CMD_ERR_NOREDO 850
#define CMD_ERR_PARALLEL 851
#define CMD_ERR_LINORDANG 852
#define CMD_ERR_ARCCIRCLE 853
#define CMD_ERR_LINEARCCIRCLE 854
#define CMD_ERR_DIMENSION 855
#define CMD_ERR_UNABLE 856 // Used
#define CMD_ERR_NODIMSTYLES 857
#define CMD_ERR_DISPDIMVARS 858
#define CMD_ERR_LINEARCCIRPLY 859
#define CMD_ERR_FITCURVE 860
#define CMD_ERR_FINDVIEW 861
//#define CMD_ERR_RADDONUT 862 **NOT USED
#define CMD_ERR_NODWGWINDOW 863
#define CMD_ERR_CHAMPOLYARC 864
#define CMD_ERR_BULGESIZE 865
#define CMD_ERR_INSERTDEF 866
#define CMD_ERR_FINDDIMSTYLE 867
#define CMD_ERR_NOQUICKSNAP 868
#define CMD_ERR_CHAMFERPLADJ 869
#define CMD_ERR_NONCOINCENDPTS 870
#define CMD_ERR_TOOMUCHDATA 871
#define CMD_ERR_FINDCONVFACT 872
#define CMD_ERR_NOPREVZOOM 873
#define CMD_ERR_UNRECOGMENU 874
#define CMD_ERR_GRIDTOOSMALL 875
#define CMD_ERR_GRIDTOOLARGE 876
#define CMD_ERR_POSORZERO 877
#define CMD_ERR_UNRECOGENTRY 878
#define CMD_ERR_PTOUTSIDELIMITS 879
#define CMD_ERR_NODESTROY 880
#define CMD_ERR_CHAMTOOCLOSE 881
#define CMD_ERR_NOEFFECT 882
#define CMD_ERR_TILEMODE0 883
#define CMD_ERR_TILEMODE1 884
#define CMD_ERR_BDRYSET 885
#define CMD_ERR_MESH3D 886
#define CMD_ERR_NOXREFFOUND 887
#define CMD_ERR_COPLANAR 888
#define CMD_ERR_DUPENTITY 889
#define CMD_ERR_OSNAPENT 890
#define CMD_ERR_NOEXTDWGS 891
#define CMD_ERR_INT0TO16 892
#define CMD_ERR_NOATTRIBS 893
#define CMD_ERR_XREFEXIST 894
#define CMD_ERR_NOTINUCS 895
#define CMD_ERR_FINDFILE 896
#define CMD_ERR_GOTFILE 897
#define CMD_ERR_BLKREF 898
#define CMD_ERR_XREFREF 899
#define CMD_ERR_ATTRIBUTE 900
#define CMD_ERR_CHAMDISTLG2 901
#define CMD_ERR_CHAMDISTLG3 902
#define CMD_ERR_DUPFILE 903
#define CMD_ERR_ZOOMIN 904
#define CMD_ERR_ZOOMOUT 905
#define CMD_ERR_UNSUPPORTED 906
#define CMD_ERR_SYSVARVAL 907
#define CMD_ERR_FILLETPLINE 908
#define CMD_ERR_FILLETCAP 909
#define CMD_ERR_NOTBFOUND 911
#define CMD_ERR_NOVIEWPORTS 912
#define CMD_ERR_XPLODXREF 913
#define CMD_ERR_ANYNAME 914
#define CMD_ERR_DWGHASIMAGE 915
#define CMD_ERR_DWGHASACIS 916
#define CMD_ERR_DWGHASHATCH 917
#define CMD_ERR_DWGHASPROXY 918
#define CMD_ERR_BADGEOMETRY 919
#define CMD_ERR_NOTINPSPACE 920
#define CMD_ERR_NOTHINGTODO 921
#define CMD_ERR_FINDSTYLE 922
#define CMD_ERR_NOTRANSPARENT 923
#define CMD_ERR_PLINESEGS 924
#define CMD_ERR_NOSELECT 925
#define CMD_ERR_BLKNAMETOOLONG 926
#define CMD_ERR_SURFTABS 927
#define CMD_ERR_FINDFILE2 928
#define CMD_ERR_HATCHBDRY 929
#define CMD_ERR_LAYERNAME 930
#define CMD_ERR_ANGLE 931
#define CMD_ERR_SPHEREDIVS 932
#define CMD_ERR_OFFSHARPCURVE 933
#define CMD_ERR_DONTUSEEND 934
#define CMD_ERR_OPTIONNOTSUP 935
#define CMD_ERR_ZOOMPERCENT 936
#define CMD_ERR_TRIMENT 937
#define CMD_ERR_NOVPCONFIG 938
#define CMD_ERR_XRCURLAY 939
#define CMD_ERR_NOFROZEN 940
#define CMD_ERR_NOLASTAXIS 941
#define CMD_ERR_ANGLEPI 942
#define CMD_ERR_INSERTACIS 943
#define CMD_ERR_INSERTPROXY 944
#define CMD_ERR_FINDXREF 945
#define CMD_ERR_OPENXREF 946
#define CMD_ERR_LOADXREF 947
#define CMD_ERR_INSERTXREF 948
#define CMD_ERR_INSERTHATCH 949
#define CMD_ERR_INSERTIMAGE 950
#define CMD_ERR_PASTEACIS 951
#define CMD_ERR_PASTEPROXY 952
#define CMD_ERR_PASTEHATCH 953
#define CMD_ERR_PASTEIMAGE 954
#define CMD_ERR_PERSPECTIVE 955
#define CMD_ERR_UNDODISABLE 956
#define CMD_ERR_BADARGUMENT 957
#define CMD_ERR_MAXACTVP 958
#define CMD_ERR_BADRENDER 959
#define CMD_ERR_NOCHANGEABLE 960
#define CMD_ERR_SAVEFILE 961
#define CMD_ERR_CANTDEFUCS 962
#define CMD_ERR_NOACTIVEVP 963
#define CMD_ERR_SHADEPERSP 964 //temporary error stmt for shade
#define CMD_ERR_HIDEPERSP 965 //temporary error stmt for hide
#define CMD_ERR_EMPTYDWG 966
#define CMD_ERR_DXFNEWONLY 967
#define CMD_ERR_UNUSEDVARS 968
#define CMD_ERR_EXPORTFILE 969
#define CMD_ERR_INTRANGE 970
#define CMD_ERR_WBLOCKACIS 971
#define CMD_ERR_WBLOCKPROXY 972
#define CMD_ERR_WBLOCKHATCH 973
#define CMD_ERR_WBLOCKIMAGE 974
#define CMD_ERR_INVALIDDLL 975
#define CMD_ERR_SYSNOMEM 976
#define CMD_ERR_ACCESS_DENIED 977
#define CMD_ERR_OUTOFMEMORY 978
#define CMD_ERR_NOT_READY 979
#define CMD_ERR_PROC_NOTFOUND 980
#define CMD_ERR_DLLNOTFOUND 981
#define CMD_ERR_DLLLOADPROB 982
#define CMD_ERR_CANTFINDAPP 983
#define CMD_ERR_UNLOADING 985
#define CMD_ERR_BADENTPOINT 986
#define CMD_ERR_FINDUNLOAD 987
#define CMD_ERR_ENTSINSET 988
#define CMD_ERR_CANTFINDFILE 989
#define CMD_ERR_CANTOPENFILE 990
#define CMD_ERR_CANTLOADREN 991
#define CMD_ERR_FLATTENED 992
#define CMD_ERR_NOTPARALLEL 993
#define CMD_ERR_CANTFINDMENU 994
#define CMD_ERR_CANTFINDDWG 995
#define CMD_ERR_PLEASESPEC 996
#define CMD_ERR_BADVPORTNUM 997
#define CMD_ERR_GETOPENFILE 998
#define CMD_ERR_CANTOPENDWG 999
#define CMD_ERR_REBUILDTABLE 1000
#define CMD_ERR_BUILDTABLE 1001
#define CMD_ERR_CREATEBLOCK 1002
#define CMD_ERR_NOTABLEITEM 1003
#define CMD_ERR_ALREADYEXISTS 1004
#define CMD_ERR_WASRENAMEDAS 1005
#define CMD_ERR_EXPLODEACIS 1006
#define CMD_ERR_UNSUPPORTEDA2KENT 1007
#define CMD_ERR_DIMBLKDOESNOTEXIST 1008
#define CMD_ERR_DIMBLK1DOESNOTEXIST 1009
#define CMD_ERR_DIMBLK2DOESNOTEXIST 1010
namespace MC
{
DLL_EXPORT_CMDS void MdCmdErrorPrompt( int ErrNo, short DispMode, void *arg1=NULL, void *arg2=NULL, void *arg3=NULL);
// ResourceString -- class for loading resource strings
// WARNING - NOT MByte Enabled - use a BSTR..
// and don't create static string in production (resource only)
#ifdef NDEBUG
#define _ResourceString(id,string) (__ResourceString(id,NULL))
#else
#define _ResourceString(id,string) (__ResourceString(id,string))
#endif
#define ResourceString(id,string) ((LPCTSTR)_ResourceString(id,_T(string)))
class DLL_EXPORT_CMDS __ResourceString
{
public:
__ResourceString( int resourceID, LPCTSTR t);
~__ResourceString();
operator LPCTSTR();
protected:
LPCTSTR m_loaded;
LPCTSTR m_string;
int m_id;
TCHAR m_buffer[32];
};
/*D.Gavrilov*/// The following macros are used for loading and concatenating
// resource strings which are the parts of a one string. It's for localising
// (Loc@le cannot process strings longer than 255 symbols).
#define LOADSTRINGS_2(id) CString s_part1, s_part2, s_all; \
s_part1.LoadString(id##__part1); \
s_part2.LoadString(id##__part2); \
s_all = s_part1 + s_part2;
#define LOADSTRINGS_3(id) CString s_part1, s_part2, s_part3, s_all; \
s_part1.LoadString(id##__part1); \
s_part2.LoadString(id##__part2); \
s_part3.LoadString(id##__part3); \
s_all = s_part1 + s_part2 + s_part3;
#define LOADSTRINGS_4(id) CString s_part1, s_part2, s_part3, s_part4, s_all; \
s_part1.LoadString(id##__part1); \
s_part2.LoadString(id##__part2); \
s_part3.LoadString(id##__part3); \
s_part4.LoadString(id##__part4); \
s_all = s_part1 + s_part2 + s_part3 + s_part4;
#define LOADSTRINGS_5(id) CString s_part1, s_part2, s_part3, s_part4, s_part5, s_all; \
s_part1.LoadString(id##__part1); \
s_part2.LoadString(id##__part2); \
s_part3.LoadString(id##__part3); \
s_part4.LoadString(id##__part4); \
s_part5.LoadString(id##__part5); \
s_all = s_part1 + s_part2 + s_part3 + s_part4 + s_part5;
#define LOAD_COMMAND_OPTIONS_2(id) CString s_part1, s_part2, s_all; \
s_part1.LoadString(id##__part1); \
s_part2.LoadString(id##__part2); \
s_all = s_part1 + " " + s_part2;
#define LOAD_COMMAND_OPTIONS_3(id) CString s_part1, s_part2, s_part3, s_all; \
s_part1.LoadString(id##__part1); \
s_part2.LoadString(id##__part2); \
s_part3.LoadString(id##__part3); \
s_all = s_part1 + " " + s_part2 + " " + s_part3;
#define LOAD_COMMAND_OPTIONS_4(id) CString s_part1, s_part2, s_part3, s_part4, s_all; \
s_part1.LoadString(id##__part1); \
s_part2.LoadString(id##__part2); \
s_part3.LoadString(id##__part3); \
s_part4.LoadString(id##__part4); \
s_all = s_part1 + " " + s_part2 + " " + s_part3 + " " + s_part4;
#define LOAD_COMMAND_OPTIONS_5(id) CString s_part1, s_part2, s_part3, s_part4, s_part5, s_all; \
s_part1.LoadString(id##__part1); \
s_part2.LoadString(id##__part2); \
s_part3.LoadString(id##__part3); \
s_part4.LoadString(id##__part4); \
s_part5.LoadString(id##__part5); \
s_all = s_part1 + " " + s_part2 + " " + s_part3 + " " + s_part4 + " " + s_part5;
// ***********************************************************
// lb`cÌÀsW
[ÆckkŤL
//
///////////////////
// è
#define RTNORM 0
#define RTERROR -5001
class DLL_EXPORT_CMDS ProgressMeter
{
public:
virtual void Start()=0;
virtual void Stop()=0;
virtual void Percent( int percentDone)=0;
};
DLL_EXPORT_CMDS void SetAdviseProgressMeter( ProgressMeter *pMeter );
DLL_EXPORT_CMDS int db_progresspercent(int percentDone);
DLL_EXPORT_CMDS int db_progressstart();
DLL_EXPORT_CMDS int db_progressstop();
//
//// date conversion
//DLL_EXPORT_CMDS void db_jul2greg(double dJul,short *pYear,short *pMonth,short *pDay,short *pDow,short *pHour,short *pMin,double *pSec);
// ***********************************************************
// lb`cÌÀsW
[ÆckkŤL
//
class DLL_EXPORT_CMDS MCadSharedGlobals
{
public:
static void SetMCadAppInstance( HINSTANCE hInstance );
static HINSTANCE GetMCadAppInstance( void );
static void SetMCadResourceInstance( HINSTANCE hInstance );
static HINSTANCE GetMCadResourceInstance( void );
static void SetCmdMessage(int (*pfunct)(const char *,...));
static void CallCmdMessage(const char *); // message printed on command line
private:
static HINSTANCE zm_hAppInstance;
static HINSTANCE zm_hResourceInstance;
static int (*m_pMessageFunct) (const char*,...);
private:
public:
MCadSharedGlobals();
~MCadSharedGlobals();
};
} // namespace MC |
f148c75b2ef80a86811e6d5fa64f67483f6991f3 | a2c3028bbb015596e6d1b83fe23bd4c9fda0d72d | /info/wip/in-process/src/apk/htxn/ngml/rz-ngml/kernel/document/rz-ngml-document.cpp | 871c01eaa58dcfce6b6b32cc571af6ebb24919b2 | [] | no_license | scignscape/ntxh | 1c025b0571ecde6b25062c4013bf8a47aeb7fdcb | ee9576360c1962afb742830828670aca5fa153d6 | refs/heads/master | 2023-04-01T07:20:26.138527 | 2021-03-17T17:59:48 | 2021-03-17T17:59:48 | 225,418,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,492 | cpp | rz-ngml-document.cpp |
// Copyright Nathaniel Christen 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)
#include "rz-ngml-document.h"
#include "relae-graph/relae-parser.templates.h"
#include "rzns.h"
#include "kernel/grammar/rz-ngml-grammar.h"
#include "kernel/rz-ngml-root.h"
#include "kernel/graph/rz-ngml-node.h"
#include "kernel/graph/rz-ngml-graph.h"
#include "kernel/grammar/rz-ngml-parser.h"
#include "kernel/grammar/rz-ngml-graph-build.h"
#include "tile/rz-ngml-tile.h"
#include "annotation/rz-ngml-annotation-tile.h"
#include "tag-command/rz-ngml-tag-command.h"
#include <QFileInfo>
#include <QtAlgorithms>
#include "rzns.h"
USING_RZNS(NGML)
NGML_Document::NGML_Document()
: parsing_mode_(NGML_Parsing_Modes::NGML),
graph_(nullptr), grammar_(nullptr), annotations_(nullptr)
{
}
void NGML_Document::write_annotations(QString path, QMap<QString, caon_ptr<NGML_Annotation_Tile>>& annotations)
{
qDebug() << "Writing to path: " << path;
QString contents;
contents = "<html><body><table>";
QStringList qsl = annotations.keys();
for(QString& qs : qsl)
{
if(qs.startsWith("*:"))
qs = qs.mid(2);
}
qSort(qsl.begin(), qsl.end());
for(QString qs : qsl)
{
QString key = qs.simplified();
caon_ptr<NGML_Annotation_Tile> tile = annotations[qs];
QString value = tile->tile().simplified();
contents += QString("\n<tr><td class='annotation-key'>%1</td>"
"<td class='annotation-value'>%2</td></tr>").arg(key).arg(value);
}
contents += "\n</table></body></html>";
save_file(path, contents);
}
void NGML_Document::write_local_annotations(QString path)
{
QString contents;
QMapIterator<QString, caon_ptr<NGML_Annotation_Tile> >
it(local_annotations_);
contents = "<html><body><table>";
while(it.hasNext())
{
it.next();
QString key = it.key().simplified();
caon_ptr<NGML_Annotation_Tile> tile = it.value();
QString value = tile->tile().simplified();
if(!value.isEmpty())
{
value.replace(0, 1, value[0].toUpper());
}
if(key.startsWith("*:"))
{
key = key.mid(2);
}
contents += QString("\n<tr><td>%1</td><td>%2</td></tr>").arg(key).arg(value);
}
contents += "\n</table></body></html>";
save_file(path, contents);
}
QString NGML_Document::escape_unicode(QString contents)
{
QString result;
QString isAcsii;
QString tmp;
for(QChar cr : contents)
{
int uni = cr.unicode();
if(uni > 128)
{
tmp.setNum(uni);
tmp.prepend("\\u");
result += tmp;
}
else if(cr.toLatin1() != QChar(0))
{
isAcsii = static_cast<QString>(cr.toLatin1());
result += isAcsii;
}
else
{
tmp.setNum(cr.unicode());
tmp.prepend("\\u");
result += tmp;
}
}
return result;
}
void NGML_Document::use_light_xml()
{
document_info_.init_light_xml();
}
void NGML_Document::tag_command_annotation(caon_ptr<NGML_Tile> nt, caon_ptr<NGML_Annotation_Tile> tile)
{
QString key = nt->raw_text();
if(annotations_)
{
if(!annotations_->contains(key))
{
annotations_->insert(key, tile);
}
}
if(!local_annotations_.contains(key))
{
local_annotations_.insert(key, tile);
}
}
void NGML_Document::tag_command_annotation(caon_ptr<NGML_Annotation_Tile> tile)
{
QString key = tile->subject();
if(annotations_)
{
if(!annotations_->contains(key))
{
annotations_->insert(key, tile);
}
}
if(!local_annotations_.contains(key))
{
local_annotations_.insert(key, tile);
}
}
QString NGML_Document::save_hrefs()
{
QString path = local_path_;
path += ".hrefs";
document_info_.save_hrefs(path);
return path;
}
QString NGML_Document::save_quotes()
{
QString path = local_path_;
path += ".quotes";
document_info_.save_quotes(path);
return path;
}
QString NGML_Document::file_name()
{
QFileInfo qfi(local_path_);
return qfi.baseName();
}
QString NGML_Document::save_light_xml()
{
if(document_info_.light_xml())
{
QString path = local_path_;
path += ".light.xml";
document_info_.save_light_xml(path);
return path;
}
else
{
return QString();
}
}
QString NGML_Document::save_word_count()
{
QString path = local_path_;
path += ".count";
document_info_.save_word_count(path);
return path;
}
QString NGML_Document::save_word_stream()
{
QString path = local_path_;
path += ".stream";
document_info_.save_word_stream(path);
return path;
}
void NGML_Document::save_file(QString path, QString contents)
{
QFile file(path);
if(file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QTextStream out(&file);
out << contents;
}
}
void NGML_Document::load_file(QString path)
{
QFile file(path);
if(file.open(QFile::ReadOnly | QIODevice::Text))
{
raw_text_ = file.readAll();
local_path_ = path;
}
}
void NGML_Document::set_grammar(caon_ptr<NGML_Grammar> grammar)
{
if(grammar)
grammar_ = grammar;
else
grammar_ = caon_ptr<NGML_Grammar>( new NGML_Grammar() );
}
void NGML_Document::parse()
{
caon_ptr<NGML_Root> root = caon_ptr<NGML_Root>( new NGML_Root() );
caon_ptr<NGML_Node> node = caon_ptr<NGML_Node>( new NGML_Node(root) );
graph_ = caon_ptr<NGML_Graph> ( new NGML_Graph(node) );
parser_ = caon_ptr<NGML_Parser> ( new NGML_Parser(graph_) );
graph_build_ = caon_ptr<NGML_Graph_Build>(
new NGML_Graph_Build(*graph_, document_info_) );
graph_build_->init();
graph_build_->set_current_parsing_mode(parsing_mode_);
grammar_->init(*parser_, *graph_, *graph_build_);
grammar_->compile(*parser_, *graph_, raw_text_);
}
void NGML_Document::check_sdi_tag_command_info()
{
if(sdi_tag_command_info_path_.isEmpty())
{
NGML_Tag_Command::set_needs_sdi_mark_check([](QString name) -> bool
{
static QStringList qsl {
"cq-", "dq-", "qq-", "sq-"
};
for(const QString& qs : qsl)
{
if(name.startsWith(qs))
return true;
}
return false;
});
}
}
void NGML_Document::load_and_parse(QString path, caon_ptr<NGML_Grammar> grammar)
{
check_sdi_tag_command_info();
load_file(path);
set_grammar(grammar);
parse();
}
NGML_Document::~NGML_Document()
{
}
// // Quick cleanup of HTML documents being converted to XML
// -- not very reliable.
void NGML_Document::clean_html(QString& str)
{
QRegularExpression script_rx("<script.*?</script>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(script_rx, "");
QRegularExpression script_rx_remaining("<script.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(script_rx_remaining, "");
QRegularExpression link_rx("<link.*?</link>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(link_rx, "");
QRegularExpression link_rx_remaining("<link.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(link_rx_remaining, "");
QRegularExpression style_rx("<style.*?</style>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(style_rx, "");
QRegularExpression style_rx_remaining("<style.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(style_rx_remaining, "");
QRegularExpression button_rx("<button.*?</button>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(button_rx, "");
QRegularExpression button_rx_remaining("<button.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(button_rx_remaining, "");
QRegularExpression iframe_rx("<iframe.*?</iframe>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(iframe_rx, "");
QRegularExpression iframe_rx_remaining("<iframe.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(iframe_rx_remaining, "");
QRegularExpression form_rx("<form.*?</form>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(form_rx, "");
QRegularExpression form_rx_remaining("<form.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(form_rx_remaining, "");
QRegularExpression meta_rx("<meta.*?</meta>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(meta_rx, "");
QRegularExpression meta_rx_remaining("<meta.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(meta_rx_remaining, "");
QRegularExpression img_rx("<img.*?</img>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(img_rx, "");
QRegularExpression img_rx_remaining("<img.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(img_rx_remaining, "");
QRegularExpression video_rx("<video.*?</video>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(video_rx, "");
QRegularExpression video_rx_remaining("<video.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(video_rx_remaining, "");
QRegularExpression object_rx("<object.*?</object>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(object_rx, "");
QRegularExpression object_rx_remaining("<object.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(object_rx_remaining, "");
QRegularExpression param_rx("<param.*?</param>",
QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(param_rx, "");
QRegularExpression param_rx_remaining("<param.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(param_rx_remaining, "");
QRegularExpression base_rx("<base.*?</base>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(base_rx, "");
QRegularExpression base_rx_remaining("<base.*?/?>", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(base_rx_remaining, "");
QRegularExpression comment_rx("<!--.*?-->", QRegularExpression::DotMatchesEverythingOption | QRegularExpression::CaseInsensitiveOption);
str.replace(comment_rx, "");
str.replace(QRegularExpression("<![^>]+>"), "");
str.replace("<br>", "");
str.replace("<hr>", "");
str.replace(QRegularExpression("\\n\\s*\\n"), "\n");
str.replace(QRegularExpression("<html[^>]+>"), "<html>" );
str.replace("–", "–");
str.replace("—", "—");
str.replace("‘", "‘");
str.replace("’", "’");
str.replace("“", "“");
str.replace("”", "”");
str.replace(" ", "");
QRegularExpression eos_word_rx("([\\\\a-z]{2,}\\.(?=\\s))");
str.replace(eos_word_rx, "\\1 ");
QRegularExpression eos_caps_word_rx("([\\\\A-Z]{2,}\\.(?=\\s))");
str.replace(eos_caps_word_rx, "\\1 ");
str.replace(" ", " ");
str.replace(QRegularExpression("=\"([^\"]+)=\""), "=\"\\1$EQ$\"");
}
|
892da6e341874d72c6a569d51d7693f59885dc89 | 0d1acf76962a679f041277596c720675e774be54 | /FGameEngine/FGameEngine/Material.cpp | b6dd01bacb8b6b7adf100efd7aa94d5361e7bf88 | [] | no_license | changefc/FGameEngine | b50deb222ca3d2d0352b13d6aa1612b00da2a4a8 | 8d3905bc7ee1234bce6b79084a482a1e1b93373b | refs/heads/master | 2020-04-20T05:44:42.429254 | 2019-02-15T13:57:43 | 2019-02-15T13:57:43 | 168,663,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 305 | cpp | Material.cpp | #include "stdafx.h"
#include "Material.h"
Material::Material(Shader* _shader, glm::vec3 _ambient, unsigned int _diffuse, unsigned int _specular, float _shininess)
{
shader = _shader;
ambient = _ambient;
diffuse = _diffuse;
specular = _specular;
shininess = _shininess;
}
Material::~Material()
{
}
|
a44f861c13575035196a7b8284978411c315da46 | 73ad00c1eb3c6931a306500015f46a60b09a230e | /Twar/Twar/SubScene/Battle/Effect/Effect.cpp | 43bf0ab52231a2036c410509f56ca8eb67eaec37 | [] | no_license | human-osaka-game-2016/T-SEN | a74d11b73b668d498183f2c93d35bc4458369f3a | 11e750dd5883b137ea256d2f512d2a7ee1780472 | refs/heads/master | 2021-06-20T08:51:50.327183 | 2017-07-03T00:59:54 | 2017-07-03T00:59:54 | 69,837,692 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,089 | cpp | Effect.cpp | /**
* @file Effect.cpp
* @brief Effectクラス実装
* @author haga
*/
//-------------------------------------------------------------------------------------------------------------------------------------//
//Includes
//-------------------------------------------------------------------------------------------------------------------------------------//
#include "GameLib/GameLib.h"
#include "Effect.h"
//-------------------------------------------------------------------------------------------------------------------------------------//
//Public functions
//-------------------------------------------------------------------------------------------------------------------------------------//
Effect::Effect(D3DXVECTOR3 pos, int texID, int vtxID)
: m_Pos(pos)
, m_TexID(texID)
, m_VtxID(vtxID)
, m_AnimeTimeCount(0)
, m_AnimePatternCount(0)
, m_IsEnd(false)
{
}
Effect::~Effect()
{
}
//--------------------------------------------------------------------------------------------------------------------------------------//
//Protected functions
//--------------------------------------------------------------------------------------------------------------------------------------//
// 座標を3D空間に変換する関数
void Effect::Transform3D()
{
D3DXMATRIX matPosition; // 位置座標行列
D3DXMatrixIdentity(&m_MatWorld);
D3DXMatrixTranslation(&matPosition, m_Pos.x, m_Pos.y, m_Pos.z);
TransformBillboard(); // ビルボード変換
D3DXMatrixMultiply(&m_MatWorld, &m_MatWorld, &matPosition);
GameLib::Instance().GetDevice()->SetTransform(D3DTS_WORLD, &m_MatWorld);
}
// ビルボード処理を行う関数
void Effect::TransformBillboard()
{
D3DXMATRIX matCuurentView; // 現在のビュー行列を格納する変数
GameLib::Instance().GetDevice()->GetTransform(D3DTS_VIEW, &matCuurentView);
D3DXMatrixInverse(&matCuurentView, NULL, &matCuurentView); // 逆行列作成
matCuurentView._41 = 0.0f;
matCuurentView._42 = 0.0f;
matCuurentView._43 = 0.0f;
D3DXMatrixMultiply(&m_MatWorld, &m_MatWorld, &matCuurentView);
}
|
219deabd8b42f7fbf8b484a6e85ac22b8256ef6e | 1eddfc58034e70dbf32c93c5ecdfc47e377eca84 | /boredom.cpp | 9e558982b4a62048359d275237c8ce44474314a9 | [] | no_license | Rodagui/CodeForces-Solutions | ec90ad3806ca6025c9f588eb298b33a47f097bd4 | fbcce297deb645ea8f6d7a30297071a12e447489 | refs/heads/master | 2022-07-27T21:36:20.656936 | 2022-07-15T00:54:17 | 2022-07-15T00:54:17 | 178,289,421 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 737 | cpp | boredom.cpp | /*A. Boredom*/
#include <bits/stdc++.h>
using namespace std;
using Long = long long;
vector <Long> freq(100005, 0);
vector <Long> memo(100005, -1);
Long maxPoints(Long i);
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
Long maximo = 0;
Long tam;
Long f;
cin >> tam;
for (int i = 0; i < tam; ++i)
{
cin >> f;
if(f > maximo)
maximo = f;
freq[f]++;
}
cout << maxPoints(maximo);
return 0;
}
Long maxPoints(Long i){
if(i <= 0){
return 0;
}
if(memo[i] != -1)
return memo[i];
Long ans = 0;
if(freq[i] > 0){
ans = i * freq[i] + maxPoints(i - 2);
}
ans = max(ans, maxPoints(i - 1));
memo[i] = ans;
return ans;
} |
1bcc9d82e1f563206519ffb0842de2fea07098a1 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5688567749672960_1/C++/babaji/Alarge.cpp | 6efc17dc56ec7d86580d3d80fa911d9a24590cfd | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,399 | cpp | Alarge.cpp | #include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define mp make_pair
#define bg begin()
#define en end()
#define Y second
#define X first
typedef long long ll;
#define fi freopen("input.txt","r",stdin)
#define fo freopen("output.txt","w",stdout)
const double pi = acos(-1.0);
const double eps = 1e-8;
#define print(a) cout<<(#a)<<" = "<<a<<"\n";
#define fill(a,val) memset(a ,val, sizeof(a) );
#define sz(s) ((int)(s.size()))
vector <string> parse(string s, string c)
{
int len = c.length(), p = -len, np;
vector <string> ans;
do
{
np = s.find(c, p+len);
ans.push_back(s.substr(p+len, np - p - len));
p = np;
}
while (p != string::npos);
return ans;
}
/*Solution code starts here */
inline ll rever( ll in)
{
ll ans =0;
ll save= in;
while(in!=0)
{
ans = ans * 10;
ans = ans + in%10;
in = in/10;
}
return ans;
}
int go(ll in)
{
if( in < 10)
return in;
int cn = 0 ;
while( (in%10) !=1 )
{
in--;
cn++;
}
ll rv = rever(in);
if( rv>=in )
return cn+1+go(in-1);
return cn+go(rv)+1;//eke reverse ka
}
void solve(int test)
{
int in;
cin>>in;
printf("Case #%d: %d\n",test,go(in));
}
int main()
{
int test;
cin>>test;
for(int i=1;i<=test;i++)
{
solve(i);
}
return 0;
}
|
13772b2b81de28c0e352d76c240c8ce39d31ab76 | 32e00536648218757130654d92336fcfcd10522a | /HeapSort.cpp | 29be539c1904c267552c0c0852d7e2ec36c0cc2a | [] | no_license | PYPARA/Algorithms | 64476da459ec1bf9ee83fdcb988c55c38a315ddb | cb64e08c164435b1d0b3017ebb0d82adc4c12148 | refs/heads/master | 2021-01-11T15:44:32.123304 | 2017-02-21T10:30:21 | 2017-02-21T10:30:21 | 79,918,195 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,501 | cpp | HeapSort.cpp | #include<iostream>
void MaxHeapify(int *a, int i, int heap_size) {
int l = 2 * i + 1;
int r = 2 * i + 2;
int largest = i;
if (l < heap_size && a[l] > a[i]) {
largest = l;
}
if (r < heap_size && a[r] > a[largest]) {
largest = r;
}
if (largest != i) {
int temp = a[i];
a[i] = a[largest];
a[largest] = temp;
MaxHeapify(a, largest, heap_size);
}
}
void BuildMaxHeap(int *a, int len) {
int heap_size = len;
for (int i = (len-1) / 2; i >= 0; --i) {
MaxHeapify(a, i,heap_size);
}
}
void HeapSort(int *a, int len) {
int heap_size = len;
BuildMaxHeap(a, len);
for (int i = len-1; i>=1;--i) {
int max = a[0];
a[0] = a[i];
a[i] = max;
--heap_size;
MaxHeapify(a, 0,heap_size);
}
}
int main() {
int a[31] = { 5,6,8,7,41,2,3,1,64,84,31,24,6,1,7,7,6,3,2,1,4,5,6,8,4,5,2,16,315,6541,3151 };
HeapSort(a, 31);
for (auto c : a) {
std::cout << c << " ";
}
std::cout << std::endl;
return 0;
}
/*
MAX-HEAPIFY (A,i)
1. l=LEFT(i)
2. r=RIGHT(i)
3. if l <= A.heap-size and A[l]>A[i]
4. largest=l
5. else largest=i
6. if r <= A.heap-size and A[r]>A[largest]
7. largest=r
8. if largest!=i
9. exchangeA[i] with A[largest]
10. MAX-HEAPIFY (A,largest)
BUILD-MAX-HEAP(A)
1. A.heap-size = A.length
2. for i= [A.length/2] downto 1
3. MAX-HEAPIFY (A,i)
HEAPSORT(A)
1. BUILD-MAX-HEAP(A)
2. for i=A.length downto 2
3. exchange A[1] with A[i]
A.heapsize =A.heap-size - 1
MAX-HEAPIFY (A,1)
*/ |
3eb0d4c91bbb08fe708759851ebb96c95a54453a | 297ac87d9352a19b0f15656b485d0ef56ea5fce7 | /accordian.cpp | 3d8bb31651467f7f11e5651603d5d06d7a259510 | [] | no_license | eddiebarry/cp_code | ef48de9029b61e9adda966e3e95792da3d0ed978 | abbcc76056fb62a125dd84f132fc2d62011b0b0a | refs/heads/master | 2020-05-02T17:09:41.644921 | 2019-03-27T23:41:49 | 2019-03-27T23:41:49 | 178,090,177 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,064 | cpp | accordian.cpp | /*
* Note: This template uses some c++11 functions , so you have to compile it with c++11 flag.
* Example:- $ g++ -std=c++11 c++Template.cpp
*
* Author : Denzil Bernard
* Handle: 1_mn_RMY
*
*/
#include <stdio.h>
#include <vector>
#include <iostream>
using namespace std;
/******* All Required define Pre-Processors and typedef Constants *******/
#define FOR(i, j, k, in) for (int i=j ; i<k ; i+=in)
#define RFOR(i, j, k, in) for (int i=j ; i>=k ; i-=in)
#define REP(i, j) FOR(i, 0, j, 1)
#define RREP(i, j) RFOR(i, j, 0, 1)
#define all(cont) cont.begin(), cont.end()
#define rall(cont) cont.end(), cont.begin()
#define FOREACH(it, l) for (auto it = l.begin(); it != l.end(); it++)
#define IN(A, B, C) assert( B <= A && A <= C)
#define MP make_pair
#define PB push_back
#define MOD 1000000007
#define read(type) readInt<type>()
#define ll long long
ll SI(){
ll x;
cin>>x;
return x;
}
/********** Main() function **********/
int main()
{
string s;
cin>>s;
int n = s.size();
bool start_bracket = false, start_colon = false, end_bracket = false, end_colon = false;
ll start_idx = -1, end_idx = -1;
REP(i,n){
if(s[i]=='['){
start_bracket = true;
}
if(start_bracket){
if(s[i]==':'){
start_colon = true;
start_idx = i;
break;
}
}
}
REP(i,n){
// cout<<s[n-1-i]<<" ";
if(s[n-1-i]==']'){
end_bracket = true;
}
if(end_bracket){
if(s[n-1-i]==':'){
end_colon = true;
end_idx = n - 1 -i;
break;
}
}
}
// cout<<end_idx<<" "<<start_idx<<"\n";
if((start_idx < end_idx) && start_bracket && start_colon && end_bracket && end_colon){
ll ans = 0;
FOR(i,start_idx,end_idx,1){
if(s[i]==124){
ans++;
}
}
cout<<ans+4<<"\n";
}
else{
cout<<-1<<"\n";
}
return 0;
}
|
e6c74fe2582f96be570badfff2ca94fabab41b10 | e6a5fce33aad4fcba37842e135a51ba441b06f48 | /Algorithms/Implementation/JumpingOnTheClouds.cpp | 97e447d982efe67a9b0a9fc21dfe75a64a9bc1e2 | [
"MIT"
] | permissive | pavstar619/HackerRank | 6710ddd450b06fbb69da5abad9f570e5e26bbbc0 | 697ee46b6e621ad884a064047461d7707b1413cd | refs/heads/master | 2020-06-18T18:53:53.421685 | 2020-02-18T09:35:48 | 2020-02-18T09:35:48 | 196,408,726 | 0 | 0 | MIT | 2019-07-11T14:18:16 | 2019-07-11T14:18:16 | null | UTF-8 | C++ | false | false | 487 | cpp | JumpingOnTheClouds.cpp | #include <bits/stdc++.h>
using namespace std;
int jumpingOnClouds(vector<int> v)
{
int i = 0, n = v.size(), con = 0;
while(i < n - 1){
if(i + 2 >= n || v[i+2] == 1){
i++;
con++;
}
else{
i += 2;
con++;
}
}
return con;
}
int main()
{
int n;
cin >> n;
vector<int> c(n);
for(int i = 0; i < n; i++)
cin >> c[i];
cout << jumpingOnClouds(c) << endl;
return 0;
}
|
134482a8602335c62dd69d579180a730854cbac7 | 3b48d5381fb68df286e8dbb966b6a6c1d67b46c6 | /tests/copy.cpp | 0d6d01a6fea89f70605a8f59c41aef493494b0a3 | [] | no_license | rhicspin/opencdev | d71520a5b65252085a964d291e2bc014335e5d41 | 10e0f9e4cf4d23912130e73ce80df75a98289eb8 | refs/heads/master | 2021-01-22T12:08:50.973365 | 2017-04-08T22:33:30 | 2017-04-08T22:33:59 | 22,018,408 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 648 | cpp | copy.cpp | /* vim: set sw=3: */
#include <boost/test/unit_test.hpp>
#include <opencdev.h>
BOOST_AUTO_TEST_SUITE(copy)
// A test to see if pimpl memory management works fine
BOOST_AUTO_TEST_CASE(double_free_test)
{
opencdev::LocalLogReader log_reader(TEST_DATA_PATH);
opencdev::result_t result;
{
opencdev::LocalLogReader log_reader2(log_reader);
log_reader2.query_timerange("RHIC/Polarimeter/Yellow/biasReadbacks", 0, 1, &result);
BOOST_CHECK(result.size() == 0);
}
log_reader.query_timerange("RHIC/Polarimeter/Yellow/biasReadbacks", 0, 1, &result);
BOOST_CHECK(result.size() == 0);
}
BOOST_AUTO_TEST_SUITE_END()
|
73e6fd0e309ae7d16d370313f6554b9568833640 | 42ba73134eeca961230044e4cef29a5fc35e3529 | /TktkDirectX12GameLib/TktkDX12GameLib/inc/TktkDX12Game/UtilityProcessManager/ResourceHandleGetter/SystemResourceHandleGetter/IdType/SystemDepthStencilBufferType.h | 4c0661794b4510cbf29fe3efc9cdc73b11cf5651 | [] | no_license | tktk2104/TktkDirectX12GameLib | 5b9ef672ce0a99bbce8a156751b423ef840729b3 | 4d037ec603d9f30d8c4ed3fb4474cfaea49c8ac9 | refs/heads/master | 2023-02-22T14:38:10.101382 | 2020-12-03T04:55:05 | 2020-12-03T04:55:05 | 287,092,170 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 293 | h | SystemDepthStencilBufferType.h | #ifndef SYSTEM_DEPTH_STENCIL_BUFFER_TYPE_H_
#define SYSTEM_DEPTH_STENCIL_BUFFER_TYPE_H_
namespace tktk
{
// システムで使用している深度ステンシルバッファの種類
enum class SystemDsBufferType
{
Basic,
ShadowMap
};
}
#endif // !SYSTEM_DEPTH_STENCIL_BUFFER_TYPE_H_ |
7e5669bc403f27b21d1ede9d9ded25b9ad53ef58 | fe73361edb1a0b5786ca05d0b1ab2af5deb180af | /内存管理_请求调页_1950072_郑柯凡/请求调页源码_1950072_郑柯凡/viraddress.cpp | 3abc8928accce6e9c62b72ef964232a6ec66b4c1 | [] | no_license | kefan-zheng/OS | 1334be9b67d023cf2f404c0b80f1832217e279e5 | 9e622b20bc9db861c44bef25f4a909a4a168950d | refs/heads/main | 2023-08-10T20:18:52.493883 | 2021-09-15T13:29:19 | 2021-09-15T13:29:19 | 369,163,759 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 734 | cpp | viraddress.cpp | #include "viraddress.h"
VirAddress::VirAddress()
{
pageContentID = 0;
pageTableID2 = 0;
pageTableID3 = 0;
pageOffsets = 0;
}
int VirAddress::getpageContentID()
{
return this->pageContentID;
}
int VirAddress::getpageTableID2()
{
return this->pageTableID2;
}
int VirAddress::getpageTableID3()
{
return this->pageTableID3;
}
int VirAddress::getpageOffsets()
{
return this->pageOffsets;
}
void VirAddress::modifypageContentID(int tar)
{
this->pageContentID=tar;
}
void VirAddress::modifypageTableID2(int tar)
{
this->pageTableID2=tar;
}
void VirAddress::modifypageTableID3(int tar)
{
this->pageTableID3=tar;
}
void VirAddress::modifypageOffsets(int tar)
{
this->pageOffsets=tar;
}
|
d00e674dbe564f4dfd3324fd920bff266f55c9ba | 4e09d9f9cd17b49465ae3a76a6ac54009445ec16 | /Textures/Source.cpp | 4ccf1c0d4c96118fa4a505b2ac377e175cca500a | [] | no_license | ZyronMelancon/Year2 | cd2be6baa0b1cff0e0f052a89473b50637199e90 | 6a5fdb74873273ec19e0a61d7141c0141d5efbf9 | refs/heads/master | 2021-01-19T08:11:14.667772 | 2017-10-09T23:03:25 | 2017-10-09T23:03:25 | 100,650,616 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 146 | cpp | Source.cpp | #include "TextureApplication.h"
void main()
{
Application * app = new TextureApplication();
app->run("Texture Application", 800, 600, false);
} |
a4e836403dfd9a76a557904be2e1e67e15d6403b | adc2a917ff170973fe866d064c64b6b2cdcaa68d | /P_Euler_15.cpp | 79cf127d37c1df88578e6a6bf0295d307f7bf178 | [] | no_license | adelgadoj/Ejercicios_Proyecto_Euler | 511ae0620a350290be746f508b70f427c935063e | a5f3026dcef327e7a5ada9c0fada6e1904cd22db | refs/heads/main | 2023-04-14T02:37:00.107145 | 2021-04-28T15:13:05 | 2021-04-28T15:15:04 | 360,959,519 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,389 | cpp | P_Euler_15.cpp | //#PROBLEMA 15
//#Lattice paths
/*
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down,
there are exactly 6 routes to the bottom right corner.
How many such routes are there through a 20×20 grid?
*/
#include <vector>
#include <deque>
#include <utility>
#include <iostream>
using namespace std;
int main()
{
int tests;
cin >> tests;
while (tests--)
{
int width, height;
cin >> width >> height;
long long Unknown = 0;
vector<vector<long long>> grid(width + 1);
for (auto& column : grid)
column.resize(height + 1, Unknown);
grid[width][height] = 1;
deque<pair<int,int>> next;
next.push_back(make_pair(width - 1, height));
next.push_back(make_pair(width, height - 1));
while (!next.empty())
{
auto current = next.front();
next.pop_front();
auto x = current.first;
auto y = current.second;
if (grid[x][y] != Unknown)
continue;
long long routes = 0;
if (x < width)
routes += grid[x + 1][y];
if (y < height)
routes += grid[x][y + 1];
#define ORIGINAL
#ifndef ORIGINAL
routes %= 1000000007;
#endif
grid[x][y] = routes;
if (x > 0)
next.push_back(make_pair(x - 1, y));
if (y > 0)
next.push_back(make_pair(x, y - 1));
}
cout << grid[0][0] << std::endl;
}
return 0;
}
|
7cf566dbfac95dc4b733dce300cc032c5215aa31 | 41ab1a4c6c74e3e58c1189643b6a16a08ec9beb1 | /zzz_Eds_C++_Examples/Classes_Inheritance/inheritance_sample_v1.cpp | c3015c362659fdb0e493740cf80b6831a8bb50c3 | [] | no_license | APrioriRainbows/C_Plus_Plus_Repo_Public | 22df6129da80dcc9a7d0d0ef9b459cbc83a69f15 | 9237013866f777744a99b1bc187a346f0c76f17e | refs/heads/master | 2022-04-17T19:59:01.720467 | 2020-04-11T04:39:48 | 2020-04-11T04:39:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,285 | cpp | inheritance_sample_v1.cpp | // ****************************************************
// Inheritance of Classes example
// By Ed
// ****************************************************
#include <iostream>
using namespace std;
// *****************************************************************************************************
// What is Inheritance?
// Inheritance is the idea that you can "inherit" functionality (i.e. functions and variables) from another class.
// Similar to Templates, Inheritance helps you cut down on code duplication (and copying and pasting code
// from one place to the next) by allowing you to "inherit" the code from one Class to another.
// *****************************************************************************************************
// Difference between the Base vs. Derived Class:
// The Base Class -- This is the main Class that has all the code that will be shared with
// other sub-Classes.
// The Derived Class -- This is the Class that will "inherit" all the functionality from the main Base Class.
// *****************************************************************************************************
// Create/declare a Base Class
class MotherBaseClass {
public:
// function sample
void sayYourLastName(){
cout << "I am a Rodriguezzz!" <<endl;
}
};
// Create a Derived Class that inherits the code from the Base Class
class DaughterDerivedClass : public MotherBaseClass {
public:
// I inherited my code from the Base Class!!!
};
int main()
{
// Base Class:
//Create an Object using your MotherBaseClass Class
MotherBaseClass edsAwesomeBaseObject;
// cout
cout << "The mother says:" << endl;
// Access the sayYourLastName function inside your Class
edsAwesomeBaseObject.sayYourLastName();
// Derived Class:
// Display to the screen the message that the Derived Class 'inherited' from the Base Class
DaughterDerivedClass edsAwesomeDerivedObject;
cout << endl << "The daughter says:" << endl;
edsAwesomeDerivedObject.sayYourLastName();
return 0;
} |
c9ed5ed792bacb182f473b8fcb4e09f37459f85c | 64d6fb738f2c2193c13368b479f2af6d88d6b889 | /feature-extractor/simple_sgd_svm/svm/loss.h | 3dfdca58c67d1e3a5db0e061431459a946fcdbdc | [] | no_license | yikuizhai/face-verification-system | de68b10211283c17274fd05fa0b6832aa120bef5 | 2fe62f50a8478ea09de1c9adaaeaf029305cbbf5 | refs/heads/master | 2021-01-15T14:02:38.148169 | 2013-09-04T05:28:52 | 2013-09-04T05:28:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 249 | h | loss.h | /*
* loss.h
*
* Created on: 29 Apr, 2013
* Author: harvey
*/
#ifndef LOSS_H_
#define LOSS_H_
class HingeLoss {
public:
static double loss(double wx, double y);
static double dloss(double wx, double y);
};
#endif /* LOSS_H_ */
|
a648a295c2a8f5ee460ae06323e059aef5a2127b | b65df15a5da287c313c51c22a90e23ffc061d60f | /LeetCode_C++/452_findMinArrowShots/solution.h | 4d10087518ee0cfb0b468bcde4cebcdf5984f23e | [
"MIT"
] | permissive | Yiluhuakai22/algorigthm-study | 5ed2cc577d615e6dd7b57e395b864dabf0aba34f | 084ca94342020e4333045c136886eef0292e4eae | refs/heads/main | 2023-07-03T10:57:14.495596 | 2021-08-09T07:41:32 | 2021-08-09T09:15:03 | 375,208,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,243 | h | solution.h | #include <algorithm>
#include <vector>
using std::min;
using std::vector;
class Solution
{
public:
int findMinArrowShots(vector<vector<int>> &points)
{
size_t count = points.size();
sort(points.begin(), points.end(), [](vector<int> a, vector<int> b)
{ return a[0] < b[0]; });
int n = 1;
vector<int> inter = points[0];
for (size_t i = 1; i < count; i++)
{
// 区间有交集
if (points[i][0] <= inter[1])
{
inter[0] = min(points[i][0], inter[1]);
inter[1] = min(points[i][1], inter[1]);
}
else
{
// 区间没有交集
++n;
inter = points[i];
}
}
return n;
}
int findMinArrowShots2(vector<vector<int>> &points)
{
sort(points.begin(), points.end(), [](vector<int> a, vector<int> b)
{ return a[1] < b[1]; });
int n = 1, pos = points[0][1];
for (const vector<int> &balloon : points)
{
if (balloon[0] > pos)
{
++n;
pos = balloon[1];
}
}
return n;
}
}; |
95bbb2435c9df5123c7918d0696850ac9fe1c70c | db5ea260f9c009d5d9616c09cef331a0a8916140 | /source/HeatEq.cpp | 54a4322e792aed8d6f3e689e4952b57884269738 | [] | no_license | clairemorel/Code_NS_Cmo | ce72800d340c23ae2657134adcdaef2203f419d5 | 6c89efdd725352e3856044944b6307ab36731308 | refs/heads/master | 2021-01-19T10:31:38.315720 | 2016-06-02T14:02:16 | 2016-06-02T14:02:16 | 60,078,741 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,840 | cpp | HeatEq.cpp | // My Libraries
#include <libNavierStokes/HeatEq.hpp>
using namespace std;
using namespace bitpit;
vector<double> HeatEq::computeTNext(PabloUniform& gridCart, double& dt, double& temps, KSP& ksp, Mat& Mat_poisson, Vec& RHS, Vec& Solution){
computeVectorT(gridCart,dt, RHS);
if (temps == dt) {
computeMatrixDiamond(gridCart, dt, Mat_poisson);
KSPSetOperators(ksp, Mat_poisson, Mat_poisson);
KSPSetFromOptions(ksp);
KSPSetUp(ksp);
}
KSPSolve(ksp, RHS, Solution);
PetscScalar *vecArray;
VecGetArray(Solution, &vecArray);
for (int i = 0; i < gridCart.getNumOctants(); ++i) {
m_T[i] = (double)PetscRealPart(vecArray[i]);
}
VecRestoreArray(Solution, &vecArray);
return m_T;
};
void HeatEq::computeVectorT(PabloUniform& gridCart, double& dt, Vec& RHS){
for (int i = 0; i < gridCart.getNumOctants(); ++i){
if ( sqrt(pow(gridCart.getCenter(i)[0],2)+pow(gridCart.getCenter(i)[1],2) )<= m_radius ) m_pen = 1;
else m_pen =0;
m_T[i] += m_pen*m_lambda*m_TBarre*dt;
// Find global index
int g_i=gridCart.getGlobalIdx(i);
VecSetValues(RHS, 1,&g_i, &m_T[i], INSERT_VALUES);
}
MPI_Barrier(PETSC_COMM_WORLD);
VecAssemblyBegin(RHS);
VecAssemblyEnd(RHS);
};
void HeatEq::computeMatrix(PabloUniform& gridCart, double& dt, Mat& Mat_poisson){
vector<uint32_t> owners(2,0);
darray3 center0, center1;
PetscScalar value00, value11, value01, value10;
PetscInt g_n0, g_n1;
double kappa=1.e0;
Intersection *inter;
Octant *ghostOct;
for (int i = 0; i < gridCart.getNumIntersections(); ++i) {
inter=gridCart.getIntersection(i);
owners=gridCart.getOwners(inter);
bool boundary=gridCart.getBound(inter);
if (!boundary) {
// no ghost
if (!gridCart.getIsGhost(inter)){
// Find global index
g_n0=gridCart.getGlobalIdx(owners[0]);
g_n1=gridCart.getGlobalIdx(owners[1]);
center0=gridCart.getCenter(owners[0]);
center1=gridCart.getCenter(owners[1]);
double deltaCenter=sqrt( pow(center0[0]-center1[0],2) + pow(center0[1]-center1[1],2) );
value00 = kappa*dt/gridCart.getArea(owners[0])*gridCart.getArea(inter)/deltaCenter;
value11 = kappa*dt/gridCart.getArea(owners[1])*gridCart.getArea(inter)/deltaCenter;
value01 = -kappa*dt/gridCart.getArea(owners[0])*gridCart.getArea(inter)/deltaCenter;
value10 = -kappa*dt/gridCart.getArea(owners[1])*gridCart.getArea(inter)/deltaCenter;
}
else {
g_n0=gridCart.getGlobalIdx(owners[0]);
g_n1=gridCart.getGhostGlobalIdx(owners[1]);
ghostOct = gridCart.getGhostOctant(owners[1]);
center0=gridCart.getCenter(owners[0]);
center1=gridCart.getCenter(ghostOct);
double deltaCenter=sqrt( pow(center0[0]-center1[0],2) + pow(center0[1]-center1[1],2) );
value00 = kappa*dt/gridCart.getArea(owners[0])*gridCart.getArea(inter)/deltaCenter;
value11 = 0;
value01 = -kappa*dt/gridCart.getArea(owners[0])*gridCart.getArea(inter)/deltaCenter;
value10 = 0;
}
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n1, &value01, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n0, &value10, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n0, &value00, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n1, &value11, ADD_VALUES);
}
}
for (int j = 0; j < gridCart.getNumOctants(); ++j){
if ( sqrt(pow(gridCart.getCenter(j)[0],2)+ pow(gridCart.getCenter(j)[1],2)) <= m_radius )
m_pen=1;
else
m_pen =0;
// Find Global index
int g_j=gridCart.getGlobalIdx(j);
value00= 1+m_pen*m_lambda*dt;
MatSetValues(Mat_poisson, 1, &g_j, 1, &g_j, &value00, ADD_VALUES);
}
MatAssemblyBegin(Mat_poisson,MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(Mat_poisson,MAT_FINAL_ASSEMBLY);
/*PetscViewerSetFormat(PETSC_VIEWER_STDOUT_WORLD,PETSC_VIEWER_ASCII_DENSE);
MatView(Mat_poisson, PETSC_VIEWER_STDOUT_WORLD);*/
}
void HeatEq::computeMatrixDiamond(PabloUniform& gridCart, double& dt, Mat& Mat_poisson){
vector<uint32_t> owners(2,0);
Intersection *inter;
Octant *OctOwner, *Oct_n, *Oct_f2, *Oct_f1;
PetscInt g_n0, g_n1, g_n3, g_n2, g_nn;
PetscScalar value00, value11, value01, value10, value0N, value02, value03, value1N, value12, value13;
double kappa=1.e0, TaucenterX, TaucenterY;
bool ifiner;
darray3 center0, center1, node_n1, node_n2;
darr3vector nodes;
uint iface;
vector<uint32_t> neigh_n, neigh_f2, neigh_f1;
vector<bool> isghost_n, isghost_f2, isghost_f1;
int TautbX, TautbY, NormalX, NormalY;
vector<double> interpt, interpb;
for (int i = 0; i < gridCart.getNumIntersections(); ++i) {
inter=gridCart.getIntersection(i);
owners=gridCart.getOwners(inter);
bool boundary=gridCart.getBound(inter);
bool bound=0, nodeTop=0, face1=0;
if (!boundary) {
if (!gridCart.getIsGhost(inter)) {
// Find Global index
g_n0=gridCart.getGlobalIdx(owners[0]);
g_n1=gridCart.getGlobalIdx(owners[1]);
OctOwner=gridCart.getOctant(owners[1]);
if (gridCart.getLevel(owners[0])==gridCart.getLevel(owners[1])) {
value00 = kappa*dt/gridCart.getVolume(owners[0]);
value11 = kappa*dt/gridCart.getVolume(owners[1]);
value01 = -kappa*dt/gridCart.getVolume(owners[0]);
value10 = -kappa*dt/gridCart.getVolume(owners[1]);
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n1, &value01, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n0, &value10, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n0, &value00, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n1, &value11, ADD_VALUES);
}
}
// ghost
else {
g_n0=gridCart.getGlobalIdx(owners[0]);
g_n1=gridCart.getGhostGlobalIdx(owners[1]);
OctOwner=gridCart.getGhostOctant(owners[1]);
if (gridCart.getLevel(OctOwner)==gridCart.getLevel(owners[0])) {
value00 = kappa*dt/gridCart.getVolume(owners[0]);
value01 = -kappa*dt/gridCart.getVolume(owners[0]);
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n1, &value01, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n0, &value00, ADD_VALUES);
}
}
if (gridCart.getLevel(OctOwner)!=gridCart.getLevel(owners[0])){
ifiner=gridCart.getFiner(inter);
center0=gridCart.getCenter(owners[0]);
center1=gridCart.getCenter(OctOwner);
double deltaCenter=sqrt( pow(center0[0]-center1[0],2) + pow(center0[1]-center1[1],2) );
nodes=gridCart.getNodes(inter);
TautbX=1/sqrt(pow(nodes[1][0]-nodes[0][0],2)+pow(nodes[1][1]-nodes[0][1],2))*(nodes[1][0]-nodes[0][0]);
TautbY=1/sqrt(pow(nodes[1][0]-nodes[0][0],2)+pow(nodes[1][1]-nodes[0][1],2))*(nodes[1][1]-nodes[0][1]);
TaucenterX=1/sqrt(pow(center1[0]-center0[0],2)+pow(center1[1]-center0[1],2))*(center1[0]-center0[0]);
TaucenterY=1/sqrt(pow(center1[0]-center0[0],2)+pow(center1[1]-center0[1],2))*(center1[1]-center0[1]);
// if owners[0] is the finest octant
if (!ifiner) {
iface=gridCart.getFace(inter);
NormalX=gridCart.getNormal(inter)[0];
NormalY=gridCart.getNormal(inter)[1];
if (iface==0){
gridCart.findNeighbours(owners[0],2,1,neigh_f1,isghost_f1);
gridCart.findNeighbours(owners[0],3,1,neigh_f2,isghost_f2);
gridCart.findNeighbours(owners[0],0,2,neigh_n,isghost_n);
if (neigh_n.size()==0) {
gridCart.findNeighbours(owners[0],2,2,neigh_n,isghost_n);
nodeTop=1;
if (neigh_n.size()==0) bound=1;
}
}
else if (iface==1){
gridCart.findNeighbours(owners[0],2,1,neigh_f1,isghost_f1);
gridCart.findNeighbours(owners[0],3,1,neigh_f2,isghost_f2);
gridCart.findNeighbours(owners[0],1,2,neigh_n,isghost_n);
if (neigh_n.size()==0) {
gridCart.findNeighbours(owners[0],3,2,neigh_n,isghost_n);
nodeTop=1;
if (neigh_n.size()==0) bound=1;
}
}
else if (iface==2){
gridCart.findNeighbours(owners[0],0,1,neigh_f1,isghost_f1);
gridCart.findNeighbours(owners[0],1,1,neigh_f2,isghost_f2);
gridCart.findNeighbours(owners[0],0,2,neigh_n,isghost_n);
if (neigh_n.size()==0) {
gridCart.findNeighbours(owners[0],1,2,neigh_n,isghost_n);
nodeTop=1;
if (neigh_n.size()==0) bound=1;
}
}
else if (iface==3){
gridCart.findNeighbours(owners[0],0,1,neigh_f1,isghost_f1);
gridCart.findNeighbours(owners[0],1,1,neigh_f2,isghost_f2);
gridCart.findNeighbours(owners[0],2,2,neigh_n,isghost_n);
if (neigh_n.size()==0) {
gridCart.findNeighbours(owners[0],3,2,neigh_n,isghost_n);
nodeTop=1;
if (neigh_n.size()==0) bound=1;
}
}
}
// if owners[1] is the finest octant
else {
iface=gridCart.getFace(inter);
NormalX=-gridCart.getNormal(inter)[0];
NormalY=-gridCart.getNormal(inter)[1];
if (iface==0){
node_n1=gridCart.getNode(owners[0],1);
node_n2=gridCart.getNode(owners[0],3);
if (node_n1[0]==nodes[0][0] && node_n1[1]==nodes[0][1]) {
gridCart.findNeighbours(owners[0],1,2,neigh_n,isghost_n);
gridCart.findNeighbours(owners[0],2,1,neigh_f2,isghost_f2);
face1=1;
if (neigh_f2.size()==2) {
neigh_f2[0]=neigh_f2[1];
isghost_f2[0]=isghost_f2[1];
}
}
else if (node_n2[0]==nodes[1][0] && node_n2[1]==nodes[1][1]){
gridCart.findNeighbours(owners[0],3,2,neigh_n,isghost_n);
gridCart.findNeighbours(owners[0],3,1,neigh_f2,isghost_f2);
nodeTop=1;
if (neigh_f2.size()==2) {
neigh_f2[0]=neigh_f2[1];
isghost_f2[0]=isghost_f2[1];
}
}
if (neigh_n.size()==0) bound=1;
gridCart.findNeighbours(owners[0],1,1,neigh_f1,isghost_f1);
if (isghost_f1[0]==1) g_n3=gridCart.getGhostGlobalIdx(neigh_f1[0]);
else g_n3=gridCart.getGlobalIdx(neigh_f1[0]);
if (g_n3==g_n1) {
neigh_f1[0]=neigh_f1[1];
isghost_f1[0]=isghost_f1[1];
}
}
else if (iface==1){
node_n1=gridCart.getNode(owners[0],0);
node_n2=gridCart.getNode(owners[0],2);
if (node_n1[0]==nodes[0][0] && node_n1[1]==nodes[0][1]) {
gridCart.findNeighbours(owners[0],0,2,neigh_n,isghost_n);
gridCart.findNeighbours(owners[0],2,1,neigh_f2,isghost_f2);
face1=1;
}
else if (node_n2[0]==nodes[1][0] && node_n2[1]==nodes[1][1]){
gridCart.findNeighbours(owners[0],2,2,neigh_n,isghost_n);
gridCart.findNeighbours(owners[0],3,1,neigh_f2,isghost_f2);
nodeTop=1;
}
if (neigh_n.size()==0) bound=1;
gridCart.findNeighbours(owners[0],0,1,neigh_f1,isghost_f1);
if (isghost_f1[0]==1) g_n3=gridCart.getGhostGlobalIdx(neigh_f1[0]);
else g_n3=gridCart.getGlobalIdx(neigh_f1[0]);
if (g_n3==g_n1) {
neigh_f1[0]=neigh_f1[1];
isghost_f1[0]=isghost_f1[1];
}
}
else if (iface==2){
node_n1=gridCart.getNode(owners[0],2);
node_n2=gridCart.getNode(owners[0],3);
if (node_n1[0]==nodes[0][0] && node_n1[1]==nodes[0][1]) {
gridCart.findNeighbours(owners[0],2,2,neigh_n,isghost_n);
gridCart.findNeighbours(owners[0],0,1,neigh_f2,isghost_f2);
face1=1;
if (neigh_f2.size()==2) {
neigh_f2[0]=neigh_f2[1];
isghost_f2[0]=isghost_f2[1];
}
}
else if (node_n2[0]==nodes[1][0] && node_n2[1]==nodes[1][1]){
gridCart.findNeighbours(owners[0],3,2,neigh_n,isghost_n);
gridCart.findNeighbours(owners[0],1,1,neigh_f2,isghost_f2);
nodeTop=1;
if (neigh_f2.size()==2) {
neigh_f2[0]=neigh_f2[1];
isghost_f2[0]=isghost_f2[1];
}
}
if (neigh_n.size()==0) bound=1;
gridCart.findNeighbours(owners[0],3,1,neigh_f1,isghost_f1);
if (isghost_f1[0]==1) g_n3=gridCart.getGhostGlobalIdx(neigh_f1[0]);
else g_n3=gridCart.getGlobalIdx(neigh_f1[0]);
if (g_n3==g_n1) {
neigh_f1[0]=neigh_f1[1];
isghost_f1[0]=isghost_f1[1];
}
}
else if (iface==3){
node_n1=gridCart.getNode(owners[0],0);
node_n2=gridCart.getNode(owners[0],1);
if (node_n1[0]==nodes[0][0] && node_n1[1]==nodes[0][1]) {
gridCart.findNeighbours(owners[0],0,2,neigh_n,isghost_n);
gridCart.findNeighbours(owners[0],0,1,neigh_f2,isghost_f2);
face1=1;
}
else if (node_n2[0]==nodes[1][0] && node_n2[1]==nodes[1][1]){
gridCart.findNeighbours(owners[0],1,2,neigh_n,isghost_n);
gridCart.findNeighbours(owners[0],1,1,neigh_f2,isghost_f2);
nodeTop=1;
}
if (neigh_n.size()==0) bound=1;
gridCart.findNeighbours(owners[0],2,1,neigh_f1,isghost_f1);
if (isghost_f1[0]==1) g_n3=gridCart.getGhostGlobalIdx(neigh_f1[0]);
else g_n3=gridCart.getGlobalIdx(neigh_f1[0]);
if (g_n3==g_n1) {
neigh_f1[0]=neigh_f1[1];
isghost_f1[0]=isghost_f1[1];
}
}
} // end ifiner
if (!bound) {
if (isghost_n[0]==1) {
g_nn=gridCart.getGhostGlobalIdx(neigh_n[0]);
Oct_n=gridCart.getGhostOctant(neigh_n[0]);
}
else {
g_nn=gridCart.getGlobalIdx(neigh_n[0]);
Oct_n=gridCart.getOctant(neigh_n[0]);
}
if (isghost_f2[0]==1) {
g_n2=gridCart.getGhostGlobalIdx(neigh_f2[0]);
Oct_f2=gridCart.getGhostOctant(neigh_f2[0]);
}
else {
g_n2=gridCart.getGlobalIdx(neigh_f2[0]);
Oct_f2=gridCart.getOctant(neigh_f2[0]);
}
if (isghost_f1[0]==1) {
g_n3=gridCart.getGhostGlobalIdx(neigh_f1[0]);
Oct_f1=gridCart.getGhostOctant(neigh_f1[0]);
}
else {
g_n3=gridCart.getGlobalIdx(neigh_f1[0]);
Oct_f1=gridCart.getOctant(neigh_f1[0]);
}
if (nodeTop){
interpt = interp4p(gridCart, nodes[1], owners[0], OctOwner, Oct_f2, Oct_n);
interpb = interp3p(gridCart, nodes[0], owners[0], OctOwner, Oct_f1);
if (TautbX == 0) {
value0N = kappa*dt/gridCart.getVolume(owners[0])*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpt[3];
value02 = kappa*dt/gridCart.getVolume(owners[0])*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpt[2];
value03 = -kappa*dt/gridCart.getVolume(owners[0])*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[2];
value1N = -kappa*dt/gridCart.getVolume(OctOwner)*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpt[3];
value12 = -kappa*dt/gridCart.getVolume(OctOwner)*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpt[2];
value13 = kappa*dt/gridCart.getVolume(OctOwner)*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[2];
}
else {
value0N = kappa*dt/gridCart.getVolume(owners[0])*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpt[3];
value02 = kappa*dt/gridCart.getVolume(owners[0])*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpt[2];
value03 = -kappa*dt/gridCart.getVolume(owners[0])*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[2];
value1N = -kappa*dt/gridCart.getVolume(OctOwner)*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpt[3];
value12 = -kappa*dt/gridCart.getVolume(OctOwner)*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpt[2];
value13 = kappa*dt/gridCart.getVolume(OctOwner)*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[2];
}
}
else if (face1) {
interpt = interp3p(gridCart, nodes[1], owners[0], OctOwner, Oct_f1);
interpb = interp4p(gridCart, nodes[0], owners[0], OctOwner, Oct_f2, Oct_n);
if (TautbX == 0) {
value0N = -kappa*dt/gridCart.getVolume(owners[0])*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[3];
value02 = -kappa*dt/gridCart.getVolume(owners[0])*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[2];
value03 = kappa*dt/gridCart.getVolume(owners[0])*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpt[2];
value1N = kappa*dt/gridCart.getVolume(OctOwner)*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[3];
value12 = kappa*dt/gridCart.getVolume(OctOwner)*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[2];
value13 = -kappa*dt/gridCart.getVolume(OctOwner)*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpt[2];
}
else {
value0N = -kappa*dt/gridCart.getVolume(owners[0])*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[3];
value02 = -kappa*dt/gridCart.getVolume(owners[0])*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[2];
value03 = kappa*dt/gridCart.getVolume(owners[0])*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpt[2];
value1N = kappa*dt/gridCart.getVolume(OctOwner)*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[3];
value12 = kappa*dt/gridCart.getVolume(OctOwner)*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[2];
value13 = -kappa*dt/gridCart.getVolume(OctOwner)*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpt[2];
}
}
else {
interpt = interp3p(gridCart, nodes[1], owners[0], OctOwner, Oct_f2);
interpb = interp4p(gridCart, nodes[0], owners[0], OctOwner, Oct_f1, Oct_n);
if (TautbX == 0) {
value0N = -kappa*dt/gridCart.getVolume(owners[0])*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[3];
value02 = kappa*dt/gridCart.getVolume(owners[0])*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpt[2];
value03 = -kappa*dt/gridCart.getVolume(owners[0])*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[2];
value1N = kappa*dt/gridCart.getVolume(OctOwner)*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[3];
value12 = -kappa*dt/gridCart.getVolume(OctOwner)*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpt[2];
value13 = kappa*dt/gridCart.getVolume(OctOwner)*(NormalX*TaucenterY)/(TaucenterX*TautbY)*interpb[2];
}
else {
value0N = -kappa*dt/gridCart.getVolume(owners[0])*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[3];
value02 = kappa*dt/gridCart.getVolume(owners[0])*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpt[2];
value03 = -kappa*dt/gridCart.getVolume(owners[0])*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[2];
value1N = kappa*dt/gridCart.getVolume(OctOwner)*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[3];
value12 = -kappa*dt/gridCart.getVolume(OctOwner)*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpt[2];
value13 = kappa*dt/gridCart.getVolume(OctOwner)*(NormalY*TaucenterX)/(TaucenterY*TautbX)*interpb[2];
}
}
if (gridCart.getIsGhost(inter)){
value1N = 0;
value12 = 0;
value13 = 0;
}
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_nn, &value0N, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n3, &value03, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n2, &value02, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_nn, &value1N, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n3, &value13, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n2, &value12, ADD_VALUES);
if (!gridCart.getIsGhost(inter)) {
if (TautbX ==0 ){
value00 = - kappa*dt/gridCart.getVolume(owners[0])*NormalX/TaucenterX*(-gridCart.getArea(inter)/deltaCenter + TaucenterY/TautbY*(interpb[0]-interpt[0]));
value01 = - kappa*dt/gridCart.getVolume(owners[0])*NormalX/TaucenterX*(gridCart.getArea(inter)/deltaCenter + TaucenterY/TautbY*(interpb[1]-interpt[1]));
value10 = - kappa*dt/gridCart.getVolume(OctOwner)*NormalX/TaucenterX*(gridCart.getArea(inter)/deltaCenter - TaucenterY/TautbY*(interpb[0]-interpt[0]));
value11 = - kappa*dt/gridCart.getVolume(OctOwner)*NormalX/TaucenterX*(-gridCart.getArea(inter)/deltaCenter - TaucenterY/TautbY*(interpb[1]-interpt[1]));
}
else {
value00 = - kappa*dt/gridCart.getVolume(owners[0])*NormalY/TaucenterY*(-gridCart.getArea(inter)/deltaCenter + TaucenterX/TautbX*(interpb[0]-interpt[0]));
value01 = - kappa*dt/gridCart.getVolume(owners[0])*NormalY/TaucenterY*(gridCart.getArea(inter)/deltaCenter + TaucenterX/TautbX*(interpb[1]-interpt[1]));
value10 = - kappa*dt/gridCart.getVolume(OctOwner)*NormalY/TaucenterY*(gridCart.getArea(inter)/deltaCenter - TaucenterX/TautbX*(interpb[0]-interpt[0]));
value11 = - kappa*dt/gridCart.getVolume(OctOwner)*NormalY/TaucenterY*(-gridCart.getArea(inter)/deltaCenter - TaucenterX/TautbX*(interpb[1]-interpt[1]));
}
}
else {
if (TautbX ==0 ){
value00 = - kappa*dt/gridCart.getVolume(owners[0])*NormalX/TaucenterX*(-gridCart.getArea(inter)/deltaCenter + TaucenterY/TautbY*(interpb[0]-interpt[0]));
value10 = 0;
value01 = - kappa*dt/gridCart.getVolume(owners[0])*NormalX/TaucenterX*(gridCart.getArea(inter)/deltaCenter + TaucenterY/TautbY*(interpb[1]-interpt[1]));
value11= 0;
}
else {
value00 = - kappa*dt/gridCart.getVolume(owners[0])*NormalY/TaucenterY*(-gridCart.getArea(inter)/deltaCenter + TaucenterX/TautbX*(interpb[0]-interpt[0]));
value10 = 0;
value01 = - kappa*dt/gridCart.getVolume(owners[0])*NormalY/TaucenterY*(gridCart.getArea(inter)/deltaCenter + TaucenterX/TautbX*(interpb[1]-interpt[1]));
value11 = 0;
}
}
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n1, &value01, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n0, &value10, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n0, &value00, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n1, &value11, ADD_VALUES);
} // end of !bound
else{
if (!gridCart.getIsGhost(inter)){
value00 = kappa*dt/gridCart.getVolume(owners[0])*gridCart.getArea(inter)/deltaCenter;
value11 = kappa*dt/gridCart.getVolume(OctOwner)*gridCart.getArea(inter)/deltaCenter;
value01 = -kappa*dt/gridCart.getVolume(owners[0])*gridCart.getArea(inter)/deltaCenter;
value10 = -kappa*dt/gridCart.getVolume(OctOwner)*gridCart.getArea(inter)/deltaCenter;
}
else {
value00 = kappa*dt/gridCart.getVolume(owners[0])*gridCart.getArea(inter)/deltaCenter;
value11 = 0;
value01 = -kappa*dt/gridCart.getVolume(owners[0])*gridCart.getArea(inter)/deltaCenter;
value10 = 0;
}
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n1, &value01, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n0, &value10, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n0, 1, &g_n0, &value00, ADD_VALUES);
MatSetValues(Mat_poisson, 1, &g_n1, 1, &g_n1, &value11, ADD_VALUES);
}
} // end of level difference
} // end of !boundary
} // end of intersection loop
for (int j = 0; j < gridCart.getNumOctants(); ++j){
if ( sqrt(pow(gridCart.getCenter(j)[0],2)+ pow(gridCart.getCenter(j)[1],2)) <= m_radius )
m_pen=1;
else
m_pen =0;
// Find Global index
int g_j=gridCart.getGlobalIdx(j);
value00= 1+m_pen*m_lambda*dt;
MatSetValues(Mat_poisson, 1, &g_j, 1, &g_j, &value00, ADD_VALUES);
}
MatAssemblyBegin(Mat_poisson,MAT_FINAL_ASSEMBLY);
MatAssemblyEnd(Mat_poisson,MAT_FINAL_ASSEMBLY);
//MatView(Mat_poisson, PETSC_VIEWER_STDOUT_WORLD);
};
vector<int> HeatEq::getNeighbours(PabloUniform& gridCart,int i){
vector<int> result(6,0);
vector<uint32_t> owners(2,0);
bool finer=gridCart.getFiner(gridCart.getIntersection(i));
int int_owner=0;
if (finer) int_owner=1;
owners=gridCart.getOwners(gridCart.getIntersection(i));
result[0]=owners[0+int_owner];
result[1]=owners[1-int_owner];
if (gridCart.getIsGhost(gridCart.getIntersection(i)))
{
if (finer){
result[0]=-1;
result[1]=owners[0];
}
else{
result[1]=-1;
result[0]=owners[0];
}
result[2]=owners[0+int_owner]*int_owner;
result[3]=owners[1-int_owner]*(1-int_owner);
result[4]=int_owner;
result[5]=1-int_owner;
}
if (owners[0]==owners[1] && !gridCart.getIsGhost(gridCart.getIntersection(i)))
{
if (finer)
{
result[0]=owners[1];
result[1]=-1;
}
else{
result[0]=owners[0];
result[1]=-1;
}
}
return result;
};
vector<double> HeatEq::interp4p(PabloUniform& gridCart, darray3 nodes, int owner, Octant*& Oct1, Octant*& Oct2, Octant*& Oct3){
vector<double> value(4,0);
double x0, y0, x1, y1, x2, y2, x3, y3;
double intermed1, xdif, ydif, xydif, intermed2, intermed3, intermed4;
double long1, long2, long3, long4, long5, long6, long7, long8, long9, long10, long11, long12, long13, long14;
x0=gridCart.getCenter(owner)[0]; y0=gridCart.getCenter(owner)[1];
x1=gridCart.getCenter(Oct1)[0]; y1=gridCart.getCenter(Oct1)[1];
x2=gridCart.getCenter(Oct2)[0]; y2=gridCart.getCenter(Oct2)[1];
x3=gridCart.getCenter(Oct3)[0]; y3=gridCart.getCenter(Oct3)[1];
xdif = x0-x1; ydif = y0-y1; xydif = x0*y0-x1*y1;
intermed1 = (x1-x2)/(x0-x1); intermed2 = intermed1*(y0-y1)-(y1-y2);
intermed3 = x1*y1-x2*y2-(x1-x2)/(x0-x1)*xydif; intermed4 = (x2-x3)/intermed3*xydif/xdif-(x2*y2-x3*y3)/intermed3;
long1 = ydif/xdif*(x2-x3) + (x2-x3)/intermed3*intermed2*xydif/xdif - (y2-y3) - (x2*y2-x3*y3)/intermed3*intermed2;
long2 = (x2-x3)/xdif - (x2*y2-x3*y3)/intermed3*intermed1 + (x2-x3)/intermed3*intermed1*xydif/xdif;
long3 = (x2*y2-x3*y3)/intermed3*(1+intermed1) - (x2-x3)/xdif - (x2-x3)/intermed3*(1+intermed1)*xydif/xdif;
long4 = intermed2/long1*long2 - intermed1; long5 = intermed2/long1*long3 + 1+intermed1; long6 = intermed2/long1*(intermed4-1) - 1;
long7 = 1 - ydif/long1*long2 - xydif/intermed3*long4; long8 = -1 - ydif/long1*long3 - xydif/intermed3*long5;
long9 = -ydif/long1*(intermed4-1) - xydif/intermed3*long6; long10 = -ydif/long1 - xydif/intermed3*intermed2/long1;
long11 = 1 - x0/xdif*long7 - y0/long1*long2 - x0*y0/intermed3*long4; long12 = -x0/xdif*long8 - y0/long1*long3 - x0*y0/intermed3*long5;
long13 = -x0/xdif*long9 - y0/long1*(intermed4-1) - x0*y0/intermed3*long6; long14 = -x0/xdif*long10 - y0/long1 - x0*y0/intermed3*intermed2/long1;
value[0] = long11 + nodes[0]/xdif*long7 + nodes[1]/long1*long2 + nodes[0]*nodes[1]/intermed3*long4;
value[1] = long12 + nodes[0]/xdif*long8 + nodes[1]/long1*long3 + nodes[0]*nodes[1]/intermed3*long5;
value[2] = long13 + nodes[0]/xdif*long9 + nodes[1]/long1*(intermed4-1) + nodes[0]*nodes[1]/intermed3*long6;
value[3] = long14 + nodes[0]/xdif*long10 + nodes[1]/long1 + nodes[0]*nodes[1]/intermed3*intermed2/long1;
return value;
};
vector<double> HeatEq::interp3p(PabloUniform& gridCart, darray3 nodes, int owner, Octant*& Oct1, Octant*& Oct2){
vector<double> value(3,0);
double x0, y0, x1, y1, x2, y2;
double intermed1, xdif, ydif, intermed2;
x0=gridCart.getCenter(owner)[0]; y0=gridCart.getCenter(owner)[1];
x1=gridCart.getCenter(Oct1)[0]; y1=gridCart.getCenter(Oct1)[1];
x2=gridCart.getCenter(Oct2)[0]; y2=gridCart.getCenter(Oct2)[1];
xdif=x0-x1; ydif=y0-y1;
intermed1=(x1-x2)/(x0-x1); intermed2=intermed1*(y0-y1)-(y1-y2);
value[0] = 1 - x0/xdif + (x0*ydif)/(xdif*intermed2)*intermed1 - y0/intermed2*intermed1 + nodes[0]/xdif*(1-intermed1/intermed2*ydif) + nodes[1]/intermed2*intermed1;
value[1] = x0/xdif + (x0*ydif)/(xdif*intermed2)*(-1-intermed1) + y0/intermed2*(1+intermed1) + nodes[0]/xdif*((1+intermed1)/intermed2*ydif-1) + nodes[1]/intermed2*(-1-intermed1);
value[2] = (x0*ydif)/(xdif*intermed2) - y0/intermed2 - nodes[0]/xdif*ydif/intermed2 + nodes[1]/intermed2;
return value;
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.