text stringlengths 54 60.6k |
|---|
<commit_before>// STL
#include <iostream>
#include <string>
// CppUnit
#include <extracppunit/CppUnitCore.hpp>
// StdAir
#include <stdair/STDAIR_Types.hpp>
#include <stdair/bom/BomRootKey.hpp>
#include <stdair/bom/InventoryKey.hpp>
#include <stdair/bom/FlightDateKey.hpp>
#include <stdair/bom/SegmentDateKey.hpp>
#include <stdair/bom/LegDateKey.hpp>
#include <stdair/bom/SegmentCabinKey.hpp>
#include <stdair/bom/LegCabinKey.hpp>
#include <stdair/bom/BookingClassKey.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/bom/FlightDate.hpp>
#include <stdair/bom/SegmentDate.hpp>
#include <stdair/bom/LegDate.hpp>
#include <stdair/bom/SegmentCabin.hpp>
#include <stdair/bom/LegCabin.hpp>
#include <stdair/bom/BookingClass.hpp>
#include <stdair/bom/Network.hpp>
#include <stdair/bom/BomList.hpp>
#include <stdair/bom/BomMap.hpp>
#include <stdair/bom/AirlineFeatureSet.hpp>
#include <stdair/bom/AirlineFeature.hpp>
#include <stdair/factory/FacBomContent.hpp>
#include <stdair/factory/FacSupervisor.hpp>
#include <stdair/service/Logger.hpp>
// AirSched
#include <airsched/factory/FacSupervisor.hpp>
#include <airsched/command/Simulator.hpp>
#include <airsched/AIRSCHED_Service.hpp>
// AirSched Test Suite
#include <test/airsched/AirlineScheduleTestSuite.hpp>
// //////////////////////////////////////////////////////////////////////
void externalMemoryManagementHelper() {
/**
The standard initialisation requires an (CSV) input file to be given.
The initialisation then parses that file and builds the corresponding
inventories.
<br><br>
So, though inventories are already built by the initialisation process,
another one is built from scratch, in order to test the stdair object
construction with a fine granularity.
*/
try {
// Input file name
std::string lInputFilename ("../samples/schedule02.csv");
// Output log File
std::string lLogFilename ("AirlineScheduleTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Initialise the set of required airline features
stdair::AirlineFeatureSet& lAirlineFeatureSet =
stdair::FacBomContent::instance().create<stdair::AirlineFeatureSet>();
// Initialise an AirlineFeature object
const stdair::AirlineCode_T lAirlineCode ("BA");
stdair::AirlineFeatureKey_T lAirlineFeatureKey (lAirlineCode);
stdair::AirlineFeature& lAirlineFeature = stdair::FacBomContent::
instance().create<stdair::AirlineFeature> (lAirlineFeatureKey);
stdair::FacBomContent::
linkWithParent<stdair::AirlineFeature> (lAirlineFeature,
lAirlineFeatureSet);
// The analysis starts at January 1, 2000
const stdair::Date_T lStartAnalysisDate (2000, 1, 1);
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
AIRSCHED::AIRSCHED_Service airschedService (lLogParams,
lAirlineFeatureSet,
lStartAnalysisDate,
lInputFilename);
// DEBUG
STDAIR_LOG_DEBUG ("Welcome to Air-Schedule");
// Step 0.0: initialisation
// Create the root of the Bom tree (i.e., a BomRoot object)
stdair::BomRoot& lBomRoot =
stdair::FacBomContent::instance().create<stdair::BomRoot>();
// Step 0.1: Inventory level
// Create an Inventory (BA)
stdair::InventoryKey_T lInventoryKey (lAirlineCode);
stdair::Inventory& lInventory =
stdair::FacBomContent::instance().create<stdair::Inventory>(lInventoryKey);
stdair::FacBomContent::linkWithParent<stdair::Inventory> (lInventory,
lBomRoot);
// Display the inventory
STDAIR_LOG_DEBUG ("Inventory: " << lInventory.toString());
// Step 0.2: Flight-date level
// Create a FlightDate (BA15/10-JUN-2010)
const stdair::FlightNumber_T lFlightNumber = 15;
const stdair::Date_T lDate (2010, 6, 10);
stdair::FlightDateKey_T lFlightDateKey (lFlightNumber, lDate);
stdair::FlightDate& lFlightDate = stdair::FacBomContent::
instance().create<stdair::FlightDate> (lFlightDateKey);
stdair::FacBomContent::linkWithParent<stdair::FlightDate> (lFlightDate,
lInventory);
// Display the flight-date
STDAIR_LOG_DEBUG ("FlightDate: " << lFlightDate.toString());
// Step 0.3: Segment-date level
// Create a first SegmentDate (LHR-SYD)
const stdair::AirportCode_T lLHR ("LHR");
const stdair::AirportCode_T lSYD ("SYD");
stdair::SegmentDateKey_T lSegmentDateKey (lLHR, lSYD);
stdair::SegmentDate& lLHRSYDSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lLHRSYDSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRSYDSegment.toString());
// Create a second SegmentDate (LHR-BKK)
const stdair::AirportCode_T lBKK ("BKK");
lSegmentDateKey = stdair::SegmentDateKey_T (lLHR, lBKK);
stdair::SegmentDate& lLHRBKKSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lLHRBKKSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRBKKSegment.toString());
// Create a third SegmentDate (BKK-SYD)
lSegmentDateKey = stdair::SegmentDateKey_T (lBKK, lSYD);
stdair::SegmentDate& lBKKSYDSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lBKKSYDSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lBKKSYDSegment.toString());
// Step 0.4: Leg-date level
// Create a first LegDate (LHR)
stdair::LegDateKey_T lLegDateKey (lLHR);
stdair::LegDate& lLHRLeg =
stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
stdair::FacBomContent::linkWithParent<stdair::LegDate>(lLHRLeg, lFlightDate);
// Display the leg-date
STDAIR_LOG_DEBUG ("LegDate: " << lLHRLeg.toString());
// Create a second LegDate (BKK)
lLegDateKey = stdair::LegDateKey_T (lBKK);
stdair::LegDate& lBKKLeg =
stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
stdair::FacBomContent::linkWithParent<stdair::LegDate>(lBKKLeg, lFlightDate);
// Display the leg-date
STDAIR_LOG_DEBUG ("LegDate: " << lBKKLeg.toString());
// Step 0.5: segment-cabin level
// Create a SegmentCabin (Y) of the Segment LHR-BKK;
const stdair::CabinCode_T lY ("Y");
stdair::SegmentCabinKey_T lYSegmentCabinKey (lY);
stdair::SegmentCabin& lLHRBKKSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lLHRBKKSegmentYCabin,lLHRBKKSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRBKKSegmentYCabin.toString());
// Create a SegmentCabin (Y) of the Segment BKK-SYD;
stdair::SegmentCabin& lBKKSYDSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lBKKSYDSegmentYCabin,lBKKSYDSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lBKKSYDSegmentYCabin.toString());
// Create a SegmentCabin (Y) of the Segment LHR-SYD;
stdair::SegmentCabin& lLHRSYDSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lLHRSYDSegmentYCabin,lLHRSYDSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRSYDSegmentYCabin.toString());
// Step 0.6: leg-cabin level
// Create a LegCabin (Y) of the Leg LHR-BKK;
stdair::LegCabinKey_T lYLegCabinKey (lY);
stdair::LegCabin& lLHRLegYCabin =
stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
stdair::FacBomContent::linkWithParent<stdair::LegCabin> (lLHRLegYCabin,
lLHRLeg);
// Display the leg-cabin
STDAIR_LOG_DEBUG ("LegCabin: " << lLHRLegYCabin.toString());
// Create a LegCabin (Y) of the Leg BKK-SYD;
stdair::LegCabin& lBKKLegYCabin =
stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
stdair::FacBomContent::linkWithParent<stdair::LegCabin> (lBKKLegYCabin,
lBKKLeg);
// Display the leg-cabin
STDAIR_LOG_DEBUG ("LegCabin: " << lBKKLegYCabin.toString());
// Step 0.7: booking class level
// Create a BookingClass (Q) of the Segment LHR-BKK, cabin Y;
const stdair::ClassCode_T lQ ("Q");
stdair::BookingClassKey_T lQBookingClassKey (lQ);
stdair::BookingClass& lLHRBKKSegmentYCabinQClass =
stdair::FacBomContent::
instance().create<stdair::BookingClass> (lQBookingClassKey);
stdair::FacBomContent::
linkWithParent<stdair::BookingClass> (lLHRBKKSegmentYCabinQClass,
lLHRBKKSegmentYCabin);
// Display the booking class
STDAIR_LOG_DEBUG ("BookingClass: "
<< lLHRBKKSegmentYCabinQClass.toString());
// Browse the BomRoot and display the created objects.
STDAIR_LOG_DEBUG ("Browse the BomRoot");
const stdair::InventoryList_T& lInventoryList = lBomRoot.getInventoryList();
for (stdair::InventoryList_T::iterator itInv = lInventoryList.begin();
itInv != lInventoryList.end(); ++itInv) {
const stdair::Inventory& lCurrentInventory = *itInv;
STDAIR_LOG_DEBUG ("Inventory: " << lCurrentInventory.toString());
}
// Close the Log outputFile
logOutputFile.close();
// Clean the memory.
// stdair::FacSupervisor::instance().cleanBomContentLayer();
// stdair::FacSupervisor::instance().cleanBomStructureLayer();
// AIRSCHED::FacSupervisor::instance().cleanServiceLayer();
// AIRSCHED::FacSupervisor::instance().cleanLoggerService();
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void AirlineScheduleTestSuite::externalMemoryManagement() {
CPPUNIT_ASSERT_NO_THROW (externalMemoryManagementHelper(););
}
// //////////////////////////////////////////////////////////////////////
void scheduleParsingHelper() {
try {
// DEBUG
STDAIR_LOG_DEBUG ("Schedule Parsing Test");
// Output log File
std::string lLogFilename ("AirlineScheduleTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Input file name
std::string lInputFilename ("../samples/schedule02.csv");
// Create a dummy AirlineFeature object for the test.
stdair::AirlineFeatureSet& lAirlineFeatureSet =
stdair::FacBomContent::instance().create<stdair::AirlineFeatureSet>();
const stdair::AirlineCode_T lAirlineCode ("BA");
stdair::AirlineFeatureKey_T lAirlineFeatureKey (lAirlineCode);
stdair::AirlineFeature& lAirlineFeature = stdair::FacBomContent::
instance().create<stdair::AirlineFeature> (lAirlineFeatureKey);
stdair::FacBomContent::
linkWithParent<stdair::AirlineFeature> (lAirlineFeature,
lAirlineFeatureSet);
const stdair::Date_T lStartAnalysisDate (2000, 1, 1);
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
AIRSCHED::AIRSCHED_Service airschedService (lLogParams,
lAirlineFeatureSet,
lStartAnalysisDate,
lInputFilename);
// Start a mini-simulation
airschedService.simulate();
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void AirlineScheduleTestSuite::scheduleParsing() {
CPPUNIT_ASSERT_NO_THROW (scheduleParsingHelper(););
}
// //////////////////////////////////////////////////////////////////////
AirlineScheduleTestSuite::AirlineScheduleTestSuite () {
_describeKey << "Running test on AIRSCHED Optimisation function";
}
// /////////////// M A I N /////////////////
CPPUNIT_MAIN()
<commit_msg>1. Integrated more initialisation procedures within the STDAIR_Service object. 2. Added a sample stdair::DBManagerForAirlines class.<commit_after>// STL
#include <iostream>
#include <string>
// CppUnit
#include <extracppunit/CppUnitCore.hpp>
// StdAir
#include <stdair/STDAIR_Types.hpp>
#include <stdair/bom/BomRootKey.hpp>
#include <stdair/bom/InventoryKey.hpp>
#include <stdair/bom/FlightDateKey.hpp>
#include <stdair/bom/SegmentDateKey.hpp>
#include <stdair/bom/LegDateKey.hpp>
#include <stdair/bom/SegmentCabinKey.hpp>
#include <stdair/bom/LegCabinKey.hpp>
#include <stdair/bom/BookingClassKey.hpp>
#include <stdair/bom/BomRoot.hpp>
#include <stdair/bom/Inventory.hpp>
#include <stdair/bom/FlightDate.hpp>
#include <stdair/bom/SegmentDate.hpp>
#include <stdair/bom/LegDate.hpp>
#include <stdair/bom/SegmentCabin.hpp>
#include <stdair/bom/LegCabin.hpp>
#include <stdair/bom/BookingClass.hpp>
#include <stdair/bom/Network.hpp>
#include <stdair/bom/BomList.hpp>
#include <stdair/bom/BomMap.hpp>
#include <stdair/factory/FacBomContent.hpp>
#include <stdair/factory/FacSupervisor.hpp>
#include <stdair/service/Logger.hpp>
// AirSched
#include <airsched/factory/FacSupervisor.hpp>
#include <airsched/command/Simulator.hpp>
#include <airsched/AIRSCHED_Service.hpp>
// AirSched Test Suite
#include <test/airsched/AirlineScheduleTestSuite.hpp>
// //////////////////////////////////////////////////////////////////////
void externalMemoryManagementHelper() {
/**
The standard initialisation requires an (CSV) input file to be given.
The initialisation then parses that file and builds the corresponding
inventories.
<br><br>
So, though inventories are already built by the initialisation process,
another one is built from scratch, in order to test the stdair object
construction with a fine granularity.
*/
try {
// Input file name
std::string lInputFilename ("../samples/schedule02.csv");
// Output log File
std::string lLogFilename ("AirlineScheduleTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// The analysis starts at January 1, 2000
const stdair::Date_T lStartAnalysisDate (2000, 1, 1);
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
AIRSCHED::AIRSCHED_Service airschedService (lLogParams, lStartAnalysisDate,
lInputFilename);
// DEBUG
STDAIR_LOG_DEBUG ("Welcome to Air-Schedule");
// Step 0.0: initialisation
// Create the root of the Bom tree (i.e., a BomRoot object)
stdair::BomRoot& lBomRoot =
stdair::FacBomContent::instance().create<stdair::BomRoot>();
// Step 0.1: Inventory level
// Create an Inventory (BA)
const stdair::AirlineCode_T lAirlineCode ("BA");
stdair::InventoryKey_T lInventoryKey (lAirlineCode);
stdair::Inventory& lInventory =
stdair::FacBomContent::instance().create<stdair::Inventory>(lInventoryKey);
stdair::FacBomContent::linkWithParent<stdair::Inventory> (lInventory,
lBomRoot);
// Display the inventory
STDAIR_LOG_DEBUG ("Inventory: " << lInventory.toString());
// Step 0.2: Flight-date level
// Create a FlightDate (BA15/10-JUN-2010)
const stdair::FlightNumber_T lFlightNumber = 15;
const stdair::Date_T lDate (2010, 6, 10);
stdair::FlightDateKey_T lFlightDateKey (lFlightNumber, lDate);
stdair::FlightDate& lFlightDate = stdair::FacBomContent::
instance().create<stdair::FlightDate> (lFlightDateKey);
stdair::FacBomContent::linkWithParent<stdair::FlightDate> (lFlightDate,
lInventory);
// Display the flight-date
STDAIR_LOG_DEBUG ("FlightDate: " << lFlightDate.toString());
// Step 0.3: Segment-date level
// Create a first SegmentDate (LHR-SYD)
const stdair::AirportCode_T lLHR ("LHR");
const stdair::AirportCode_T lSYD ("SYD");
stdair::SegmentDateKey_T lSegmentDateKey (lLHR, lSYD);
stdair::SegmentDate& lLHRSYDSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lLHRSYDSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRSYDSegment.toString());
// Create a second SegmentDate (LHR-BKK)
const stdair::AirportCode_T lBKK ("BKK");
lSegmentDateKey = stdair::SegmentDateKey_T (lLHR, lBKK);
stdair::SegmentDate& lLHRBKKSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lLHRBKKSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lLHRBKKSegment.toString());
// Create a third SegmentDate (BKK-SYD)
lSegmentDateKey = stdair::SegmentDateKey_T (lBKK, lSYD);
stdair::SegmentDate& lBKKSYDSegment =
stdair::FacBomContent::
instance().create<stdair::SegmentDate> (lSegmentDateKey);
stdair::FacBomContent::linkWithParent<stdair::SegmentDate> (lBKKSYDSegment,
lFlightDate);
// Display the segment-date
STDAIR_LOG_DEBUG ("SegmentDate: " << lBKKSYDSegment.toString());
// Step 0.4: Leg-date level
// Create a first LegDate (LHR)
stdair::LegDateKey_T lLegDateKey (lLHR);
stdair::LegDate& lLHRLeg =
stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
stdair::FacBomContent::linkWithParent<stdair::LegDate>(lLHRLeg, lFlightDate);
// Display the leg-date
STDAIR_LOG_DEBUG ("LegDate: " << lLHRLeg.toString());
// Create a second LegDate (BKK)
lLegDateKey = stdair::LegDateKey_T (lBKK);
stdair::LegDate& lBKKLeg =
stdair::FacBomContent::instance().create<stdair::LegDate> (lLegDateKey);
stdair::FacBomContent::linkWithParent<stdair::LegDate>(lBKKLeg, lFlightDate);
// Display the leg-date
STDAIR_LOG_DEBUG ("LegDate: " << lBKKLeg.toString());
// Step 0.5: segment-cabin level
// Create a SegmentCabin (Y) of the Segment LHR-BKK;
const stdair::CabinCode_T lY ("Y");
stdair::SegmentCabinKey_T lYSegmentCabinKey (lY);
stdair::SegmentCabin& lLHRBKKSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lLHRBKKSegmentYCabin,lLHRBKKSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRBKKSegmentYCabin.toString());
// Create a SegmentCabin (Y) of the Segment BKK-SYD;
stdair::SegmentCabin& lBKKSYDSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lBKKSYDSegmentYCabin,lBKKSYDSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lBKKSYDSegmentYCabin.toString());
// Create a SegmentCabin (Y) of the Segment LHR-SYD;
stdair::SegmentCabin& lLHRSYDSegmentYCabin =
stdair::FacBomContent::
instance().create<stdair::SegmentCabin> (lYSegmentCabinKey);
stdair::FacBomContent::
linkWithParent<stdair::SegmentCabin> (lLHRSYDSegmentYCabin,lLHRSYDSegment);
// Display the segment-cabin
STDAIR_LOG_DEBUG ("SegmentCabin: " << lLHRSYDSegmentYCabin.toString());
// Step 0.6: leg-cabin level
// Create a LegCabin (Y) of the Leg LHR-BKK;
stdair::LegCabinKey_T lYLegCabinKey (lY);
stdair::LegCabin& lLHRLegYCabin =
stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
stdair::FacBomContent::linkWithParent<stdair::LegCabin> (lLHRLegYCabin,
lLHRLeg);
// Display the leg-cabin
STDAIR_LOG_DEBUG ("LegCabin: " << lLHRLegYCabin.toString());
// Create a LegCabin (Y) of the Leg BKK-SYD;
stdair::LegCabin& lBKKLegYCabin =
stdair::FacBomContent::instance().create<stdair::LegCabin> (lYLegCabinKey);
stdair::FacBomContent::linkWithParent<stdair::LegCabin> (lBKKLegYCabin,
lBKKLeg);
// Display the leg-cabin
STDAIR_LOG_DEBUG ("LegCabin: " << lBKKLegYCabin.toString());
// Step 0.7: booking class level
// Create a BookingClass (Q) of the Segment LHR-BKK, cabin Y;
const stdair::ClassCode_T lQ ("Q");
stdair::BookingClassKey_T lQBookingClassKey (lQ);
stdair::BookingClass& lLHRBKKSegmentYCabinQClass =
stdair::FacBomContent::
instance().create<stdair::BookingClass> (lQBookingClassKey);
stdair::FacBomContent::
linkWithParent<stdair::BookingClass> (lLHRBKKSegmentYCabinQClass,
lLHRBKKSegmentYCabin);
// Display the booking class
STDAIR_LOG_DEBUG ("BookingClass: "
<< lLHRBKKSegmentYCabinQClass.toString());
// Browse the BomRoot and display the created objects.
STDAIR_LOG_DEBUG ("Browse the BomRoot");
const stdair::InventoryList_T& lInventoryList = lBomRoot.getInventoryList();
for (stdair::InventoryList_T::iterator itInv = lInventoryList.begin();
itInv != lInventoryList.end(); ++itInv) {
const stdair::Inventory& lCurrentInventory = *itInv;
STDAIR_LOG_DEBUG ("Inventory: " << lCurrentInventory.toString());
}
// Close the Log outputFile
logOutputFile.close();
// Clean the memory.
// stdair::FacSupervisor::instance().cleanBomContentLayer();
// stdair::FacSupervisor::instance().cleanBomStructureLayer();
// AIRSCHED::FacSupervisor::instance().cleanServiceLayer();
// AIRSCHED::FacSupervisor::instance().cleanLoggerService();
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void AirlineScheduleTestSuite::externalMemoryManagement() {
CPPUNIT_ASSERT_NO_THROW (externalMemoryManagementHelper(););
}
// //////////////////////////////////////////////////////////////////////
void scheduleParsingHelper() {
try {
// DEBUG
STDAIR_LOG_DEBUG ("Schedule Parsing Test");
// Output log File
std::string lLogFilename ("AirlineScheduleTestSuite.log");
// Set the log parameters
std::ofstream logOutputFile;
// open and clean the log outputfile
logOutputFile.open (lLogFilename.c_str());
logOutputFile.clear();
// Input file name
std::string lInputFilename ("../samples/schedule02.csv");
const stdair::Date_T lStartAnalysisDate (2000, 1, 1);
const stdair::BasLogParams lLogParams (stdair::LOG::DEBUG, logOutputFile);
AIRSCHED::AIRSCHED_Service airschedService (lLogParams, lStartAnalysisDate,
lInputFilename);
// Start a mini-simulation
airschedService.simulate();
} catch (const std::exception& stde) {
std::cerr << "Standard exception: " << stde.what() << std::endl;
} catch (...) {
std::cerr << "Unknown exception" << std::endl;
}
}
// //////////////////////////////////////////////////////////////////////
void AirlineScheduleTestSuite::scheduleParsing() {
CPPUNIT_ASSERT_NO_THROW (scheduleParsingHelper(););
}
// //////////////////////////////////////////////////////////////////////
AirlineScheduleTestSuite::AirlineScheduleTestSuite () {
_describeKey << "Running test on AIRSCHED Optimisation function";
}
// /////////////// M A I N /////////////////
CPPUNIT_MAIN()
<|endoftext|> |
<commit_before>#include <stdio.h>
#include "ds3.h"
#include "test.h"
#include <boost/test/unit_test.hpp>
#include <glib.h>
BOOST_AUTO_TEST_CASE( bulk_put ) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "unit_test_bucket";
uint64_t num_objs;
printf("-----Testing Bulk PUT-------\n");
populate_with_objects(client, bucket_name);
request = ds3_init_get_bucket(bucket_name);
error = ds3_get_bucket(client, request, &response);
ds3_free_request(request);
num_objs = response->num_objects;
BOOST_CHECK(error == NULL);
BOOST_CHECK_EQUAL(num_objs, 5);
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/beowulf.txt"));
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE( prefix ) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "unit_test_bucket";
uint64_t num_objs;
printf("-----Testing Prefix-------\n");
populate_with_objects(client, bucket_name);
request = ds3_init_get_bucket(bucket_name);
ds3_request_set_prefix(request, "resources/beo");
error = ds3_get_bucket(client, request, &response);
ds3_free_request(request);
BOOST_CHECK(error == NULL);
num_objs = response->num_objects;
BOOST_CHECK_EQUAL(num_objs, 1);
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/beowulf.txt"));
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE( delimiter ) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "unit_test_bucket";
uint64_t num_objs;
printf("-----Testing Delimiter-------\n");
populate_with_objects(client, bucket_name);
request = ds3_init_get_bucket(bucket_name);
ds3_request_set_delimiter(request, "/");
error = ds3_get_bucket(client, request, &response);
ds3_free_request(request);
BOOST_CHECK(error == NULL);
num_objs = response->num_objects;
BOOST_CHECK_EQUAL(num_objs, 0);
BOOST_CHECK_EQUAL(response->num_common_prefixes, 1);
BOOST_CHECK_EQUAL(strcmp(response->common_prefixes[0]->value, "resources/"), 0);
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE(marker) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "bucket_test_marker";
uint64_t num_objs;
printf("-----Testing Marker-------\n");
populate_with_objects(client,bucket_name);
request = ds3_init_get_bucket(bucket_name);
ds3_request_set_marker(request,"resources/sherlock_holmes.txt");
error = ds3_get_bucket(client,request,&response);
ds3_free_request(request);
handle_error(error);
num_objs = response->num_objects;
BOOST_CHECK_EQUAL(num_objs, 3);
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/tale_of_two_cities.txt"));
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/ulysses.txt"));
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/ulysses_large.txt"));
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE(max_keys) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "bucket_test_max_keys";
uint64_t num_objs;
printf("-----Testing Max-Keys-------\n");
populate_with_objects(client,bucket_name);
request = ds3_init_get_bucket(bucket_name);
ds3_request_set_max_keys(request,2);
error = ds3_get_bucket(client,request,&response);
ds3_free_request(request);
handle_error(error);
num_objs = response->num_objects;
BOOST_CHECK_EQUAL(num_objs, 2);
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/beowulf.txt"));
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/sherlock_holmes.txt"));
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
//testing get_bucket with bucket_name/ with trailing slash
BOOST_AUTO_TEST_CASE( put_bucket_bucket_name_with_trailing_slash){
printf("-----Testing get_bucket with bucket_name/ with trailing slash-------\n");
ds3_client* client = get_client();
const char* bucket_name = "trailing_slash/";
ds3_request* request = ds3_init_put_bucket(bucket_name);
ds3_error* error = ds3_put_bucket(client, request);
ds3_free_request(request);
BOOST_CHECK(error == NULL);
handle_error(error);
request = ds3_init_get_bucket(bucket_name);
ds3_get_bucket_response* response;
error = ds3_get_bucket(client, request, &response);
ds3_free_request(request);
BOOST_CHECK(error == NULL);
BOOST_CHECK_EQUAL( g_strcmp0(response->name->value, "trailing_slash"), 0);
ds3_free_bucket_response(response);
handle_error(error);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE(md5_checksum) {
uint64_t i, n, checksums;
const char* bucket_name = "bucket_test_md5";
ds3_request* request;
const char* books[] ={"resources/beowulf.txt"};
ds3_client* client = get_client();
ds3_error* error;
ds3_bulk_object_list* obj_list;
ds3_bulk_response* response;
ds3_allocate_chunk_response* chunk_response;
printf("-----Testing Checksums-------\n");
obj_list = ds3_convert_file_list(books, 1);
for (checksums = 0; checksums < 5; checksums ++) {
request = ds3_init_put_bucket(bucket_name);
error = ds3_put_bucket(client, request);
ds3_free_request(request);
handle_error(error);
request = ds3_init_put_bulk(bucket_name, obj_list);
error = ds3_bulk(client, request, &response);
ds3_free_request(request);
handle_error(error);
for (n = 0; n < response->list_size; n ++) {
request = ds3_init_allocate_chunk(response->list[n]->chunk_id->value);
error = ds3_allocate_chunk(client, request, &chunk_response);
ds3_free_request(request);
handle_error(error);
BOOST_REQUIRE(chunk_response->retry_after == 0);
BOOST_REQUIRE(chunk_response->objects != NULL);
for (i = 0; i < chunk_response->objects->size; i++) {
ds3_bulk_object bulk_object = chunk_response->objects->list[i];
FILE* file = fopen(bulk_object.name->value, "r");
request = ds3_init_put_object_for_job(bucket_name, bulk_object.name->value, bulk_object.offset, bulk_object.length, response->job_id->value);
switch(checksums) {
case 0:
ds3_request_set_md5(request,"rCu751L6xhB5zyL+soa3fg==");
break;
case 1:
ds3_request_set_sha256(request,"SbLeE3Wb46VCj1atLhS3FRC/Li87wTGH1ZtYIqOjO+E=");
break;
case 2:
ds3_request_set_sha512(request,"qNLwiDVNQ3YCYs9gjyB2LS5cYHMvKdnLaMveIazkWKROKr03F9i+sV5YEvTBjY6YowRE8Hsqw+iwP9KOKM0Xvw==");
break;
case 3:
ds3_request_set_crc32(request,"bgHSXg==");
break;
case 4:
ds3_request_set_crc32c(request, "+ZBZbQ==");
break;
}
if (bulk_object.offset > 0) {
fseek(file, bulk_object.offset, SEEK_SET);
}
error = ds3_put_object(client, request, file, ds3_read_from_file);
ds3_free_request(request);
fclose(file);
handle_error(error);
}
ds3_free_allocate_chunk_response(chunk_response);
}
ds3_free_bulk_response(response);
clear_bucket(client, bucket_name);
}
ds3_free_bulk_object_list(obj_list);
free_client(client);
}
<commit_msg>fixed missed spelling in test<commit_after>#include <stdio.h>
#include "ds3.h"
#include "test.h"
#include <boost/test/unit_test.hpp>
#include <glib.h>
BOOST_AUTO_TEST_CASE( bulk_put ) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "unit_test_bucket";
uint64_t num_objs;
printf("-----Testing Bulk PUT-------\n");
populate_with_objects(client, bucket_name);
request = ds3_init_get_bucket(bucket_name);
error = ds3_get_bucket(client, request, &response);
ds3_free_request(request);
num_objs = response->num_objects;
BOOST_CHECK(error == NULL);
BOOST_CHECK_EQUAL(num_objs, 5);
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/beowulf.txt"));
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE( prefix ) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "unit_test_bucket";
uint64_t num_objs;
printf("-----Testing Prefix-------\n");
populate_with_objects(client, bucket_name);
request = ds3_init_get_bucket(bucket_name);
ds3_request_set_prefix(request, "resources/beo");
error = ds3_get_bucket(client, request, &response);
ds3_free_request(request);
BOOST_CHECK(error == NULL);
num_objs = response->num_objects;
BOOST_CHECK_EQUAL(num_objs, 1);
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/beowulf.txt"));
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE( delimiter ) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "unit_test_bucket";
uint64_t num_objs;
printf("-----Testing Delimiter-------\n");
populate_with_objects(client, bucket_name);
request = ds3_init_get_bucket(bucket_name);
ds3_request_set_delimiter(request, "/");
error = ds3_get_bucket(client, request, &response);
ds3_free_request(request);
BOOST_CHECK(error == NULL);
num_objs = response->num_objects;
BOOST_CHECK_EQUAL(num_objs, 0);
BOOST_CHECK_EQUAL(response->num_common_prefixes, 1);
BOOST_CHECK_EQUAL(strcmp(response->common_prefixes[0]->value, "resources/"), 0);
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE(marker) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "bucket_test_marker";
uint64_t num_objs;
printf("-----Testing Marker-------\n");
populate_with_objects(client,bucket_name);
request = ds3_init_get_bucket(bucket_name);
ds3_request_set_marker(request,"resources/sherlock_holmes.txt");
error = ds3_get_bucket(client,request,&response);
ds3_free_request(request);
handle_error(error);
num_objs = response->num_objects;
BOOST_CHECK_EQUAL(num_objs, 3);
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/tale_of_two_cities.txt"));
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/ulysses.txt"));
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/ulysses_large.txt"));
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE(max_keys) {
ds3_request* request;
ds3_error* error;
ds3_get_bucket_response* response;
ds3_client* client = get_client();
const char* bucket_name = "bucket_test_max_keys";
uint64_t num_objs;
printf("-----Testing Max-Keys-------\n");
populate_with_objects(client,bucket_name);
request = ds3_init_get_bucket(bucket_name);
ds3_request_set_max_keys(request,2);
error = ds3_get_bucket(client,request,&response);
ds3_free_request(request);
handle_error(error);
num_objs = response->num_objects;
BOOST_CHECK_EQUAL(num_objs, 2);
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/beowulf.txt"));
BOOST_CHECK(contains_object(response->objects, num_objs, "resources/sherlock_holmes.txt"));
ds3_free_bucket_response(response);
clear_bucket(client, bucket_name);
free_client(client);
}
//testing get_bucket with bucket_name/ with trailing slash
BOOST_AUTO_TEST_CASE( put_bucket_bucket_name_with_trailing_slash){
printf("-----Testing get_bucket with bucket_name/ with trailing slash-------\n");
ds3_client* client = get_client();
const char* bucket_name = "trailing_slash/";
ds3_request* request = ds3_init_put_bucket(bucket_name);
ds3_error* error = ds3_put_bucket(client, request);
ds3_free_request(request);
BOOST_CHECK(error == NULL);
handle_error(error);
request = ds3_init_get_bucket(bucket_name);
ds3_get_bucket_response* response;
error = ds3_get_bucket(client, request, &response);
ds3_free_request(request);
BOOST_CHECK(error == NULL);
BOOST_CHECK_EQUAL( g_strcmp0(response->name->value, "trailing_slash"), 0);
ds3_free_bucket_response(response);
handle_error(error);
clear_bucket(client, bucket_name);
free_client(client);
}
BOOST_AUTO_TEST_CASE(checksum) {
uint64_t i, n, checksums;
const char* bucket_name = "bucket_test";
ds3_request* request;
const char* books[] ={"resources/beowulf.txt"};
ds3_client* client = get_client();
ds3_error* error;
ds3_bulk_object_list* obj_list;
ds3_bulk_response* response;
ds3_allocate_chunk_response* chunk_response;
printf("-----Testing Checksums-------\n");
obj_list = ds3_convert_file_list(books, 1);
for (checksums = 0; checksums < 5; checksums ++) {
request = ds3_init_put_bucket(bucket_name);
error = ds3_put_bucket(client, request);
ds3_free_request(request);
handle_error(error);
request = ds3_init_put_bulk(bucket_name, obj_list);
error = ds3_bulk(client, request, &response);
ds3_free_request(request);
handle_error(error);
for (n = 0; n < response->list_size; n ++) {
request = ds3_init_allocate_chunk(response->list[n]->chunk_id->value);
error = ds3_allocate_chunk(client, request, &chunk_response);
ds3_free_request(request);
handle_error(error);
BOOST_REQUIRE(chunk_response->retry_after == 0);
BOOST_REQUIRE(chunk_response->objects != NULL);
for (i = 0; i < chunk_response->objects->size; i++) {
ds3_bulk_object bulk_object = chunk_response->objects->list[i];
FILE* file = fopen(bulk_object.name->value, "r");
request = ds3_init_put_object_for_job(bucket_name, bulk_object.name->value, bulk_object.offset, bulk_object.length, response->job_id->value);
switch(checksums) {
case 0:
ds3_request_set_md5(request,"rCu751L6xhB5zyL+soa3fg==");
break;
case 1:
ds3_request_set_sha256(request,"SbLeE3Wb46VCj1atLhS3FRC/Li87wTGH1ZtYIqOjO+E=");
break;
case 2:
ds3_request_set_sha512(request,"qNLwiDVNQ3YCYs9gjyB2LS5cYHMvKdnLaMveIazkWKROKr03F9i+sV5YEvTBjY6YowRE8Hsqw+iwP9KOKM0Xvw==");
break;
case 3:
ds3_request_set_crc32(request,"bgHSXg==");
break;
case 4:
ds3_request_set_crc32c(request, "+ZBZbQ==");
break;
}
if (bulk_object.offset > 0) {
fseek(file, bulk_object.offset, SEEK_SET);
}
error = ds3_put_object(client, request, file, ds3_read_from_file);
ds3_free_request(request);
fclose(file);
handle_error(error);
}
ds3_free_allocate_chunk_response(chunk_response);
}
ds3_free_bulk_response(response);
clear_bucket(client, bucket_name);
}
ds3_free_bulk_object_list(obj_list);
free_client(client);
}
<|endoftext|> |
<commit_before>/* OpenSceneGraph example, osgtexture3D.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture1D>
#include <osg/Texture2D>
#include <osg/Texture3D>
#include <osg/TextureRectangle>
#include <osg/ImageSequence>
#include <osg/Geode>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgViewer/Viewer>
#include <iostream>
//
// A simple demo demonstrating how to set on an animated texture using an osg::ImageSequence
//
osg::StateSet* createState()
{
osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;
imageSequence->setDuration(2.0);
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posx.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negx.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posy.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negy.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posz.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negz.png"));
#if 1
osg::Texture2D* texture = new osg::Texture2D;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
//texture->setUpdateCallback(new osg::ImageSequence::UpdateCallback);
#else
osg::TextureRectangle* texture = new osg::TextureRectangle;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
// texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
//texture->setUpdateCallback(new osg::ImageSequence::UpdateCallback);
#endif
// create the StateSet to store the texture data
osg::StateSet* stateset = new osg::StateSet;
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
return stateset;
}
osg::Node* createModel()
{
// create the geometry of the model, just a simple 2d quad right now.
osg::Geode* geode = new osg::Geode;
geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0.0f,0.0f,0.0), osg::Vec3(1.0f,0.0f,0.0), osg::Vec3(0.0f,0.0f,1.0f)));
geode->setStateSet(createState());
return geode;
}
int main(int argc, char **argv)
{
osg::ArgumentParser arguments(&argc,argv);
// construct the viewer.
osgViewer::Viewer viewer(arguments);
// create a model from the images and pass it to the viewer.
viewer.setSceneData(createModel());
std::string filename;
if (arguments.read("-o",filename))
{
osgDB::writeNodeFile(*viewer.getSceneData(),filename);
}
return viewer.run();
}
<commit_msg>Added event handler to toggling looping and play/pause<commit_after>/* OpenSceneGraph example, osgtexture3D.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <osg/Node>
#include <osg/Geometry>
#include <osg/Notify>
#include <osg/Texture1D>
#include <osg/Texture2D>
#include <osg/Texture3D>
#include <osg/TextureRectangle>
#include <osg/ImageSequence>
#include <osg/Geode>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/WriteFile>
#include <osgViewer/Viewer>
#include <iostream>
//
// A simple demo demonstrating how to set on an animated texture using an osg::ImageSequence
//
osg::StateSet* createState()
{
osg::ref_ptr<osg::ImageSequence> imageSequence = new osg::ImageSequence;
imageSequence->setDuration(2.0);
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posx.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negx.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posy.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negy.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/posz.png"));
imageSequence->addImage(osgDB::readImageFile("Cubemap_axis/negz.png"));
#if 1
osg::Texture2D* texture = new osg::Texture2D;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
//texture->setUpdateCallback(new osg::ImageSequence::UpdateCallback);
#else
osg::TextureRectangle* texture = new osg::TextureRectangle;
texture->setFilter(osg::Texture::MIN_FILTER,osg::Texture::LINEAR);
texture->setFilter(osg::Texture::MAG_FILTER,osg::Texture::LINEAR);
texture->setWrap(osg::Texture::WRAP_R,osg::Texture::REPEAT);
// texture->setResizeNonPowerOfTwoHint(false);
texture->setImage(imageSequence.get());
//texture->setTextureSize(512,512);
//texture->setUpdateCallback(new osg::ImageSequence::UpdateCallback);
#endif
// create the StateSet to store the texture data
osg::StateSet* stateset = new osg::StateSet;
stateset->setTextureAttributeAndModes(0,texture,osg::StateAttribute::ON);
return stateset;
}
osg::Node* createModel()
{
// create the geometry of the model, just a simple 2d quad right now.
osg::Geode* geode = new osg::Geode;
geode->addDrawable(osg::createTexturedQuadGeometry(osg::Vec3(0.0f,0.0f,0.0), osg::Vec3(1.0f,0.0f,0.0), osg::Vec3(0.0f,0.0f,1.0f)));
geode->setStateSet(createState());
return geode;
}
osg::ImageStream* s_imageStream = 0;
class MovieEventHandler : public osgGA::GUIEventHandler
{
public:
MovieEventHandler():_trackMouse(false),_playToggle(true) {}
void setMouseTracking(bool track) { _trackMouse = track; }
bool getMouseTracking() const { return _trackMouse; }
void set(osg::Node* node);
virtual bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv);
virtual void getUsage(osg::ApplicationUsage& usage) const;
typedef std::vector< osg::observer_ptr<osg::ImageStream> > ImageStreamList;
protected:
virtual ~MovieEventHandler() {}
class FindImageStreamsVisitor : public osg::NodeVisitor
{
public:
FindImageStreamsVisitor(ImageStreamList& imageStreamList):
_imageStreamList(imageStreamList) {}
virtual void apply(osg::Geode& geode)
{
apply(geode.getStateSet());
for(unsigned int i=0;i<geode.getNumDrawables();++i)
{
apply(geode.getDrawable(i)->getStateSet());
}
traverse(geode);
}
virtual void apply(osg::Node& node)
{
apply(node.getStateSet());
traverse(node);
}
inline void apply(osg::StateSet* stateset)
{
if (!stateset) return;
osg::StateAttribute* attr = stateset->getTextureAttribute(0,osg::StateAttribute::TEXTURE);
if (attr)
{
osg::Texture2D* texture2D = dynamic_cast<osg::Texture2D*>(attr);
if (texture2D) apply(dynamic_cast<osg::ImageStream*>(texture2D->getImage()));
osg::TextureRectangle* textureRec = dynamic_cast<osg::TextureRectangle*>(attr);
if (textureRec) apply(dynamic_cast<osg::ImageStream*>(textureRec->getImage()));
}
}
inline void apply(osg::ImageStream* imagestream)
{
if (imagestream)
{
_imageStreamList.push_back(imagestream);
s_imageStream = imagestream;
}
}
ImageStreamList& _imageStreamList;
};
bool _playToggle;
bool _trackMouse;
ImageStreamList _imageStreamList;
};
void MovieEventHandler::set(osg::Node* node)
{
_imageStreamList.clear();
if (node)
{
FindImageStreamsVisitor fisv(_imageStreamList);
node->accept(fisv);
}
}
bool MovieEventHandler::handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa, osg::Object*, osg::NodeVisitor* nv)
{
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYDOWN):
{
if (ea.getKey()=='p')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ((*itr)->getStatus()==osg::ImageStream::PLAYING)
{
// playing, so pause
std::cout<<"Pause"<<std::endl;
(*itr)->pause();
}
else
{
// playing, so pause
std::cout<<"Play"<<std::endl;
(*itr)->play();
}
}
return true;
}
else if (ea.getKey()=='r')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
std::cout<<"Restart"<<std::endl;
(*itr)->rewind();
(*itr)->play();
}
return true;
}
else if (ea.getKey()=='L')
{
for(ImageStreamList::iterator itr=_imageStreamList.begin();
itr!=_imageStreamList.end();
++itr)
{
if ( (*itr)->getLoopingMode() == osg::ImageStream::LOOPING)
{
std::cout<<"Toggle Looping Off"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::NO_LOOPING );
}
else
{
std::cout<<"Toggle Looping On"<<std::endl;
(*itr)->setLoopingMode( osg::ImageStream::LOOPING );
}
}
return true;
}
return false;
}
default:
return false;
}
return false;
}
void MovieEventHandler::getUsage(osg::ApplicationUsage& usage) const
{
usage.addKeyboardMouseBinding("p","Play/Pause movie");
usage.addKeyboardMouseBinding("r","Restart movie");
usage.addKeyboardMouseBinding("l","Toggle looping of movie");
}
int main(int argc, char **argv)
{
osg::ArgumentParser arguments(&argc,argv);
// construct the viewer.
osgViewer::Viewer viewer(arguments);
// create a model from the images and pass it to the viewer.
viewer.setSceneData(createModel());
// pass the model to the MovieEventHandler so it can pick out ImageStream's to manipulate.
MovieEventHandler* meh = new MovieEventHandler();
meh->set( viewer.getSceneData() );
viewer.addEventHandler( meh );
std::string filename;
if (arguments.read("-o",filename))
{
osgDB::writeNodeFile(*viewer.getSceneData(),filename);
}
return viewer.run();
}
<|endoftext|> |
<commit_before>//
// file : fnv1a.hpp
// in : file:///home/tim/projects/ntools/hash/fnv1a.hpp
//
// created by : Timothée Feuillet
// date: Mon May 22 2017 16:30:57 GMT-0400 (EDT)
//
//
// Copyright (c) 2017 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifndef __N_1298911746129055067_381318754_FNV1A_HPP__
#define __N_1298911746129055067_381318754_FNV1A_HPP__
#include <cstdint>
#include <cstddef>
#include "../ct_list.hpp"
#include "../embed.hpp"
namespace neam
{
namespace ct
{
namespace hash
{
namespace internal
{
using fnv_return_types = type_list<uint32_t, uint64_t>;
template<typename T> static constexpr T fnv_offset_basis = T();
template<> constexpr uint64_t fnv_offset_basis<uint64_t> = 0xcbf29ce484222325ul;
template<> constexpr uint32_t fnv_offset_basis<uint32_t> = 0x811c9dc5u;
template<typename T> static constexpr T fnv_prime = T();
template<> constexpr uint64_t fnv_prime<uint64_t> = 0x100000001b3ul;
template<> constexpr uint32_t fnv_prime<uint32_t> = 0x01000193u;
} // namespace internal
template<size_t BitCount, typename T>
static constexpr auto fnv1a(const T *const data, size_t len) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
constexpr size_t index = BitCount / 32 - 1;
using type = list::get_type<internal::fnv_return_types, index>;
static_assert(sizeof(T) == 1, "Input type must be 8bit");
static_assert(internal::fnv_offset_basis<type> != 0, "Invalid offset basis (are you using a supported type ?)");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = internal::fnv_offset_basis<type>;
for (size_t i = 0; i < len; ++i)
hash = ((uint8_t)(data)[i] ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, size_t StrLen>
static constexpr auto fnv1a(const char (&str)[StrLen]) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
constexpr size_t index = BitCount / 32 - 1;
using type = list::get_type<internal::fnv_return_types, index>;
static_assert(internal::fnv_offset_basis<type> != 0, "Invalid offset basis (are you using a supported type ?)");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = internal::fnv_offset_basis<type>;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < StrLen - 1; ++i)
hash = ((uint8_t)(str[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, size_t StrLen>
static constexpr auto fnv1a_continue(list::get_type<internal::fnv_return_types, BitCount / 32 - 1> initial,
const char (&str)[StrLen]) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
using type = list::get_type<internal::fnv_return_types, BitCount / 32 - 1>;
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = initial;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < StrLen - 1; ++i)
hash = ((uint8_t)(str[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
} // namespace hash
} // namespace ct
} // namespace neam
#endif // __N_1298911746129055067_381318754_FNV1A_HPP__
<commit_msg>improve a bit the fnv hash api<commit_after>//
// file : fnv1a.hpp
// in : file:///home/tim/projects/ntools/hash/fnv1a.hpp
//
// created by : Timothée Feuillet
// date: Mon May 22 2017 16:30:57 GMT-0400 (EDT)
//
//
// Copyright (c) 2017 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifndef __N_1298911746129055067_381318754_FNV1A_HPP__
#define __N_1298911746129055067_381318754_FNV1A_HPP__
#include <cstdint>
#include <cstddef>
#include "../ct_list.hpp"
#include "../embed.hpp"
namespace neam
{
namespace ct
{
namespace hash
{
namespace internal
{
using fnv_return_types = type_list<uint32_t, uint64_t>;
template<typename T> static constexpr T fnv_offset_basis = T();
template<> constexpr uint64_t fnv_offset_basis<uint64_t> = 0xcbf29ce484222325ul;
template<> constexpr uint32_t fnv_offset_basis<uint32_t> = 0x811c9dc5u;
template<typename T> static constexpr T fnv_prime = T();
template<> constexpr uint64_t fnv_prime<uint64_t> = 0x100000001b3ul;
template<> constexpr uint32_t fnv_prime<uint32_t> = 0x01000193u;
} // namespace internal
template<size_t BitCount, typename T>
static constexpr auto fnv1a(const T *const data, size_t len) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
constexpr size_t index = BitCount / 32 - 1;
using type = list::get_type<internal::fnv_return_types, index>;
static_assert(sizeof(T) == 1, "Input type must be 8bit");
static_assert(internal::fnv_offset_basis<type> != 0, "Invalid offset basis (are you using a supported type ?)");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = internal::fnv_offset_basis<type>;
for (size_t i = 0; i < len; ++i)
hash = ((uint8_t)(data)[i] ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, size_t StrLen>
static constexpr auto fnv1a(const char (&str)[StrLen]) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
constexpr size_t index = BitCount / 32 - 1;
using type = list::get_type<internal::fnv_return_types, index>;
static_assert(internal::fnv_offset_basis<type> != 0, "Invalid offset basis (are you using a supported type ?)");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = internal::fnv_offset_basis<type>;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < StrLen - 1; ++i)
hash = ((uint8_t)(str[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, typename T>
static constexpr auto fnv1a_continue(list::get_type<internal::fnv_return_types, BitCount / 32 - 1> initial,
const T* const data, size_t len) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
using type = list::get_type<internal::fnv_return_types, BitCount / 32 - 1>;
static_assert(sizeof(T) == 1, "Input type must be 8bit");
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = initial;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < len - 1; ++i)
hash = ((uint8_t)(data[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
template<size_t BitCount, size_t StrLen>
static constexpr auto fnv1a_continue(list::get_type<internal::fnv_return_types, BitCount / 32 - 1> initial,
const char (&str)[StrLen]) -> auto
{
static_assert(BitCount == 32 || BitCount == 64, "We only support 32 and 64bit FNV-1a hash function");
using type = list::get_type<internal::fnv_return_types, BitCount / 32 - 1>;
static_assert(internal::fnv_prime<type> != 0, "Invalid prime (are you using a supported type ?)");
type hash = initial;
// StrLen - 1 is to skip the ending \0
for (size_t i = 0; i < StrLen - 1; ++i)
hash = ((uint8_t)(str[i]) ^ hash) * internal::fnv_prime<type>;
return hash;
}
} // namespace hash
} // namespace ct
} // namespace neam
#endif // __N_1298911746129055067_381318754_FNV1A_HPP__
<|endoftext|> |
<commit_before>/** @file editorviewmviface.cpp
* @brief Класс, реализующий интерфейс представления в схеме Model/View
* */
#include <QtGui>
#include "editorviewmviface.h"
#include "editorview.h"
#include "editorviewscene.h"
#include "../kernel/definitions.h"
#include "../umllib/uml_element.h"
#include "editormanager.h"
#include "../mainwindow/mainwindow.h"
using namespace qReal;
EditorViewMViface::EditorViewMViface(EditorView *view, EditorViewScene *scene)
: QAbstractItemView(0)
{
mView = view;
mScene = scene;
mScene->mv_iface = this;
mScene->view = mView;
}
EditorViewMViface::~EditorViewMViface()
{
clearItems();
}
QRect EditorViewMViface::visualRect(const QModelIndex &) const
{
return QRect();
}
void EditorViewMViface::scrollTo(const QModelIndex &, ScrollHint)
{
}
QModelIndex EditorViewMViface::indexAt(const QPoint &) const
{
return QModelIndex();
}
QModelIndex EditorViewMViface::moveCursor(QAbstractItemView::CursorAction,
Qt::KeyboardModifiers)
{
return QModelIndex();
}
int EditorViewMViface::horizontalOffset() const
{
return 0;
}
int EditorViewMViface::verticalOffset() const
{
return 0;
}
bool EditorViewMViface::isIndexHidden(const QModelIndex &) const
{
return false;
}
void EditorViewMViface::setSelection(const QRect&, QItemSelectionModel::SelectionFlags )
{
}
QRegion EditorViewMViface::visualRegionForSelection(const QItemSelection &) const
{
return QRegion();
}
void EditorViewMViface::reset()
{
mScene->clearScene();
clearItems();
//для того, чтобы работало с экстерминатусом.
if (model() && model()->rowCount(QModelIndex()) == 0)
mScene->setEnabled(false);
// so that our diagram be nicer
QGraphicsRectItem *rect = mScene->addRect(QRect(-1000, -1000, 2000, 2000));
mScene->removeItem(rect);
delete rect;
if (model())
rowsInserted(rootIndex(), 0, model()->rowCount(rootIndex()) - 1);
}
void EditorViewMViface::setRootIndex(const QModelIndex &index)
{
QAbstractItemView::setRootIndex(index);
reset();
}
void EditorViewMViface::rowsInserted(QModelIndex const &parent, int start, int end)
{
/*
qDebug() << "========== rowsInserted" << parent << start << end;
qDebug() << "rowsInserted: adding items" << parent;
*/
for (int row = start; row <= end; ++row) {
QPersistentModelIndex current = model()->index(row, 0, parent);
Id uuid = current.data(roles::idRole).value<Id>();
Id parent_uuid;
if (parent != rootIndex())
parent_uuid = parent.data(roles::idRole).value<Id>();
mScene->setEnabled(true);
//если добавляем диаграмму в корень
if (!parent.isValid()) {
setRootIndex(current);
continue;
}
if (uuid == ROOT_ID)
continue;
UML::Element *e = mScene->mainWindow()->manager()->graphicalObject(uuid);
if (e) {
e->setIndex(current);
if (parent_uuid != Id() && item(parent) != NULL)
e->setParentItem(item(parent));
else
mScene->addItem(e);
setItem(current, e);
e->updateData();
e->connectToPort();
}
if (model()->hasChildren(current)) {
rowsInserted(current, 0, model()->rowCount(current) - 1);
}
}
QAbstractItemView::rowsInserted(parent, start, end);
}
void EditorViewMViface::rowsAboutToBeRemoved(QModelIndex const &parent, int start, int end)
{
for (int row = start; row <= end; ++row) {
QModelIndex curr = model()->index(row, 0, parent);
mScene->removeItem(item(curr));
delete item(curr);
removeItem(curr);
}
//потому что из модели элементы удаляются только после того, как удалятся из графической части.
if (parent == QModelIndex() && model()->rowCount(parent) == start - end + 1)
mScene->setEnabled(false);
QAbstractItemView::rowsAboutToBeRemoved(parent, start, end);
}
void EditorViewMViface::rowsAboutToBeMoved(QModelIndex const &sourceParent, int sourceStart, int sourceEnd, QModelIndex const &destinationParent, int destinationRow)
{
Q_ASSERT(sourceStart == sourceEnd); // Можно перемещать только один элемент за раз.
QPersistentModelIndex movedElementIndex = sourceParent.child(sourceStart, 0);
if (!item(movedElementIndex)) {
// Перемещаемого элемента на сцене уже нет.
// TODO: элемент надо добавлять на сцену, если тут его нет, а в модели есть.
// Пока такое не рассматриваем.
qDebug() << "Trying to move element that already does not exist on a current scene, that's strange";
return;
}
UML::Element* movedElement = item(movedElementIndex);
if (!item(destinationParent)) {
// Элемента-родителя на сцене нет, так что это скорее всего корневой элемент.
qDebug() << "parent does not exist on a current scene, setting as NULL";
movedElement->setParentItem(NULL);
return;
}
UML::Element* newParent = item(destinationParent);
movedElement->setParentItem(newParent);
}
void EditorViewMViface::rowsMoved(QModelIndex const &sourceParent, int sourceStart, int sourceEnd, QModelIndex const &destinationParent, int destinationRow)
{
Q_ASSERT(sourceStart == sourceEnd);
QPersistentModelIndex movedElementIndex = destinationParent.child(destinationRow, 0);
Q_ASSERT(movedElementIndex.isValid());
if (!item(movedElementIndex)) {
// Перемещённого элемента на сцене нет, так что и заботиться о нём не надо
qDebug() << "element does not exist on a current scene, aborting";
return;
}
UML::Element* movedElement = item(movedElementIndex);
movedElement->updateData();
}
void EditorViewMViface::dataChanged(const QModelIndex &topLeft,
const QModelIndex &bottomRight)
{
for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
QModelIndex curr = topLeft.sibling(row, 0);
if (item(curr))
item(curr)->updateData();
}
}
EditorViewScene *EditorViewMViface::scene() const
{
return mScene;
}
void EditorViewMViface::clearItems()
{
foreach (IndexElementPair pair, mItems)
delete pair.second;
mItems.clear();
}
UML::Element *EditorViewMViface::item(QPersistentModelIndex const &index) const
{
foreach (IndexElementPair pair, mItems) {
if (pair.first == index)
return pair.second;
}
return NULL;
}
void EditorViewMViface::setItem(QPersistentModelIndex const &index, UML::Element *item)
{
IndexElementPair pair(index, item);
if (!mItems.contains(pair))
mItems.insert(pair);
}
void EditorViewMViface::removeItem(QPersistentModelIndex const &index)
{
foreach (IndexElementPair pair, mItems) {
if (pair.first == index)
mItems.remove(pair);
}
}
<commit_msg>Более умное удаление - с учётом того прискорбного факта, что элемент удаляет своих сыновей сам.<commit_after>/** @file editorviewmviface.cpp
* @brief Класс, реализующий интерфейс представления в схеме Model/View
* */
#include <QtGui>
#include "editorviewmviface.h"
#include "editorview.h"
#include "editorviewscene.h"
#include "../kernel/definitions.h"
#include "../umllib/uml_element.h"
#include "editormanager.h"
#include "../mainwindow/mainwindow.h"
using namespace qReal;
EditorViewMViface::EditorViewMViface(EditorView *view, EditorViewScene *scene)
: QAbstractItemView(0)
{
mView = view;
mScene = scene;
mScene->mv_iface = this;
mScene->view = mView;
}
EditorViewMViface::~EditorViewMViface()
{
clearItems();
}
QRect EditorViewMViface::visualRect(const QModelIndex &) const
{
return QRect();
}
void EditorViewMViface::scrollTo(const QModelIndex &, ScrollHint)
{
}
QModelIndex EditorViewMViface::indexAt(const QPoint &) const
{
return QModelIndex();
}
QModelIndex EditorViewMViface::moveCursor(QAbstractItemView::CursorAction,
Qt::KeyboardModifiers)
{
return QModelIndex();
}
int EditorViewMViface::horizontalOffset() const
{
return 0;
}
int EditorViewMViface::verticalOffset() const
{
return 0;
}
bool EditorViewMViface::isIndexHidden(const QModelIndex &) const
{
return false;
}
void EditorViewMViface::setSelection(const QRect&, QItemSelectionModel::SelectionFlags )
{
}
QRegion EditorViewMViface::visualRegionForSelection(const QItemSelection &) const
{
return QRegion();
}
void EditorViewMViface::reset()
{
mScene->clearScene();
clearItems();
//для того, чтобы работало с экстерминатусом.
if (model() && model()->rowCount(QModelIndex()) == 0)
mScene->setEnabled(false);
// so that our diagram be nicer
QGraphicsRectItem *rect = mScene->addRect(QRect(-1000, -1000, 2000, 2000));
mScene->removeItem(rect);
delete rect;
if (model())
rowsInserted(rootIndex(), 0, model()->rowCount(rootIndex()) - 1);
}
void EditorViewMViface::setRootIndex(const QModelIndex &index)
{
QAbstractItemView::setRootIndex(index);
reset();
}
void EditorViewMViface::rowsInserted(QModelIndex const &parent, int start, int end)
{
/*
qDebug() << "========== rowsInserted" << parent << start << end;
qDebug() << "rowsInserted: adding items" << parent;
*/
for (int row = start; row <= end; ++row) {
QPersistentModelIndex current = model()->index(row, 0, parent);
Id uuid = current.data(roles::idRole).value<Id>();
Id parent_uuid;
if (parent != rootIndex())
parent_uuid = parent.data(roles::idRole).value<Id>();
mScene->setEnabled(true);
//если добавляем диаграмму в корень
if (!parent.isValid()) {
setRootIndex(current);
continue;
}
if (uuid == ROOT_ID)
continue;
UML::Element *e = mScene->mainWindow()->manager()->graphicalObject(uuid);
if (e) {
e->setIndex(current);
if (parent_uuid != Id() && item(parent) != NULL)
e->setParentItem(item(parent));
else
mScene->addItem(e);
setItem(current, e);
e->updateData();
e->connectToPort();
}
if (model()->hasChildren(current)) {
rowsInserted(current, 0, model()->rowCount(current) - 1);
}
}
QAbstractItemView::rowsInserted(parent, start, end);
}
void EditorViewMViface::rowsAboutToBeRemoved(QModelIndex const &parent, int start, int end)
{
for (int row = start; row <= end; ++row) {
QModelIndex curr = model()->index(row, 0, parent);
mScene->removeItem(item(curr));
delete item(curr);
removeItem(curr);
}
//потому что из модели элементы удаляются только после того, как удалятся из графической части.
if (parent == QModelIndex() && model()->rowCount(parent) == start - end + 1)
mScene->setEnabled(false);
QAbstractItemView::rowsAboutToBeRemoved(parent, start, end);
}
void EditorViewMViface::rowsAboutToBeMoved(QModelIndex const &sourceParent, int sourceStart, int sourceEnd, QModelIndex const &destinationParent, int destinationRow)
{
Q_ASSERT(sourceStart == sourceEnd); // Можно перемещать только один элемент за раз.
QPersistentModelIndex movedElementIndex = sourceParent.child(sourceStart, 0);
if (!item(movedElementIndex)) {
// Перемещаемого элемента на сцене уже нет.
// TODO: элемент надо добавлять на сцену, если тут его нет, а в модели есть.
// Пока такое не рассматриваем.
qDebug() << "Trying to move element that already does not exist on a current scene, that's strange";
return;
}
UML::Element* movedElement = item(movedElementIndex);
if (!item(destinationParent)) {
// Элемента-родителя на сцене нет, так что это скорее всего корневой элемент.
movedElement->setParentItem(NULL);
return;
}
UML::Element* newParent = item(destinationParent);
movedElement->setParentItem(newParent);
}
void EditorViewMViface::rowsMoved(QModelIndex const &sourceParent, int sourceStart, int sourceEnd, QModelIndex const &destinationParent, int destinationRow)
{
Q_ASSERT(sourceStart == sourceEnd);
QPersistentModelIndex movedElementIndex = destinationParent.child(destinationRow, 0);
Q_ASSERT(movedElementIndex.isValid());
if (!item(movedElementIndex)) {
// Перемещённого элемента на сцене нет, так что и заботиться о нём не надо
return;
}
UML::Element* movedElement = item(movedElementIndex);
movedElement->updateData();
}
void EditorViewMViface::dataChanged(const QModelIndex &topLeft,
const QModelIndex &bottomRight)
{
for (int row = topLeft.row(); row <= bottomRight.row(); ++row) {
QModelIndex curr = topLeft.sibling(row, 0);
if (item(curr))
item(curr)->updateData();
}
}
EditorViewScene *EditorViewMViface::scene() const
{
return mScene;
}
void EditorViewMViface::clearItems()
{
QList<QGraphicsItem *> toRemove;
foreach (IndexElementPair pair, mItems)
if (!pair.second->parentItem())
toRemove.append(pair.second);
foreach (QGraphicsItem *item, toRemove)
delete item;
mItems.clear();
}
UML::Element *EditorViewMViface::item(QPersistentModelIndex const &index) const
{
foreach (IndexElementPair pair, mItems) {
if (pair.first == index)
return pair.second;
}
return NULL;
}
void EditorViewMViface::setItem(QPersistentModelIndex const &index, UML::Element *item)
{
IndexElementPair pair(index, item);
if (!mItems.contains(pair))
mItems.insert(pair);
}
void EditorViewMViface::removeItem(QPersistentModelIndex const &index)
{
foreach (IndexElementPair pair, mItems) {
if (pair.first == index)
mItems.remove(pair);
}
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_USE_THREADS
#include "main.h"
#include <iostream>
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
using std::isnan;
static void test_multithread_elementwise()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(3, 11));
out.device(thread_pool_device) = in1 + in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
static void test_multithread_compound_assignment()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(3, 11));
out.device(thread_pool_device) = in1;
out.device(thread_pool_device) += in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
template<int DataLayout>
static void test_multithread_contraction()
{
Tensor<float, 4, DataLayout> t_left(30, 50, 37, 31);
Tensor<float, 5, DataLayout> t_right(37, 31, 70, 2, 10);
Tensor<float, 5, DataLayout> t_result(30, 50, 70, 2, 10);
t_left.setRandom();
t_right.setRandom();
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 2> dims({{DimPair(2, 0), DimPair(3, 1)}});
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 1500, 1147);
MapXf m_right(t_right.data(), 1147, 1400);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(1500, 1400);
Eigen::ThreadPoolDevice thread_pool_device(4);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
VERIFY(&t_result.data()[i] != &m_result.data()[i]);
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_contraction_corner_cases()
{
Tensor<float, 2, DataLayout> t_left(32, 500);
Tensor<float, 2, DataLayout> t_right(32, 28*28);
Tensor<float, 2, DataLayout> t_result(500, 28*28);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result = t_result.constant(NAN);
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims{{DimPair(0, 0)}};
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 32, 500);
MapXf m_right(t_right.data(), 32, 28*28);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(500, 28*28);
Eigen::ThreadPoolDevice thread_pool_device(12);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected at index " << i << " : " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_result.resize (1, 28*28);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 500);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (500, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 500);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (1, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_multithread_contraction_agrees_with_singlethread() {
int contract_size = internal::random<int>(1, 5000);
Tensor<float, 3, DataLayout> left(internal::random<int>(1, 80),
contract_size,
internal::random<int>(1, 100));
Tensor<float, 4, DataLayout> right(internal::random<int>(1, 25),
internal::random<int>(1, 37),
contract_size,
internal::random<int>(1, 51));
left.setRandom();
right.setRandom();
// add constants to shift values away from 0 for more precision
left += left.constant(1.5f);
right += right.constant(1.5f);
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims({{DimPair(1, 2)}});
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(2, 11));
Tensor<float, 5, DataLayout> st_result;
st_result = left.contract(right, dims);
Tensor<float, 5, DataLayout> tp_result(st_result.dimensions());
tp_result.device(thread_pool_device) = left.contract(right, dims);
VERIFY(dimensions_match(st_result.dimensions(), tp_result.dimensions()));
for (ptrdiff_t i = 0; i < st_result.size(); i++) {
// if both of the values are very small, then do nothing (because the test will fail
// due to numerical precision issues when values are small)
if (fabs(st_result.data()[i] - tp_result.data()[i]) >= 1e-4) {
VERIFY_IS_APPROX(st_result.data()[i], tp_result.data()[i]);
}
}
}
static void test_memcpy() {
for (int i = 0; i < 5; ++i) {
const int num_threads = internal::random<int>(3, 11);
Eigen::ThreadPoolDevice thread_pool_device(num_threads);
const int size = internal::random<int>(13, 7632);
Tensor<float, 1> t1(size);
t1.setRandom();
std::vector<float> result(size);
thread_pool_device.memcpy(&result[0], t1.data(), size*sizeof(float));
for (int i = 0; i < size; i++) {
VERIFY_IS_EQUAL(t1(i), result[i]);
}
}
}
static void test_multithread_random()
{
Eigen::ThreadPoolDevice device(2);
Tensor<float, 1> t(1 << 20);
t.device(device) = t.random<Eigen::internal::NormalRandomGenerator<float>>();
}
void test_cxx11_tensor_thread_pool()
{
CALL_SUBTEST(test_multithread_elementwise());
CALL_SUBTEST(test_multithread_compound_assignment());
CALL_SUBTEST(test_multithread_contraction<ColMajor>());
CALL_SUBTEST(test_multithread_contraction<RowMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<ColMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<RowMajor>());
// Exercise various cases that have been problematic in the past.
CALL_SUBTEST(test_contraction_corner_cases<ColMajor>());
CALL_SUBTEST(test_contraction_corner_cases<RowMajor>());
CALL_SUBTEST(test_memcpy());
CALL_SUBTEST(test_multithread_random());
}
<commit_msg>Fixed compilation error<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#define EIGEN_USE_THREADS
#include "main.h"
#include <iostream>
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
static void test_multithread_elementwise()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(3, 11));
out.device(thread_pool_device) = in1 + in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
static void test_multithread_compound_assignment()
{
Tensor<float, 3> in1(2,3,7);
Tensor<float, 3> in2(2,3,7);
Tensor<float, 3> out(2,3,7);
in1.setRandom();
in2.setRandom();
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(3, 11));
out.device(thread_pool_device) = in1;
out.device(thread_pool_device) += in2 * 3.14f;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_APPROX(out(i,j,k), in1(i,j,k) + in2(i,j,k) * 3.14f);
}
}
}
}
template<int DataLayout>
static void test_multithread_contraction()
{
Tensor<float, 4, DataLayout> t_left(30, 50, 37, 31);
Tensor<float, 5, DataLayout> t_right(37, 31, 70, 2, 10);
Tensor<float, 5, DataLayout> t_result(30, 50, 70, 2, 10);
t_left.setRandom();
t_right.setRandom();
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 2> dims({{DimPair(2, 0), DimPair(3, 1)}});
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 1500, 1147);
MapXf m_right(t_right.data(), 1147, 1400);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(1500, 1400);
Eigen::ThreadPoolDevice thread_pool_device(4);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
VERIFY(&t_result.data()[i] != &m_result.data()[i]);
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_contraction_corner_cases()
{
Tensor<float, 2, DataLayout> t_left(32, 500);
Tensor<float, 2, DataLayout> t_right(32, 28*28);
Tensor<float, 2, DataLayout> t_result(500, 28*28);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result = t_result.constant(NAN);
// this contraction should be equivalent to a single matrix multiplication
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims{{DimPair(0, 0)}};
typedef Map<Matrix<float, Dynamic, Dynamic, DataLayout>> MapXf;
MapXf m_left(t_left.data(), 32, 500);
MapXf m_right(t_right.data(), 32, 28*28);
Matrix<float, Dynamic, Dynamic, DataLayout> m_result(500, 28*28);
Eigen::ThreadPoolDevice thread_pool_device(12);
// compute results by separate methods
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected at index " << i << " : " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_result.resize (1, 28*28);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 500);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (500, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 500);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
t_left.resize(32, 1);
t_right.resize(32, 4);
t_left = (t_left.constant(-0.5f) + t_left.random()) * 2.0f;
t_right = (t_right.constant(-0.6f) + t_right.random()) * 2.0f;
t_result.resize (1, 4);
t_result = t_result.constant(NAN);
t_result.device(thread_pool_device) = t_left.contract(t_right, dims);
new(&m_left) MapXf(t_left.data(), 32, 1);
new(&m_right) MapXf(t_right.data(), 32, 4);
m_result = m_left.transpose() * m_right;
for (ptrdiff_t i = 0; i < t_result.size(); i++) {
assert(!std::isnan(t_result.data()[i]));
if (fabs(t_result.data()[i] - m_result.data()[i]) >= 1e-4) {
std::cout << "mismatch detected: " << t_result.data()[i] << " vs " << m_result.data()[i] << std::endl;
assert(false);
}
}
}
template<int DataLayout>
static void test_multithread_contraction_agrees_with_singlethread() {
int contract_size = internal::random<int>(1, 5000);
Tensor<float, 3, DataLayout> left(internal::random<int>(1, 80),
contract_size,
internal::random<int>(1, 100));
Tensor<float, 4, DataLayout> right(internal::random<int>(1, 25),
internal::random<int>(1, 37),
contract_size,
internal::random<int>(1, 51));
left.setRandom();
right.setRandom();
// add constants to shift values away from 0 for more precision
left += left.constant(1.5f);
right += right.constant(1.5f);
typedef Tensor<float, 1>::DimensionPair DimPair;
Eigen::array<DimPair, 1> dims({{DimPair(1, 2)}});
Eigen::ThreadPoolDevice thread_pool_device(internal::random<int>(2, 11));
Tensor<float, 5, DataLayout> st_result;
st_result = left.contract(right, dims);
Tensor<float, 5, DataLayout> tp_result(st_result.dimensions());
tp_result.device(thread_pool_device) = left.contract(right, dims);
VERIFY(dimensions_match(st_result.dimensions(), tp_result.dimensions()));
for (ptrdiff_t i = 0; i < st_result.size(); i++) {
// if both of the values are very small, then do nothing (because the test will fail
// due to numerical precision issues when values are small)
if (fabs(st_result.data()[i] - tp_result.data()[i]) >= 1e-4) {
VERIFY_IS_APPROX(st_result.data()[i], tp_result.data()[i]);
}
}
}
static void test_memcpy() {
for (int i = 0; i < 5; ++i) {
const int num_threads = internal::random<int>(3, 11);
Eigen::ThreadPoolDevice thread_pool_device(num_threads);
const int size = internal::random<int>(13, 7632);
Tensor<float, 1> t1(size);
t1.setRandom();
std::vector<float> result(size);
thread_pool_device.memcpy(&result[0], t1.data(), size*sizeof(float));
for (int i = 0; i < size; i++) {
VERIFY_IS_EQUAL(t1(i), result[i]);
}
}
}
static void test_multithread_random()
{
Eigen::ThreadPoolDevice device(2);
Tensor<float, 1> t(1 << 20);
t.device(device) = t.random<Eigen::internal::NormalRandomGenerator<float>>();
}
void test_cxx11_tensor_thread_pool()
{
CALL_SUBTEST(test_multithread_elementwise());
CALL_SUBTEST(test_multithread_compound_assignment());
CALL_SUBTEST(test_multithread_contraction<ColMajor>());
CALL_SUBTEST(test_multithread_contraction<RowMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<ColMajor>());
CALL_SUBTEST(test_multithread_contraction_agrees_with_singlethread<RowMajor>());
// Exercise various cases that have been problematic in the past.
CALL_SUBTEST(test_contraction_corner_cases<ColMajor>());
CALL_SUBTEST(test_contraction_corner_cases<RowMajor>());
CALL_SUBTEST(test_memcpy());
CALL_SUBTEST(test_multithread_random());
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbImage.h"
#include "itkUnaryFunctorImageFilter.h"
#include "otbScalarToRainbowRGBPixelFunctor.h"
int otbScalarToRainbowRGBPixelFunctorNew(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef unsigned char PixelType;
typedef itk::RGBPixel<PixelType> RGBPixelType;
typedef otb::Image<PixelType, 2> ImageType;
typedef otb::Image<RGBPixelType, 2> RGBImageType;
typedef otb::Functor::ScalarToRainbowRGBPixelFunctor<PixelType>
ColorMapFunctorType;
typedef itk::UnaryFunctorImageFilter<ImageType,
RGBImageType, ColorMapFunctorType> ColorMapFilterType;
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->GetFunctor().SetMaximum(150);
colormapper->GetFunctor().SetMinimum(70);
std::cout << colormapper << std::endl;
return EXIT_SUCCESS;
}
<commit_msg>COMP: use non-deprecated functions<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "otbImage.h"
#include "itkUnaryFunctorImageFilter.h"
#include "otbScalarToRainbowRGBPixelFunctor.h"
int otbScalarToRainbowRGBPixelFunctorNew(int itkNotUsed(argc), char * itkNotUsed(argv) [])
{
typedef unsigned char PixelType;
typedef itk::RGBPixel<PixelType> RGBPixelType;
typedef otb::Image<PixelType, 2> ImageType;
typedef otb::Image<RGBPixelType, 2> RGBImageType;
typedef otb::Functor::ScalarToRainbowRGBPixelFunctor<PixelType>
ColorMapFunctorType;
typedef itk::UnaryFunctorImageFilter<ImageType,
RGBImageType, ColorMapFunctorType> ColorMapFilterType;
ColorMapFilterType::Pointer colormapper = ColorMapFilterType::New();
colormapper->GetFunctor().SetMaximumInputValue(150);
colormapper->GetFunctor().SetMinimumInputValue(70);
std::cout << colormapper << std::endl;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// $Id: gnuplot_io.C,v 1.4 2005-06-08 16:38:17 spetersen Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <fstream>
#include <map>
// Local includes
#include "elem.h"
#include "mesh_base.h"
#include "gnuplot_io.h"
GnuPlotIO::GnuPlotIO(const MeshBase& mesh, const std::string& title, bool grid)
:
MeshOutput<MeshBase> (mesh),
_title(title),
_grid(grid)
{
}
void GnuPlotIO::write(const std::string& fname)
{
if(libMesh::processor_id() == 0)
this->write_solution(fname);
}
void GnuPlotIO::write_nodal_data (const std::string& fname,
const std::vector<Number>& soln,
const std::vector<std::string>& names)
{
if(libMesh::processor_id() == 0)
this->write_solution(fname, &soln, &names);
}
void GnuPlotIO::write_solution(const std::string& fname,
const std::vector<Number>* soln,
const std::vector<std::string>* names)
{
assert(libMesh::processor_id() == 0);
const MeshBase& mesh = MeshOutput<MeshBase>::mesh();
std::stringstream data_stream_name;
data_stream_name << fname << "_data";
const std::string data_file_name = data_stream_name.str();
// This class is designed only for use with 1D meshes
assert (mesh.mesh_dimension() == 1);
// Create an output stream for script file
std::ofstream out(fname.c_str());
if (!out.good())
{
std::cerr << "ERROR: opening output file " << fname
<< std::endl;
error();
}
// The number of variables in the equation system
const unsigned int n_vars = names->size();
// Write header to stream
out << "# This file was generated by gnuplot_io.C\n"
<< "# Stores 1D solution data in GNUplot format\n"
<< "# Execute this by loading gnuplot and typing "
<< "\"call '" << fname << "'\"\n"
<< "reset\n"
<< "set title \"" << _title << "\"\n"
<< "set xlabel \"x\"\n"
<< "set autoscale\n"
<< "set xtics nomirror\n";
if(_grid)
{
// construct string for xtic positions at element edges
std::string xtics;
std::stringstream xtics_stream;
MeshBase::const_element_iterator it = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator end_it =
mesh.active_local_elements_end();
unsigned int count = 0;
unsigned int n_active_elem = mesh.n_active_elem();
for( ; it != end_it; ++it)
{
Elem* el = *it;
// if el is the left edge of the mesh, print its left node position
if(el->neighbor(0) == NULL)
{
xtics_stream << "\"\" " << (*(el->get_node(0)))(0) << ", \\\n";
}
xtics_stream << "\"\" " << (*(el->get_node(1)))(0);
if(count+1 != n_active_elem)
{
xtics_stream << ", \\\n";
}
count++;
}
xtics = xtics_stream.str();
out << "set x2tics (" << xtics << ")\nset grid noxtics noytics x2tics\n";
}
out << "plot \"" << data_file_name << "\" using 1:2 title \"" << (*names)[0]
<< "\" with lines";
if(n_vars > 1)
{
for(unsigned int i=1; i<n_vars; i++)
{
out << ", \\\n\"data\" using 1:" << i+2
<< " title \"" << (*names)[i] << "\" with lines";
}
}
out.close();
// Create an output stream for data file
std::ofstream data(data_file_name.c_str());
if (!data.good())
{
std::cerr << "ERROR: opening output data file " << std::endl;
error();
}
data << "# This file contains libMesh solution data "
<< "to be plotted in GNUplot\n\n";
// get ordered nodal data using a map
typedef std::pair<Real, std::vector<Number> > key_value_pair;
typedef std::map<Real, std::vector<Number> > map_type;
typedef map_type::iterator map_iterator;
map_type node_map;
for(unsigned int i=0; i<mesh.n_nodes(); i++)
{
std::vector<Number> values;
if( (names != NULL) && (soln != NULL) )
{
assert(soln->size() == mesh.n_nodes()*n_vars);
for(unsigned int c=0; c<n_vars; c++)
{
values.push_back( (*soln)[i*n_vars + c] );
}
}
node_map.insert(key_value_pair( mesh.point(i)(0) , values ));
}
map_iterator map_it = node_map.begin();
const map_iterator end_map_it = node_map.end();
for( ; map_it != end_map_it; ++map_it)
{
key_value_pair kvp = *map_it;
std::vector<Number> values = kvp.second;
data << kvp.first << "\t";
for(unsigned int i=0; i<values.size(); i++)
{
data << values[i] << "\t";
}
data << "\n";
}
data.close();
}
<commit_msg>Fixed bug in gnuplot_io.C to allow correct plotting of multiple variables<commit_after>// $Id: gnuplot_io.C,v 1.5 2005-06-08 17:07:03 knezed01 Exp $
// The libMesh Finite Element Library.
// Copyright (C) 2002-2005 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// C++ includes
#include <fstream>
#include <map>
// Local includes
#include "elem.h"
#include "mesh_base.h"
#include "gnuplot_io.h"
GnuPlotIO::GnuPlotIO(const MeshBase& mesh, const std::string& title, bool grid)
:
MeshOutput<MeshBase> (mesh),
_title(title),
_grid(grid)
{
}
void GnuPlotIO::write(const std::string& fname)
{
if(libMesh::processor_id() == 0)
this->write_solution(fname);
}
void GnuPlotIO::write_nodal_data (const std::string& fname,
const std::vector<Number>& soln,
const std::vector<std::string>& names)
{
if(libMesh::processor_id() == 0)
this->write_solution(fname, &soln, &names);
}
void GnuPlotIO::write_solution(const std::string& fname,
const std::vector<Number>* soln,
const std::vector<std::string>* names)
{
assert(libMesh::processor_id() == 0);
const MeshBase& mesh = MeshOutput<MeshBase>::mesh();
std::stringstream data_stream_name;
data_stream_name << fname << "_data";
const std::string data_file_name = data_stream_name.str();
// This class is designed only for use with 1D meshes
assert (mesh.mesh_dimension() == 1);
// Create an output stream for script file
std::ofstream out(fname.c_str());
if (!out.good())
{
std::cerr << "ERROR: opening output file " << fname
<< std::endl;
error();
}
// The number of variables in the equation system
const unsigned int n_vars = names->size();
// Write header to stream
out << "# This file was generated by gnuplot_io.C\n"
<< "# Stores 1D solution data in GNUplot format\n"
<< "# Execute this by loading gnuplot and typing "
<< "\"call '" << fname << "'\"\n"
<< "reset\n"
<< "set title \"" << _title << "\"\n"
<< "set xlabel \"x\"\n"
<< "set autoscale\n"
<< "set xtics nomirror\n";
if(_grid)
{
// construct string for xtic positions at element edges
std::string xtics;
std::stringstream xtics_stream;
MeshBase::const_element_iterator it = mesh.active_local_elements_begin();
const MeshBase::const_element_iterator end_it =
mesh.active_local_elements_end();
unsigned int count = 0;
unsigned int n_active_elem = mesh.n_active_elem();
for( ; it != end_it; ++it)
{
Elem* el = *it;
// if el is the left edge of the mesh, print its left node position
if(el->neighbor(0) == NULL)
{
xtics_stream << "\"\" " << (*(el->get_node(0)))(0) << ", \\\n";
}
xtics_stream << "\"\" " << (*(el->get_node(1)))(0);
if(count+1 != n_active_elem)
{
xtics_stream << ", \\\n";
}
count++;
}
xtics = xtics_stream.str();
out << "set x2tics (" << xtics << ")\nset grid noxtics noytics x2tics\n";
}
out << "plot \"" << data_file_name << "\" using 1:2 title \"" << (*names)[0]
<< "\" with lines";
if(n_vars > 1)
{
for(unsigned int i=1; i<n_vars; i++)
{
out << ", \\\n\"" << data_file_name << "\" using 1:" << i+2
<< " title \"" << (*names)[i] << "\" with lines";
}
}
out.close();
// Create an output stream for data file
std::ofstream data(data_file_name.c_str());
if (!data.good())
{
std::cerr << "ERROR: opening output data file " << std::endl;
error();
}
data << "# This file contains libMesh solution data "
<< "to be plotted in GNUplot\n\n";
// get ordered nodal data using a map
typedef std::pair<Real, std::vector<Number> > key_value_pair;
typedef std::map<Real, std::vector<Number> > map_type;
typedef map_type::iterator map_iterator;
map_type node_map;
for(unsigned int i=0; i<mesh.n_nodes(); i++)
{
std::vector<Number> values;
if( (names != NULL) && (soln != NULL) )
{
assert(soln->size() == mesh.n_nodes()*n_vars);
for(unsigned int c=0; c<n_vars; c++)
{
values.push_back( (*soln)[i*n_vars + c] );
}
}
node_map.insert(key_value_pair( mesh.point(i)(0) , values ));
}
map_iterator map_it = node_map.begin();
const map_iterator end_map_it = node_map.end();
for( ; map_it != end_map_it; ++map_it)
{
key_value_pair kvp = *map_it;
std::vector<Number> values = kvp.second;
data << kvp.first << "\t";
for(unsigned int i=0; i<values.size(); i++)
{
data << values[i] << "\t";
}
data << "\n";
}
data.close();
}
<|endoftext|> |
<commit_before>
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <boost/program_options.hpp>
// TODO: remove this include (node.h) from this file as it's an implementation detail
#include "avro/node/node.h"
#include "filter/filter.h"
#include "filter/compiler.h"
#include "fileemitor.h"
#include "worker.h"
namespace po = boost::program_options;
std::mutex screenMutex;
std::string recordSeparator = "\n";
void outDocument(const std::string &what) {
std::lock_guard<std::mutex> screenLock(screenMutex);
std::cout.write(what.data(), what.size());
std::cout << recordSeparator;
}
void updateSeparator(std::string &sep) {
std::string res;
bool esc = false;
for(char c : sep) {
if (esc) {
switch(c) {
case 'n':
res += '\n';
break;
case 't':
res += '\t';
break;
default:
res += c;
}
esc = false;
continue;
}
if (c == '\\') {
esc = true;
} else {
res += c;
}
}
sep = res;
}
int main(int argc, const char * argv[]) {
std::cout.sync_with_stdio(false);
std::string condition;
int limit = -1;
u_int jobs = 4;
std::string fields;
bool printProcessingFile = false;
bool countMode = false;
std::string fieldSeparator = "\t";
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Show help message")
("input-file,f", po::value< std::vector<std::string> >(), "input files")
("condition,c", po::value< std::string >(&condition), "expression")
("limit,n", po::value< int >(&limit)->default_value(-1), "maximum number of records (default -1 means no limit)")
("fields,l", po::value< std::string >(&fields), "fields to output")
("print-file", po::bool_switch(&printProcessingFile), "Print name of processing file")
("jobs,j", po::value< u_int >(&jobs), "Number of threads to run")
("count-only", po::bool_switch(&countMode), "Count of matched records, don't print them")
("record-separator", po::value<std::string>(&recordSeparator)->default_value("\\n"), "Record separator (\\n by default)")
("field-separator", po::value<std::string>(&fieldSeparator)->default_value("\\t"), "Field separator for TSV output (\\t by default)")
;
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map vm;
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
updateSeparator(recordSeparator);
updateSeparator(fieldSeparator);
filter::Compiler filterCompiler;
std::shared_ptr<filter::Filter> filter;
if (!condition.empty()) {
try {
filter = filterCompiler.compile(condition);
} catch(const filter::Compiler::CompileError &e) {
std::cerr << "Condition complile failed: " << std::endl;
std::cerr << e.what() << std::endl;
return 1;
}
}
if (vm.count("input-file")) {
const auto &fileList = vm["input-file"].as< std::vector<std::string> >();
FileEmitor emitor(fileList, limit, outDocument);
emitor.setFilter(filter);
emitor.setTsvFieldList(fields, fieldSeparator);
if (printProcessingFile) {
emitor.enablePrintProcessingFile();
}
if (countMode) {
emitor.enableCountOnlyMode();
}
std::vector<std::thread> workers;
for(u_int i = 0; i < jobs; ++i) { // TODO: check for inadequate values
workers.emplace_back(
std::thread(Worker(emitor))
);
}
for(auto &p : workers) {
p.join();
}
if (countMode) {
std::cout << "Matched documents: " << emitor.getCountedDocuments() << std::endl;
}
} else {
std::cerr << "No input files" << std::endl;
return 1;
}
return 0;
}
<commit_msg>Catch exception about bad arguments<commit_after>
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <boost/program_options.hpp>
// TODO: remove this include (node.h) from this file as it's an implementation detail
#include "avro/node/node.h"
#include "filter/filter.h"
#include "filter/compiler.h"
#include "fileemitor.h"
#include "worker.h"
namespace po = boost::program_options;
std::mutex screenMutex;
std::string recordSeparator = "\n";
void outDocument(const std::string &what) {
std::lock_guard<std::mutex> screenLock(screenMutex);
std::cout.write(what.data(), what.size());
std::cout << recordSeparator;
}
void updateSeparator(std::string &sep) {
std::string res;
bool esc = false;
for(char c : sep) {
if (esc) {
switch(c) {
case 'n':
res += '\n';
break;
case 't':
res += '\t';
break;
default:
res += c;
}
esc = false;
continue;
}
if (c == '\\') {
esc = true;
} else {
res += c;
}
}
sep = res;
}
int main(int argc, const char * argv[]) {
std::cout.sync_with_stdio(false);
std::string condition;
int limit = -1;
u_int jobs = 4;
std::string fields;
bool printProcessingFile = false;
bool countMode = false;
std::string fieldSeparator = "\t";
po::options_description desc("Allowed options");
desc.add_options()
("help,h", "Show help message")
("input-file,f", po::value< std::vector<std::string> >(), "input files")
("condition,c", po::value< std::string >(&condition), "expression")
("limit,n", po::value< int >(&limit)->default_value(-1), "maximum number of records (default -1 means no limit)")
("fields,l", po::value< std::string >(&fields), "fields to output")
("print-file", po::bool_switch(&printProcessingFile), "Print name of processing file")
("jobs,j", po::value< u_int >(&jobs), "Number of threads to run")
("count-only", po::bool_switch(&countMode), "Count of matched records, don't print them")
("record-separator", po::value<std::string>(&recordSeparator)->default_value("\\n"), "Record separator (\\n by default)")
("field-separator", po::value<std::string>(&fieldSeparator)->default_value("\\t"), "Field separator for TSV output (\\t by default)")
;
po::positional_options_description p;
p.add("input-file", -1);
po::variables_map vm;
try {
po::store(po::command_line_parser(argc, argv).
options(desc).positional(p).run(), vm);
po::notify(vm);
} catch(const boost::program_options::error &e) {
std::cerr << "Sorry, I couldn't parse arguments: " << e.what() << std::endl;
return 1;
}
if (vm.count("help")) {
std::cout << desc << "\n";
return 1;
}
updateSeparator(recordSeparator);
updateSeparator(fieldSeparator);
filter::Compiler filterCompiler;
std::shared_ptr<filter::Filter> filter;
if (!condition.empty()) {
try {
filter = filterCompiler.compile(condition);
} catch(const filter::Compiler::CompileError &e) {
std::cerr << "Condition complile failed: " << std::endl;
std::cerr << e.what() << std::endl;
return 1;
}
}
if (vm.count("input-file")) {
const auto &fileList = vm["input-file"].as< std::vector<std::string> >();
FileEmitor emitor(fileList, limit, outDocument);
emitor.setFilter(filter);
emitor.setTsvFieldList(fields, fieldSeparator);
if (printProcessingFile) {
emitor.enablePrintProcessingFile();
}
if (countMode) {
emitor.enableCountOnlyMode();
}
std::vector<std::thread> workers;
for(u_int i = 0; i < jobs; ++i) { // TODO: check for inadequate values
workers.emplace_back(
std::thread(Worker(emitor))
);
}
for(auto &p : workers) {
p.join();
}
if (countMode) {
std::cout << "Matched documents: " << emitor.getCountedDocuments() << std::endl;
}
} else {
std::cerr << "No input files" << std::endl;
return 1;
}
return 0;
}
<|endoftext|> |
<commit_before>#include "HedgeLib/String.h"
#include "INString.h"
#include <algorithm>
#ifdef _WIN32
#include <Windows.h>
#endif
const char* const hl_EmptyString = "";
#ifdef _WIN32
const hl_NativeStr const hl_EmptyStringNative = L"";
#endif
template<typename str1_t, typename str2_t>
bool hl_INStringsEqualInvASCII(const str1_t* str1, const str2_t* str2)
{
if (str1 == reinterpret_cast<const str1_t*>(str2)) return true;
if (!str1 || !*str1) return false;
while (*str1 || *str2)
{
if (*str1 != static_cast<str1_t>(*str2) && HL_TOLOWERASCII(*str1) !=
static_cast<str1_t>(HL_TOLOWERASCII(*str2)))
{
return false;
}
++str1;
++str2;
}
return true;
}
template bool hl_INStringsEqualInvASCII<char, char>(const char* str1, const char* str2);
#ifdef _WIN32
template bool hl_INStringsEqualInvASCII<hl_NativeChar, hl_NativeChar>(
const hl_NativeChar* str1, const hl_NativeChar* str2);
template bool hl_INStringsEqualInvASCII<char, hl_NativeChar>(
const char* str1, const hl_NativeChar* str2);
template bool hl_INStringsEqualInvASCII<hl_NativeChar, char>(
const hl_NativeChar* str1, const char* str2);
#endif
bool hl_StringsEqualInvASCII(const char* str1, const char* str2)
{
return hl_INStringsEqualInvASCII(str1, str2);
}
bool hl_StringsEqualInvASCIINative(
const hl_NativeStr str1, const hl_NativeStr str2)
{
return hl_INStringsEqualInvASCII(str1, str2);
}
size_t hl_INStringGetReqUTF16BufferCountUTF8(const char* str, size_t len)
{
#ifdef _WIN32
// Figure out the amount of characters in the UTF-8 string
int strLen = MultiByteToWideChar(CP_UTF8, 0, str,
(len == 0) ? -1 : static_cast<int>(len), nullptr, 0);
return static_cast<size_t>(strLen);
#endif
// TODO: Support for non-Windows platforms
return 0;
}
size_t hl_StringGetReqUTF16BufferCountUTF8(const char* str, size_t len)
{
return (str) ? hl_INStringGetReqUTF16BufferCountUTF8(str, len) : 0;
}
size_t hl_INStringGetReqUTF8BufferCountUTF16(const uint16_t* str, size_t len)
{
#ifdef _WIN32
// Figure out the amount of characters in the UTF-16 string
int strLen = WideCharToMultiByte(CP_UTF8, 0,
reinterpret_cast<const wchar_t*>(str), (len == 0) ?
-1 : static_cast<int>(len), nullptr, 0, NULL, NULL);
return static_cast<size_t>(strLen);
#endif
// TODO: Support for non-Windows platforms
return 0;
}
size_t hl_StringGetReqUTF8BufferCountUTF16(const uint16_t* str, size_t len)
{
return (str) ? hl_INStringGetReqUTF8BufferCountUTF16(str, len) : 0;
}
HL_RESULT hl_INStringConvertUTF8ToUTF16NoAlloc(const char* u8str,
uint16_t* u16str, size_t u16bufLen, size_t u8bufLen)
{
#ifdef _WIN32
// Convert the UTF-8 string to UTF-16 and store it in the buffer
MultiByteToWideChar(CP_UTF8, 0, u8str,
(u8bufLen == 0) ? -1 : static_cast<int>(u8bufLen),
reinterpret_cast<wchar_t*>(u16str),
static_cast<int>(u16bufLen)); // TODO: Error checking?
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF8ToUTF16NoAlloc(
const char* u8str, uint16_t* u16str, size_t u8bufLen)
{
#ifdef _WIN32
// Determine the size of the buffer required to hold the string's UTF-16 equivalent
size_t u16bufLen = hl_INStringGetReqUTF16BufferCountUTF8(u8str);
// Convert to UTF-16
return hl_INStringConvertUTF8ToUTF16NoAlloc(u8str,
u16str, u16bufLen, u8bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF8ToUTF16(const char* u8str,
uint16_t** u16str, size_t u16bufLen, size_t u8bufLen)
{
#ifdef _WIN32
// Allocate a buffer big enough to hold the UTF-16 string
*u16str = static_cast<uint16_t*>(malloc(
u16bufLen * sizeof(uint16_t)));
if (!*u16str) return HL_ERROR_OUT_OF_MEMORY;
// Convert to UTF-16
return hl_INStringConvertUTF8ToUTF16NoAlloc(
u8str, *u16str, u16bufLen, u8bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF8ToUTF16(const char* u8str,
uint16_t** u16str, size_t u8bufLen)
{
#ifdef _WIN32
// Determine the size of the buffer required to hold the string's UTF-16 equivalent
size_t u16bufLen = hl_INStringGetReqUTF16BufferCountUTF8(u8str);
// Convert to UTF-16
return hl_INStringConvertUTF8ToUTF16(
u8str, u16str, u16bufLen, u8bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
enum HL_RESULT hl_StringConvertUTF8ToUTF16(const char* u8str,
uint16_t** u16str, size_t u8bufLen)
{
if (!u8str || !u16str) return HL_ERROR_UNKNOWN;
return hl_INStringConvertUTF8ToUTF16(u8str, u16str, u8bufLen);
}
HL_RESULT hl_INStringConvertUTF8ToNative(const char* u8str,
hl_NativeStr* nativeStr, size_t u8bufLen)
{
#ifdef _WIN32
return hl_INStringConvertUTF8ToUTF16(u8str,
reinterpret_cast<uint16_t**>(nativeStr), u8bufLen);
#else
// Allocate a buffer big enough to hold a copy of the string
if (u8bufLen == 0) u8bufLen = (strlen(u8str) + 1);
*nativeStr = static_cast<hl_NativeStr>(malloc(u8bufLen));
if (!*nativeStr) return HL_ERROR_OUT_OF_MEMORY;
// Copy the string
std::copy(u8str, u8str + u8bufLen, *nativeStr);
return HL_SUCCESS;
#endif
}
enum HL_RESULT hl_StringConvertUTF8ToNative(const char* u8str,
hl_NativeStr* nativeStr, size_t u8bufLen)
{
if (!u8str || !nativeStr) return HL_ERROR_UNKNOWN;
return hl_INStringConvertUTF8ToNative(u8str, nativeStr, u8bufLen);
}
HL_RESULT hl_INStringConvertUTF16ToUTF8NoAlloc(const uint16_t* u16str,
char* u8str, size_t u8bufLen, size_t u16bufLen)
{
#ifdef _WIN32
// Convert the UTF-16 string to UTF-8 and store it in the buffer
WideCharToMultiByte(CP_UTF8, 0, reinterpret_cast<const wchar_t*>(u16str),
(u16bufLen == 0) ? -1 : static_cast<int>(u16bufLen),
u8str, static_cast<int>(u8bufLen), NULL, NULL); // TODO: Error checking?
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF16ToUTF8NoAlloc(
const uint16_t* u16str, char* u8str, size_t u16bufLen)
{
#ifdef _WIN32
// Determine the size of the buffer required to hold the string's UTF-8 equivalent
size_t u8bufLen = hl_INStringGetReqUTF8BufferCountUTF16(u16str);
// Convert to UTF-8
return hl_INStringConvertUTF16ToUTF8NoAlloc(u16str,
u8str, u8bufLen, u16bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF16ToUTF8(const uint16_t* u16str,
char** u8str, size_t u8bufLen, size_t u16bufLen)
{
#ifdef _WIN32
// Allocate a buffer big enough to hold the UTF-8 string
*u8str = static_cast<char*>(malloc(u8bufLen));
if (!*u8str) return HL_ERROR_OUT_OF_MEMORY;
// Convert to UTF-8
return hl_INStringConvertUTF16ToUTF8NoAlloc(
u16str, *u8str, u8bufLen, u16bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF16ToUTF8(const uint16_t* u16str,
char** u8str, size_t u16bufLen)
{
#ifdef _WIN32
// Determine the size of the buffer required to hold the string's UTF-8 equivalent
size_t u8bufLen = hl_INStringGetReqUTF8BufferCountUTF16(u16str);
// Convert to UTF-8
return hl_INStringConvertUTF16ToUTF8(
u16str, u8str, u8bufLen, u16bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
enum HL_RESULT hl_StringConvertUTF16ToUTF8(
const uint16_t* u16str, char** u8str, size_t u16bufLen)
{
if (!u16str || !u8str) return HL_ERROR_UNKNOWN;
return hl_INStringConvertUTF16ToUTF8(u16str, u8str, u16bufLen);
}
HL_RESULT hl_INStringConvertUTF16ToNative(
const uint16_t* u16str, hl_NativeStr* nativeStr, size_t u16bufLen)
{
#ifdef _WIN32
// Allocate a buffer big enough to hold a copy of the string
if (u16bufLen == 0)
{
u16bufLen = (wcslen(
reinterpret_cast<const wchar_t*>(u16str)) + 1);
}
*nativeStr = static_cast<hl_NativeStr>(malloc(u16bufLen));
if (!*nativeStr) return HL_ERROR_OUT_OF_MEMORY;
// Copy the string
std::copy(u16str, u16str + u16bufLen + 1, *nativeStr);
return HL_SUCCESS;
#else
return hl_INStringConvertUTF16ToUTF8(
u16str, nativeStr, u16bufLen);
#endif
}
enum HL_RESULT hl_StringConvertUTF16ToNative(
const uint16_t* u16str, hl_NativeStr* nativeStr, size_t u16bufLen)
{
if (!u16str || !nativeStr) return HL_ERROR_UNKNOWN;
return hl_INStringConvertUTF16ToNative(u16str, nativeStr, u16bufLen);
}
<commit_msg>Fix not passing in user-specified buffer length<commit_after>#include "HedgeLib/String.h"
#include "INString.h"
#include <algorithm>
#ifdef _WIN32
#include <Windows.h>
#endif
const char* const hl_EmptyString = "";
#ifdef _WIN32
const hl_NativeStr const hl_EmptyStringNative = L"";
#endif
template<typename str1_t, typename str2_t>
bool hl_INStringsEqualInvASCII(const str1_t* str1, const str2_t* str2)
{
if (str1 == reinterpret_cast<const str1_t*>(str2)) return true;
if (!str1 || !*str1) return false;
while (*str1 || *str2)
{
if (*str1 != static_cast<str1_t>(*str2) && HL_TOLOWERASCII(*str1) !=
static_cast<str1_t>(HL_TOLOWERASCII(*str2)))
{
return false;
}
++str1;
++str2;
}
return true;
}
template bool hl_INStringsEqualInvASCII<char, char>(const char* str1, const char* str2);
#ifdef _WIN32
template bool hl_INStringsEqualInvASCII<hl_NativeChar, hl_NativeChar>(
const hl_NativeChar* str1, const hl_NativeChar* str2);
template bool hl_INStringsEqualInvASCII<char, hl_NativeChar>(
const char* str1, const hl_NativeChar* str2);
template bool hl_INStringsEqualInvASCII<hl_NativeChar, char>(
const hl_NativeChar* str1, const char* str2);
#endif
bool hl_StringsEqualInvASCII(const char* str1, const char* str2)
{
return hl_INStringsEqualInvASCII(str1, str2);
}
bool hl_StringsEqualInvASCIINative(
const hl_NativeStr str1, const hl_NativeStr str2)
{
return hl_INStringsEqualInvASCII(str1, str2);
}
size_t hl_INStringGetReqUTF16BufferCountUTF8(const char* str, size_t len)
{
#ifdef _WIN32
// Figure out the amount of characters in the UTF-8 string
int strLen = MultiByteToWideChar(CP_UTF8, 0, str,
(len == 0) ? -1 : static_cast<int>(len), nullptr, 0);
return static_cast<size_t>(strLen);
#endif
// TODO: Support for non-Windows platforms
return 0;
}
size_t hl_StringGetReqUTF16BufferCountUTF8(const char* str, size_t len)
{
return (str) ? hl_INStringGetReqUTF16BufferCountUTF8(str, len) : 0;
}
size_t hl_INStringGetReqUTF8BufferCountUTF16(const uint16_t* str, size_t len)
{
#ifdef _WIN32
// Figure out the amount of characters in the UTF-16 string
int strLen = WideCharToMultiByte(CP_UTF8, 0,
reinterpret_cast<const wchar_t*>(str), (len == 0) ?
-1 : static_cast<int>(len), nullptr, 0, NULL, NULL);
return static_cast<size_t>(strLen);
#endif
// TODO: Support for non-Windows platforms
return 0;
}
size_t hl_StringGetReqUTF8BufferCountUTF16(const uint16_t* str, size_t len)
{
return (str) ? hl_INStringGetReqUTF8BufferCountUTF16(str, len) : 0;
}
HL_RESULT hl_INStringConvertUTF8ToUTF16NoAlloc(const char* u8str,
uint16_t* u16str, size_t u16bufLen, size_t u8bufLen)
{
#ifdef _WIN32
// Convert the UTF-8 string to UTF-16 and store it in the buffer
MultiByteToWideChar(CP_UTF8, 0, u8str,
(u8bufLen == 0) ? -1 : static_cast<int>(u8bufLen),
reinterpret_cast<wchar_t*>(u16str),
static_cast<int>(u16bufLen)); // TODO: Error checking?
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF8ToUTF16NoAlloc(
const char* u8str, uint16_t* u16str, size_t u8bufLen)
{
#ifdef _WIN32
// Determine the size of the buffer required to hold the string's UTF-16 equivalent
size_t u16bufLen = hl_INStringGetReqUTF16BufferCountUTF8(
u8str, u8bufLen);
// Convert to UTF-16
return hl_INStringConvertUTF8ToUTF16NoAlloc(u8str,
u16str, u16bufLen, u8bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF8ToUTF16(const char* u8str,
uint16_t** u16str, size_t u16bufLen, size_t u8bufLen)
{
#ifdef _WIN32
// Allocate a buffer big enough to hold the UTF-16 string
*u16str = static_cast<uint16_t*>(malloc(
u16bufLen * sizeof(uint16_t)));
if (!*u16str) return HL_ERROR_OUT_OF_MEMORY;
// Convert to UTF-16
return hl_INStringConvertUTF8ToUTF16NoAlloc(
u8str, *u16str, u16bufLen, u8bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF8ToUTF16(const char* u8str,
uint16_t** u16str, size_t u8bufLen)
{
#ifdef _WIN32
// Determine the size of the buffer required to hold the string's UTF-16 equivalent
size_t u16bufLen = hl_INStringGetReqUTF16BufferCountUTF8(
u8str, u8bufLen);
// Convert to UTF-16
return hl_INStringConvertUTF8ToUTF16(
u8str, u16str, u16bufLen, u8bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
enum HL_RESULT hl_StringConvertUTF8ToUTF16(const char* u8str,
uint16_t** u16str, size_t u8bufLen)
{
if (!u8str || !u16str) return HL_ERROR_UNKNOWN;
return hl_INStringConvertUTF8ToUTF16(u8str, u16str, u8bufLen);
}
HL_RESULT hl_INStringConvertUTF8ToNative(const char* u8str,
hl_NativeStr* nativeStr, size_t u8bufLen)
{
#ifdef _WIN32
return hl_INStringConvertUTF8ToUTF16(u8str,
reinterpret_cast<uint16_t**>(nativeStr), u8bufLen);
#else
// Allocate a buffer big enough to hold a copy of the string
if (u8bufLen == 0) u8bufLen = (strlen(u8str) + 1);
*nativeStr = static_cast<hl_NativeStr>(malloc(u8bufLen));
if (!*nativeStr) return HL_ERROR_OUT_OF_MEMORY;
// Copy the string
std::copy(u8str, u8str + u8bufLen, *nativeStr);
return HL_SUCCESS;
#endif
}
enum HL_RESULT hl_StringConvertUTF8ToNative(const char* u8str,
hl_NativeStr* nativeStr, size_t u8bufLen)
{
if (!u8str || !nativeStr) return HL_ERROR_UNKNOWN;
return hl_INStringConvertUTF8ToNative(u8str, nativeStr, u8bufLen);
}
HL_RESULT hl_INStringConvertUTF16ToUTF8NoAlloc(const uint16_t* u16str,
char* u8str, size_t u8bufLen, size_t u16bufLen)
{
#ifdef _WIN32
// Convert the UTF-16 string to UTF-8 and store it in the buffer
WideCharToMultiByte(CP_UTF8, 0, reinterpret_cast<const wchar_t*>(u16str),
(u16bufLen == 0) ? -1 : static_cast<int>(u16bufLen),
u8str, static_cast<int>(u8bufLen), NULL, NULL); // TODO: Error checking?
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF16ToUTF8NoAlloc(
const uint16_t* u16str, char* u8str, size_t u16bufLen)
{
#ifdef _WIN32
// Determine the size of the buffer required to hold the string's UTF-8 equivalent
size_t u8bufLen = hl_INStringGetReqUTF8BufferCountUTF16(
u16str, u16bufLen);
// Convert to UTF-8
return hl_INStringConvertUTF16ToUTF8NoAlloc(u16str,
u8str, u8bufLen, u16bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF16ToUTF8(const uint16_t* u16str,
char** u8str, size_t u8bufLen, size_t u16bufLen)
{
#ifdef _WIN32
// Allocate a buffer big enough to hold the UTF-8 string
*u8str = static_cast<char*>(malloc(u8bufLen));
if (!*u8str) return HL_ERROR_OUT_OF_MEMORY;
// Convert to UTF-8
return hl_INStringConvertUTF16ToUTF8NoAlloc(
u16str, *u8str, u8bufLen, u16bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
HL_RESULT hl_INStringConvertUTF16ToUTF8(const uint16_t* u16str,
char** u8str, size_t u16bufLen)
{
#ifdef _WIN32
// Determine the size of the buffer required to hold the string's UTF-8 equivalent
size_t u8bufLen = hl_INStringGetReqUTF8BufferCountUTF16(
u16str, u16bufLen);
// Convert to UTF-8
return hl_INStringConvertUTF16ToUTF8(
u16str, u8str, u8bufLen, u16bufLen);
#endif
// TODO: Support for non-Windows platforms
return HL_SUCCESS;
}
enum HL_RESULT hl_StringConvertUTF16ToUTF8(
const uint16_t* u16str, char** u8str, size_t u16bufLen)
{
if (!u16str || !u8str) return HL_ERROR_UNKNOWN;
return hl_INStringConvertUTF16ToUTF8(u16str, u8str, u16bufLen);
}
HL_RESULT hl_INStringConvertUTF16ToNative(
const uint16_t* u16str, hl_NativeStr* nativeStr, size_t u16bufLen)
{
#ifdef _WIN32
// Allocate a buffer big enough to hold a copy of the string
if (u16bufLen == 0)
{
u16bufLen = (wcslen(
reinterpret_cast<const wchar_t*>(u16str)) + 1);
}
*nativeStr = static_cast<hl_NativeStr>(malloc(u16bufLen));
if (!*nativeStr) return HL_ERROR_OUT_OF_MEMORY;
// Copy the string
std::copy(u16str, u16str + u16bufLen + 1, *nativeStr);
return HL_SUCCESS;
#else
return hl_INStringConvertUTF16ToUTF8(
u16str, nativeStr, u16bufLen);
#endif
}
enum HL_RESULT hl_StringConvertUTF16ToNative(
const uint16_t* u16str, hl_NativeStr* nativeStr, size_t u16bufLen)
{
if (!u16str || !nativeStr) return HL_ERROR_UNKNOWN;
return hl_INStringConvertUTF16ToNative(u16str, nativeStr, u16bufLen);
}
<|endoftext|> |
<commit_before>/**
* The MIT License (MIT)
*
* Copyright (c) 2013-2020 Winlin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_KERNEL_LOG_HPP
#define SRS_KERNEL_LOG_HPP
#include <srs_core.hpp>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <srs_kernel_consts.hpp>
// The log level, for example:
// if specified Debug level, all level messages will be logged.
// if specified Warn level, only Warn/Error/Fatal level messages will be logged.
enum SrsLogLevel
{
SrsLogLevelForbidden = 0x00,
// Only used for very verbose debug, generally,
// we compile without this level for high performance.
SrsLogLevelVerbose = 0x01,
SrsLogLevelInfo = 0x02,
SrsLogLevelTrace = 0x04,
SrsLogLevelWarn = 0x08,
SrsLogLevelError = 0x10,
SrsLogLevelDisabled = 0x20,
};
// The log interface provides method to write log.
// but we provides some macro, which enable us to disable the log when compile.
// @see also SmtDebug/SmtTrace/SmtWarn/SmtError which is corresponding to Debug/Trace/Warn/Fatal.
class ISrsLog
{
public:
ISrsLog();
virtual ~ISrsLog();
public:
// Initialize log utilities.
virtual srs_error_t initialize();
// Reopen the log file for log rotate.
virtual void reopen();
public:
// The log for verbose, very verbose information.
virtual void verbose(const char* tag, int context_id, const char* fmt, ...);
// The log for debug, detail information.
virtual void info(const char* tag, int context_id, const char* fmt, ...);
// The log for trace, important information.
virtual void trace(const char* tag, int context_id, const char* fmt, ...);
// The log for warn, warn is something should take attention, but not a error.
virtual void warn(const char* tag, int context_id, const char* fmt, ...);
// The log for error, something error occur, do something about the error, ie. close the connection,
// but we will donot abort the program.
virtual void error(const char* tag, int context_id, const char* fmt, ...);
};
// The context id manager to identify context, for instance, the green-thread.
// Usage:
// _srs_context->generate_id(); // when thread start.
// _srs_context->get_id(); // get current generated id.
// int old_id = _srs_context->set_id(1000); // set context id if need to merge thread context.
// The context for multiple clients.
class ISrsThreadContext
{
public:
ISrsThreadContext();
virtual ~ISrsThreadContext();
public:
// Generate the id for current context.
virtual int generate_id();
// Get the generated id of current context.
virtual int get_id();
// Set the id of current context.
// @return the previous id value; 0 if no context.
virtual int set_id(int v);
};
// @global User must provides a log object
extern ISrsLog* _srs_log;
// @global User must implements the LogContext and define a global instance.
extern ISrsThreadContext* _srs_context;
// Log style.
// Use __FUNCTION__ to print c method
// Use __PRETTY_FUNCTION__ to print c++ class:method
#if 1
#define srs_verbose(msg, ...) _srs_log->verbose(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#endif
#if 0
#define srs_verbose(msg, ...) _srs_log->verbose(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#endif
#if 0
#define srs_verbose(msg, ...) _srs_log->verbose(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#endif
// TODO: FIXME: Add more verbose and info logs.
#ifndef SRS_AUTO_VERBOSE
#undef srs_verbose
#define srs_verbose(msg, ...) (void)0
#endif
#ifndef SRS_AUTO_INFO
#undef srs_info
#define srs_info(msg, ...) (void)0
#endif
#ifndef SRS_AUTO_TRACE
#undef srs_trace
#define srs_trace(msg, ...) (void)0
#endif
inline void srs_trace_data(const char* data_p, int len, const char* dscr)
{
const int MAX = 256;
char debug_data[MAX];
char debug_len = 0;
debug_len += sprintf(debug_data + debug_len, "%s", dscr);
for (int index = 0; index < len; index++) {
if (index % 16 == 0) {
debug_len += sprintf(debug_data + debug_len, "\r\n");
}
debug_len += sprintf(debug_data + debug_len, " %02x", (unsigned char)data_p[index]);
if (index >= 32) {
break;
}
}
srs_trace("%s", debug_data);
return;
}
#endif
<commit_msg>Remove noused debug function srs_trace_data<commit_after>/**
* The MIT License (MIT)
*
* Copyright (c) 2013-2020 Winlin
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef SRS_KERNEL_LOG_HPP
#define SRS_KERNEL_LOG_HPP
#include <srs_core.hpp>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <srs_kernel_consts.hpp>
// The log level, for example:
// if specified Debug level, all level messages will be logged.
// if specified Warn level, only Warn/Error/Fatal level messages will be logged.
enum SrsLogLevel
{
SrsLogLevelForbidden = 0x00,
// Only used for very verbose debug, generally,
// we compile without this level for high performance.
SrsLogLevelVerbose = 0x01,
SrsLogLevelInfo = 0x02,
SrsLogLevelTrace = 0x04,
SrsLogLevelWarn = 0x08,
SrsLogLevelError = 0x10,
SrsLogLevelDisabled = 0x20,
};
// The log interface provides method to write log.
// but we provides some macro, which enable us to disable the log when compile.
// @see also SmtDebug/SmtTrace/SmtWarn/SmtError which is corresponding to Debug/Trace/Warn/Fatal.
class ISrsLog
{
public:
ISrsLog();
virtual ~ISrsLog();
public:
// Initialize log utilities.
virtual srs_error_t initialize();
// Reopen the log file for log rotate.
virtual void reopen();
public:
// The log for verbose, very verbose information.
virtual void verbose(const char* tag, int context_id, const char* fmt, ...);
// The log for debug, detail information.
virtual void info(const char* tag, int context_id, const char* fmt, ...);
// The log for trace, important information.
virtual void trace(const char* tag, int context_id, const char* fmt, ...);
// The log for warn, warn is something should take attention, but not a error.
virtual void warn(const char* tag, int context_id, const char* fmt, ...);
// The log for error, something error occur, do something about the error, ie. close the connection,
// but we will donot abort the program.
virtual void error(const char* tag, int context_id, const char* fmt, ...);
};
// The context id manager to identify context, for instance, the green-thread.
// Usage:
// _srs_context->generate_id(); // when thread start.
// _srs_context->get_id(); // get current generated id.
// int old_id = _srs_context->set_id(1000); // set context id if need to merge thread context.
// The context for multiple clients.
class ISrsThreadContext
{
public:
ISrsThreadContext();
virtual ~ISrsThreadContext();
public:
// Generate the id for current context.
virtual int generate_id();
// Get the generated id of current context.
virtual int get_id();
// Set the id of current context.
// @return the previous id value; 0 if no context.
virtual int set_id(int v);
};
// @global User must provides a log object
extern ISrsLog* _srs_log;
// @global User must implements the LogContext and define a global instance.
extern ISrsThreadContext* _srs_context;
// Log style.
// Use __FUNCTION__ to print c method
// Use __PRETTY_FUNCTION__ to print c++ class:method
#if 1
#define srs_verbose(msg, ...) _srs_log->verbose(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(NULL, _srs_context->get_id(), msg, ##__VA_ARGS__)
#endif
#if 0
#define srs_verbose(msg, ...) _srs_log->verbose(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(__FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#endif
#if 0
#define srs_verbose(msg, ...) _srs_log->verbose(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_info(msg, ...) _srs_log->info(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_trace(msg, ...) _srs_log->trace(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_warn(msg, ...) _srs_log->warn(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#define srs_error(msg, ...) _srs_log->error(__PRETTY_FUNCTION__, _srs_context->get_id(), msg, ##__VA_ARGS__)
#endif
// TODO: FIXME: Add more verbose and info logs.
#ifndef SRS_AUTO_VERBOSE
#undef srs_verbose
#define srs_verbose(msg, ...) (void)0
#endif
#ifndef SRS_AUTO_INFO
#undef srs_info
#define srs_info(msg, ...) (void)0
#endif
#ifndef SRS_AUTO_TRACE
#undef srs_trace
#define srs_trace(msg, ...) (void)0
#endif
#endif
<|endoftext|> |
<commit_before>//Create, Draw and fit a TGraph2DErrors
//Author: Olivier Couet
#include <TMath.h>
#include <TGraph2DErrors.h>
#include <TRandom.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TF2.h>
void graph2derrorsfit()
{
TCanvas *c1 = new TCanvas("c1");
Double_t rnd, x, y, z, ex, ey, ez;
Double_t e = 0.3;
Int_t nd = 500;
TRandom r;
TF2 *f2 = new TF2("f2","1000*(([0]*sin(x)/x)*([1]*sin(y)/y))+200",-6,6,-6,6);
f2->SetParameters(1,1);
TGraph2DErrors *dte = new TGraph2DErrors(nd);
// Fill the 2D graph
for (Int_t i=0; i<nd; i++) {
f2->GetRandom2(x,y);
rnd = r.Uniform(-e,e); // Generate a random number in [-e,e]
z = f2->Eval(x,y)*(1+rnd);
dte->SetPoint(i,x,y,z);
ex = 0.05*r.Rndm();
ey = 0.05*r.Rndm();
ez = TMath::Abs(z*rnd);
dte->SetPointError(i,ex,ey,ez);
}
f2->SetParameters(0.5,1.5);
dte->Fit(f2);
TF2 *fit2 = (TF2*)dte->FindObject("f2");
fit2->SetTitle("Minuit fit result on the Graph2DErrors points");
fit2->Draw("surf1");
dte->Draw("same p0");
}
<commit_msg>- Make sure that the fitted surface and the points are plotted using the same range in Z.<commit_after>//Create, Draw and fit a TGraph2DErrors
//Author: Olivier Couet
#include <TMath.h>
#include <TGraph2DErrors.h>
#include <TRandom.h>
#include <TStyle.h>
#include <TCanvas.h>
#include <TF2.h>
void graph2derrorsfit()
{
TCanvas *c1 = new TCanvas("c1");
Double_t rnd, x, y, z, ex, ey, ez;
Double_t e = 0.3;
Int_t nd = 500;
TRandom r;
TF2 *f2 = new TF2("f2","1000*(([0]*sin(x)/x)*([1]*sin(y)/y))+200",-6,6,-6,6);
f2->SetParameters(1,1);
TGraph2DErrors *dte = new TGraph2DErrors(nd);
// Fill the 2D graph
Double_t zmax = 0;
for (Int_t i=0; i<nd; i++) {
f2->GetRandom2(x,y);
rnd = r.Uniform(-e,e); // Generate a random number in [-e,e]
z = f2->Eval(x,y)*(1+rnd);
if (z>zmax) zmax = z;
dte->SetPoint(i,x,y,z);
ex = 0.05*r.Rndm();
ey = 0.05*r.Rndm();
ez = TMath::Abs(z*rnd);
dte->SetPointError(i,ex,ey,ez);
}
f2->SetParameters(0.5,1.5);
dte->Fit(f2);
TF2 *fit2 = (TF2*)dte->FindObject("f2");
fit2->SetTitle("Minuit fit result on the Graph2DErrors points");
fit2->SetMaximum(zmax);
gStyle->SetHistTopMargin(0);
fit2->Draw("surf1");
dte->Draw("same p0");
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <stdio.h>
#include "db/dbformat.h"
#include "port/port.h"
#include "util/coding.h"
namespace leveldb {
static uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
assert(seq <= kMaxSequenceNumber);
assert(t <= kValueTypeForSeek);
return (seq << 8) | t;
}
void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
result->append(key.user_key.data(), key.user_key.size());
PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
}
std::string ParsedInternalKey::DebugString() const {
char buf[50];
snprintf(buf, sizeof(buf), "' @ %llu : %d",
(unsigned long long) sequence,
int(type));
std::string result = "'";
result += user_key.ToString();
result += buf;
return result;
}
const char* InternalKeyComparator::Name() const {
return "leveldb.InternalKeyComparator";
}
int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
// Order by:
// increasing user key (according to user-supplied comparator)
// decreasing sequence number
// decreasing type (though sequence# should be enough to disambiguate)
int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
if (r == 0) {
const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
// Q: 为啥降序排序呢?
if (anum > bnum) {
r = -1;
} else if (anum < bnum) {
r = +1;
}
}
return r;
}
void InternalKeyComparator::FindShortestSeparator(
std::string* start,
const Slice& limit) const {
// Attempt to shorten the user portion of the key
Slice user_start = ExtractUserKey(*start);
Slice user_limit = ExtractUserKey(limit);
std::string tmp(user_start.data(), user_start.size());
user_comparator_->FindShortestSeparator(&tmp, user_limit);
if (user_comparator_->Compare(*start, tmp) < 0) {
// 这里应该是 Compare(*user_start, tmp); 最新 rocksdb 已经修复了这个 bug.
// 按我理解这里 tmp 属于 (user_start, user_limit) 之间, 所以我觉得这里并不一定非得是 kMaxSequenceNumber,
// kValueTypeForSeek. 因为这里任何 user_key 与 tmp 都不会相同, 即在 InternalKeyComparator::Compare()
// 时不会试图比较 sequence#.
// User key has become larger. Tack on the earliest possible
// number to the shortened user key.
PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
assert(this->Compare(*start, tmp) < 0);
assert(this->Compare(tmp, limit) < 0);
start->swap(tmp);
}
}
void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
Slice user_key = ExtractUserKey(*key);
std::string tmp(user_key.data(), user_key.size());
user_comparator_->FindShortSuccessor(&tmp);
if (user_comparator_->Compare(user_key, tmp) < 0) {
// User key has become larger. Tack on the earliest possible
// number to the shortened user key.
PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
assert(this->Compare(*key, tmp) < 0);
key->swap(tmp);
}
}
LargeValueRef LargeValueRef::Make(const Slice& value, CompressionType ctype) {
LargeValueRef result;
port::SHA1_Hash(value.data(), value.size(), &result.data[0]);
EncodeFixed64(&result.data[20], value.size());
result.data[28] = static_cast<unsigned char>(ctype);
return result;
}
std::string LargeValueRefToFilenameString(const LargeValueRef& h) {
assert(sizeof(h.data) == LargeValueRef::ByteSize());
assert(sizeof(h.data) == 29); // So we can hardcode the array size of buf
static const char tohex[] = "0123456789abcdef";
char buf[20*2];
for (int i = 0; i < 20; i++) {
buf[2*i] = tohex[(h.data[i] >> 4) & 0xf];
buf[2*i+1] = tohex[h.data[i] & 0xf];
}
std::string result = std::string(buf, sizeof(buf));
result += "-";
result += NumberToString(h.ValueSize());
result += "-";
result += NumberToString(static_cast<uint64_t>(h.compression_type()));
return result;
}
static uint32_t hexvalue(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return 10 + c - 'A';
} else {
assert(c >= 'a' && c <= 'f');
return 10 + c - 'a';
}
}
bool FilenameStringToLargeValueRef(const Slice& s, LargeValueRef* h) {
Slice in = s;
if (in.size() < 40) {
return false;
}
for (int i = 0; i < 20; i++) {
if (!isxdigit(in[i*2]) || !isxdigit(in[i*2+1])) {
return false;
}
unsigned char c = (hexvalue(in[i*2])<<4) | hexvalue(in[i*2+1]);
h->data[i] = c;
}
in.remove_prefix(40);
uint64_t value_size, ctype;
if (ConsumeChar(&in, '-') &&
ConsumeDecimalNumber(&in, &value_size) &&
ConsumeChar(&in, '-') &&
ConsumeDecimalNumber(&in, &ctype) &&
in.empty() &&
// 如果以后新增一种压缩类型, 导致 kLightweightCompression 不是最大的了, 那么不知道要修改多少地方呢?
// 这里应该使用类似 IsValidCompressionType() 来判断的.
(ctype <= kLightweightCompression)) {
EncodeFixed64(&h->data[20], value_size);
h->data[28] = static_cast<unsigned char>(ctype);
return true;
} else {
return false;
}
}
}
<commit_msg>doc(dbformat): add doc<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <stdio.h>
#include "db/dbformat.h"
#include "port/port.h"
#include "util/coding.h"
namespace leveldb {
static uint64_t PackSequenceAndType(uint64_t seq, ValueType t) {
assert(seq <= kMaxSequenceNumber);
assert(t <= kValueTypeForSeek);
return (seq << 8) | t;
}
void AppendInternalKey(std::string* result, const ParsedInternalKey& key) {
result->append(key.user_key.data(), key.user_key.size());
PutFixed64(result, PackSequenceAndType(key.sequence, key.type));
}
std::string ParsedInternalKey::DebugString() const {
char buf[50];
snprintf(buf, sizeof(buf), "' @ %llu : %d",
(unsigned long long) sequence,
int(type));
std::string result = "'";
result += user_key.ToString();
result += buf;
return result;
}
const char* InternalKeyComparator::Name() const {
return "leveldb.InternalKeyComparator";
}
int InternalKeyComparator::Compare(const Slice& akey, const Slice& bkey) const {
// Order by:
// increasing user key (according to user-supplied comparator)
// decreasing sequence number
// decreasing type (though sequence# should be enough to disambiguate)
int r = user_comparator_->Compare(ExtractUserKey(akey), ExtractUserKey(bkey));
if (r == 0) {
const uint64_t anum = DecodeFixed64(akey.data() + akey.size() - 8);
const uint64_t bnum = DecodeFixed64(bkey.data() + bkey.size() - 8);
// Q: 为啥降序排序呢? 按我理解 sequence 越大表明越新, 倒序排序可以让越新的 key 记录摆在前面.
if (anum > bnum) {
r = -1;
} else if (anum < bnum) {
r = +1;
}
}
return r;
}
void InternalKeyComparator::FindShortestSeparator(
std::string* start,
const Slice& limit) const {
// Attempt to shorten the user portion of the key
Slice user_start = ExtractUserKey(*start);
Slice user_limit = ExtractUserKey(limit);
std::string tmp(user_start.data(), user_start.size());
user_comparator_->FindShortestSeparator(&tmp, user_limit);
if (user_comparator_->Compare(*start, tmp) < 0) {
// 这里应该是 Compare(*user_start, tmp); 最新 rocksdb 已经修复了这个 bug.
// 按我理解这里 tmp 属于 (user_start, user_limit) 之间, 所以我觉得这里并不一定非得是 kMaxSequenceNumber,
// kValueTypeForSeek. 因为这里任何 user_key 与 tmp 都不会相同, 即在 InternalKeyComparator::Compare()
// 时不会试图比较 sequence#.
// User key has become larger. Tack on the earliest possible
// number to the shortened user key.
PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
assert(this->Compare(*start, tmp) < 0);
assert(this->Compare(tmp, limit) < 0);
start->swap(tmp);
}
}
void InternalKeyComparator::FindShortSuccessor(std::string* key) const {
Slice user_key = ExtractUserKey(*key);
std::string tmp(user_key.data(), user_key.size());
user_comparator_->FindShortSuccessor(&tmp);
if (user_comparator_->Compare(user_key, tmp) < 0) {
// User key has become larger. Tack on the earliest possible
// number to the shortened user key.
PutFixed64(&tmp, PackSequenceAndType(kMaxSequenceNumber,kValueTypeForSeek));
assert(this->Compare(*key, tmp) < 0);
key->swap(tmp);
}
}
LargeValueRef LargeValueRef::Make(const Slice& value, CompressionType ctype) {
LargeValueRef result;
port::SHA1_Hash(value.data(), value.size(), &result.data[0]);
EncodeFixed64(&result.data[20], value.size());
result.data[28] = static_cast<unsigned char>(ctype);
return result;
}
std::string LargeValueRefToFilenameString(const LargeValueRef& h) {
assert(sizeof(h.data) == LargeValueRef::ByteSize());
assert(sizeof(h.data) == 29); // So we can hardcode the array size of buf
static const char tohex[] = "0123456789abcdef";
char buf[20*2];
for (int i = 0; i < 20; i++) {
buf[2*i] = tohex[(h.data[i] >> 4) & 0xf];
buf[2*i+1] = tohex[h.data[i] & 0xf];
}
std::string result = std::string(buf, sizeof(buf));
result += "-";
result += NumberToString(h.ValueSize());
result += "-";
result += NumberToString(static_cast<uint64_t>(h.compression_type()));
return result;
}
static uint32_t hexvalue(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'A' && c <= 'F') {
return 10 + c - 'A';
} else {
assert(c >= 'a' && c <= 'f');
return 10 + c - 'a';
}
}
bool FilenameStringToLargeValueRef(const Slice& s, LargeValueRef* h) {
Slice in = s;
if (in.size() < 40) {
return false;
}
for (int i = 0; i < 20; i++) {
if (!isxdigit(in[i*2]) || !isxdigit(in[i*2+1])) {
return false;
}
unsigned char c = (hexvalue(in[i*2])<<4) | hexvalue(in[i*2+1]);
h->data[i] = c;
}
in.remove_prefix(40);
uint64_t value_size, ctype;
if (ConsumeChar(&in, '-') &&
ConsumeDecimalNumber(&in, &value_size) &&
ConsumeChar(&in, '-') &&
ConsumeDecimalNumber(&in, &ctype) &&
in.empty() &&
// 如果以后新增一种压缩类型, 导致 kLightweightCompression 不是最大的了, 那么不知道要修改多少地方呢?
// 这里应该使用类似 IsValidCompressionType() 来判断的.
(ctype <= kLightweightCompression)) {
EncodeFixed64(&h->data[20], value_size);
h->data[28] = static_cast<unsigned char>(ctype);
return true;
} else {
return false;
}
}
}
<|endoftext|> |
<commit_before>//---------------------------------------------------------
// Copyright 2015 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish.cpp -- main driver program
//
#include <string>
#include <map>
#include <functional>
#include "logsum.h"
#include "nanopolish_extract.h"
#include "nanopolish_call_variants.h"
#include "nanopolish_consensus.h"
#include "nanopolish_eventalign.h"
#include "nanopolish_getmodel.h"
#include "nanopolish_methyltrain.h"
#include "nanopolish_call_methylation.h"
#include "nanopolish_scorereads.h"
#include "nanopolish_phase_reads.h"
#include "nanopolish_train_poremodel_from_basecalls.h"
int print_usage(int argc, char **argv);
int print_version(int argc, char **argv);
static std::map< std::string, std::function<int(int, char**)> > programs = {
{"help", print_usage},
{"--help", print_usage},
{"--version", print_version},
{"extract", extract_main},
{"consensus", consensus_main},
{"eventalign", eventalign_main},
{"getmodel", getmodel_main},
{"variants", call_variants_main},
{"methyltrain", methyltrain_main},
{"scorereads", scorereads_main} ,
{"phase-reads", phase_reads_main} ,
{"call-methylation", call_methylation_main},
{"train-poremodel-from-basecalls", train_poremodel_from_basecalls_main}
};
int print_usage(int, char **)
{
std::cout << "usage: nanopolish [command] [options]" << std::endl;
std::cout << " valid commands: " << std::endl;
for (const auto &item : programs){
std::cout << " " << item.first << std::endl;
}
std::cout << " for help on given command, type nanopolish command --help" << std::endl;
return 0;
}
int print_version(int, char **)
{
static const char *VERSION_MESSAGE =
"nanopolish version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2015-2017 Ontario Institute for Cancer Research\n";
std::cout << VERSION_MESSAGE << std::endl;
return 0;
}
int main(int argc, char** argv)
{
int ret = 0;
if(argc <= 1) {
printf("error: no command provided\n");
print_usage(argc - 1 , argv + 1);
return 0;
} else {
std::string command(argv[1]);
auto iter = programs.find(command);
if (iter != programs.end())
ret = iter->second( argc - 1, argv + 1);
else
ret = print_usage( argc - 1, argv + 1);
}
// Emit a warning when some reads had to be skipped
extern int g_total_reads;
extern int g_unparseable_reads;
extern int g_qc_fail_reads;
extern int g_failed_calibration_reads;
fprintf(stderr, "[post-run summary] total reads: %d unparseable: %d qc fail: %d could not calibrate: %d\n", g_total_reads, g_unparseable_reads, g_qc_fail_reads, g_failed_calibration_reads);
return ret;
}
<commit_msg>dont show post-run stats if no reads parsed by SquiggleRead<commit_after>//---------------------------------------------------------
// Copyright 2015 Ontario Institute for Cancer Research
// Written by Jared Simpson (jared.simpson@oicr.on.ca)
//---------------------------------------------------------
//
// nanopolish.cpp -- main driver program
//
#include <string>
#include <map>
#include <functional>
#include "logsum.h"
#include "nanopolish_extract.h"
#include "nanopolish_call_variants.h"
#include "nanopolish_consensus.h"
#include "nanopolish_eventalign.h"
#include "nanopolish_getmodel.h"
#include "nanopolish_methyltrain.h"
#include "nanopolish_call_methylation.h"
#include "nanopolish_scorereads.h"
#include "nanopolish_phase_reads.h"
#include "nanopolish_train_poremodel_from_basecalls.h"
int print_usage(int argc, char **argv);
int print_version(int argc, char **argv);
static std::map< std::string, std::function<int(int, char**)> > programs = {
{"help", print_usage},
{"--help", print_usage},
{"--version", print_version},
{"extract", extract_main},
{"consensus", consensus_main},
{"eventalign", eventalign_main},
{"getmodel", getmodel_main},
{"variants", call_variants_main},
{"methyltrain", methyltrain_main},
{"scorereads", scorereads_main} ,
{"phase-reads", phase_reads_main} ,
{"call-methylation", call_methylation_main},
{"train-poremodel-from-basecalls", train_poremodel_from_basecalls_main}
};
int print_usage(int, char **)
{
std::cout << "usage: nanopolish [command] [options]" << std::endl;
std::cout << " valid commands: " << std::endl;
for (const auto &item : programs){
std::cout << " " << item.first << std::endl;
}
std::cout << " for help on given command, type nanopolish command --help" << std::endl;
return 0;
}
int print_version(int, char **)
{
static const char *VERSION_MESSAGE =
"nanopolish version " PACKAGE_VERSION "\n"
"Written by Jared Simpson.\n"
"\n"
"Copyright 2015-2017 Ontario Institute for Cancer Research\n";
std::cout << VERSION_MESSAGE << std::endl;
return 0;
}
int main(int argc, char** argv)
{
int ret = 0;
if(argc <= 1) {
printf("error: no command provided\n");
print_usage(argc - 1 , argv + 1);
return 0;
} else {
std::string command(argv[1]);
auto iter = programs.find(command);
if (iter != programs.end())
ret = iter->second( argc - 1, argv + 1);
else
ret = print_usage( argc - 1, argv + 1);
}
// Emit a warning when some reads had to be skipped
extern int g_total_reads;
extern int g_unparseable_reads;
extern int g_qc_fail_reads;
extern int g_failed_calibration_reads;
if(g_total_reads > 0) {
fprintf(stderr, "[post-run summary] total reads: %d unparseable: %d qc fail: %d could not calibrate: %d\n", g_total_reads, g_unparseable_reads, g_qc_fail_reads, g_failed_calibration_reads);
}
return ret;
}
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include "Exception.h"
#include <decaf/util/logging/LoggerDefines.h>
#include <decaf/internal/AprPool.h>
#include <sstream>
#include <apr_strings.h>
using namespace std;
using namespace decaf;
using namespace decaf::internal;
using namespace decaf::lang;
using namespace decaf::util::logging;
////////////////////////////////////////////////////////////////////////////////
Exception::Exception() throw() : Throwable(), cause( NULL ) {
}
////////////////////////////////////////////////////////////////////////////////
Exception::Exception( const Exception& ex ) throw() : Throwable(), cause( NULL ) {
*this = ex;
}
////////////////////////////////////////////////////////////////////////////////
Exception::Exception( const std::exception* cause ) throw() : Throwable(), cause( NULL ) {
this->initCause( cause );
}
////////////////////////////////////////////////////////////////////////////////
Exception::Exception( const char* file, const int lineNumber,
const char* msg, ... ) throw() : Throwable(), cause( NULL ) {
va_list vargs;
va_start( vargs, msg ) ;
buildMessage( msg, vargs );
va_end( vargs );
// Set the first mark for this exception.
setMark( file, lineNumber );
}
////////////////////////////////////////////////////////////////////////////////
Exception::Exception( const char* file, const int lineNumber,
const std::exception* cause,
const char* msg, ... ) throw() : Throwable(), cause( NULL ) {
va_list vargs;
va_start( vargs, msg ) ;
this->buildMessage( msg, vargs );
va_end( vargs );
// Store the cause
this->initCause( cause );
// Set the first mark for this exception.
this->setMark( file, lineNumber );
}
////////////////////////////////////////////////////////////////////////////////
Exception::~Exception() throw(){
delete this->cause;
}
////////////////////////////////////////////////////////////////////////////////
void Exception::setMessage( const char* msg, ... ){
va_list vargs;
va_start( vargs, msg );
buildMessage( msg, vargs );
va_end( vargs );
}
////////////////////////////////////////////////////////////////////////////////
void Exception::buildMessage( const char* format, va_list& vargs ) {
// Allocate buffer with a guess of it's size
AprPool pool;
// Allocate a buffer of the specified size.
char* buffer = apr_pvsprintf( pool.getAprPool(), format, vargs );
// Guessed size was enough. Assign the string.
message.assign( buffer, strlen( buffer ) );
}
////////////////////////////////////////////////////////////////////////////////
void Exception::setMark( const char* file, const int lineNumber ) {
// Add this mark to the end of the stack trace.
stackTrace.push_back( std::make_pair( (std::string)file, (int)lineNumber ) );
//std::ostringstream stream;
//stream << "\tFILE: " << stackTrace[stackTrace.size()-1].first;
//stream << ", LINE: " << stackTrace[stackTrace.size()-1].second;
//decaf::util::logger::SimpleLogger logger("com.yadda2");
//logger.log( stream.str() );
}
////////////////////////////////////////////////////////////////////////////////
Exception* Exception::clone() const {
return new Exception( *this );
}
////////////////////////////////////////////////////////////////////////////////
std::vector< std::pair< std::string, int> > Exception::getStackTrace() const {
return stackTrace;
}
////////////////////////////////////////////////////////////////////////////////
void Exception::setStackTrace(
const std::vector< std::pair< std::string, int> >& trace ) {
this->stackTrace = trace;
}
////////////////////////////////////////////////////////////////////////////////
void Exception::printStackTrace() const {
printStackTrace( std::cerr );
}
////////////////////////////////////////////////////////////////////////////////
void Exception::printStackTrace( std::ostream& stream ) const {
stream << getStackTraceString();
}
////////////////////////////////////////////////////////////////////////////////
std::string Exception::getStackTraceString() const {
// Create the output stream.
std::ostringstream stream;
// Write the message and each stack entry.
stream << message << std::endl;
for( unsigned int ix=0; ix<stackTrace.size(); ++ix ){
stream << "\tFILE: " << stackTrace[ix].first;
stream << ", LINE: " << stackTrace[ix].second;
stream << std::endl;
}
// Return the string from the output stream.
return stream.str();
}
////////////////////////////////////////////////////////////////////////////////
Exception& Exception::operator =( const Exception& ex ){
this->message = ex.message;
this->stackTrace = ex.stackTrace;
this->initCause( ex.cause );
return *this;
}
////////////////////////////////////////////////////////////////////////////////
void Exception::initCause( const std::exception* cause ) {
if( cause == NULL || cause == this ) {
return;
}
if( this->cause != NULL ) {
delete this->cause;
}
const Exception* ptrCause = dynamic_cast<const Exception*>( cause );
if( ptrCause == NULL ) {
this->cause = new Exception( __FILE__, __LINE__, cause->what() );
} else {
this->cause = ptrCause->clone();
}
if( this->message == "" ) {
this->message = cause->what();
}
}
<commit_msg>change the make_pair call from a std::string cast to a std::string temporary.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include "Exception.h"
#include <decaf/util/logging/LoggerDefines.h>
#include <decaf/internal/AprPool.h>
#include <sstream>
#include <apr_strings.h>
using namespace std;
using namespace decaf;
using namespace decaf::internal;
using namespace decaf::lang;
using namespace decaf::util::logging;
////////////////////////////////////////////////////////////////////////////////
Exception::Exception() throw() : Throwable(), cause( NULL ) {
}
////////////////////////////////////////////////////////////////////////////////
Exception::Exception( const Exception& ex ) throw() : Throwable(), cause( NULL ) {
*this = ex;
}
////////////////////////////////////////////////////////////////////////////////
Exception::Exception( const std::exception* cause ) throw() : Throwable(), cause( NULL ) {
this->initCause( cause );
}
////////////////////////////////////////////////////////////////////////////////
Exception::Exception( const char* file, const int lineNumber,
const char* msg, ... ) throw() : Throwable(), cause( NULL ) {
va_list vargs;
va_start( vargs, msg ) ;
buildMessage( msg, vargs );
va_end( vargs );
// Set the first mark for this exception.
setMark( file, lineNumber );
}
////////////////////////////////////////////////////////////////////////////////
Exception::Exception( const char* file, const int lineNumber,
const std::exception* cause,
const char* msg, ... ) throw() : Throwable(), cause( NULL ) {
va_list vargs;
va_start( vargs, msg ) ;
this->buildMessage( msg, vargs );
va_end( vargs );
// Store the cause
this->initCause( cause );
// Set the first mark for this exception.
this->setMark( file, lineNumber );
}
////////////////////////////////////////////////////////////////////////////////
Exception::~Exception() throw(){
delete this->cause;
}
////////////////////////////////////////////////////////////////////////////////
void Exception::setMessage( const char* msg, ... ){
va_list vargs;
va_start( vargs, msg );
buildMessage( msg, vargs );
va_end( vargs );
}
////////////////////////////////////////////////////////////////////////////////
void Exception::buildMessage( const char* format, va_list& vargs ) {
// Allocate buffer with a guess of it's size
AprPool pool;
// Allocate a buffer of the specified size.
char* buffer = apr_pvsprintf( pool.getAprPool(), format, vargs );
// Guessed size was enough. Assign the string.
message.assign( buffer, strlen( buffer ) );
}
////////////////////////////////////////////////////////////////////////////////
void Exception::setMark( const char* file, const int lineNumber ) {
// Add this mark to the end of the stack trace.
stackTrace.push_back( std::make_pair( std::string( file ), (int)lineNumber ) );
//std::ostringstream stream;
//stream << "\tFILE: " << stackTrace[stackTrace.size()-1].first;
//stream << ", LINE: " << stackTrace[stackTrace.size()-1].second;
//decaf::util::logger::SimpleLogger logger("com.yadda2");
//logger.log( stream.str() );
}
////////////////////////////////////////////////////////////////////////////////
Exception* Exception::clone() const {
return new Exception( *this );
}
////////////////////////////////////////////////////////////////////////////////
std::vector< std::pair< std::string, int> > Exception::getStackTrace() const {
return stackTrace;
}
////////////////////////////////////////////////////////////////////////////////
void Exception::setStackTrace(
const std::vector< std::pair< std::string, int> >& trace ) {
this->stackTrace = trace;
}
////////////////////////////////////////////////////////////////////////////////
void Exception::printStackTrace() const {
printStackTrace( std::cerr );
}
////////////////////////////////////////////////////////////////////////////////
void Exception::printStackTrace( std::ostream& stream ) const {
stream << getStackTraceString();
}
////////////////////////////////////////////////////////////////////////////////
std::string Exception::getStackTraceString() const {
// Create the output stream.
std::ostringstream stream;
// Write the message and each stack entry.
stream << message << std::endl;
for( unsigned int ix=0; ix<stackTrace.size(); ++ix ){
stream << "\tFILE: " << stackTrace[ix].first;
stream << ", LINE: " << stackTrace[ix].second;
stream << std::endl;
}
// Return the string from the output stream.
return stream.str();
}
////////////////////////////////////////////////////////////////////////////////
Exception& Exception::operator =( const Exception& ex ){
this->message = ex.message;
this->stackTrace = ex.stackTrace;
this->initCause( ex.cause );
return *this;
}
////////////////////////////////////////////////////////////////////////////////
void Exception::initCause( const std::exception* cause ) {
if( cause == NULL || cause == this ) {
return;
}
if( this->cause != NULL ) {
delete this->cause;
}
const Exception* ptrCause = dynamic_cast<const Exception*>( cause );
if( ptrCause == NULL ) {
this->cause = new Exception( __FILE__, __LINE__, cause->what() );
} else {
this->cause = ptrCause->clone();
}
if( this->message == "" ) {
this->message = cause->what();
}
}
<|endoftext|> |
<commit_before>// Filename: config_event.cxx
// Created by: drose (14Dec99)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "config_event.h"
#include "asyncTask.h"
#include "asyncTaskChain.h"
#include "asyncTaskManager.h"
#include "asyncTaskPause.h"
#include "asyncTaskSequence.h"
#include "buttonEventList.h"
#include "event.h"
#include "eventHandler.h"
#include "eventParameter.h"
#include "genericAsyncTask.h"
#include "pointerEventList.h"
#include "pythonTask.h"
#include "dconfig.h"
Configure(config_event);
NotifyCategoryDef(event, "");
NotifyCategoryDef(task, "");
ConfigureFn(config_event) {
AsyncTask::init_type();
AsyncTaskChain::init_type();
AsyncTaskManager::init_type();
AsyncTaskPause::init_type();
AsyncTaskSequence::init_type();
ButtonEventList::init_type();
PointerEventList::init_type();
Event::init_type();
EventHandler::init_type();
EventStoreValueBase::init_type();
EventStoreInt::init_type("EventStoreInt");
EventStoreDouble::init_type("EventStoreDouble");
EventStoreString::init_type("EventStoreString");
EventStoreWstring::init_type("EventStoreWstring");
EventStoreTypedRefCount::init_type();
GenericAsyncTask::init_type();
PythonTask::init_type();
ButtonEventList::register_with_read_factory();
EventStoreInt::register_with_read_factory();
EventStoreDouble::register_with_read_factory();
EventStoreString::register_with_read_factory();
}
<commit_msg>Compile without python<commit_after>// Filename: config_event.cxx
// Created by: drose (14Dec99)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "config_event.h"
#include "asyncTask.h"
#include "asyncTaskChain.h"
#include "asyncTaskManager.h"
#include "asyncTaskPause.h"
#include "asyncTaskSequence.h"
#include "buttonEventList.h"
#include "event.h"
#include "eventHandler.h"
#include "eventParameter.h"
#include "genericAsyncTask.h"
#include "pointerEventList.h"
#include "pythonTask.h"
#include "dconfig.h"
Configure(config_event);
NotifyCategoryDef(event, "");
NotifyCategoryDef(task, "");
ConfigureFn(config_event) {
AsyncTask::init_type();
AsyncTaskChain::init_type();
AsyncTaskManager::init_type();
AsyncTaskPause::init_type();
AsyncTaskSequence::init_type();
ButtonEventList::init_type();
PointerEventList::init_type();
Event::init_type();
EventHandler::init_type();
EventStoreValueBase::init_type();
EventStoreInt::init_type("EventStoreInt");
EventStoreDouble::init_type("EventStoreDouble");
EventStoreString::init_type("EventStoreString");
EventStoreWstring::init_type("EventStoreWstring");
EventStoreTypedRefCount::init_type();
GenericAsyncTask::init_type();
#ifdef HAVE_PYTHON
PythonTask::init_type();
#endif
ButtonEventList::register_with_read_factory();
EventStoreInt::register_with_read_factory();
EventStoreDouble::register_with_read_factory();
EventStoreString::register_with_read_factory();
}
<|endoftext|> |
<commit_before>/**
Copyright 2017 Daniel Garcia Vaglio <degv364@gmail.com> Esteban Zamora Alvarado <>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/
// FIXME: check if one can include c++ auto killing pointer in this microcontroller, if yes
// avoid using normal pointers at all cost :)
#ifdef TESTING
#include <iostream>
// FIXME: check if this can be included in microcontroller
#include <cstdint>
#endif
#include "hi_def.hh"
#ifndef HI_UTILS_TEMP
#define HI_UTILS_TEMP
//Templated, to increase generality
template<typename INT, typename FLOAT>
class Hi_dual_mean_fifo{
private:
// count to know if one have enough values to have valid results
uint16_t current_valid_values;
//array to store values
INT data[MAX_SAMPLES];
//limit of the fifo
uint16_t subs_index;
// get mean until this member
uint16_t comp_index;
// 5 seconds mean
FLOAT mean;
// last second mean
FLOAT last_mean;
/*
* Reset data to a value
*/
hi_return_e
reset_to_value(INT value){
//reset count of valid values
this->current_valid_values = 0;
for (uint16_t index; index< MAX_SAMPLES; index++){
this->data[index] = value;
}
this->mean = (FLOAT)value;
this->last_mean = (FLOAT)value;
return HI_RETURN_OK;
}
/*
* MOve pointer to next sample
*/
hi_return_e
move_next_sample(){
this->subs_index=(this->subs_index+MAX_SAMPLES-1)%MAX_SAMPLES;
this->comp_index=(this->comp_index+MAX_SAMPLES-1)%MAX_SAMPLES;
return HI_RETURN_OK;
}
public:
Hi_dual_mean_fifo(void){
this->subs_index = 0;
this->comp_index = SAMPLES_PER_SECOND;
this->reset_to_value(0);
}
~Hi_dual_mean_fifo(void){
// FIXME:add destructor
reset_to_value(0);
}
/*
* Adds a new sample
*/
hi_return_e
add_sample(INT sample){
//update 5 second mean
this->mean+=(FLOAT)this->data[this->comp_index]/MEAN_SAMPLES;
this->mean-=(FLOAT)this->data[this->subs_index]/MEAN_SAMPLES;
//update last second mean
this->last_mean+=(FLOAT)sample/SAMPLES_PER_SECOND;
this->last_mean-=(FLOAT)this->data[this->comp_index]/SAMPLES_PER_SECOND;
//update data
this->data[this->subs_index] = sample;
this->move_next_sample();
//update valid data count
this->current_valid_values =
(this->current_valid_values>=MAX_SAMPLES) ? MAX_SAMPLES : this->current_valid_values+1;
return HI_RETURN_OK;
}
/*
* Returns true if the last second mean is more than 5% of the last 5 second mean and,
* there are enough valid values
*/
hi_return_e
is_last_second_big(bool *is_big){
// get percentage
FLOAT five_percent;
five_percent = this->mean * 0.05;
if (this->mean+five_percent<this->last_mean){
*is_big = (this->current_valid_values >= MAX_SAMPLES);
}
else{
*is_big = false;
}
return HI_RETURN_OK;
}
#ifdef TESTING
FLOAT
get_mean(){
return this->mean;
}
FLOAT
get_last_mean(){
return this->last_mean;
}
#endif
};
#endif //HI_UTILS_TEMP
<commit_msg>Add bad parameters handling to dual fifo class<commit_after>/**
Copyright 2017 Daniel Garcia Vaglio <degv364@gmail.com> Esteban Zamora Alvarado <>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**/
// FIXME: check if one can include c++ auto killing pointer in this microcontroller, if yes
// avoid using normal pointers at all cost :)
#ifdef TESTING
#include <iostream>
// FIXME: check if this can be included in microcontroller
#include <cstdint>
#endif
#include "hi_def.hh"
#ifndef HI_UTILS_TEMP
#define HI_UTILS_TEMP
//Templated, to increase generality
template<typename INT, typename FLOAT>
class Hi_dual_mean_fifo{
private:
// count to know if one have enough values to have valid results
uint16_t current_valid_values;
//array to store values
INT data[MAX_SAMPLES];
//limit of the fifo
uint16_t subs_index;
// get mean until this member
uint16_t comp_index;
// 5 seconds mean
FLOAT mean;
// last second mean
FLOAT last_mean;
/*
* Reset data to a value
*/
hi_return_e
reset_to_value(INT value){
//reset count of valid values
this->current_valid_values = 0;
for (uint16_t index; index< MAX_SAMPLES; index++){
this->data[index] = value;
}
this->mean = (FLOAT)value;
this->last_mean = (FLOAT)value;
return HI_RETURN_OK;
}
/*
* MOve pointer to next sample
*/
hi_return_e
move_next_sample(){
this->subs_index=(this->subs_index+MAX_SAMPLES-1)%MAX_SAMPLES;
this->comp_index=(this->comp_index+MAX_SAMPLES-1)%MAX_SAMPLES;
return HI_RETURN_OK;
}
public:
Hi_dual_mean_fifo(void){
this->subs_index = 0;
this->comp_index = SAMPLES_PER_SECOND;
this->reset_to_value(0);
}
~Hi_dual_mean_fifo(void){
// FIXME:add destructor
reset_to_value(0);
}
/*
* Adds a new sample
*/
hi_return_e
add_sample(INT sample){
//update 5 second mean
this->mean+=(FLOAT)this->data[this->comp_index]/MEAN_SAMPLES;
this->mean-=(FLOAT)this->data[this->subs_index]/MEAN_SAMPLES;
//update last second mean
this->last_mean+=(FLOAT)sample/SAMPLES_PER_SECOND;
this->last_mean-=(FLOAT)this->data[this->comp_index]/SAMPLES_PER_SECOND;
//update data
this->data[this->subs_index] = sample;
this->move_next_sample();
//update valid data count
this->current_valid_values =
(this->current_valid_values>=MAX_SAMPLES) ? MAX_SAMPLES : this->current_valid_values+1;
return HI_RETURN_OK;
}
/*
* Returns true if the last second mean is more than 5% of the last 5 second mean and,
* there are enough valid values
*/
hi_return_e
is_last_second_big(bool *is_big){
FLOAT five_percent;
if (is_big == NULL){
return HI_RETURN_BAD_PARAM;
}
five_percent = this->mean * 0.05;
if (this->mean+five_percent<this->last_mean){
*is_big = (this->current_valid_values >= MAX_SAMPLES);
}
else{
*is_big = false;
}
return HI_RETURN_OK;
}
#ifdef TESTING
FLOAT
get_mean(){
return this->mean;
}
FLOAT
get_last_mean(){
return this->last_mean;
}
#endif
};
#endif //HI_UTILS_TEMP
<|endoftext|> |
<commit_before>#include "lab1_widget.hxx"
#include <QFileDialog>
#include <QString>
#include <QFile>
#include <QDebug>
#include <QTextStream>
#include <QProcess>
#include <QMessageBox>
#include <cassert>
Lab1_Widget::Lab1_Widget(QWidget *parent) :
QWidget(parent),
main_layout( new QVBoxLayout(this)),
buttons_layout( new QHBoxLayout(nullptr)),
input_button( new QPushButton(trUtf8("View input"), this)),
output_button( new QPushButton(trUtf8("View output"), this)),
label( new QLabel(this)),
open_button( new QPushButton(trUtf8("Open file"), this))
{
input_button->setEnabled(false);
output_button->setEnabled(false);
buttons_layout->addWidget(input_button);
buttons_layout->addWidget(output_button);
main_layout->addLayout(buttons_layout);
main_layout->addWidget(label);
main_layout->addWidget(open_button);
connect(open_button, SIGNAL(clicked()), this, SLOT(open_and_solve()));
connect(input_button, SIGNAL(clicked()), this, SLOT(view_input()));
connect(output_button, SIGNAL(clicked()), this, SLOT(view_output()));
if (!prepare_script())
close();
}
Lab1_Widget::~Lab1_Widget()
{
delete buttons_layout;
}
bool Lab1_Widget::prepare_script()
{
static const QString SCRIPT("mask=tmp_$$\n"
"/bin/cp $1 $mask.tex\n"
"/usr/bin/latex $mask.tex\n"
"/usr/bin/dvipng -D 600 $mask.dvi -o $mask.png\n"
"/usr/bin/convert -scale 400x400 $mask.png $2.png\n"
"/bin/rm -f $mask.*\n");
script = new QTemporaryFile(this);
if (!script->open()) {
qDebug() << trUtf8("Cannot open script file.");
return false;
}
QTextStream outs(script);
outs << SCRIPT;
outs.flush();
script->close();
return true;
}
bool Lab1_Widget::read_matrix(const QString& filename)
{
QFile file(filename);
if (!file.exists()) {
qDebug() << trUtf8("File doesn't exist");
return false;
}
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << trUtf8("Cannot open file for reading");
return false;
}
std::size_t n;
QTextStream in(&file);
in >> n;
if (in.atEnd()) {
qDebug() << trUtf8("Empty file");
return false;
}
auto result = new bnu::matrix< qreal >(n, n + 1, 0.0);
for (auto i(0); n != i; ++i)
for (auto j(0); n >= j; ++j) {
QString _value;
in >> _value;
if (in.atEnd()) {
qDebug() << trUtf8("Unexpected end of file");
delete result;
return false;
}
bool conversion_is_ok;
auto value = _value.toDouble(&conversion_is_ok);
if (!conversion_is_ok) {
qDebug() << trUtf8("Incorrect value: ") + _value;
delete result;
return false;
}
result->insert_element(i, j, value);
}
A = *result;
return true;
}
QString Lab1_Widget::matrix_to_string() const
{
assert(A.size1() < A.size2());
QString result("\\left(\\begin{array}{");
for (auto i(0); A.size1() != i; ++i)
result += "c";
result += "|c}";
for (auto i(0); A.size1() != i; ++i) {
for (auto j(0); A.size2() != j; ++j) {
result += QString("%1").arg(A(i, j), 0, 'f', 3);
if (A.size2() - 1 != j)
result += " & ";
}
result += "\\\\";
}
result += "\\end{array}\\right)";
return result;
}
bool Lab1_Widget::compile_latex_string(const QString& input,
const QString& filename) const
{
QTemporaryFile file;
if (!file.open()) {
qDebug() << tr("Cannot open temporary file.");
return false;
}
QTextStream out(&file);
out << "\\documentclass[12pt]{scrartcl}\n\\usepackage[utf8]{inputenc}\n"
"\\usepackage{concrete}\n\\begin{document}\n\\thispagestyle{empty}\n"
"\\setbox0=\\hbox{$";
out << input;
out << "$}\n\\textheight=\\ht0\n\\advance\\textwidth by 2em\n"
"\\advance\\textheight by 2\\dp0\n"
"\\vbox{\\vss\\hbox{\\hss\\copy0\\hss}\\vss}\n\\end{document}";
out.flush();
file.close();
QProcess process;
QStringList arguments;
arguments << script->fileName() << file.fileName() << filename;
process.start("/bin/sh", arguments);
return process.waitForFinished();
}
int Lab1_Widget::determinant_sign(const bnu::permutation_matrix< std::size_t
>& pm) const
{
auto pm_sign( 1 );
const auto size( pm.size() );
for (auto i( 0 ); size != i; ++i)
if (i != pm(i))
pm_sign *= -1;
return pm_sign;
}
double Lab1_Widget::determinant( const bnu::matrix< double >& A) const
{
bnu::matrix< double > m(A.size1(), A.size1(), 0.0);
for (auto i( 0 ); A.size1() != i; ++i)
for (auto j( 0 ); A.size1() != j; ++j)
m(i, j) = A(i, j);
bnu::permutation_matrix< std::size_t > pm(m.size1());
auto det(1.0);
if ( bnu::lu_factorize(m, pm))
{
det = 0.0;
}
else
{
for (auto i( 0 ); m.size1() != i; ++i)
det *= m(i, i);
det = det * determinant_sign( pm );
}
return det;
}
void Lab1_Widget::solve(const double epsilon)
{
for (auto p(0); A.size1() != p; ++p) {
auto divider(A(p, p));
for (auto i(0); A.size1() != i; ++i) {
if (i != p) {
auto scale(A(i, p));
for (auto j(0); A.size2() != j; ++j) {
A(i, j) = (A(p, j) * scale / divider) - A(i, j);
}
}
}
}
for (auto p(0); A.size1() != p; ++p) {
auto scale(A(p, p));
for (auto j(0); A.size2() != j; ++j) {
if ((epsilon < qAbs(A(p, j))) && (epsilon < qAbs(scale))) {
A(p, j) /= scale;
} else {
A(p, j) = 0.0;
}
}
}
}
void Lab1_Widget::open_and_solve()
{
input_button->setEnabled(false);
output_button->setEnabled(false);
label->clear();
auto filename = QFileDialog::getOpenFileName(this,
trUtf8("Select input file"),
"/home/");
auto is_ok = read_matrix(filename);
if (!is_ok) {
qDebug() << trUtf8("There was an error while reading matrix.");
QMessageBox::critical(this, trUtf8("Error"),
trUtf8("There was an error with reading from file"));
} else {
if (!compile_latex_string(matrix_to_string(), "/tmp/input")) {
qDebug() << trUtf8("Cannot compile input matrix into PNG.");
QMessageBox::critical(this, trUtf8("Error"),
trUtf8("Cannot compile input matrix into PNG."));
return;
}
if (0.0001 > qAbs(determinant(A)))
{
QMessageBox::critical(this, trUtf8("Error"),
trUtf8("det(A) = 0!"));
return;
}
solve();
if (!compile_latex_string(matrix_to_string(), "/tmp/output")) {
qDebug() << trUtf8("Cannot compile output matrix into PNG.");
QMessageBox::critical(this, trUtf8("Error"),
trUtf8("Cannot compile output matrix into PNG."));
return;
}
view_input();
}
}
void Lab1_Widget::view_input()
{
label->setPixmap(QPixmap("/tmp/input.png"));
input_button->setEnabled(false);
output_button->setEnabled(true);
}
void Lab1_Widget::view_output()
{
label->setPixmap(QPixmap("/tmp/output.png"));
input_button->setEnabled(true);
output_button->setEnabled(false);
}
// kate: indent-mode cstyle; indent-width 4; replace-tabs on;
<commit_msg>+minimum size for lab1<commit_after>#include "lab1_widget.hxx"
#include <QFileDialog>
#include <QString>
#include <QFile>
#include <QDebug>
#include <QTextStream>
#include <QProcess>
#include <QMessageBox>
#include <QSize>
#include <cassert>
Lab1_Widget::Lab1_Widget(QWidget *parent) :
QWidget(parent),
main_layout( new QVBoxLayout(this)),
buttons_layout( new QHBoxLayout(nullptr)),
input_button( new QPushButton(trUtf8("View input"), this)),
output_button( new QPushButton(trUtf8("View output"), this)),
label( new QLabel(this)),
open_button( new QPushButton(trUtf8("Open file"), this))
{
input_button->setEnabled(false);
output_button->setEnabled(false);
buttons_layout->addWidget(input_button);
buttons_layout->addWidget(output_button);
main_layout->addLayout(buttons_layout);
main_layout->addWidget(label);
main_layout->addWidget(open_button);
connect(open_button, SIGNAL(clicked()), this, SLOT(open_and_solve()));
connect(input_button, SIGNAL(clicked()), this, SLOT(view_input()));
connect(output_button, SIGNAL(clicked()), this, SLOT(view_output()));
setMinimumSize(QSize(418, 198));
if (!prepare_script())
close();
}
Lab1_Widget::~Lab1_Widget()
{
delete buttons_layout;
}
bool Lab1_Widget::prepare_script()
{
static const QString SCRIPT("mask=tmp_$$\n"
"/bin/cp $1 $mask.tex\n"
"/usr/bin/latex $mask.tex\n"
"/usr/bin/dvipng -D 600 $mask.dvi -o $mask.png\n"
"/usr/bin/convert -scale 400x400 $mask.png $2.png\n"
"/bin/rm -f $mask.*\n");
script = new QTemporaryFile(this);
if (!script->open()) {
qDebug() << trUtf8("Cannot open script file.");
return false;
}
QTextStream outs(script);
outs << SCRIPT;
outs.flush();
script->close();
return true;
}
bool Lab1_Widget::read_matrix(const QString& filename)
{
QFile file(filename);
if (!file.exists()) {
qDebug() << trUtf8("File doesn't exist");
return false;
}
if (!file.open(QIODevice::ReadOnly)) {
qDebug() << trUtf8("Cannot open file for reading");
return false;
}
std::size_t n;
QTextStream in(&file);
in >> n;
if (in.atEnd()) {
qDebug() << trUtf8("Empty file");
return false;
}
auto result = new bnu::matrix< qreal >(n, n + 1, 0.0);
for (auto i(0); n != i; ++i)
for (auto j(0); n >= j; ++j) {
QString _value;
in >> _value;
if (in.atEnd()) {
qDebug() << trUtf8("Unexpected end of file");
delete result;
return false;
}
bool conversion_is_ok;
auto value = _value.toDouble(&conversion_is_ok);
if (!conversion_is_ok) {
qDebug() << trUtf8("Incorrect value: ") + _value;
delete result;
return false;
}
result->insert_element(i, j, value);
}
A = *result;
return true;
}
QString Lab1_Widget::matrix_to_string() const
{
assert(A.size1() < A.size2());
QString result("\\left(\\begin{array}{");
for (auto i(0); A.size1() != i; ++i)
result += "c";
result += "|c}";
for (auto i(0); A.size1() != i; ++i) {
for (auto j(0); A.size2() != j; ++j) {
result += QString("%1").arg(A(i, j), 0, 'f', 3);
if (A.size2() - 1 != j)
result += " & ";
}
result += "\\\\";
}
result += "\\end{array}\\right)";
return result;
}
bool Lab1_Widget::compile_latex_string(const QString& input,
const QString& filename) const
{
QTemporaryFile file;
if (!file.open()) {
qDebug() << tr("Cannot open temporary file.");
return false;
}
QTextStream out(&file);
out << "\\documentclass[12pt]{scrartcl}\n\\usepackage[utf8]{inputenc}\n"
"\\usepackage{concrete}\n\\begin{document}\n\\thispagestyle{empty}\n"
"\\setbox0=\\hbox{$";
out << input;
out << "$}\n\\textheight=\\ht0\n\\advance\\textwidth by 2em\n"
"\\advance\\textheight by 2\\dp0\n"
"\\vbox{\\vss\\hbox{\\hss\\copy0\\hss}\\vss}\n\\end{document}";
out.flush();
file.close();
QProcess process;
QStringList arguments;
arguments << script->fileName() << file.fileName() << filename;
process.start("/bin/sh", arguments);
return process.waitForFinished();
}
int Lab1_Widget::determinant_sign(const bnu::permutation_matrix< std::size_t
>& pm) const
{
auto pm_sign( 1 );
const auto size( pm.size() );
for (auto i( 0 ); size != i; ++i)
if (i != pm(i))
pm_sign *= -1;
return pm_sign;
}
double Lab1_Widget::determinant( const bnu::matrix< double >& A) const
{
bnu::matrix< double > m(A.size1(), A.size1(), 0.0);
for (auto i( 0 ); A.size1() != i; ++i)
for (auto j( 0 ); A.size1() != j; ++j)
m(i, j) = A(i, j);
bnu::permutation_matrix< std::size_t > pm(m.size1());
auto det(1.0);
if ( bnu::lu_factorize(m, pm))
{
det = 0.0;
}
else
{
for (auto i( 0 ); m.size1() != i; ++i)
det *= m(i, i);
det = det * determinant_sign( pm );
}
return det;
}
void Lab1_Widget::solve(const double epsilon)
{
for (auto p(0); A.size1() != p; ++p) {
auto divider(A(p, p));
for (auto i(0); A.size1() != i; ++i) {
if (i != p) {
auto scale(A(i, p));
for (auto j(0); A.size2() != j; ++j) {
A(i, j) = (A(p, j) * scale / divider) - A(i, j);
}
}
}
}
for (auto p(0); A.size1() != p; ++p) {
auto scale(A(p, p));
for (auto j(0); A.size2() != j; ++j) {
if ((epsilon < qAbs(A(p, j))) && (epsilon < qAbs(scale))) {
A(p, j) /= scale;
} else {
A(p, j) = 0.0;
}
}
}
}
void Lab1_Widget::open_and_solve()
{
input_button->setEnabled(false);
output_button->setEnabled(false);
label->clear();
auto filename = QFileDialog::getOpenFileName(this,
trUtf8("Select input file"),
"/home/");
auto is_ok = read_matrix(filename);
if (!is_ok) {
qDebug() << trUtf8("There was an error while reading matrix.");
QMessageBox::critical(this, trUtf8("Error"),
trUtf8("There was an error with reading from file"));
} else {
if (!compile_latex_string(matrix_to_string(), "/tmp/input")) {
qDebug() << trUtf8("Cannot compile input matrix into PNG.");
QMessageBox::critical(this, trUtf8("Error"),
trUtf8("Cannot compile input matrix into PNG."));
return;
}
if (0.0001 > qAbs(determinant(A)))
{
QMessageBox::critical(this, trUtf8("Error"),
trUtf8("det(A) = 0!"));
return;
}
solve();
if (!compile_latex_string(matrix_to_string(), "/tmp/output")) {
qDebug() << trUtf8("Cannot compile output matrix into PNG.");
QMessageBox::critical(this, trUtf8("Error"),
trUtf8("Cannot compile output matrix into PNG."));
return;
}
view_input();
}
}
void Lab1_Widget::view_input()
{
label->setPixmap(QPixmap("/tmp/input.png"));
input_button->setEnabled(false);
output_button->setEnabled(true);
}
void Lab1_Widget::view_output()
{
label->setPixmap(QPixmap("/tmp/output.png"));
input_button->setEnabled(true);
output_button->setEnabled(false);
}
// kate: indent-mode cstyle; indent-width 4; replace-tabs on;
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl; //Print out Hello World
cout << "Aaron Skomra" << endl; //Edit Hello World to print out your name
//Printing "David Snyder" to the command line
cout << "David Snyder" << endl;
cout << "Ben Huddle" << endl; // Printing out Ben Huddle
return 0;
}
<commit_msg>Added my name to the file.<commit_after>#include <iostream>
using namespace std;
int main() {
cout << "Hello World" << endl; //Print out Hello World
cout << "Aaron Skomra" << endl; //Edit Hello World to print out your name
//Printing "David Snyder" to the command line
cout << "David Snyder" << endl;
cout << "Ben Huddle" << endl; // Printing out Ben Huddle
// This is a change I've made
cout << "Jess VanDerwalker" << endl;
return 0;
}
<|endoftext|> |
<commit_before>/***************************************************************************
jabberprotocol.cpp - Jabber Plugin
-------------------
begin : Fri Apr 12 2002
copyright : (C) 2002 by Daniel Stone
email : daniel@raging.dropbear.id.au
***************************************************************************
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <qcursor.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include "kopete.h"
#include "jabberprotocol.h"
#include "statusbaricon.h"
JabberProtocol::JabberProtocol(): QObject(0, "JabberProtocol"), KopeteProtocol() {
kdDebug() << "\nJabber plugin: Loading ..." << endl;
initIcons();
initActions();
authContact = new KMessageBox;
protocol = new KJabber;
connect(protocol, SIGNAL(contactUpdated(QString, QString, QString, QString)), this, SLOT(slotContactUpdated(QString, QString, QString, QString)));
connect(protocol, SIGNAL(userWantsAuth(QString)), this, SLOT(slotUserWantsAuth(QString)));
connect(protocol, SIGNAL(newContact(QString, QString, QString)), this, SLOT(slotNewContact(QString, QString, QString)));
statusBarIcon = new StatusBarIcon();
QObject::connect(statusBarIcon, SIGNAL(rightClicked(const QPoint)), this, SLOT(slotIconRightClicked(const QPoint)));
statusBarIcon->setPixmap(offlineIcon);
mPrefs = new JabberPreferences("jabber_protocol_32", this);
connect(mPrefs, SIGNAL(saved(void)), this, SLOT(settingsChanged(void)));
KGlobal::config()->setGroup("Jabber");
if ((KGlobal::config()->readEntry("UserID", "") == "" ) || (KGlobal::config()->readEntry("Password", "") == "" )) {
QString emptyText = i18n( "<qt>If you have a Jabber account, please configure it in the Kopete Settings. If you don't, please create one with another app; registering is not yet supported in Kopete.</qt>" );
QString emptyCaption = i18n( "No Jabber Configuration found!" );
KMessageBox::error(kopeteapp->mainWindow(), emptyText, emptyCaption);
}
mIsConnected = false;
/** Autoconnect if is selected in config */
if (KGlobal::config()->readBoolEntry("AutoConnect", "0")) {
Connect();
}
slotSettingsChanged();
}
JabberProtocol::~JabberProtocol()
{
}
void JabberProtocol::init()
{
}
bool JabberProtocol::unload()
{
kdDebug() << "Jabber plugin: Unloading...\n";
if( kopeteapp->statusBar() )
{
kopeteapp->statusBar()->removeWidget(statusBarIcon);
delete statusBarIcon;
}
emit protocolUnloading();
return true;
}
void JabberProtocol::Connect() {
if (!isConnected()) {
kdDebug() << "Jabber plugin: Attempting to connect to Jabber server " << m_Server << ":" << m_Port << endl;
kdDebug() << "Jabber plugin: Using UserID " << m_Username << " with password " << m_Password << endl;
protocol->Connect(m_Server, m_Port, m_Username, m_Password, m_Resource);
mIsConnected = true;
statusBarIcon->setPixmap(onlineIcon);
}
else if (isAway()) { /* They're really away, and they want to un-away. */
slotGoOnline();
}
else { /* Nope, just your regular crack junky. */
kdDebug() << "Jabber plugin: Ignoring connect request (already connected)." << endl;
}
}
void JabberProtocol::Disconnect() {
if (isConnected()) {
protocol->Disconnect();
kdDebug() << "Jabber plugin: Disconnected." << endl;
mIsConnected = false;
statusBarIcon->setPixmap(offlineIcon);
emit nukeContacts(false);
}
else { /* Again, what's with the crack? Sheez. */
kdDebug() << "Jabber plugin: Ignoring disconnect request (not connected)." << endl;
}
}
void JabberProtocol::slotConnect() {
Connect();
}
void JabberProtocol::slotDisconnect() {
Disconnect();
}
bool JabberProtocol::isConnected() const {
return mIsConnected;
}
void JabberProtocol::setAway(void) {
slotSetAway();
}
void JabberProtocol::setAvailable(void) {
slotGoOnline();
}
bool JabberProtocol::isAway(void) const {
if (isConnected()) {
return (protocol->getStatus() == "away" || protocol->getStatus() == "xa" || protocol->getStatus() == "dnd");
}
else {
return false;
}
}
QString JabberProtocol::protocolIcon() const {
return "jabber_protocol_32";
}
AddContactPage *JabberProtocol::createAddContactWidget(QWidget *parent) {
return new JabberAddContactPage(this, parent);
}
void JabberProtocol::initIcons() {
KIconLoader *loader = KGlobal::iconLoader();
KStandardDirs dir;
onlineIcon = QPixmap(loader->loadIcon("jabber_online", KIcon::User));
offlineIcon = QPixmap(loader->loadIcon("jabber_offline", KIcon::User));
awayIcon = QPixmap(loader->loadIcon("jabber_away", KIcon::User));
naIcon = QPixmap(loader->loadIcon("jabber_na", KIcon::User));
connectingIcon = QMovie(dir.findResource("data","kopete/pics/jabber_connecting.mng"));
}
void JabberProtocol::initActions() {
actionGoOnline = new KAction (i18n("Online"), "jabber_online", 0, this, SLOT(slotConnect()), this, "actionJabberConnect" );
actionGoAway = new KAction (i18n("Away"), "jabber_away", 0, this, SLOT(slotSetAway()), this, "actionJabberConnect");
actionGoXA = new KAction(i18n("Extended Away"), "jabber_away", 0, this, SLOT(slotSetXA()), this, "actionJabberConnect");
actionGoDND = new KAction(i18n("Do Not Disturb"), "jabber_na", 0, this, SLOT(slotSetDND()), this, "actionJabberConnect");
actionGoOffline = new KAction (i18n("Offline"), "jabber_offline", 0, this, SLOT(slotDisconnect()), this, "actionJabberConnect" );
actionStatusMenu = new KActionMenu("Jabber",this);
actionStatusMenu->insert(actionGoOnline);
actionStatusMenu->insert(actionGoAway);
actionStatusMenu->insert(actionGoXA);
actionStatusMenu->insert(actionGoDND);
actionStatusMenu->insert(actionGoOffline);
actionStatusMenu->plug(kopeteapp->systemTray()->contextMenu(), 1);
}
void JabberProtocol::slotConnecting() { /* Aw, look at the cute widdle MNG. */
statusBarIcon->setMovie(connectingIcon);
}
void JabberProtocol::slotConnected() {
mIsConnected = true;
kdDebug() << "Jabber plugin: Connected to Jabber server." << endl;
slotGoOnline();
}
void JabberProtocol::slotDisconnected() {
mIsConnected = false;
}
void JabberProtocol::slotGoOnline() {
kdDebug() << "Jabber plugin: Going online!" << endl;
if (!isConnected()) {
Connect();
}
else {
protocol->setPresence("online", "");
}
statusBarIcon->setPixmap(onlineIcon);
}
void JabberProtocol::slotGoOffline()
{
kdDebug() << "Jabber plugin: Going offline." << endl;
Disconnect();
statusBarIcon->setPixmap(offlineIcon);
}
void JabberProtocol::slotSetAway()
{
kdDebug() << "Jabber plugin: Setting away mode." << endl;
protocol->setPresence("away", "");
statusBarIcon->setPixmap(awayIcon);
}
void JabberProtocol::slotSetXA()
{
kdDebug() << "Jabber plugin: Setting extended away mode." << endl;
protocol->setPresence("xa", "");
statusBarIcon->setPixmap(awayIcon);
}
void JabberProtocol::slotSetDND()
{
kdDebug() << "Jabber plugin: Setting do not disturb mode." << endl;
protocol->setPresence("dnd", "");
statusBarIcon->setPixmap(naIcon);
}
void JabberProtocol::slotIconRightClicked (const QPoint) {
QString handle = m_Username + "@" + m_Server;
popup = new KPopupMenu(statusBarIcon);
popup->insertTitle(handle);
actionGoOnline->plug (popup);
actionGoOffline->plug (popup);
actionGoAway->plug (popup);
actionGoXA->plug (popup);
actionGoDND->plug (popup);
popup->popup(QCursor::pos());
}
void JabberProtocol::removeUser (QString userID) {
kdDebug() << "Jabber plugin: Protocol removing user " << userID << endl;
protocol->removeUser(userID);
}
void JabberProtocol::renameContact(QString userID, QString name) {
kdDebug() << "Jabber plugin: Protocol renaming user " << userID << " to " << name << endl;
protocol->renameUser(userID, name);
}
void JabberProtocol::moveUser(QString userID, QString group, QString name, JabberContact *contact) {
kdDebug() << "Jabber plugin: Protocol moving user " << userID << " to " << group << endl;
protocol->moveUser(userID, name, group);
kopeteapp->contactList()->moveContact(contact, group);
}
void JabberProtocol::addContact(QString userID) {
kdDebug() << "Jabber plugin: Protocol adding user " << userID << endl;
protocol->addUser(userID);
}
void JabberProtocol::slotUserWantsAuth(QString userID) {
if (authContact->questionYesNo(kopeteapp->mainWindow(), i18n("The Jabber user ") + userID + i18n(" wants to add you to your contact list. Do you want to authorize them?"), i18n("Authorize Jabber user?")) == 3) {
protocol->authUser(userID);
}
}
void JabberProtocol::slotContactUpdated(QString userID, QString name, QString status, QString reason) {
emit contactUpdated(userID, name, status, reason);
}
void JabberProtocol::slotNewContact(QString userID, QString name, QString group) {
if (group == QString("")) {
group = i18n("Unknown");
}
kopeteapp->contactList()->addContact(new JabberContact(userID, name, group, this), group);
}
void JabberProtocol::slotSettingsChanged() {
m_Username = KGlobal::config()->readEntry("UserID", "");
m_Password = KGlobal::config()->readEntry("Password", "");
m_Resource = KGlobal::config()->readEntry("Resource", "Kopete");
m_Server = KGlobal::config()->readEntry("Server", "jabber.org");
m_Port = KGlobal::config()->readNumEntry("Port", 5222);
}
#include "jabberprotocol.moc"
// vim: set ts=4 sts=4 sw=4 noet:
<commit_msg>... and fix auto-connect ...<commit_after>/***************************************************************************
jabberprotocol.cpp - Jabber Plugin
-------------------
begin : Fri Apr 12 2002
copyright : (C) 2002 by Daniel Stone
email : daniel@raging.dropbear.id.au
***************************************************************************
***************************************************************************
* *
* 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. *
* *
***************************************************************************/
#include <qcursor.h>
#include <kdebug.h>
#include <kiconloader.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <ksimpleconfig.h>
#include <kstandarddirs.h>
#include "kopete.h"
#include "jabberprotocol.h"
#include "statusbaricon.h"
JabberProtocol::JabberProtocol(): QObject(0, "JabberProtocol"), KopeteProtocol() {
kdDebug() << "\nJabber plugin: Loading ..." << endl;
initIcons();
initActions();
authContact = new KMessageBox;
protocol = new KJabber;
connect(protocol, SIGNAL(contactUpdated(QString, QString, QString, QString)), this, SLOT(slotContactUpdated(QString, QString, QString, QString)));
connect(protocol, SIGNAL(userWantsAuth(QString)), this, SLOT(slotUserWantsAuth(QString)));
connect(protocol, SIGNAL(newContact(QString, QString, QString)), this, SLOT(slotNewContact(QString, QString, QString)));
statusBarIcon = new StatusBarIcon();
QObject::connect(statusBarIcon, SIGNAL(rightClicked(const QPoint)), this, SLOT(slotIconRightClicked(const QPoint)));
statusBarIcon->setPixmap(offlineIcon);
mPrefs = new JabberPreferences("jabber_protocol_32", this);
connect(mPrefs, SIGNAL(saved(void)), this, SLOT(settingsChanged(void)));
KGlobal::config()->setGroup("Jabber");
if ((KGlobal::config()->readEntry("UserID", "") == "" ) || (KGlobal::config()->readEntry("Password", "") == "" )) {
QString emptyText = i18n( "<qt>If you have a Jabber account, please configure it in the Kopete Settings. If you don't, please create one with another app; registering is not yet supported in Kopete.</qt>" );
QString emptyCaption = i18n( "No Jabber Configuration found!" );
KMessageBox::error(kopeteapp->mainWindow(), emptyText, emptyCaption);
}
mIsConnected = false;
slotSettingsChanged();
/** Autoconnect if is selected in config */
if (KGlobal::config()->readBoolEntry("AutoConnect", "0")) {
Connect();
}
}
JabberProtocol::~JabberProtocol()
{
}
void JabberProtocol::init()
{
}
bool JabberProtocol::unload()
{
kdDebug() << "Jabber plugin: Unloading...\n";
if( kopeteapp->statusBar() )
{
kopeteapp->statusBar()->removeWidget(statusBarIcon);
delete statusBarIcon;
}
emit protocolUnloading();
return true;
}
void JabberProtocol::Connect() {
if (!isConnected()) {
kdDebug() << "Jabber plugin: Attempting to connect to Jabber server " << m_Server << ":" << m_Port << endl;
kdDebug() << "Jabber plugin: Using UserID " << m_Username << " with password " << m_Password << endl;
protocol->Connect(m_Server, m_Port, m_Username, m_Password, m_Resource);
mIsConnected = true;
statusBarIcon->setPixmap(onlineIcon);
}
else if (isAway()) { /* They're really away, and they want to un-away. */
slotGoOnline();
}
else { /* Nope, just your regular crack junky. */
kdDebug() << "Jabber plugin: Ignoring connect request (already connected)." << endl;
}
}
void JabberProtocol::Disconnect() {
if (isConnected()) {
protocol->Disconnect();
kdDebug() << "Jabber plugin: Disconnected." << endl;
mIsConnected = false;
statusBarIcon->setPixmap(offlineIcon);
emit nukeContacts(false);
}
else { /* Again, what's with the crack? Sheez. */
kdDebug() << "Jabber plugin: Ignoring disconnect request (not connected)." << endl;
}
}
void JabberProtocol::slotConnect() {
Connect();
}
void JabberProtocol::slotDisconnect() {
Disconnect();
}
bool JabberProtocol::isConnected() const {
return mIsConnected;
}
void JabberProtocol::setAway(void) {
slotSetAway();
}
void JabberProtocol::setAvailable(void) {
slotGoOnline();
}
bool JabberProtocol::isAway(void) const {
if (isConnected()) {
return (protocol->getStatus() == "away" || protocol->getStatus() == "xa" || protocol->getStatus() == "dnd");
}
else {
return false;
}
}
QString JabberProtocol::protocolIcon() const {
return "jabber_protocol_32";
}
AddContactPage *JabberProtocol::createAddContactWidget(QWidget *parent) {
return new JabberAddContactPage(this, parent);
}
void JabberProtocol::initIcons() {
KIconLoader *loader = KGlobal::iconLoader();
KStandardDirs dir;
onlineIcon = QPixmap(loader->loadIcon("jabber_online", KIcon::User));
offlineIcon = QPixmap(loader->loadIcon("jabber_offline", KIcon::User));
awayIcon = QPixmap(loader->loadIcon("jabber_away", KIcon::User));
naIcon = QPixmap(loader->loadIcon("jabber_na", KIcon::User));
connectingIcon = QMovie(dir.findResource("data","kopete/pics/jabber_connecting.mng"));
}
void JabberProtocol::initActions() {
actionGoOnline = new KAction (i18n("Online"), "jabber_online", 0, this, SLOT(slotConnect()), this, "actionJabberConnect" );
actionGoAway = new KAction (i18n("Away"), "jabber_away", 0, this, SLOT(slotSetAway()), this, "actionJabberConnect");
actionGoXA = new KAction(i18n("Extended Away"), "jabber_away", 0, this, SLOT(slotSetXA()), this, "actionJabberConnect");
actionGoDND = new KAction(i18n("Do Not Disturb"), "jabber_na", 0, this, SLOT(slotSetDND()), this, "actionJabberConnect");
actionGoOffline = new KAction (i18n("Offline"), "jabber_offline", 0, this, SLOT(slotDisconnect()), this, "actionJabberConnect" );
actionStatusMenu = new KActionMenu("Jabber",this);
actionStatusMenu->insert(actionGoOnline);
actionStatusMenu->insert(actionGoAway);
actionStatusMenu->insert(actionGoXA);
actionStatusMenu->insert(actionGoDND);
actionStatusMenu->insert(actionGoOffline);
actionStatusMenu->plug(kopeteapp->systemTray()->contextMenu(), 1);
}
void JabberProtocol::slotConnecting() { /* Aw, look at the cute widdle MNG. */
statusBarIcon->setMovie(connectingIcon);
}
void JabberProtocol::slotConnected() {
mIsConnected = true;
kdDebug() << "Jabber plugin: Connected to Jabber server." << endl;
slotGoOnline();
}
void JabberProtocol::slotDisconnected() {
mIsConnected = false;
}
void JabberProtocol::slotGoOnline() {
kdDebug() << "Jabber plugin: Going online!" << endl;
if (!isConnected()) {
Connect();
}
else {
protocol->setPresence("online", "");
}
statusBarIcon->setPixmap(onlineIcon);
}
void JabberProtocol::slotGoOffline()
{
kdDebug() << "Jabber plugin: Going offline." << endl;
Disconnect();
statusBarIcon->setPixmap(offlineIcon);
}
void JabberProtocol::slotSetAway()
{
kdDebug() << "Jabber plugin: Setting away mode." << endl;
protocol->setPresence("away", "");
statusBarIcon->setPixmap(awayIcon);
}
void JabberProtocol::slotSetXA()
{
kdDebug() << "Jabber plugin: Setting extended away mode." << endl;
protocol->setPresence("xa", "");
statusBarIcon->setPixmap(awayIcon);
}
void JabberProtocol::slotSetDND()
{
kdDebug() << "Jabber plugin: Setting do not disturb mode." << endl;
protocol->setPresence("dnd", "");
statusBarIcon->setPixmap(naIcon);
}
void JabberProtocol::slotIconRightClicked (const QPoint) {
QString handle = m_Username + "@" + m_Server;
popup = new KPopupMenu(statusBarIcon);
popup->insertTitle(handle);
actionGoOnline->plug (popup);
actionGoOffline->plug (popup);
actionGoAway->plug (popup);
actionGoXA->plug (popup);
actionGoDND->plug (popup);
popup->popup(QCursor::pos());
}
void JabberProtocol::removeUser (QString userID) {
kdDebug() << "Jabber plugin: Protocol removing user " << userID << endl;
protocol->removeUser(userID);
}
void JabberProtocol::renameContact(QString userID, QString name) {
kdDebug() << "Jabber plugin: Protocol renaming user " << userID << " to " << name << endl;
protocol->renameUser(userID, name);
}
void JabberProtocol::moveUser(QString userID, QString group, QString name, JabberContact *contact) {
kdDebug() << "Jabber plugin: Protocol moving user " << userID << " to " << group << endl;
protocol->moveUser(userID, name, group);
kopeteapp->contactList()->moveContact(contact, group);
}
void JabberProtocol::addContact(QString userID) {
kdDebug() << "Jabber plugin: Protocol adding user " << userID << endl;
protocol->addUser(userID);
}
void JabberProtocol::slotUserWantsAuth(QString userID) {
if (authContact->questionYesNo(kopeteapp->mainWindow(), i18n("The Jabber user ") + userID + i18n(" wants to add you to your contact list. Do you want to authorize them?"), i18n("Authorize Jabber user?")) == 3) {
protocol->authUser(userID);
}
}
void JabberProtocol::slotContactUpdated(QString userID, QString name, QString status, QString reason) {
emit contactUpdated(userID, name, status, reason);
}
void JabberProtocol::slotNewContact(QString userID, QString name, QString group) {
if (group == QString("")) {
group = i18n("Unknown");
}
kopeteapp->contactList()->addContact(new JabberContact(userID, name, group, this), group);
}
void JabberProtocol::slotSettingsChanged() {
m_Username = KGlobal::config()->readEntry("UserID", "");
m_Password = KGlobal::config()->readEntry("Password", "");
m_Resource = KGlobal::config()->readEntry("Resource", "Kopete");
m_Server = KGlobal::config()->readEntry("Server", "jabber.org");
m_Port = KGlobal::config()->readNumEntry("Port", 5222);
}
#include "jabberprotocol.moc"
// vim: set ts=4 sts=4 sw=4 noet:
<|endoftext|> |
<commit_before>/*
* master.cpp - master program for Team PI
*
* Wire(0) -> capTouch -> pixies -> SRF08s -> slave2 -> slave3
* Wire1 -> slave1
* by Brian Chen
* (C) Team PI 2015
*/
#include <WProgram.h>
#include <i2c_t3.h>
#include <SPI.h>
#include <slaves.h>
#include <piCommon.h>
#include <PixyI2C.h> // modified for i2c_t3
#include <SRF08.h>
#include <fastTrig.h>
#include <PID.h>
#include <DebugUtils.h>
#define LED 13
#define RAMMING_SPEED 200
#define NORMAL_SPEED 130
uint32_t loopCount = 0;
/**********************************************************/
/* Slave1 */
/**********************************************************/
union float2bytes { float f; uint8_t b[sizeof(float)]; };
float2bytes f2b;
uint8_t inBuffer[22] = {0};
float bearing;
float bearing_offset;
int32_t bearing_int;
/**********************************************************/
/* Orbit */
/**********************************************************/
float orbit_l = 0.5;
float orbit_k = 1.0;
int16_t targetDir;
uint8_t targetVelocity;
/**********************************************************/
/* Face forwards */
/**********************************************************/
#define BEARING_KP 0.8
#define BEARING_KD 0
int32_t targetBearing = 0;
int32_t rotatationCorrection;
PID bearingPID (&bearing_int, &rotatationCorrection, &targetBearing,
BEARING_KP, 0, BEARING_KD, -255, 255, 1000);
/**********************************************************/
/* Backspin */
/**********************************************************/
int16_t backspinSpeed = 0;
/**********************************************************/
/* Kicker */
/**********************************************************/
#define KICK_TIME 4000
#define KICK_DELAY 30
#define KICK_DURATION 90
#define KICK_SIG 21
#define KICK_ANA A3
bool kicking = false;
bool kickDelayComplete = false;
elapsedMillis capChargedTime = 0;
/**********************************************************/
/* Camera */
/**********************************************************/
#define PIXY1_ADDRESS 0x54 // default i2c address
#define MIN_BLOCK_AREA 1500
PixyI2C pixy1(PIXY1_ADDRESS);
int16_t blocks = 0;
int16_t goalAngle = 0;
int16_t goalAngle_rel_field = 0;
uint16_t goalArea = 0;
elapsedMillis lGoalDetectTime = 0;
bool goalDetected = false;
/**********************************************************/
/* Ultrasonics */
/**********************************************************/
#define SRF_BACK_ADDRESS 0x70 // 0xE0
#define SRF_RIGHT_ADDRESS 0x71 // 0xE2
#define SRF_LEFT_ADDRESS 0x72 // 0xE4
SRF08 srfBack(SRF_BACK_ADDRESS);
SRF08 srfRight(SRF_RIGHT_ADDRESS);
SRF08 srfLeft(SRF_LEFT_ADDRESS);
int16_t backDistance, rightDistance, leftDistance;
/**********************************************************/
/* TSOPS */
/**********************************************************/
uint8_t tsopAngleByte;
int16_t tsopAngle;
int16_t tsopAngle_r_goal; // tsop angle relative to goal
uint8_t tsopStrength;
uint8_t ballDistance;
uint8_t tsopData[24] = {0};
/**********************************************************/
/* LASER */
/**********************************************************/
#define LASER_SIG A1
#define LASER_REF 152
bool ballInZone = false;
void kick(){
if (!kicking){
// not yet kicking start kick
kicking = true;
capChargedTime = 0;
Serial.print(millis());
Serial.println("KICK_MOTORS");
}
}
void checkEndKick(){
if (kicking){
if (!kickDelayComplete && capChargedTime > KICK_DELAY){
kickDelayComplete = true;
digitalWriteFast(KICK_SIG, HIGH);
capChargedTime = 0; // now effectively discharge time
Serial.print(millis());
Serial.println("KICK");
}
else if (kickDelayComplete){
// currently actually kicking
if (capChargedTime >= KICK_DURATION){
// end kick
kicking = false;
kickDelayComplete = false;
digitalWriteFast(KICK_SIG, LOW);
capChargedTime = 0;
//Serial.print(analogRead(KICK_ANA));
Serial.print(millis());
Serial.println("END");
}
}
}
else{
digitalWriteFast(KICK_SIG, LOW);
}
}
void calibIMUOffset(){
Slave1.requestPacket(SLAVE1_COMMANDS::CALIB_OFFSET);
// for (int i = 0; i < 50; i++){
// Slave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET);
// Slave1.receivePacket(inBuffer, 7, true);
// f2b.b[0] = inBuffer[2];
// f2b.b[1] = inBuffer[3];
// f2b.b[2] = inBuffer[4];
// f2b.b[3] = inBuffer[5];
// bearing_offset += -f2b.f;
// delay(1);
// }
// bearing_offset /= 50;
}
void getSlave1Data(){
Slave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET);
Slave1.receivePacket(inBuffer, 7, true);
f2b.b[0] = inBuffer[2];
f2b.b[1] = inBuffer[3];
f2b.b[2] = inBuffer[4];
f2b.b[3] = inBuffer[5];
bearing = f2b.f;
bearing_int = (int32_t)(bearing);
TOBEARING180(bearing_int);
TOBEARING180(bearing);
}
void getSlave2Data(){
Slave2.getTSOPAngleStrength(tsopAngle, tsopStrength);
TOBEARING180(tsopAngle);
tsopAngle_r_goal = tsopAngle - goalAngle;
TOBEARING180(tsopAngle_r_goal);
}
void getGoalData(){
goalArea = pixy1.blocks[0].width * pixy1.blocks[0].height;
if (blocks > 0 && blocks < 1000
&& goalArea > MIN_BLOCK_AREA
&& abs(bearing) < 90
){
goalDetected = true;
goalAngle = (pixy1.blocks[0].x - 160) * 75 / 360;
goalAngle_rel_field = goalAngle + bearing_int;
lGoalDetectTime = 0;
// Serial.print("goaldetected");
// Serial.println(blocks);
}
else if (lGoalDetectTime > 100){
// hasn't seen goal for 100ms
goalDetected = false;
goalAngle = 0;
}
}
void getBackspinSpeed(){
if (!kicking){
if (tsopStrength > 70){
if (abs(targetDir) < 60){
if (ballInZone){
// we're going forwards and we have the ball
// no need for too much spin
backspinSpeed = 200;
}
else{
// forwards but ball not here yet!
backspinSpeed = 200;
}
}
else{
if (ballInZone){
// we're not going forwards but we have the ball
// best to spin a bit more as we need to guide the ball more
backspinSpeed = 150;
}
else{
// most common. Should only spin when ball is in front
if (abs(tsopAngle) < 60){
backspinSpeed = 120;
}
else{
// no chance of getting ball any time soon
backspinSpeed = 0;
}
}
}
}
else{
// no ball detected!
backspinSpeed = 0;
}
}
else{
backspinSpeed = -255;
}
}
void checkBallInZone(){
if (analogRead(LASER_SIG) < LASER_REF
&& abs(tsopAngle) < 30
&& tsopStrength > 150){
ballInZone = true;
}
else{
ballInZone = false;
}
}
void serialDebug(){
Serial.printf("%d\t%d\t%d\t%.0f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n",
micros(),
goalAngle_rel_field,
goalArea,
bearing,
backDistance,
rightDistance,
leftDistance,
tsopAngle,
tsopStrength,
ballInZone,
targetDir,
targetVelocity,
rotatationCorrection);
if(Serial.available()){
char serialCommand = Serial.read();
CLEARSERIAL(); // make sure you only read first byte and clear everything else
if (serialCommand == 'i'){
Serial.println("DEBUG INFO");
Serial.printf("%s %s %s %s %s %s %s %s %s %s %s %s %s %s \n",
"micros()",
"goalAngle_rel_field",
"goalArea",
"bearing",
"backDistance",
"rightDistance",
"leftDistance",
"tsopAngle",
"tsopStrength",
"ballInZone",
"targetDir",
"targetVelocity",
"rotatationCorrection");
Serial.println("PRESS ANY KEY TO CONTINUE");
// wait for key
while(!Serial.available());
CLEARSERIAL();
}
else{
Serial.println("UNKNOWN COMMAND");
}
}
}
int main(void){
Serial.begin(115200);
Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, I2C_RATE_400);
SPI.setSCK(14);
SPI.begin();
Slave1.begin(115200);
Slave2.begin();
Slave3.begin();
pinMode(LED, OUTPUT);
pinMode(LASER_SIG, INPUT);
pinMode(KICK_SIG, OUTPUT);
pinMode(KICK_ANA, INPUT);
digitalWrite(KICK_SIG, LOW);
digitalWrite(LED, HIGH);
delay(1000);
calibIMUOffset();
while(1){
// save some time here as reading srf08's has seen to dramatically decrease performance
switch(loopCount % 4){
case 0: blocks = pixy1.getBlocks(); break;
case 1: srfBack.getRangeIfCan(backDistance); break;
case 2: srfRight.getRangeIfCan(rightDistance); break;
case 3: srfLeft.getRangeIfCan(leftDistance); break;
}
/* orientation/imu */
getSlave1Data();
/* end orientation/imu */
/* tsops */
getSlave2Data();
/* end tsops */
/* goal detection */
getGoalData();
/* end goal detection */
/* face forwards */
if (goalDetected){
targetBearing = goalAngle_rel_field;
}
else{
targetBearing = 0;
}
bearingPID.update();
/* end face forwards */
/* ball in zone */
checkBallInZone();
/* end ball in zone */
/*movement control*/
targetVelocity = NORMAL_SPEED;
orbit_k = 1;
if (tsopStrength > 156){
orbit_k = 1.0;
}
else if (tsopStrength > 150){
orbit_k = 0.9;
}
else if (tsopStrength > 140){
orbit_k = 0.8;
}
else if (tsopStrength > 130){
orbit_k = 0.7;
}
else if (tsopStrength > 120){
orbit_k = 0.6;
}
else if (tsopStrength > 100){
orbit_k = 0.55;
}
else if (tsopStrength > 70){
orbit_k = 0.5;
}
else{
targetVelocity = 0;
}
// if (tsopAngle > 90){
// targetDir = (orbit_k * 180 - 90 + tsopAngle);
// }
// else if (tsopAngle < -90){
// targetDir = (orbit_k * -180 + 90 + tsopAngle);
// }
// else{
targetDir = (270 - abs(tsopAngle * orbit_k)) / 90 * tsopAngle * orbit_k;
// }
goalAngle = 0;
if (ballInZone && goalDetected && abs(goalAngle) < 10){
// GO!
targetDir = goalAngle;
targetVelocity = RAMMING_SPEED;
// kick!
if (capChargedTime > KICK_TIME){
kick();
}
}
checkEndKick();
/* end movement control */
/* backspin control */
getBackspinSpeed();
/* end backspin control */
if (targetDir < 0) targetDir += 360;
targetDir = targetDir * 255/360;
// Slave3.moveRobot((uint8_t)targetDir, targetVelocity, rotatationCorrection);
Slave3.moveMotorE(backspinSpeed);
/* debugging */
serialDebug();
/* end debugging */
loopCount++; // update loop count
}
}<commit_msg>added led blinking<commit_after>/*
* master.cpp - master program for Team PI
*
* Wire(0) -> capTouch -> pixies -> SRF08s -> slave2 -> slave3
* Wire1 -> slave1
* by Brian Chen
* (C) Team PI 2015
*/
#include <WProgram.h>
#include <i2c_t3.h>
#include <SPI.h>
#include <slaves.h>
#include <piCommon.h>
#include <PixyI2C.h> // modified for i2c_t3
#include <SRF08.h>
#include <fastTrig.h>
#include <PID.h>
#include <DebugUtils.h>
#define LED 13
#define RAMMING_SPEED 200
#define NORMAL_SPEED 130
uint32_t loopCount = 0;
// blink
elapsedMillis ledElapsedTime;
bool ledState = true;
uint32_t ledBlinkTime = 500;
/**********************************************************/
/* Slave1 */
/**********************************************************/
union float2bytes { float f; uint8_t b[sizeof(float)]; };
float2bytes f2b;
uint8_t inBuffer[22] = {0};
float bearing;
float bearing_offset;
int32_t bearing_int;
/**********************************************************/
/* Orbit */
/**********************************************************/
float orbit_l = 0.5;
float orbit_k = 1.0;
int16_t targetDir;
uint8_t targetVelocity;
/**********************************************************/
/* Face forwards */
/**********************************************************/
#define BEARING_KP 0.8
#define BEARING_KD 0
int32_t targetBearing = 0;
int32_t rotatationCorrection;
PID bearingPID (&bearing_int, &rotatationCorrection, &targetBearing,
BEARING_KP, 0, BEARING_KD, -255, 255, 1000);
/**********************************************************/
/* Backspin */
/**********************************************************/
int16_t backspinSpeed = 0;
/**********************************************************/
/* Kicker */
/**********************************************************/
#define KICK_TIME 4000
#define KICK_DELAY 30
#define KICK_DURATION 90
#define KICK_SIG 21
#define KICK_ANA A3
bool kicking = false;
bool kickDelayComplete = false;
elapsedMillis capChargedTime = 0;
/**********************************************************/
/* Camera */
/**********************************************************/
#define PIXY1_ADDRESS 0x54 // default i2c address
#define MIN_BLOCK_AREA 1500
PixyI2C pixy1(PIXY1_ADDRESS);
int16_t blocks = 0;
int16_t goalAngle = 0;
int16_t goalAngle_rel_field = 0;
uint16_t goalArea = 0;
elapsedMillis lGoalDetectTime = 0;
bool goalDetected = false;
/**********************************************************/
/* Ultrasonics */
/**********************************************************/
#define SRF_BACK_ADDRESS 0x70 // 0xE0
#define SRF_RIGHT_ADDRESS 0x71 // 0xE2
#define SRF_LEFT_ADDRESS 0x72 // 0xE4
SRF08 srfBack(SRF_BACK_ADDRESS);
SRF08 srfRight(SRF_RIGHT_ADDRESS);
SRF08 srfLeft(SRF_LEFT_ADDRESS);
int16_t backDistance, rightDistance, leftDistance;
/**********************************************************/
/* TSOPS */
/**********************************************************/
uint8_t tsopAngleByte;
int16_t tsopAngle;
int16_t tsopAngle_r_goal; // tsop angle relative to goal
uint8_t tsopStrength;
uint8_t ballDistance;
uint8_t tsopData[24] = {0};
/**********************************************************/
/* LASER */
/**********************************************************/
#define LASER_SIG A1
#define LASER_REF 152
bool ballInZone = false;
inline void ledBlink(){
// led blinking
if (ledElapsedTime > ledBlinkTime){
if (ledState){
digitalWriteFast(LED, HIGH);
}
else{
digitalWriteFast(LED, LOW);
}
ledState = !ledState;
ledElapsedTime = 0;
}
}
void kick(){
if (!kicking){
// not yet kicking start kick
kicking = true;
capChargedTime = 0;
Serial.print(millis());
Serial.println("KICK_MOTORS");
}
}
void checkEndKick(){
if (kicking){
if (!kickDelayComplete && capChargedTime > KICK_DELAY){
kickDelayComplete = true;
digitalWriteFast(KICK_SIG, HIGH);
capChargedTime = 0; // now effectively discharge time
Serial.print(millis());
Serial.println("KICK");
}
else if (kickDelayComplete){
// currently actually kicking
if (capChargedTime >= KICK_DURATION){
// end kick
kicking = false;
kickDelayComplete = false;
digitalWriteFast(KICK_SIG, LOW);
capChargedTime = 0;
//Serial.print(analogRead(KICK_ANA));
Serial.print(millis());
Serial.println("END");
}
}
}
else{
digitalWriteFast(KICK_SIG, LOW);
}
}
void calibIMUOffset(){
Slave1.requestPacket(SLAVE1_COMMANDS::CALIB_OFFSET);
// for (int i = 0; i < 50; i++){
// Slave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET);
// Slave1.receivePacket(inBuffer, 7, true);
// f2b.b[0] = inBuffer[2];
// f2b.b[1] = inBuffer[3];
// f2b.b[2] = inBuffer[4];
// f2b.b[3] = inBuffer[5];
// bearing_offset += -f2b.f;
// delay(1);
// }
// bearing_offset /= 50;
}
void getSlave1Data(){
Slave1.requestPacket(SLAVE1_COMMANDS::REQUEST_STANDARD_PACKET);
Slave1.receivePacket(inBuffer, 7, true);
f2b.b[0] = inBuffer[2];
f2b.b[1] = inBuffer[3];
f2b.b[2] = inBuffer[4];
f2b.b[3] = inBuffer[5];
bearing = f2b.f;
bearing_int = (int32_t)(bearing);
TOBEARING180(bearing_int);
TOBEARING180(bearing);
}
void getSlave2Data(){
Slave2.getTSOPAngleStrength(tsopAngle, tsopStrength);
TOBEARING180(tsopAngle);
tsopAngle_r_goal = tsopAngle - goalAngle;
TOBEARING180(tsopAngle_r_goal);
}
void getGoalData(){
goalArea = pixy1.blocks[0].width * pixy1.blocks[0].height;
if (blocks > 0 && blocks < 1000
&& goalArea > MIN_BLOCK_AREA
&& abs(bearing) < 90
){
goalDetected = true;
goalAngle = (pixy1.blocks[0].x - 160) * 75 / 360;
goalAngle_rel_field = goalAngle + bearing_int;
lGoalDetectTime = 0;
// Serial.print("goaldetected");
// Serial.println(blocks);
}
else if (lGoalDetectTime > 100){
// hasn't seen goal for 100ms
goalDetected = false;
goalAngle = 0;
}
}
void getBackspinSpeed(){
if (!kicking){
if (tsopStrength > 70){
if (abs(targetDir) < 60){
if (ballInZone){
// we're going forwards and we have the ball
// no need for too much spin
backspinSpeed = 200;
}
else{
// forwards but ball not here yet!
backspinSpeed = 200;
}
}
else{
if (ballInZone){
// we're not going forwards but we have the ball
// best to spin a bit more as we need to guide the ball more
backspinSpeed = 150;
}
else{
// most common. Should only spin when ball is in front
if (abs(tsopAngle) < 60){
backspinSpeed = 120;
}
else{
// no chance of getting ball any time soon
backspinSpeed = 0;
}
}
}
}
else{
// no ball detected!
backspinSpeed = 0;
}
}
else{
backspinSpeed = -255;
}
}
void checkBallInZone(){
if (analogRead(LASER_SIG) < LASER_REF
&& abs(tsopAngle) < 30
&& tsopStrength > 150){
ballInZone = true;
}
else{
ballInZone = false;
}
}
void serialDebug(){
Serial.printf("%d\t%d\t%d\t%.0f\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\t%d\n",
micros(),
goalAngle_rel_field,
goalArea,
bearing,
backDistance,
rightDistance,
leftDistance,
tsopAngle,
tsopStrength,
ballInZone,
targetDir,
targetVelocity,
rotatationCorrection);
if(Serial.available()){
char serialCommand = Serial.read();
CLEARSERIAL(); // make sure you only read first byte and clear everything else
if (serialCommand == 'i'){
Serial.println("DEBUG INFO");
Serial.printf("%s %s %s %s %s %s %s %s %s %s %s %s %s %s \n",
"micros()",
"goalAngle_rel_field",
"goalArea",
"bearing",
"backDistance",
"rightDistance",
"leftDistance",
"tsopAngle",
"tsopStrength",
"ballInZone",
"targetDir",
"targetVelocity",
"rotatationCorrection");
Serial.println("PRESS ANY KEY TO CONTINUE");
// wait for key
while(!Serial.available());
CLEARSERIAL();
}
else{
Serial.println("UNKNOWN COMMAND");
}
}
}
int main(void){
Serial.begin(115200);
Wire.begin(I2C_MASTER, 0x00, I2C_PINS_18_19, I2C_PULLUP_EXT, I2C_RATE_400);
SPI.setSCK(14);
SPI.begin();
Slave1.begin(115200);
Slave2.begin();
Slave3.begin();
pinMode(LED, OUTPUT);
pinMode(LASER_SIG, INPUT);
pinMode(KICK_SIG, OUTPUT);
pinMode(KICK_ANA, INPUT);
digitalWrite(KICK_SIG, LOW);
digitalWrite(LED, HIGH);
delay(1000);
calibIMUOffset();
while(1){
// save some time here as reading srf08's has seen to dramatically decrease performance
switch(loopCount % 4){
case 0: blocks = pixy1.getBlocks(); break;
case 1: srfBack.getRangeIfCan(backDistance); break;
case 2: srfRight.getRangeIfCan(rightDistance); break;
case 3: srfLeft.getRangeIfCan(leftDistance); break;
}
/* orientation/imu */
getSlave1Data();
/* end orientation/imu */
/* tsops */
getSlave2Data();
/* end tsops */
/* goal detection */
getGoalData();
/* end goal detection */
/* face forwards */
if (goalDetected){
targetBearing = goalAngle_rel_field;
}
else{
targetBearing = 0;
}
bearingPID.update();
/* end face forwards */
/* ball in zone */
checkBallInZone();
/* end ball in zone */
/*movement control*/
targetVelocity = NORMAL_SPEED;
orbit_k = 1;
if (tsopStrength > 156){
orbit_k = 1.0;
}
else if (tsopStrength > 150){
orbit_k = 0.9;
}
else if (tsopStrength > 140){
orbit_k = 0.8;
}
else if (tsopStrength > 130){
orbit_k = 0.7;
}
else if (tsopStrength > 120){
orbit_k = 0.6;
}
else if (tsopStrength > 100){
orbit_k = 0.55;
}
else if (tsopStrength > 70){
orbit_k = 0.5;
}
else{
targetVelocity = 0;
}
// if (tsopAngle > 90){
// targetDir = (orbit_k * 180 - 90 + tsopAngle);
// }
// else if (tsopAngle < -90){
// targetDir = (orbit_k * -180 + 90 + tsopAngle);
// }
// else{
targetDir = (270 - abs(tsopAngle * orbit_k)) / 90 * tsopAngle * orbit_k;
// }
goalAngle = 0;
if (ballInZone && goalDetected && abs(goalAngle) < 10){
// GO!
targetDir = goalAngle;
targetVelocity = RAMMING_SPEED;
// kick!
if (capChargedTime > KICK_TIME){
kick();
}
}
checkEndKick();
/* end movement control */
/* backspin control */
getBackspinSpeed();
/* end backspin control */
if (targetDir < 0) targetDir += 360;
targetDir = targetDir * 255/360;
Slave3.moveRobot((uint8_t)targetDir, targetVelocity, rotatationCorrection);
Slave3.moveMotorE(backspinSpeed);
ledBlink();
/* debugging */
serialDebug();
/* end debugging */
loopCount++; // update loop count
}
}<|endoftext|> |
<commit_before>#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <std_msgs/String.h>
#include <vector>
#include <fstream>
#include <string>
class WaypointsSaver{
public:
WaypointsSaver() :
filename_("waypoints.yaml")
{
waypoints_viz_sub_ = nh_.subscribe("waypoints_viz", 1, &WaypointsSaver::waypointsVizCallback, this);
waypoints_joy_sub_ = nh_.subscribe("waypoints_joy", 1, &WaypointsSaver::waypointsJoyCallback, this);
finish_pose_sub_ = nh_.subscribe("finish_pose", 1, &WaypointsSaver::finishPoseCallback, this);
ros::NodeHandle private_nh("~");
private_nh.param("filename", filename_, filename_);
private_nh.param("save_joy_button", save_joy_button_, 0);
private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
private_nh.param("world_frame", world_frame_, std::string("/map"));
}
void waypointsJoyCallback(const sensor_msgs::Joy &msg){
ROS_INFO_STREAM("joy = " << msg);
if(msg.buttons[save_joy_button_] == 1){
tf::StampedTransform robot_gl;
try{
tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
geometry_msgs::PointStamped point;
point.point.x = robot_gl.getOrigin().x();
point.point.y = robot_gl.getOrigin().y();
point.point.z = robot_gl.getOrigin().z();
waypoints_.push_back(point);
}catch(tf::TransformException &e){
ROS_WARN_STREAM("tf::TransformException: " << e.what());
}
}
}
void waypointsVizCallback(const geometry_msgs::PointStamped &msg){
ROS_INFO_STREAM("point = " << msg);
waypoints_.push_back(msg);
}
void finishPoseCallback(const geometry_msgs::PoseStamped &msg){
finish_pose_ = msg;
save();
waypoints_.clear();
}
void save(){
std::ofstream ofs(filename_.c_str(), std::ios::out);
ofs << "waypoints:" << std::endl;
for(int i=0; i < waypoints_.size(); i++){
ofs << " " << "- point:" << std::endl;
ofs << " x: " << waypoints_[i].point.x << std::endl;
ofs << " y: " << waypoints_[i].point.y << std::endl;
ofs << " z: " << waypoints_[i].point.z << std::endl;
}
ofs << "finish_pose:" << std::endl;
ofs << " header:" << std::endl;
ofs << " seq: " << finish_pose_.header.seq << std::endl;
ofs << " stamp: " << finish_pose_.header.stamp << std::endl;
ofs << " frame_id: " << finish_pose_.header.frame_id << std::endl;;
ofs << " pose:" << std::endl;
ofs << " position:" << std::endl;
ofs << " x: " << finish_pose_.pose.position.x << std::endl;
ofs << " y: " << finish_pose_.pose.position.y << std::endl;
ofs << " z: " << finish_pose_.pose.position.z << std::endl;
ofs << " orientation:" << std::endl;
ofs << " x: " << finish_pose_.pose.orientation.x << std::endl;
ofs << " y: " << finish_pose_.pose.orientation.y << std::endl;
ofs << " z: " << finish_pose_.pose.orientation.z << std::endl;
ofs << " w: " << finish_pose_.pose.orientation.w << std::endl;
ofs.close();
ROS_INFO_STREAM("write success");
}
void run(){
ros::spin();
}
private:
ros::Subscriber waypoints_viz_sub_;
ros::Subscriber waypoints_joy_sub_;
ros::Subscriber finish_pose_sub_;
std::vector<geometry_msgs::PointStamped> waypoints_;
geometry_msgs::PoseStamped finish_pose_;
tf::TransformListener tf_listener_;
int save_joy_button_;
ros::NodeHandle nh_;
std::string filename_;
std::string world_frame_;
std::string robot_frame_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "waypoints_saver");
WaypointsSaver saver;
saver.run();
return 0;
}
<commit_msg>Fixed a problem that failed save waypoints<commit_after>#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/PointStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <std_msgs/String.h>
#include <vector>
#include <fstream>
#include <string>
class WaypointsSaver{
public:
WaypointsSaver() :
filename_("waypoints.yaml")
{
waypoints_viz_sub_ = nh_.subscribe("waypoints_viz", 1, &WaypointsSaver::waypointsVizCallback, this);
waypoints_joy_sub_ = nh_.subscribe("waypoints_joy", 1, &WaypointsSaver::waypointsJoyCallback, this);
finish_pose_sub_ = nh_.subscribe("finish_pose", 1, &WaypointsSaver::finishPoseCallback, this);
ros::NodeHandle private_nh("~");
private_nh.param("filename", filename_, filename_);
private_nh.param("save_joy_button", save_joy_button_, 0);
private_nh.param("robot_frame", robot_frame_, std::string("/base_link"));
private_nh.param("world_frame", world_frame_, std::string("/map"));
}
void waypointsJoyCallback(const sensor_msgs::Joy &msg){
static ros::Time saved_time(0.0);
ROS_INFO_STREAM("joy = " << msg);
if(msg.buttons[save_joy_button_] == 1 && (ros::Time::now() - saved_time).toSec() > 3.0){
tf::StampedTransform robot_gl;
try{
tf_listener_.lookupTransform(world_frame_, robot_frame_, ros::Time(0.0), robot_gl);
geometry_msgs::PointStamped point;
point.point.x = robot_gl.getOrigin().x();
point.point.y = robot_gl.getOrigin().y();
point.point.z = robot_gl.getOrigin().z();
waypoints_.push_back(point);
saved_time = ros::Time::now();
}catch(tf::TransformException &e){
ROS_WARN_STREAM("tf::TransformException: " << e.what());
}
}
}
void waypointsVizCallback(const geometry_msgs::PointStamped &msg){
ROS_INFO_STREAM("point = " << msg);
waypoints_.push_back(msg);
}
void finishPoseCallback(const geometry_msgs::PoseStamped &msg){
finish_pose_ = msg;
save();
waypoints_.clear();
}
void save(){
std::ofstream ofs(filename_.c_str(), std::ios::out);
ofs << "waypoints:" << std::endl;
for(int i=0; i < waypoints_.size(); i++){
ofs << " " << "- point:" << std::endl;
ofs << " x: " << waypoints_[i].point.x << std::endl;
ofs << " y: " << waypoints_[i].point.y << std::endl;
ofs << " z: " << waypoints_[i].point.z << std::endl;
}
ofs << "finish_pose:" << std::endl;
ofs << " header:" << std::endl;
ofs << " seq: " << finish_pose_.header.seq << std::endl;
ofs << " stamp: " << finish_pose_.header.stamp << std::endl;
ofs << " frame_id: " << finish_pose_.header.frame_id << std::endl;;
ofs << " pose:" << std::endl;
ofs << " position:" << std::endl;
ofs << " x: " << finish_pose_.pose.position.x << std::endl;
ofs << " y: " << finish_pose_.pose.position.y << std::endl;
ofs << " z: " << finish_pose_.pose.position.z << std::endl;
ofs << " orientation:" << std::endl;
ofs << " x: " << finish_pose_.pose.orientation.x << std::endl;
ofs << " y: " << finish_pose_.pose.orientation.y << std::endl;
ofs << " z: " << finish_pose_.pose.orientation.z << std::endl;
ofs << " w: " << finish_pose_.pose.orientation.w << std::endl;
ofs.close();
ROS_INFO_STREAM("write success");
}
void run(){
ros::spin();
}
private:
ros::Subscriber waypoints_viz_sub_;
ros::Subscriber waypoints_joy_sub_;
ros::Subscriber finish_pose_sub_;
std::vector<geometry_msgs::PointStamped> waypoints_;
geometry_msgs::PoseStamped finish_pose_;
tf::TransformListener tf_listener_;
int save_joy_button_;
ros::NodeHandle nh_;
std::string filename_;
std::string world_frame_;
std::string robot_frame_;
};
int main(int argc, char *argv[]){
ros::init(argc, argv, "waypoints_saver");
WaypointsSaver saver;
saver.run();
return 0;
}
<|endoftext|> |
<commit_before>#if 0
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
//#include <TimeLib.h>
// Include the correct display library
// For a connection via I2C using Wire include
#include <math.h>
#include <sys/time.h>
#include <Wire.h> // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"`
// or #include "SH1106.h" alis for `#include "SH1106Wire.h"`
// For a connection via I2C using brzo_i2c (must be installed) include
// #include <brzo_i2c.h> // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Brzo.h"
// #include "SH1106Brzo.h"
// For a connection via SPI include
// #include <SPI.h> // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Spi.h"
// #include "SH1106SPi.h"
// Include the UI lib
#include "OLEDDisplayUi.h"
// Include custom images
#include "images.h"
// Use the corresponding display class:
// Initialize the OLED display using SPI
// D5 -> CLK
// D7 -> MOSI (DOUT)
// D0 -> RES
// D2 -> DC
// D8 -> CS
// SSD1306Spi display(D0, D2, D8);
// or
// SH1106Spi display(D0, D2);
// Initialize the OLED display using brzo_i2c
// D3 -> SDA
// D5 -> SCL
// SSD1306Brzo display(0x3c, D3, D5);
// or
// SH1106Brzo display(0x3c, D3, D5);
// Initialize the OLED display using Wire library
SSD1306 display(0x3c, 5, 4);
// SH1106 display(0x3c, D3, D5);
OLEDDisplayUi ui ( &display );
int screenW = 128;
int screenH = 64;
int clockCenterX = screenW/2;
int clockCenterY = ((screenH-16)/2)+16; // top yellow part is 16 px height
int clockRadius = 23;
#define SEC_PER_DAY 86400
#define SEC_PER_HOUR 3600
#define SEC_PER_MIN 60
// Similar to uint32_t system_get_time(void)
uint32_t get_usec() {
struct timeval tv;
gettimeofday(&tv,NULL);
return (tv.tv_sec*1000000 + tv.tv_usec);
//uint64_t tmp=get_time_since_boot();
//uint32_t ret=(uint32_t)tmp;
//return ret;
}
uint32_t minute() {
struct timeval tv;
gettimeofday(&tv,NULL);
return (tv.tv_sec/60);
//uint64_t tmp=get_time_since_boot();
//uint32_t ret=(uint32_t)tmp;
//return ret;
}
uint32_t second() {
struct timeval tv;
gettimeofday(&tv,NULL);
return (tv.tv_sec%60);
//uint64_t tmp=get_time_since_boot();
//uint32_t ret=(uint32_t)tmp;
//return ret;
}
uint32_t hour() {
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
//printf("TimeZone-1 = %d\n", tz.tz_minuteswest);
//printf("TimeZone-2 = %d\n", tz.tz_dsttime);
// Cast members as specific type of the members may be various
// signed integer types with Unix.
//printf("TimeVal-3 = %lld\n", (long long) tv.tv_sec);
//printf("TimeVal-4 = %lld\n", (long long) tv.tv_usec);
// Form the seconds of the day
long hms = tv.tv_sec % SEC_PER_DAY;
hms += tz.tz_dsttime * SEC_PER_HOUR;
hms -= tz.tz_minuteswest * SEC_PER_MIN;
// mod `hms` to insure in positive range of [0...SEC_PER_DAY)
hms = (hms + SEC_PER_DAY) % SEC_PER_DAY;
// Tear apart hms into h:m:s
int hour = hms / SEC_PER_HOUR;
int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN
return hour;
}
// utility function for digital clock display: prints leading 0
String twoDigits(int digits){
if(digits < 10) {
String i = '0'+String(digits);
return i;
}
else {
return String(digits);
}
}
void clockOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {
}
void analogClockFrame(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// ui.disableIndicator();
// Draw the clock face
// display->drawCircle(clockCenterX + x, clockCenterY + y, clockRadius);
display->drawCircle(clockCenterX + x, clockCenterY + y, 2);
//
//hour ticks
for( int z=0; z < 360;z= z + 30 ){
//Begin at 0° and stop at 360°
float angle = z ;
angle = ( angle / 57.29577951 ) ; //Convert degrees to radians
int x2 = ( clockCenterX + ( sin(angle) * clockRadius ) );
int y2 = ( clockCenterY - ( cos(angle) * clockRadius ) );
int x3 = ( clockCenterX + ( sin(angle) * ( clockRadius - ( clockRadius / 8 ) ) ) );
int y3 = ( clockCenterY - ( cos(angle) * ( clockRadius - ( clockRadius / 8 ) ) ) );
display->drawLine( x2 + x , y2 + y , x3 + x , y3 + y);
}
// display second hand
float angle = second() * 6 ;
angle = ( angle / 57.29577951 ) ; //Convert degrees to radians
int x3 = ( clockCenterX + ( sin(angle) * ( clockRadius - ( clockRadius / 5 ) ) ) );
int y3 = ( clockCenterY - ( cos(angle) * ( clockRadius - ( clockRadius / 5 ) ) ) );
display->drawLine( clockCenterX + x , clockCenterY + y , x3 + x , y3 + y);
//
// display minute hand
angle = minute() * 6 ;
angle = ( angle / 57.29577951 ) ; //Convert degrees to radians
x3 = ( clockCenterX + ( sin(angle) * ( clockRadius - ( clockRadius / 4 ) ) ) );
y3 = ( clockCenterY - ( cos(angle) * ( clockRadius - ( clockRadius / 4 ) ) ) );
display->drawLine( clockCenterX + x , clockCenterY + y , x3 + x , y3 + y);
//
// display hour hand
angle = hour() * 30 + int( ( minute() / 12 ) * 6 ) ;
angle = ( angle / 57.29577951 ) ; //Convert degrees to radians
x3 = ( clockCenterX + ( sin(angle) * ( clockRadius - ( clockRadius / 2 ) ) ) );
y3 = ( clockCenterY - ( cos(angle) * ( clockRadius - ( clockRadius / 2 ) ) ) );
display->drawLine( clockCenterX + x , clockCenterY + y , x3 + x , y3 + y);
}
void digitalClockFrame(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
String timenow = String(hour())+":"+twoDigits(minute())+":"+twoDigits(second());
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->setFont(ArialMT_Plain_24);
display->drawString(clockCenterX + x , clockCenterY + y, timenow );
}
// This array keeps function pointers to all frames
// frames are the single views that slide in
FrameCallback frames[] = { analogClockFrame, digitalClockFrame };
// how many frames are there?
int frameCount = 2;
// Overlays are statically drawn on top of a frame eg. a clock
OverlayCallback overlays_clk[] = { clockOverlay };
int overlaysCount_clk = 1;
void setup() {
//Serial.begin(9600);
//Serial.println();
// The ESP is capable of rendering 60fps in 80Mhz mode
// but that won't give you much time for anything else
// run it in 160Mhz mode or just set it to 30 fps
ui.setTargetFPS(60);
// Customize the active and inactive symbol
ui.setActiveSymbol(activeSymbol);
ui.setInactiveSymbol(inactiveSymbol);
// You can change this to
// TOP, LEFT, BOTTOM, RIGHT
ui.setIndicatorPosition(TOP);
// Defines where the first frame is located in the bar.
ui.setIndicatorDirection(LEFT_RIGHT);
// You can change the transition that is used
// SLIDE_LEFT, SLIDE_RIGHT, SLIDE_UP, SLIDE_DOWN
ui.setFrameAnimation(SLIDE_LEFT);
// Add frames
ui.setFrames(frames, frameCount);
// Add overlays
ui.setOverlays(overlays_clk, overlaysCount_clk);
// Initialising the UI will init the display too.
ui.init();
display.flipScreenVertically();
unsigned long secsSinceStart = millis();
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
//unsigned long epoch = secsSinceStart - seventyYears * SECS_PER_HOUR;
//setTime(epoch);
}
void loop() {
int remainingTimeBudget = ui.update();
if (remainingTimeBudget > 0) {
// You can do some work here
// Don't do stuff if you are below your
// time budget.
delay(remainingTimeBudget);
}
}
#endif
<commit_msg>Update clock example<commit_after>#if 0
// TODO, time goes negative when displaying digital clock, WHY??
/**
* The MIT License (MIT)
*
* Copyright (c) 2016 by Daniel Eichhorn
* Copyright (c) 2016 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*/
//#include <TimeLib.h>
// Include the correct display library
// For a connection via I2C using Wire include
#include <math.h>
#include <sys/time.h>
#include <Wire.h> // Only needed for Arduino 1.6.5 and earlier
#include "SSD1306.h" // alias for `#include "SSD1306Wire.h"`
// or #include "SH1106.h" alis for `#include "SH1106Wire.h"`
// For a connection via I2C using brzo_i2c (must be installed) include
// #include <brzo_i2c.h> // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Brzo.h"
// #include "SH1106Brzo.h"
// For a connection via SPI include
// #include <SPI.h> // Only needed for Arduino 1.6.5 and earlier
// #include "SSD1306Spi.h"
// #include "SH1106SPi.h"
// Include the UI lib
#include "OLEDDisplayUi.h"
// Include custom images
#include "images.h"
// Use the corresponding display class:
// Initialize the OLED display using SPI
// D5 -> CLK
// D7 -> MOSI (DOUT)
// D0 -> RES
// D2 -> DC
// D8 -> CS
// SSD1306Spi display(D0, D2, D8);
// or
// SH1106Spi display(D0, D2);
// Initialize the OLED display using brzo_i2c
// D3 -> SDA
// D5 -> SCL
// SSD1306Brzo display(0x3c, D3, D5);
// or
// SH1106Brzo display(0x3c, D3, D5);
// Initialize the OLED display using Wire library
SSD1306 display(0x3c, 5, 4);
// SH1106 display(0x3c, D3, D5);
OLEDDisplayUi ui ( &display );
int screenW = 128;
int screenH = 64;
int clockCenterX = screenW/2;
int clockCenterY = ((screenH-16)/2)+16; // top yellow part is 16 px height
int clockRadius = 23;
#define SEC_PER_DAY 86400
#define SEC_PER_HOUR 3600
#define SEC_PER_MIN 60
// Similar to uint32_t system_get_time(void)
uint32_t get_usec() {
struct timeval tv;
gettimeofday(&tv,NULL);
return (tv.tv_sec*1000000 + tv.tv_usec);
//uint64_t tmp=get_time_since_boot();
//uint32_t ret=(uint32_t)tmp;
//return ret;
}
uint32_t minute() {
struct timeval tv;
struct timezone tz;
gettimeofday(&tv,&tz);
long hms = tv.tv_sec % SEC_PER_DAY;
hms += tz.tz_dsttime * SEC_PER_HOUR;
hms -= tz.tz_minuteswest * SEC_PER_MIN;
// mod `hms` to insure in positive range of [0...SEC_PER_DAY)
hms = (hms + SEC_PER_DAY) % SEC_PER_DAY;
// Tear apart hms into h:m:s
int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
//printf("min %d\n",min);
return (min);
}
uint32_t second() {
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
long hms = tv.tv_sec % SEC_PER_DAY;
hms += tz.tz_dsttime * SEC_PER_HOUR;
hms -= tz.tz_minuteswest * SEC_PER_MIN;
// mod `hms` to insure in positive range of [0...SEC_PER_DAY)
hms = (hms + SEC_PER_DAY) % SEC_PER_DAY;
// Tear apart hms into h:m:s
//int hour = hms / SEC_PER_HOUR;
//int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN
//printf("sec %d\n",sec);
return (sec);
}
uint32_t hour() {
struct timeval tv;
struct timezone tz;
gettimeofday(&tv, &tz);
//printf("TimeZone-1 = %d\n", tz.tz_minuteswest);
//printf("TimeZone-2 = %d\n", tz.tz_dsttime);
// Cast members as specific type of the members may be various
// signed integer types with Unix.
//printf("TimeVal-3 = %lld\n", (long long) tv.tv_sec);
//printf("TimeVal-4 = %lld\n", (long long) tv.tv_usec);
// Form the seconds of the day
long hms = tv.tv_sec % SEC_PER_DAY;
hms += tz.tz_dsttime * SEC_PER_HOUR;
hms -= tz.tz_minuteswest * SEC_PER_MIN;
// mod `hms` to insure in positive range of [0...SEC_PER_DAY)
hms = (hms + SEC_PER_DAY) % SEC_PER_DAY;
// Tear apart hms into h:m:s
int hour = hms / SEC_PER_HOUR;
//int min = (hms % SEC_PER_HOUR) / SEC_PER_MIN;
//int sec = (hms % SEC_PER_HOUR) % SEC_PER_MIN; // or hms % SEC_PER_MIN
//printf("hour %d\n",hour);
return hour;
}
// utility function for digital clock display: prints leading 0
String twoDigits(int digits){
if(digits<0) {
digits=-digits;
}
if(digits < 10) {
String i = '0'+String(digits);
return i;
}
else {
return String(digits);
}
}
void clockOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {
}
void analogClockFrame(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
// ui.disableIndicator();
// Draw the clock face
// display->drawCircle(clockCenterX + x, clockCenterY + y, clockRadius);
display->drawCircle(clockCenterX + x, clockCenterY + y, 2);
//
//hour ticks
for( int z=0; z < 360;z= z + 30 ){
//Begin at 0° and stop at 360°
float angle = z ;
angle = ( angle / 57.29577951 ) ; //Convert degrees to radians
int x2 = ( clockCenterX + ( sin(angle) * clockRadius ) );
int y2 = ( clockCenterY - ( cos(angle) * clockRadius ) );
int x3 = ( clockCenterX + ( sin(angle) * ( clockRadius - ( clockRadius / 8 ) ) ) );
int y3 = ( clockCenterY - ( cos(angle) * ( clockRadius - ( clockRadius / 8 ) ) ) );
display->drawLine( x2 + x , y2 + y , x3 + x , y3 + y);
}
// display second hand
float angle = second() * 6 ;
angle = ( angle / 57.29577951 ) ; //Convert degrees to radians
int x3 = ( clockCenterX + ( sin(angle) * ( clockRadius - ( clockRadius / 5 ) ) ) );
int y3 = ( clockCenterY - ( cos(angle) * ( clockRadius - ( clockRadius / 5 ) ) ) );
display->drawLine( clockCenterX + x , clockCenterY + y , x3 + x , y3 + y);
//
// display minute hand
angle = minute() * 6 ;
angle = ( angle / 57.29577951 ) ; //Convert degrees to radians
x3 = ( clockCenterX + ( sin(angle) * ( clockRadius - ( clockRadius / 4 ) ) ) );
y3 = ( clockCenterY - ( cos(angle) * ( clockRadius - ( clockRadius / 4 ) ) ) );
display->drawLine( clockCenterX + x , clockCenterY + y , x3 + x , y3 + y);
//
// display hour hand
angle = hour() * 30 + int( ( minute() / 12 ) * 6 ) ;
angle = ( angle / 57.29577951 ) ; //Convert degrees to radians
x3 = ( clockCenterX + ( sin(angle) * ( clockRadius - ( clockRadius / 2 ) ) ) );
y3 = ( clockCenterY - ( cos(angle) * ( clockRadius - ( clockRadius / 2 ) ) ) );
display->drawLine( clockCenterX + x , clockCenterY + y , x3 + x , y3 + y);
}
void digitalClockFrame(OLEDDisplay *display, OLEDDisplayUiState* state, int16_t x, int16_t y) {
String timenow = String(hour())+":"+twoDigits(minute())+":"+twoDigits(second());
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->setFont(ArialMT_Plain_24);
display->drawString(clockCenterX + x , clockCenterY + y, timenow );
}
// This array keeps function pointers to all frames
// frames are the single views that slide in
FrameCallback frames[] = { analogClockFrame, digitalClockFrame };
// how many frames are there?
int frameCount = 2;
// Overlays are statically drawn on top of a frame eg. a clock
OverlayCallback overlays_clk[] = { clockOverlay };
int overlaysCount_clk = 1;
void setup() {
//Serial.begin(9600);
//Serial.println();
// The ESP is capable of rendering 60fps in 80Mhz mode
// but that won't give you much time for anything else
// run it in 160Mhz mode or just set it to 30 fps
ui.setTargetFPS(60);
// Customize the active and inactive symbol
ui.setActiveSymbol(activeSymbol);
ui.setInactiveSymbol(inactiveSymbol);
// You can change this to
// TOP, LEFT, BOTTOM, RIGHT
ui.setIndicatorPosition(TOP);
// Defines where the first frame is located in the bar.
ui.setIndicatorDirection(LEFT_RIGHT);
// You can change the transition that is used
// SLIDE_LEFT, SLIDE_RIGHT, SLIDE_UP, SLIDE_DOWN
ui.setFrameAnimation(SLIDE_LEFT);
// Add frames
ui.setFrames(frames, frameCount);
// Add overlays
ui.setOverlays(overlays_clk, overlaysCount_clk);
// Initialising the UI will init the display too.
ui.init();
display.flipScreenVertically();
unsigned long secsSinceStart = millis();
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
//unsigned long epoch = secsSinceStart - seventyYears * SECS_PER_HOUR;
//setTime(epoch);
}
void loop() {
int remainingTimeBudget = ui.update();
if (remainingTimeBudget > 0) {
// You can do some work here
// Don't do stuff if you are below your
// time budget.
delay(remainingTimeBudget);
}
}
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include <stdexcept>
#include "Token.hpp"
#include "TokenStream.hpp"
#include "Calculator.hpp"
void calculate(ITokenStream& tokenStream)
{
double value = 0;
Calculator parser{tokenStream};
while (std::cin)
{
Token token = tokenStream.get();
while (token.kind == END_OF_EXPR)
{
token = tokenStream.get();
}
if(token.kind == QUIT)
{
return;
}
tokenStream.putback(token);
value = parser.expression();
std::cout << "= " << value << std::endl;
}
}
TokenStream passArgsToTokenStream(const char* argv[])
{
std::cout << ">> " << argv[1] << std::endl;
std::string expression{argv[1]};
TokenStream tokenStream{expression + END_OF_EXPR + QUIT};
return tokenStream;
}
int main(int argc, const char* argv[])
{
if(argc < 2)
{
std::cout << "There aren't any operations send to Calculator" << std::endl;
return 1;
}
TokenStream tokenStream = passArgsToTokenStream(argv);
try
{
calculate(tokenStream);
return 0;
}
catch (std::logic_error& error)
{
std::cerr << error.what() << std::endl;
clean(tokenStream);
return 1;
}
catch (...)
{
std::cerr << "Unexpected exception";
return 2;
}
}
<commit_msg>Refactoring part 2<commit_after>#include <iostream>
#include <stdexcept>
#include "Token.hpp"
#include "TokenStream.hpp"
#include "Calculator.hpp"
void cleanUpMess(ITokenStream& tokenStream)
{
tokenStream.ignore(END_OF_EXPR);
}
void calculate(ITokenStream& tokenStream)
{
double value = 0;
Calculator parser{tokenStream};
while (std::cin)
{
try
{
Token token = tokenStream.get();
while (token.kind == END_OF_EXPR)
{
token = tokenStream.get();
}
if(token.kind == QUIT)
{
return;
}
tokenStream.putback(token);
value = parser.expression();
std::cout << "= " << value << std::endl;
}
catch (std::logic_error& error)
{
std::cerr << error.what() << std::endl;
cleanUpMess(tokenStream);
}
}
}
TokenStream passArgsToTokenStream(const char* argv[])
{
std::cout << ">> " << argv[1] << std::endl;
std::string expression{argv[1]};
TokenStream tokenStream{expression + END_OF_EXPR + QUIT};
return tokenStream;
}
int main(int argc, const char* argv[])
{
if(argc < 2)
{
std::cout << "There aren't any operations send to Calculator" << std::endl;
return 1;
}
TokenStream tokenStream = passArgsToTokenStream(argv);
try
{
calculate(tokenStream);
return 0;
}
catch (std::logic_error& error)
{
std::cerr << error.what() << std::endl;
clean(tokenStream);
return 1;
}
catch (...)
{
std::cerr << "Unexpected exception";
return 2;
}
}
<|endoftext|> |
<commit_before>/*
* moduleTest.cpp
*
* Created on: 2015年12月15日
* Author: nemo
*/
#include "LiveMsgTool/LiveMsgTool.h"
#include "MiTACCSC/MiTACCSC.h"
#include <iostream>
using namespace std;
int main()
{
MiTACCSC *entryReader = new MiTACCSC();
MiTACCSC *exitReader = new MiTACCSC();
LiveMsgTool *liveMsg = new LiveMsgTool();
LiveMsgTool::LiveMsgMemberFunc entryFun = &LiveMsgTool::EntryAlive;
LiveMsgTool::LiveMsgMemberFunc exitFun = &LiveMsgTool::ExitAlive;
cout << "First show" << endl;
liveMsg->showMsg();
(liveMsg->*entryFun)();
(liveMsg->*exitFun)();
// f fPtr = (f)(&LiveMsgTool::EntryAlive);
// fPtr();
// entryReader->setFunPtr( fPtr );
// entryReader->setFunPtr( (f)(&LiveMsgTool::EntryAlive) );
cout << endl << "Prepare run function" << endl;
entryReader->runFun();
exitReader->runFun();
cout << "\nEnd show" << endl;
liveMsg->showMsg();
return 0;
}
<commit_msg>Added set member function pointer as parameter.<commit_after>/*
* moduleTest.cpp
*
* Created on: 2015年12月15日
* Author: nemo
*/
#include "LiveMsgTool/LiveMsgTool.h"
#include "MiTACCSC/MiTACCSC.h"
#include <iostream>
using namespace std;
int main()
{
MiTACCSC *entryReader = new MiTACCSC();
MiTACCSC *exitReader = new MiTACCSC();
LiveMsgTool *liveMsg = new LiveMsgTool();
LiveMsgTool::LiveMsgMemberFunc entryFun = &LiveMsgTool::EntryAlive;
LiveMsgTool::LiveMsgMemberFunc exitFun = &LiveMsgTool::ExitAlive;
cout << "First show" << endl;
liveMsg->showMsg();
// (liveMsg->*entryFun)();
// (liveMsg->*exitFun)();
// f fPtr = (f)(&LiveMsgTool::EntryAlive);
// fPtr();
// typedef void (LiveMsgTool::*LiveMsgMemberFunc)();
// typedef void (*f)(void);
entryReader->setFunPtr( (f)(liveMsg->*entryFun) );
// entryReader->setFunPtr( (f)(&LiveMsgTool::EntryAlive) );
cout << endl << "Prepare run function" << endl;
entryReader->runFun();
exitReader->runFun();
cout << "\nEnd show" << endl;
liveMsg->showMsg();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>scoreboard working<commit_after><|endoftext|> |
<commit_before>#include <cassert>
#include <chrono>
#include <deque>
#include <iostream>
#include <set>
#include <utility> // pair
#include <boost/dynamic_bitset.hpp>
#include "mc/places/nopost_live.hh"
#include "mc/places/post.hh"
#include "mc/places/post_live.hh"
#include "mc/places/pre.hh"
#include "mc/places/sdd.hh"
#include "mc/places/concurrent_units.hh"
#include "mc/places/worker.hh"
namespace pnmc { namespace mc { namespace places {
namespace chrono = std::chrono;
/*------------------------------------------------------------------------------------------------*/
order
mk_order(const conf::pnmc_configuration& conf, const pn::net& net)
{
order_builder ob;
for (const auto& place : net.places())
{
ob.push(place.id);
}
return order(ob);
}
/*------------------------------------------------------------------------------------------------*/
SDD
initial_state(const order& o, const pn::net& net)
{
return SDD(o, [&](unsigned int id)
-> sdd::values::bitset<64>
{
return {net.places_by_id().find(id)->marking};
});
}
/*------------------------------------------------------------------------------------------------*/
homomorphism
transition_relation( const conf::pnmc_configuration& conf, const order& o
, const pn::net& net, boost::dynamic_bitset<>& transitions_bitset)
{
chrono::time_point<chrono::system_clock> start;
chrono::time_point<chrono::system_clock> end;
std::size_t elapsed;
start = chrono::system_clock::now();
std::set<homomorphism> operands;
operands.insert(Id<sdd_conf>());
// When computing dead transitions, we need to start numbering them from 0 as we use this
// value as an index in the bitset.
unsigned int tindex = 0;
for (const auto& transition : net.transitions())
{
homomorphism h_t = Id<sdd_conf>();
if (transition.post.empty() and transition.pre.empty() and conf.compute_dead_transitions)
{
// Empty transition, but we need to increment the transition counter.
++tindex;
}
else if (not transition.post.empty())
{
// post actions.
auto arc_cit = transition.post.begin();
if (conf.compute_dead_transitions)
{
const auto f = ValuesFunction<sdd_conf>( o, arc_cit->first
, post_live(tindex++, transitions_bitset));
h_t = Composition(h_t, sdd::carrier(o, arc_cit->first, f));
}
else
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc_cit->first, post());
h_t = Composition(h_t, sdd::carrier(o, arc_cit->first, f));
}
for (++arc_cit; arc_cit != transition.post.end(); ++arc_cit)
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc_cit->first, post());
h_t = Composition(h_t, sdd::carrier(o, arc_cit->first, f));
}
}
else if (conf.compute_dead_transitions)
{
// Target the same variable as the pre that is fired just before this fake post.
const auto place = transition.pre.begin()->first;
const auto f
= ValuesFunction<sdd_conf>( o, place
, nopost_live(tindex++, transitions_bitset));
h_t = Composition(h_t, sdd::carrier(o, place, f));
}
// pre actions.
for (const auto& arc : transition.pre)
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, pre());
h_t = Composition(h_t, sdd::carrier(o, arc.first, f));
}
operands.insert(h_t);
}
end = chrono::system_clock::now();
elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "Transition relation time: " << elapsed << "s" << std::endl;
}
start = chrono::system_clock::now();
const auto res = sdd::rewrite(o, Fixpoint(Sum<sdd_conf>(o, operands.cbegin(), operands.cend())));
end = chrono::system_clock::now();
elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "Rewrite time: " << elapsed << "s" << std::endl;
}
return res;
}
/*------------------------------------------------------------------------------------------------*/
SDD
state_space( const conf::pnmc_configuration& conf, const order& o, SDD m
, homomorphism h)
{
chrono::time_point<chrono::system_clock> start = chrono::system_clock::now();
const auto res = h(o, m);
chrono::time_point<chrono::system_clock> end = chrono::system_clock::now();
const std::size_t elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "State space computation time: " << elapsed << "s" << std::endl;
}
return res;
}
/*------------------------------------------------------------------------------------------------*/
worker::worker(const conf::pnmc_configuration& c)
: conf(c)
{}
void
worker::operator()(const pn::net& net)
const
{
auto manager = sdd::manager<sdd_conf>::init();
boost::dynamic_bitset<> transitions_bitset(net.transitions().size());
const order o = mk_order(conf, net);
assert(not o.empty() && "Empty order");
if (conf.order_show)
{
std::cout << o << std::endl;
}
const SDD m0 = initial_state(o, net);
const homomorphism h = transition_relation(conf, o, net, transitions_bitset);
if (conf.show_relation)
{
std::cout << h << std::endl;
}
const SDD m = state_space(conf, o, m0, h);
if (conf.show_nb_states)
{
std::cout << m.size().template convert_to<long double>() << " states" << std::endl;
}
if (conf.compute_dead_transitions)
{
for (std::size_t i = 0; i < net.transitions().size(); ++i)
{
std::cout << (!transitions_bitset[i]) << "\n";
}
}
if (conf.compute_concurrent_units)
{
compute_concurrent_units(conf, net, o, m);
}
if (conf.show_hash_tables_stats)
{
std::cout << manager << std::endl;
}
}
/*------------------------------------------------------------------------------------------------*/
}}} // namespace pnmc::mc::places
<commit_msg>Deactivate computation of concurrent units when in places mode. The algorithm is incorrect for the moment and the unit mode performs better.<commit_after>#include <cassert>
#include <chrono>
#include <deque>
#include <iostream>
#include <set>
#include <utility> // pair
#include <boost/dynamic_bitset.hpp>
#include "mc/places/nopost_live.hh"
#include "mc/places/post.hh"
#include "mc/places/post_live.hh"
#include "mc/places/pre.hh"
#include "mc/places/sdd.hh"
//#include "mc/places/concurrent_units.hh"
#include "mc/places/worker.hh"
namespace pnmc { namespace mc { namespace places {
namespace chrono = std::chrono;
/*------------------------------------------------------------------------------------------------*/
order
mk_order(const conf::pnmc_configuration& conf, const pn::net& net)
{
order_builder ob;
for (const auto& place : net.places())
{
ob.push(place.id);
}
return order(ob);
}
/*------------------------------------------------------------------------------------------------*/
SDD
initial_state(const order& o, const pn::net& net)
{
return SDD(o, [&](unsigned int id)
-> sdd::values::bitset<64>
{
return {net.places_by_id().find(id)->marking};
});
}
/*------------------------------------------------------------------------------------------------*/
homomorphism
transition_relation( const conf::pnmc_configuration& conf, const order& o
, const pn::net& net, boost::dynamic_bitset<>& transitions_bitset)
{
chrono::time_point<chrono::system_clock> start;
chrono::time_point<chrono::system_clock> end;
std::size_t elapsed;
start = chrono::system_clock::now();
std::set<homomorphism> operands;
operands.insert(Id<sdd_conf>());
// When computing dead transitions, we need to start numbering them from 0 as we use this
// value as an index in the bitset.
unsigned int tindex = 0;
for (const auto& transition : net.transitions())
{
homomorphism h_t = Id<sdd_conf>();
if (transition.post.empty() and transition.pre.empty() and conf.compute_dead_transitions)
{
// Empty transition, but we need to increment the transition counter.
++tindex;
}
else if (not transition.post.empty())
{
// post actions.
auto arc_cit = transition.post.begin();
if (conf.compute_dead_transitions)
{
const auto f = ValuesFunction<sdd_conf>( o, arc_cit->first
, post_live(tindex++, transitions_bitset));
h_t = Composition(h_t, sdd::carrier(o, arc_cit->first, f));
}
else
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc_cit->first, post());
h_t = Composition(h_t, sdd::carrier(o, arc_cit->first, f));
}
for (++arc_cit; arc_cit != transition.post.end(); ++arc_cit)
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc_cit->first, post());
h_t = Composition(h_t, sdd::carrier(o, arc_cit->first, f));
}
}
else if (conf.compute_dead_transitions)
{
// Target the same variable as the pre that is fired just before this fake post.
const auto place = transition.pre.begin()->first;
const auto f
= ValuesFunction<sdd_conf>( o, place
, nopost_live(tindex++, transitions_bitset));
h_t = Composition(h_t, sdd::carrier(o, place, f));
}
// pre actions.
for (const auto& arc : transition.pre)
{
homomorphism f = ValuesFunction<sdd_conf>(o, arc.first, pre());
h_t = Composition(h_t, sdd::carrier(o, arc.first, f));
}
operands.insert(h_t);
}
end = chrono::system_clock::now();
elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "Transition relation time: " << elapsed << "s" << std::endl;
}
start = chrono::system_clock::now();
const auto res = sdd::rewrite(o, Fixpoint(Sum<sdd_conf>(o, operands.cbegin(), operands.cend())));
end = chrono::system_clock::now();
elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "Rewrite time: " << elapsed << "s" << std::endl;
}
return res;
}
/*------------------------------------------------------------------------------------------------*/
SDD
state_space( const conf::pnmc_configuration& conf, const order& o, SDD m
, homomorphism h)
{
chrono::time_point<chrono::system_clock> start = chrono::system_clock::now();
const auto res = h(o, m);
chrono::time_point<chrono::system_clock> end = chrono::system_clock::now();
const std::size_t elapsed = chrono::duration_cast<chrono::seconds>(end-start).count();
if (conf.show_time)
{
std::cout << "State space computation time: " << elapsed << "s" << std::endl;
}
return res;
}
/*------------------------------------------------------------------------------------------------*/
worker::worker(const conf::pnmc_configuration& c)
: conf(c)
{}
void
worker::operator()(const pn::net& net)
const
{
auto manager = sdd::manager<sdd_conf>::init();
boost::dynamic_bitset<> transitions_bitset(net.transitions().size());
const order o = mk_order(conf, net);
assert(not o.empty() && "Empty order");
if (conf.order_show)
{
std::cout << o << std::endl;
}
const SDD m0 = initial_state(o, net);
const homomorphism h = transition_relation(conf, o, net, transitions_bitset);
if (conf.show_relation)
{
std::cout << h << std::endl;
}
const SDD m = state_space(conf, o, m0, h);
if (conf.show_nb_states)
{
std::cout << m.size().template convert_to<long double>() << " states" << std::endl;
}
if (conf.compute_dead_transitions)
{
for (std::size_t i = 0; i < net.transitions().size(); ++i)
{
std::cout << (!transitions_bitset[i]) << "\n";
}
}
if (conf.compute_concurrent_units)
{
std::cerr << "Unavailable in this mode" << std::endl;
}
if (conf.show_hash_tables_stats)
{
std::cout << manager << std::endl;
}
}
/*------------------------------------------------------------------------------------------------*/
}}} // namespace pnmc::mc::places
<|endoftext|> |
<commit_before>#include "Timers.hxx"
#include "Block_Info.hxx"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
void write_timing(const boost::filesystem::path &out_file,
const boost::filesystem::path &block_timings_filename,
const Block_Info &block_info, const Timers &timers)
{
timers.write_profile(out_file.string() + ".profiling."
+ std::to_string(El::mpi::Rank()));
if(!block_timings_filename.empty())
{
El::Matrix<double> block_timings(block_info.dimensions.size(), 1);
El::Zero(block_timings);
for(auto &index : block_info.block_indices)
{
block_timings(index, 0)
= timers.elapsed("run.step.initializeSchurComplementSolver."
"Qcomputation.Syrk.block_"
+ std::to_string(index));
// + timers.elapsed("run.step.initializeSchurComplementSolver."
// "Qcomputation.Syrk.block_" +
// std::to_string(index));
}
El::AllReduce(block_timings, El::mpi::COMM_WORLD);
if(El::mpi::Rank() == 0)
{
boost::filesystem::ofstream block_timings_file(
block_timings_filename);
for(size_t row = 0; row < block_timings.Height(); ++row)
{
block_timings_file << block_timings(row, 0) << "\n";
}
}
}
}
<commit_msg>Write integers for timing rather than doubles<commit_after>#include "Timers.hxx"
#include "Block_Info.hxx"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
void write_timing(const boost::filesystem::path &out_file,
const boost::filesystem::path &block_timings_filename,
const Block_Info &block_info, const Timers &timers)
{
timers.write_profile(out_file.string() + ".profiling."
+ std::to_string(El::mpi::Rank()));
if(!block_timings_filename.empty())
{
El::Matrix<int32_t> block_timings(block_info.dimensions.size(), 1);
El::Zero(block_timings);
for(auto &index : block_info.block_indices)
{
// cpu_timer's native resolution is nanoseconds. We round
// to milliseconds so that we are only dealing with
// integers.
block_timings(index,0)
= (timers.elapsed("run.step.initializeSchurComplementSolver."
"Qcomputation.Syrk.block_"
+ std::to_string(index)))/1000000;
// + timers.elapsed("run.step.initializeSchurComplementSolver."
// "Qcomputation.Syrk.block_" +
// std::to_string(index));
}
El::AllReduce(block_timings, El::mpi::COMM_WORLD);
if(El::mpi::Rank() == 0)
{
boost::filesystem::ofstream block_timings_file(
block_timings_filename);
for(size_t row = 0; row < block_timings.Height(); ++row)
{
block_timings_file << block_timings(row, 0) << "\n";
}
}
}
}
<|endoftext|> |
<commit_before><commit_msg>Remove some obsolete ifdefs that excluded certain tests on linux + mac.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/browser.h"
#include "base/utf_string_conversions.h"
#include "base/win/metro.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/fullscreen_controller.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
namespace {
void NewMetroWindow(Browser* source_browser, Profile* profile) {
typedef void (*FlipFrameWindows)();
static FlipFrameWindows flip_window_fn = reinterpret_cast<FlipFrameWindows>(
::GetProcAddress(base::win::GetMetroModule(), "FlipFrameWindows"));
DCHECK(flip_window_fn);
Browser* browser = browser::FindTabbedBrowser(profile, false);
if (!browser) {
Browser::OpenEmptyWindow(profile);
return;
}
browser->NewTab();
if (browser != source_browser) {
// Tell the metro_driver to flip our window. This causes the current
// browser window to be hidden and the next window to be shown.
flip_window_fn();
}
}
} // namespace
void Browser::NewWindow() {
if (base::win::GetMetroModule()) {
NewMetroWindow(this, profile_->GetOriginalProfile());
return;
}
NewEmptyWindow(profile_->GetOriginalProfile());
}
void Browser::NewIncognitoWindow() {
if (base::win::GetMetroModule()) {
NewMetroWindow(this, profile_->GetOffTheRecordProfile());
return;
}
NewEmptyWindow(profile_->GetOffTheRecordProfile());
}
void Browser::SetMetroSnapMode(bool enable) {
fullscreen_controller_->SetMetroSnapMode(enable);
}
void Browser::PinCurrentPageToStartScreen() {
HMODULE metro_module = base::win::GetMetroModule();
if (metro_module) {
GURL url;
string16 title;
TabContents* tab = GetActiveTabContents();
bookmark_utils::GetURLAndTitleToBookmark(tab->web_contents(), &url, &title);
typedef BOOL (*MetroPinUrlToStartScreen)(string16, string16);
MetroPinUrlToStartScreen metro_pin_url_to_start_screen =
reinterpret_cast<MetroPinUrlToStartScreen>(
::GetProcAddress(metro_module, "MetroPinUrlToStartScreen"));
if (!metro_pin_url_to_start_screen) {
NOTREACHED();
return;
}
VLOG(1) << __FUNCTION__ << " calling pin with title: " << title
<< " and url " << UTF8ToUTF16(url.spec());
metro_pin_url_to_start_screen(title, UTF8ToUTF16(url.spec()));
return;
}
}
<commit_msg>Fixed crash pinning secondary tiles to the start screen on windows 8.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/browser.h"
#include "base/utf_string_conversions.h"
#include "base/win/metro.h"
#include "chrome/browser/bookmarks/bookmark_utils.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/fullscreen_controller.h"
#include "chrome/browser/ui/tab_contents/tab_contents.h"
namespace {
void NewMetroWindow(Browser* source_browser, Profile* profile) {
typedef void (*FlipFrameWindows)();
static FlipFrameWindows flip_window_fn = reinterpret_cast<FlipFrameWindows>(
::GetProcAddress(base::win::GetMetroModule(), "FlipFrameWindows"));
DCHECK(flip_window_fn);
Browser* browser = browser::FindTabbedBrowser(profile, false);
if (!browser) {
Browser::OpenEmptyWindow(profile);
return;
}
browser->NewTab();
if (browser != source_browser) {
// Tell the metro_driver to flip our window. This causes the current
// browser window to be hidden and the next window to be shown.
flip_window_fn();
}
}
} // namespace
void Browser::NewWindow() {
if (base::win::GetMetroModule()) {
NewMetroWindow(this, profile_->GetOriginalProfile());
return;
}
NewEmptyWindow(profile_->GetOriginalProfile());
}
void Browser::NewIncognitoWindow() {
if (base::win::GetMetroModule()) {
NewMetroWindow(this, profile_->GetOffTheRecordProfile());
return;
}
NewEmptyWindow(profile_->GetOffTheRecordProfile());
}
void Browser::SetMetroSnapMode(bool enable) {
fullscreen_controller_->SetMetroSnapMode(enable);
}
void Browser::PinCurrentPageToStartScreen() {
HMODULE metro_module = base::win::GetMetroModule();
if (metro_module) {
GURL url;
string16 title;
TabContents* tab = GetActiveTabContents();
bookmark_utils::GetURLAndTitleToBookmark(tab->web_contents(), &url, &title);
typedef BOOL (*MetroPinUrlToStartScreen)(const string16&, const string16&);
MetroPinUrlToStartScreen metro_pin_url_to_start_screen =
reinterpret_cast<MetroPinUrlToStartScreen>(
::GetProcAddress(metro_module, "MetroPinUrlToStartScreen"));
if (!metro_pin_url_to_start_screen) {
NOTREACHED();
return;
}
VLOG(1) << __FUNCTION__ << " calling pin with title: " << title
<< " and url " << UTF8ToUTF16(url.spec());
metro_pin_url_to_start_screen(title, UTF8ToUTF16(url.spec()));
return;
}
}
<|endoftext|> |
<commit_before>
<commit_msg>Delete 1.cpp<commit_after><|endoftext|> |
<commit_before>#include "qt/create_feature_dialog.hpp"
#include "qt/draw_widget.hpp"
#include "qt/editor_dialog.hpp"
#include "qt/place_page_dialog.hpp"
#include "qt/qt_common/helpers.hpp"
#include "qt/qt_common/scale_slider.hpp"
#include "map/framework.hpp"
#include "drape_frontend/visual_params.hpp"
#include "search/result.hpp"
#include "storage/index.hpp"
#include "indexer/editable_map_object.hpp"
#include "platform/settings.hpp"
#include "platform/platform.hpp"
#include "platform/settings.hpp"
#include <QtGui/QMouseEvent>
#include <QtGui/QGuiApplication>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDesktopWidget>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QMenu>
#include <QtCore/QLocale>
#include <QtCore/QDateTime>
#include <QtCore/QThread>
#include <QtCore/QTimer>
using namespace qt::common;
namespace qt
{
DrawWidget::DrawWidget(Framework & framework, bool apiOpenGLES3, QWidget * parent)
: TBase(framework, apiOpenGLES3, parent)
, m_rubberBand(nullptr)
, m_emulatingLocation(false)
{
m_framework.SetMapSelectionListeners(
[this](place_page::Info const & info) { ShowPlacePage(info); },
[](bool /* switchFullScreenMode */) {}); // Empty deactivation listener.
m_framework.SetRouteBuildingListener(
[](routing::IRouter::ResultCode, storage::TCountriesVec const &) {});
m_framework.SetCurrentCountryChangedListener([this](storage::TCountryId const & countryId) {
m_countryId = countryId;
UpdateCountryStatus(countryId);
});
QTimer * countryStatusTimer = new QTimer(this);
VERIFY(connect(countryStatusTimer, SIGNAL(timeout()), this, SLOT(OnUpdateCountryStatusByTimer())), ());
countryStatusTimer->setSingleShot(false);
countryStatusTimer->start(1000);
}
DrawWidget::~DrawWidget()
{
delete m_rubberBand;
}
void DrawWidget::UpdateCountryStatus(storage::TCountryId const & countryId)
{
if (m_currentCountryChanged != nullptr)
{
string countryName = countryId;
auto status = m_framework.GetStorage().CountryStatusEx(countryId);
uint8_t progressInPercentage = 0;
storage::MapFilesDownloader::TProgress progressInByte = make_pair(0, 0);
if (!countryId.empty())
{
storage::NodeAttrs nodeAttrs;
m_framework.GetStorage().GetNodeAttrs(countryId, nodeAttrs);
progressInByte = nodeAttrs.m_downloadingProgress;
if (progressInByte.second != 0)
progressInPercentage = static_cast<int8_t>(100 * progressInByte.first / progressInByte.second);
}
m_currentCountryChanged(countryId, countryName, status,
progressInByte.second, progressInPercentage);
}
}
void DrawWidget::OnUpdateCountryStatusByTimer()
{
if (!m_countryId.empty())
UpdateCountryStatus(m_countryId);
}
void DrawWidget::SetCurrentCountryChangedListener(DrawWidget::TCurrentCountryChanged const & listener)
{
m_currentCountryChanged = listener;
}
void DrawWidget::DownloadCountry(storage::TCountryId const & countryId)
{
m_framework.GetStorage().DownloadNode(countryId);
if (!m_countryId.empty())
UpdateCountryStatus(m_countryId);
}
void DrawWidget::RetryToDownloadCountry(storage::TCountryId const & countryId)
{
// TODO @bykoianko
}
void DrawWidget::PrepareShutdown()
{
}
void DrawWidget::UpdateAfterSettingsChanged()
{
m_framework.EnterForeground();
}
void DrawWidget::ShowAll()
{
m_framework.ShowAll();
}
void DrawWidget::ChoosePositionModeEnable()
{
m_framework.BlockTapEvents(true /* block */);
m_framework.EnableChoosePositionMode(true /* enable */, false /* enableBounds */,
false /* applyPosition */, m2::PointD() /* position */);
}
void DrawWidget::ChoosePositionModeDisable()
{
m_framework.EnableChoosePositionMode(false /* enable */, false /* enableBounds */,
false /* applyPosition */, m2::PointD() /* position */);
m_framework.BlockTapEvents(false /* block */);
}
void DrawWidget::initializeGL()
{
MapWidget::initializeGL();
m_framework.LoadBookmarks();
}
void DrawWidget::mousePressEvent(QMouseEvent * e)
{
QOpenGLWidget::mousePressEvent(e);
m2::PointD const pt = GetDevicePoint(e);
if (IsLeftButton(e))
{
if (IsShiftModifier(e))
SubmitRoutingPoint(pt);
else if (IsAltModifier(e))
SubmitFakeLocationPoint(pt);
else
m_framework.TouchEvent(GetTouchEvent(e, df::TouchEvent::TOUCH_DOWN));
}
else if (IsRightButton(e))
{
if (!m_selectionMode || IsCommandModifier(e))
{
ShowInfoPopup(e, pt);
}
else
{
m_rubberBandOrigin = e->pos();
if (m_rubberBand == nullptr)
m_rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
m_rubberBand->setGeometry(QRect(m_rubberBandOrigin, QSize()));
m_rubberBand->show();
}
}
}
void DrawWidget::mouseMoveEvent(QMouseEvent * e)
{
QOpenGLWidget::mouseMoveEvent(e);
if (IsLeftButton(e) && !IsAltModifier(e))
m_framework.TouchEvent(GetTouchEvent(e, df::TouchEvent::TOUCH_MOVE));
if (m_selectionMode && m_rubberBand != nullptr && m_rubberBand->isVisible())
{
m_rubberBand->setGeometry(QRect(m_rubberBandOrigin, e->pos()).normalized());
}
}
void DrawWidget::mouseReleaseEvent(QMouseEvent * e)
{
QOpenGLWidget::mouseReleaseEvent(e);
if (IsLeftButton(e) && !IsAltModifier(e))
{
m_framework.TouchEvent(GetTouchEvent(e, df::TouchEvent::TOUCH_UP));
}
else if (m_selectionMode && IsRightButton(e) && m_rubberBand != nullptr &&
m_rubberBand->isVisible())
{
QPoint const lt = m_rubberBand->geometry().topLeft();
QPoint const rb = m_rubberBand->geometry().bottomRight();
m2::RectD rect;
rect.Add(m_framework.PtoG(m2::PointD(L2D(lt.x()), L2D(lt.y()))));
rect.Add(m_framework.PtoG(m2::PointD(L2D(rb.x()), L2D(rb.y()))));
m_framework.VisualizeRoadsInRect(rect);
m_rubberBand->hide();
}
}
void DrawWidget::keyPressEvent(QKeyEvent * e)
{
TBase::keyPressEvent(e);
if (IsLeftButton(QGuiApplication::mouseButtons()) &&
e->key() == Qt::Key_Control)
{
df::TouchEvent event;
event.SetTouchType(df::TouchEvent::TOUCH_DOWN);
df::Touch touch;
touch.m_id = 0;
touch.m_location = m2::PointD(L2D(QCursor::pos().x()), L2D(QCursor::pos().y()));
event.SetFirstTouch(touch);
event.SetSecondTouch(GetSymmetrical(touch));
m_framework.TouchEvent(event);
}
}
void DrawWidget::keyReleaseEvent(QKeyEvent * e)
{
TBase::keyReleaseEvent(e);
if (IsLeftButton(QGuiApplication::mouseButtons()) &&
e->key() == Qt::Key_Control)
{
df::TouchEvent event;
event.SetTouchType(df::TouchEvent::TOUCH_UP);
df::Touch touch;
touch.m_id = 0;
touch.m_location = m2::PointD(L2D(QCursor::pos().x()), L2D(QCursor::pos().y()));
event.SetFirstTouch(touch);
event.SetSecondTouch(GetSymmetrical(touch));
m_framework.TouchEvent(event);
}
else if (e->key() == Qt::Key_Alt)
m_emulatingLocation = false;
}
bool DrawWidget::Search(search::EverywhereSearchParams const & params)
{
return m_framework.SearchEverywhere(params);
}
string DrawWidget::GetDistance(search::Result const & res) const
{
string dist;
double lat, lon;
if (m_framework.GetCurrentPosition(lat, lon))
{
double dummy;
(void) m_framework.GetDistanceAndAzimut(res.GetFeatureCenter(), lat, lon, -1.0, dist, dummy);
}
return dist;
}
void DrawWidget::ShowSearchResult(search::Result const & res)
{
m_framework.ShowSearchResult(res);
}
void DrawWidget::CreateFeature()
{
auto cats = m_framework.GetEditorCategories();
CreateFeatureDialog dlg(this, cats);
if (dlg.exec() == QDialog::Accepted)
{
osm::EditableMapObject emo;
if (m_framework.CreateMapObject(m_framework.GetViewportCenter(), dlg.GetSelectedType(), emo))
{
EditorDialog dlg(this, emo);
int const result = dlg.exec();
if (result == QDialog::Accepted)
m_framework.SaveEditedMapObject(emo);
}
else
{
LOG(LWARNING, ("Error creating new map object."));
}
}
}
void DrawWidget::OnLocationUpdate(location::GpsInfo const & info)
{
if (!m_emulatingLocation)
m_framework.OnLocationUpdate(info);
}
void DrawWidget::SetMapStyle(MapStyle mapStyle)
{
m_framework.SetMapStyle(mapStyle);
}
void DrawWidget::SubmitFakeLocationPoint(m2::PointD const & pt)
{
m_emulatingLocation = true;
m2::PointD const point = m_framework.PtoG(pt);
location::GpsInfo info;
info.m_latitude = MercatorBounds::YToLat(point.y);
info.m_longitude = MercatorBounds::XToLon(point.x);
info.m_horizontalAccuracy = 10;
info.m_timestamp = QDateTime::currentMSecsSinceEpoch() / 1000.0;
m_framework.OnLocationUpdate(info);
if (m_framework.IsRoutingActive())
{
location::FollowingInfo loc;
m_framework.GetRouteFollowingInfo(loc);
LOG(LDEBUG, ("Distance:", loc.m_distToTarget, loc.m_targetUnitsSuffix, "Time:", loc.m_time,
"Turn:", routing::turns::GetTurnString(loc.m_turn), "(", loc.m_distToTurn, loc.m_turnUnitsSuffix,
") Roundabout exit number:", loc.m_exitNum));
}
}
void DrawWidget::SubmitRoutingPoint(m2::PointD const & pt)
{
if (m_framework.IsRoutingActive())
m_framework.CloseRouting();
else
m_framework.BuildRoute(m_framework.PtoG(pt), 0 /* timeoutSec */);
}
void DrawWidget::ShowPlacePage(place_page::Info const & info)
{
search::AddressInfo address;
if (info.IsFeature())
address = m_framework.GetFeatureAddressInfo(info.GetID());
else
address = m_framework.GetAddressInfoAtPoint(info.GetMercator());
PlacePageDialog dlg(this, info, address);
if (dlg.exec() == QDialog::Accepted)
{
osm::EditableMapObject emo;
if (m_framework.GetEditableMapObject(info.GetID(), emo))
{
EditorDialog dlg(this, emo);
int const result = dlg.exec();
if (result == QDialog::Accepted)
{
m_framework.SaveEditedMapObject(emo);
m_framework.UpdatePlacePageInfoForCurrentSelection();
}
else if (result == QDialogButtonBox::DestructiveRole)
{
m_framework.DeleteFeature(info.GetID());
}
}
else
{
LOG(LERROR, ("Error while trying to edit feature."));
}
}
m_framework.DeactivateMapSelection(false);
}
void DrawWidget::ShowInfoPopup(QMouseEvent * e, m2::PointD const & pt)
{
// show feature types
QMenu menu;
auto const addStringFn = [&menu](string const & s)
{
menu.addAction(QString::fromUtf8(s.c_str()));
};
m_framework.ForEachFeatureAtPoint([&](FeatureType & ft)
{
search::AddressInfo const info = m_framework.GetFeatureAddressInfo(ft);
string concat;
for (auto const & type : info.m_types)
concat += type + " ";
addStringFn(concat);
if (!info.m_name.empty())
addStringFn(info.m_name);
string const addr = info.FormatAddress();
if (!addr.empty())
addStringFn(addr);
menu.addSeparator();
}, m_framework.PtoG(pt));
menu.exec(e->pos());
}
void DrawWidget::SetRouter(routing::RouterType routerType)
{
m_framework.SetRouter(routerType);
}
void DrawWidget::SetSelectionMode(bool mode) { m_selectionMode = mode; }
// static
void DrawWidget::SetDefaultSurfaceFormat(bool apiOpenGLES3)
{
QSurfaceFormat fmt;
fmt.setAlphaBufferSize(8);
fmt.setBlueBufferSize(8);
fmt.setGreenBufferSize(8);
fmt.setRedBufferSize(8);
fmt.setStencilBufferSize(0);
fmt.setSamples(0);
fmt.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
fmt.setSwapInterval(1);
fmt.setDepthBufferSize(16);
if (apiOpenGLES3)
{
fmt.setProfile(QSurfaceFormat::CoreProfile);
fmt.setVersion(3, 2);
}
else
{
fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
fmt.setVersion(2, 1);
}
//fmt.setOption(QSurfaceFormat::DebugContext);
QSurfaceFormat::setDefaultFormat(fmt);
}
} // namespace qt
<commit_msg>Fixed qt build<commit_after>#include "qt/create_feature_dialog.hpp"
#include "qt/draw_widget.hpp"
#include "qt/editor_dialog.hpp"
#include "qt/place_page_dialog.hpp"
#include "qt/qt_common/helpers.hpp"
#include "qt/qt_common/scale_slider.hpp"
#include "map/framework.hpp"
#include "drape_frontend/visual_params.hpp"
#include "search/result.hpp"
#include "storage/index.hpp"
#include "indexer/editable_map_object.hpp"
#include "platform/settings.hpp"
#include "platform/platform.hpp"
#include "platform/settings.hpp"
#include <QtGui/QMouseEvent>
#include <QtGui/QGuiApplication>
#include <QtWidgets/QApplication>
#include <QtWidgets/QDesktopWidget>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QMenu>
#include <QtCore/QLocale>
#include <QtCore/QDateTime>
#include <QtCore/QThread>
#include <QtCore/QTimer>
using namespace qt::common;
namespace qt
{
DrawWidget::DrawWidget(Framework & framework, bool apiOpenGLES3, QWidget * parent)
: TBase(framework, apiOpenGLES3, parent)
, m_rubberBand(nullptr)
, m_emulatingLocation(false)
{
m_framework.SetMapSelectionListeners(
[this](place_page::Info const & info) { ShowPlacePage(info); },
[](bool /* switchFullScreenMode */) {}); // Empty deactivation listener.
m_framework.GetRoutingManager().SetRouteBuildingListener(
[](routing::IRouter::ResultCode, storage::TCountriesVec const &) {});
m_framework.SetCurrentCountryChangedListener([this](storage::TCountryId const & countryId) {
m_countryId = countryId;
UpdateCountryStatus(countryId);
});
QTimer * countryStatusTimer = new QTimer(this);
VERIFY(connect(countryStatusTimer, SIGNAL(timeout()), this, SLOT(OnUpdateCountryStatusByTimer())), ());
countryStatusTimer->setSingleShot(false);
countryStatusTimer->start(1000);
}
DrawWidget::~DrawWidget()
{
delete m_rubberBand;
}
void DrawWidget::UpdateCountryStatus(storage::TCountryId const & countryId)
{
if (m_currentCountryChanged != nullptr)
{
string countryName = countryId;
auto status = m_framework.GetStorage().CountryStatusEx(countryId);
uint8_t progressInPercentage = 0;
storage::MapFilesDownloader::TProgress progressInByte = make_pair(0, 0);
if (!countryId.empty())
{
storage::NodeAttrs nodeAttrs;
m_framework.GetStorage().GetNodeAttrs(countryId, nodeAttrs);
progressInByte = nodeAttrs.m_downloadingProgress;
if (progressInByte.second != 0)
progressInPercentage = static_cast<int8_t>(100 * progressInByte.first / progressInByte.second);
}
m_currentCountryChanged(countryId, countryName, status,
progressInByte.second, progressInPercentage);
}
}
void DrawWidget::OnUpdateCountryStatusByTimer()
{
if (!m_countryId.empty())
UpdateCountryStatus(m_countryId);
}
void DrawWidget::SetCurrentCountryChangedListener(DrawWidget::TCurrentCountryChanged const & listener)
{
m_currentCountryChanged = listener;
}
void DrawWidget::DownloadCountry(storage::TCountryId const & countryId)
{
m_framework.GetStorage().DownloadNode(countryId);
if (!m_countryId.empty())
UpdateCountryStatus(m_countryId);
}
void DrawWidget::RetryToDownloadCountry(storage::TCountryId const & countryId)
{
// TODO @bykoianko
}
void DrawWidget::PrepareShutdown()
{
}
void DrawWidget::UpdateAfterSettingsChanged()
{
m_framework.EnterForeground();
}
void DrawWidget::ShowAll()
{
m_framework.ShowAll();
}
void DrawWidget::ChoosePositionModeEnable()
{
m_framework.BlockTapEvents(true /* block */);
m_framework.EnableChoosePositionMode(true /* enable */, false /* enableBounds */,
false /* applyPosition */, m2::PointD() /* position */);
}
void DrawWidget::ChoosePositionModeDisable()
{
m_framework.EnableChoosePositionMode(false /* enable */, false /* enableBounds */,
false /* applyPosition */, m2::PointD() /* position */);
m_framework.BlockTapEvents(false /* block */);
}
void DrawWidget::initializeGL()
{
MapWidget::initializeGL();
m_framework.LoadBookmarks();
}
void DrawWidget::mousePressEvent(QMouseEvent * e)
{
QOpenGLWidget::mousePressEvent(e);
m2::PointD const pt = GetDevicePoint(e);
if (IsLeftButton(e))
{
if (IsShiftModifier(e))
SubmitRoutingPoint(pt);
else if (IsAltModifier(e))
SubmitFakeLocationPoint(pt);
else
m_framework.TouchEvent(GetTouchEvent(e, df::TouchEvent::TOUCH_DOWN));
}
else if (IsRightButton(e))
{
if (!m_selectionMode || IsCommandModifier(e))
{
ShowInfoPopup(e, pt);
}
else
{
m_rubberBandOrigin = e->pos();
if (m_rubberBand == nullptr)
m_rubberBand = new QRubberBand(QRubberBand::Rectangle, this);
m_rubberBand->setGeometry(QRect(m_rubberBandOrigin, QSize()));
m_rubberBand->show();
}
}
}
void DrawWidget::mouseMoveEvent(QMouseEvent * e)
{
QOpenGLWidget::mouseMoveEvent(e);
if (IsLeftButton(e) && !IsAltModifier(e))
m_framework.TouchEvent(GetTouchEvent(e, df::TouchEvent::TOUCH_MOVE));
if (m_selectionMode && m_rubberBand != nullptr && m_rubberBand->isVisible())
{
m_rubberBand->setGeometry(QRect(m_rubberBandOrigin, e->pos()).normalized());
}
}
void DrawWidget::mouseReleaseEvent(QMouseEvent * e)
{
QOpenGLWidget::mouseReleaseEvent(e);
if (IsLeftButton(e) && !IsAltModifier(e))
{
m_framework.TouchEvent(GetTouchEvent(e, df::TouchEvent::TOUCH_UP));
}
else if (m_selectionMode && IsRightButton(e) && m_rubberBand != nullptr &&
m_rubberBand->isVisible())
{
QPoint const lt = m_rubberBand->geometry().topLeft();
QPoint const rb = m_rubberBand->geometry().bottomRight();
m2::RectD rect;
rect.Add(m_framework.PtoG(m2::PointD(L2D(lt.x()), L2D(lt.y()))));
rect.Add(m_framework.PtoG(m2::PointD(L2D(rb.x()), L2D(rb.y()))));
m_framework.VisualizeRoadsInRect(rect);
m_rubberBand->hide();
}
}
void DrawWidget::keyPressEvent(QKeyEvent * e)
{
TBase::keyPressEvent(e);
if (IsLeftButton(QGuiApplication::mouseButtons()) &&
e->key() == Qt::Key_Control)
{
df::TouchEvent event;
event.SetTouchType(df::TouchEvent::TOUCH_DOWN);
df::Touch touch;
touch.m_id = 0;
touch.m_location = m2::PointD(L2D(QCursor::pos().x()), L2D(QCursor::pos().y()));
event.SetFirstTouch(touch);
event.SetSecondTouch(GetSymmetrical(touch));
m_framework.TouchEvent(event);
}
}
void DrawWidget::keyReleaseEvent(QKeyEvent * e)
{
TBase::keyReleaseEvent(e);
if (IsLeftButton(QGuiApplication::mouseButtons()) &&
e->key() == Qt::Key_Control)
{
df::TouchEvent event;
event.SetTouchType(df::TouchEvent::TOUCH_UP);
df::Touch touch;
touch.m_id = 0;
touch.m_location = m2::PointD(L2D(QCursor::pos().x()), L2D(QCursor::pos().y()));
event.SetFirstTouch(touch);
event.SetSecondTouch(GetSymmetrical(touch));
m_framework.TouchEvent(event);
}
else if (e->key() == Qt::Key_Alt)
m_emulatingLocation = false;
}
bool DrawWidget::Search(search::EverywhereSearchParams const & params)
{
return m_framework.SearchEverywhere(params);
}
string DrawWidget::GetDistance(search::Result const & res) const
{
string dist;
double lat, lon;
if (m_framework.GetCurrentPosition(lat, lon))
{
double dummy;
(void) m_framework.GetDistanceAndAzimut(res.GetFeatureCenter(), lat, lon, -1.0, dist, dummy);
}
return dist;
}
void DrawWidget::ShowSearchResult(search::Result const & res)
{
m_framework.ShowSearchResult(res);
}
void DrawWidget::CreateFeature()
{
auto cats = m_framework.GetEditorCategories();
CreateFeatureDialog dlg(this, cats);
if (dlg.exec() == QDialog::Accepted)
{
osm::EditableMapObject emo;
if (m_framework.CreateMapObject(m_framework.GetViewportCenter(), dlg.GetSelectedType(), emo))
{
EditorDialog dlg(this, emo);
int const result = dlg.exec();
if (result == QDialog::Accepted)
m_framework.SaveEditedMapObject(emo);
}
else
{
LOG(LWARNING, ("Error creating new map object."));
}
}
}
void DrawWidget::OnLocationUpdate(location::GpsInfo const & info)
{
if (!m_emulatingLocation)
m_framework.OnLocationUpdate(info);
}
void DrawWidget::SetMapStyle(MapStyle mapStyle)
{
m_framework.SetMapStyle(mapStyle);
}
void DrawWidget::SubmitFakeLocationPoint(m2::PointD const & pt)
{
m_emulatingLocation = true;
m2::PointD const point = m_framework.PtoG(pt);
location::GpsInfo info;
info.m_latitude = MercatorBounds::YToLat(point.y);
info.m_longitude = MercatorBounds::XToLon(point.x);
info.m_horizontalAccuracy = 10;
info.m_timestamp = QDateTime::currentMSecsSinceEpoch() / 1000.0;
m_framework.OnLocationUpdate(info);
if (m_framework.GetRoutingManager().IsRoutingActive())
{
location::FollowingInfo loc;
m_framework.GetRoutingManager().GetRouteFollowingInfo(loc);
LOG(LDEBUG, ("Distance:", loc.m_distToTarget, loc.m_targetUnitsSuffix, "Time:", loc.m_time,
"Turn:", routing::turns::GetTurnString(loc.m_turn), "(", loc.m_distToTurn, loc.m_turnUnitsSuffix,
") Roundabout exit number:", loc.m_exitNum));
}
}
void DrawWidget::SubmitRoutingPoint(m2::PointD const & pt)
{
auto & routingManager = m_framework.GetRoutingManager();
if (routingManager.IsRoutingActive())
routingManager.CloseRouting();
else
routingManager.BuildRoute(m_framework.PtoG(pt), 0 /* timeoutSec */);
}
void DrawWidget::ShowPlacePage(place_page::Info const & info)
{
search::AddressInfo address;
if (info.IsFeature())
address = m_framework.GetFeatureAddressInfo(info.GetID());
else
address = m_framework.GetAddressInfoAtPoint(info.GetMercator());
PlacePageDialog dlg(this, info, address);
if (dlg.exec() == QDialog::Accepted)
{
osm::EditableMapObject emo;
if (m_framework.GetEditableMapObject(info.GetID(), emo))
{
EditorDialog dlg(this, emo);
int const result = dlg.exec();
if (result == QDialog::Accepted)
{
m_framework.SaveEditedMapObject(emo);
m_framework.UpdatePlacePageInfoForCurrentSelection();
}
else if (result == QDialogButtonBox::DestructiveRole)
{
m_framework.DeleteFeature(info.GetID());
}
}
else
{
LOG(LERROR, ("Error while trying to edit feature."));
}
}
m_framework.DeactivateMapSelection(false);
}
void DrawWidget::ShowInfoPopup(QMouseEvent * e, m2::PointD const & pt)
{
// show feature types
QMenu menu;
auto const addStringFn = [&menu](string const & s)
{
menu.addAction(QString::fromUtf8(s.c_str()));
};
m_framework.ForEachFeatureAtPoint([&](FeatureType & ft)
{
search::AddressInfo const info = m_framework.GetFeatureAddressInfo(ft);
string concat;
for (auto const & type : info.m_types)
concat += type + " ";
addStringFn(concat);
if (!info.m_name.empty())
addStringFn(info.m_name);
string const addr = info.FormatAddress();
if (!addr.empty())
addStringFn(addr);
menu.addSeparator();
}, m_framework.PtoG(pt));
menu.exec(e->pos());
}
void DrawWidget::SetRouter(routing::RouterType routerType)
{
m_framework.GetRoutingManager().SetRouter(routerType);
}
void DrawWidget::SetSelectionMode(bool mode) { m_selectionMode = mode; }
// static
void DrawWidget::SetDefaultSurfaceFormat(bool apiOpenGLES3)
{
QSurfaceFormat fmt;
fmt.setAlphaBufferSize(8);
fmt.setBlueBufferSize(8);
fmt.setGreenBufferSize(8);
fmt.setRedBufferSize(8);
fmt.setStencilBufferSize(0);
fmt.setSamples(0);
fmt.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
fmt.setSwapInterval(1);
fmt.setDepthBufferSize(16);
if (apiOpenGLES3)
{
fmt.setProfile(QSurfaceFormat::CoreProfile);
fmt.setVersion(3, 2);
}
else
{
fmt.setProfile(QSurfaceFormat::CompatibilityProfile);
fmt.setVersion(2, 1);
}
//fmt.setOption(QSurfaceFormat::DebugContext);
QSurfaceFormat::setDefaultFormat(fmt);
}
} // namespace qt
<|endoftext|> |
<commit_before><commit_msg>Fix Windows build. I forgot to update the class name for Windows for in process plugins. This didn't get caught because the Windows never linked on this patch for unrelated problems.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <objbase.h>
#endif
#include <algorithm>
#include "chrome/renderer/render_thread.h"
#include "base/shared_memory.h"
#include "chrome/common/chrome_plugin_lib.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/plugin/npobject_util.h"
// TODO(port)
#if defined(OS_WIN)
#include "chrome/plugin/plugin_channel.h"
#else
#include <vector>
#include "base/scoped_handle.h"
#include "chrome/plugin/plugin_channel_base.h"
#include "webkit/glue/weburlrequest.h"
#endif
#include "chrome/renderer/net/render_dns_master.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_view.h"
#include "chrome/renderer/renderer_webkitclient_impl.h"
#include "chrome/renderer/user_script_slave.h"
#include "chrome/renderer/visitedlink_slave.h"
#include "webkit/glue/cache_manager.h"
#include "WebKit.h"
#include "WebString.h"
static const unsigned int kCacheStatsDelayMS = 2000 /* milliseconds */;
// V8 needs a 1MB stack size.
static const size_t kStackSize = 1024 * 1024;
//-----------------------------------------------------------------------------
// Methods below are only called on the owner's thread:
// When we run plugins in process, we actually run them on the render thread,
// which means that we need to make the render thread pump UI events.
RenderThread::RenderThread()
: ChildThread(
base::Thread::Options(RenderProcess::InProcessPlugins() ?
MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT, kStackSize)) {
}
RenderThread::RenderThread(const std::wstring& channel_name)
: ChildThread(
base::Thread::Options(RenderProcess::InProcessPlugins() ?
MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT, kStackSize)) {
SetChannelName(channel_name);
}
RenderThread::~RenderThread() {
}
RenderThread* RenderThread::current() {
DCHECK(!IsPluginProcess());
return static_cast<RenderThread*>(ChildThread::current());
}
void RenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
channel()->AddFilter(filter);
}
void RenderThread::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
channel()->RemoveFilter(filter);
}
void RenderThread::Resolve(const char* name, size_t length) {
return dns_master_->Resolve(name, length);
}
void RenderThread::SendHistograms() {
return histogram_snapshots_->SendHistograms();
}
void RenderThread::Init() {
// TODO(darin): Why do we need COM here? This is probably bogus.
#if defined(OS_WIN)
// The renderer thread should wind-up COM.
CoInitialize(0);
#endif
ChildThread::Init();
notification_service_.reset(new NotificationService);
cache_stats_factory_.reset(
new ScopedRunnableMethodFactory<RenderThread>(this));
visited_link_slave_.reset(new VisitedLinkSlave());
user_script_slave_.reset(new UserScriptSlave());
dns_master_.reset(new RenderDnsMaster());
histogram_snapshots_.reset(new RendererHistogramSnapshots());
}
void RenderThread::CleanUp() {
// Shutdown in reverse of the initialization order.
histogram_snapshots_.reset();
dns_master_.reset();
user_script_slave_.reset();
visited_link_slave_.reset();
if (webkit_client_.get()) {
WebKit::shutdown();
webkit_client_.reset();
}
notification_service_.reset();
ChildThread::CleanUp();
// TODO(port)
#if defined(OS_WIN)
// Clean up plugin channels before this thread goes away.
PluginChannelBase::CleanupChannels();
#endif
#if defined(OS_WIN)
CoUninitialize();
#endif
}
void RenderThread::OnUpdateVisitedLinks(base::SharedMemoryHandle table) {
DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle";
visited_link_slave_->Init(table);
}
void RenderThread::OnUpdateUserScripts(
base::SharedMemoryHandle scripts) {
DCHECK(base::SharedMemory::IsHandleValid(scripts)) << "Bad scripts handle";
user_script_slave_->UpdateScripts(scripts);
}
void RenderThread::OnControlMessageReceived(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(RenderThread, msg)
IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_NewTable, OnUpdateVisitedLinks)
IPC_MESSAGE_HANDLER(ViewMsg_SetNextPageID, OnSetNextPageID)
// TODO(port): removed from render_messages_internal.h;
// is there a new non-windows message I should add here?
IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
IPC_MESSAGE_HANDLER(ViewMsg_SetCacheCapacities, OnSetCacheCapacities)
IPC_MESSAGE_HANDLER(ViewMsg_GetRendererHistograms,
OnGetRendererHistograms)
IPC_MESSAGE_HANDLER(ViewMsg_GetCacheResourceStats,
OnGetCacheResourceStats)
IPC_MESSAGE_HANDLER(ViewMsg_PluginMessage, OnPluginMessage)
IPC_MESSAGE_HANDLER(ViewMsg_UserScripts_NewScripts,
OnUpdateUserScripts)
IPC_END_MESSAGE_MAP()
}
void RenderThread::OnPluginMessage(const FilePath& plugin_path,
const std::vector<uint8>& data) {
if (!ChromePluginLib::IsInitialized()) {
return;
}
CHECK(ChromePluginLib::IsPluginThread());
ChromePluginLib *chrome_plugin = ChromePluginLib::Find(plugin_path);
if (chrome_plugin) {
void *data_ptr = const_cast<void*>(reinterpret_cast<const void*>(&data[0]));
uint32 data_len = static_cast<uint32>(data.size());
chrome_plugin->functions().on_message(data_ptr, data_len);
}
}
void RenderThread::OnSetNextPageID(int32 next_page_id) {
// This should only be called at process initialization time, so we shouldn't
// have to worry about thread-safety.
// TODO(port)
#if !defined(OS_LINUX)
RenderView::SetNextPageID(next_page_id);
#endif
}
void RenderThread::OnCreateNewView(gfx::NativeViewId parent_hwnd,
ModalDialogEvent modal_dialog_event,
const WebPreferences& webkit_prefs,
int32 view_id) {
EnsureWebKitInitialized();
// When bringing in render_view, also bring in webkit's glue and jsbindings.
base::WaitableEvent* waitable_event = new base::WaitableEvent(
#if defined(OS_WIN)
modal_dialog_event.event);
#else
true, false);
#endif
// TODO(darin): once we have a RenderThread per RenderView, this will need to
// change to assert that we are not creating more than one view.
RenderView::Create(
this, parent_hwnd, waitable_event, MSG_ROUTING_NONE, webkit_prefs,
new SharedRenderViewCounter(0), view_id);
}
void RenderThread::OnSetCacheCapacities(size_t min_dead_capacity,
size_t max_dead_capacity,
size_t capacity) {
EnsureWebKitInitialized();
#if defined(OS_WIN) || defined(OS_LINUX)
CacheManager::SetCapacities(min_dead_capacity, max_dead_capacity, capacity);
#else
// TODO(port)
NOTIMPLEMENTED();
#endif
}
void RenderThread::OnGetCacheResourceStats() {
EnsureWebKitInitialized();
#if defined(OS_WIN) || defined(OS_LINUX)
CacheManager::ResourceTypeStats stats;
CacheManager::GetResourceTypeStats(&stats);
Send(new ViewHostMsg_ResourceTypeStats(stats));
#else
// TODO(port)
NOTIMPLEMENTED();
#endif
}
void RenderThread::OnGetRendererHistograms() {
SendHistograms();
}
void RenderThread::InformHostOfCacheStats() {
EnsureWebKitInitialized();
#if defined(OS_WIN) || defined(OS_LINUX)
CacheManager::UsageStats stats;
CacheManager::GetUsageStats(&stats);
Send(new ViewHostMsg_UpdatedCacheStats(stats));
#else
// TODO(port)
NOTIMPLEMENTED();
#endif
}
void RenderThread::InformHostOfCacheStatsLater() {
// Rate limit informing the host of our cache stats.
if (!cache_stats_factory_->empty())
return;
MessageLoop::current()->PostDelayedTask(FROM_HERE,
cache_stats_factory_->NewRunnableMethod(
&RenderThread::InformHostOfCacheStats),
kCacheStatsDelayMS);
}
void RenderThread::EnsureWebKitInitialized() {
if (webkit_client_.get())
return;
webkit_client_.reset(new RendererWebKitClientImpl);
WebKit::initialize(webkit_client_.get());
WebKit::registerURLSchemeAsLocal(ASCIIToUTF16(chrome::kChromeUIScheme));
}
<commit_msg>Remove ifdefs around parts ported by all platforms. Review URL: http://codereview.chromium.org/39016<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "build/build_config.h"
#if defined(OS_WIN)
#include <windows.h>
#include <objbase.h>
#endif
#include <algorithm>
#include "chrome/renderer/render_thread.h"
#include "base/shared_memory.h"
#include "chrome/common/chrome_plugin_lib.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/url_constants.h"
#include "chrome/plugin/npobject_util.h"
// TODO(port)
#if defined(OS_WIN)
#include "chrome/plugin/plugin_channel.h"
#else
#include <vector>
#include "base/scoped_handle.h"
#include "chrome/plugin/plugin_channel_base.h"
#include "webkit/glue/weburlrequest.h"
#endif
#include "chrome/renderer/net/render_dns_master.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_view.h"
#include "chrome/renderer/renderer_webkitclient_impl.h"
#include "chrome/renderer/user_script_slave.h"
#include "chrome/renderer/visitedlink_slave.h"
#include "webkit/glue/cache_manager.h"
#include "WebKit.h"
#include "WebString.h"
static const unsigned int kCacheStatsDelayMS = 2000 /* milliseconds */;
// V8 needs a 1MB stack size.
static const size_t kStackSize = 1024 * 1024;
//-----------------------------------------------------------------------------
// Methods below are only called on the owner's thread:
// When we run plugins in process, we actually run them on the render thread,
// which means that we need to make the render thread pump UI events.
RenderThread::RenderThread()
: ChildThread(
base::Thread::Options(RenderProcess::InProcessPlugins() ?
MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT, kStackSize)) {
}
RenderThread::RenderThread(const std::wstring& channel_name)
: ChildThread(
base::Thread::Options(RenderProcess::InProcessPlugins() ?
MessageLoop::TYPE_UI : MessageLoop::TYPE_DEFAULT, kStackSize)) {
SetChannelName(channel_name);
}
RenderThread::~RenderThread() {
}
RenderThread* RenderThread::current() {
DCHECK(!IsPluginProcess());
return static_cast<RenderThread*>(ChildThread::current());
}
void RenderThread::AddFilter(IPC::ChannelProxy::MessageFilter* filter) {
channel()->AddFilter(filter);
}
void RenderThread::RemoveFilter(IPC::ChannelProxy::MessageFilter* filter) {
channel()->RemoveFilter(filter);
}
void RenderThread::Resolve(const char* name, size_t length) {
return dns_master_->Resolve(name, length);
}
void RenderThread::SendHistograms() {
return histogram_snapshots_->SendHistograms();
}
void RenderThread::Init() {
// TODO(darin): Why do we need COM here? This is probably bogus.
#if defined(OS_WIN)
// The renderer thread should wind-up COM.
CoInitialize(0);
#endif
ChildThread::Init();
notification_service_.reset(new NotificationService);
cache_stats_factory_.reset(
new ScopedRunnableMethodFactory<RenderThread>(this));
visited_link_slave_.reset(new VisitedLinkSlave());
user_script_slave_.reset(new UserScriptSlave());
dns_master_.reset(new RenderDnsMaster());
histogram_snapshots_.reset(new RendererHistogramSnapshots());
}
void RenderThread::CleanUp() {
// Shutdown in reverse of the initialization order.
histogram_snapshots_.reset();
dns_master_.reset();
user_script_slave_.reset();
visited_link_slave_.reset();
if (webkit_client_.get()) {
WebKit::shutdown();
webkit_client_.reset();
}
notification_service_.reset();
ChildThread::CleanUp();
// TODO(port)
#if defined(OS_WIN)
// Clean up plugin channels before this thread goes away.
PluginChannelBase::CleanupChannels();
#endif
#if defined(OS_WIN)
CoUninitialize();
#endif
}
void RenderThread::OnUpdateVisitedLinks(base::SharedMemoryHandle table) {
DCHECK(base::SharedMemory::IsHandleValid(table)) << "Bad table handle";
visited_link_slave_->Init(table);
}
void RenderThread::OnUpdateUserScripts(
base::SharedMemoryHandle scripts) {
DCHECK(base::SharedMemory::IsHandleValid(scripts)) << "Bad scripts handle";
user_script_slave_->UpdateScripts(scripts);
}
void RenderThread::OnControlMessageReceived(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(RenderThread, msg)
IPC_MESSAGE_HANDLER(ViewMsg_VisitedLink_NewTable, OnUpdateVisitedLinks)
IPC_MESSAGE_HANDLER(ViewMsg_SetNextPageID, OnSetNextPageID)
// TODO(port): removed from render_messages_internal.h;
// is there a new non-windows message I should add here?
IPC_MESSAGE_HANDLER(ViewMsg_New, OnCreateNewView)
IPC_MESSAGE_HANDLER(ViewMsg_SetCacheCapacities, OnSetCacheCapacities)
IPC_MESSAGE_HANDLER(ViewMsg_GetRendererHistograms,
OnGetRendererHistograms)
IPC_MESSAGE_HANDLER(ViewMsg_GetCacheResourceStats,
OnGetCacheResourceStats)
IPC_MESSAGE_HANDLER(ViewMsg_PluginMessage, OnPluginMessage)
IPC_MESSAGE_HANDLER(ViewMsg_UserScripts_NewScripts,
OnUpdateUserScripts)
IPC_END_MESSAGE_MAP()
}
void RenderThread::OnPluginMessage(const FilePath& plugin_path,
const std::vector<uint8>& data) {
if (!ChromePluginLib::IsInitialized()) {
return;
}
CHECK(ChromePluginLib::IsPluginThread());
ChromePluginLib *chrome_plugin = ChromePluginLib::Find(plugin_path);
if (chrome_plugin) {
void *data_ptr = const_cast<void*>(reinterpret_cast<const void*>(&data[0]));
uint32 data_len = static_cast<uint32>(data.size());
chrome_plugin->functions().on_message(data_ptr, data_len);
}
}
void RenderThread::OnSetNextPageID(int32 next_page_id) {
// This should only be called at process initialization time, so we shouldn't
// have to worry about thread-safety.
// TODO(port)
#if !defined(OS_LINUX)
RenderView::SetNextPageID(next_page_id);
#endif
}
void RenderThread::OnCreateNewView(gfx::NativeViewId parent_hwnd,
ModalDialogEvent modal_dialog_event,
const WebPreferences& webkit_prefs,
int32 view_id) {
EnsureWebKitInitialized();
// When bringing in render_view, also bring in webkit's glue and jsbindings.
base::WaitableEvent* waitable_event = new base::WaitableEvent(
#if defined(OS_WIN)
modal_dialog_event.event);
#else
true, false);
#endif
// TODO(darin): once we have a RenderThread per RenderView, this will need to
// change to assert that we are not creating more than one view.
RenderView::Create(
this, parent_hwnd, waitable_event, MSG_ROUTING_NONE, webkit_prefs,
new SharedRenderViewCounter(0), view_id);
}
void RenderThread::OnSetCacheCapacities(size_t min_dead_capacity,
size_t max_dead_capacity,
size_t capacity) {
EnsureWebKitInitialized();
CacheManager::SetCapacities(min_dead_capacity, max_dead_capacity, capacity);
}
void RenderThread::OnGetCacheResourceStats() {
EnsureWebKitInitialized();
CacheManager::ResourceTypeStats stats;
CacheManager::GetResourceTypeStats(&stats);
Send(new ViewHostMsg_ResourceTypeStats(stats));
}
void RenderThread::OnGetRendererHistograms() {
SendHistograms();
}
void RenderThread::InformHostOfCacheStats() {
EnsureWebKitInitialized();
CacheManager::UsageStats stats;
CacheManager::GetUsageStats(&stats);
Send(new ViewHostMsg_UpdatedCacheStats(stats));
}
void RenderThread::InformHostOfCacheStatsLater() {
// Rate limit informing the host of our cache stats.
if (!cache_stats_factory_->empty())
return;
MessageLoop::current()->PostDelayedTask(FROM_HERE,
cache_stats_factory_->NewRunnableMethod(
&RenderThread::InformHostOfCacheStats),
kCacheStatsDelayMS);
}
void RenderThread::EnsureWebKitInitialized() {
if (webkit_client_.get())
return;
webkit_client_.reset(new RendererWebKitClientImpl);
WebKit::initialize(webkit_client_.get());
WebKit::registerURLSchemeAsLocal(ASCIIToUTF16(chrome::kChromeUIScheme));
}
<|endoftext|> |
<commit_before><commit_msg>Translate comments<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <time.h> // incluye "time"
#include <unistd.h> // incluye "usleep"
#include <stdlib.h> // incluye "rand" y "srand"
#include <mpi.h>
using namespace std;
void Filosofo( int id, int nprocesos);
void Tenedor ( int id, int nprocesos);
// ---------------------------------------------------------------------
int main (int argc, char* argv[])
{
int rank, size;
srand(time(0));
MPI_Init (&argc, &argv);
MPI_Comm_rank (MPI_COMM_WORLD, &rank);
MPI_Comm_size (MPI_COMM_WORLD, &size);
if (size != 10)
{
if (rank == 0)
cout << "El numero de procesos debe ser 10" << endl << flush ;
MPI_Finalize( );
return 0;
}
if ((rank % 2) == 0)
Filosofo(rank, size); // Los pares son Filosofos
else
Tenedor(rank, size); // Los impares son Tenedores
MPI_Finalize();
return 0;
}
// ---------------------------------------------------------------------
void Filosofo (int id, int nprocesos)
{
int izq = (id + 1) % nprocesos; // Tenedor izquierdo
int der = ((id+nprocesos) - 1) % nprocesos; // Tenedor derecho
int peticion = 1; // Valor que se envía para pedir el tenedor
int depositar = 0; // Valor que se envía para depositar el tenedor
while (true)
{
// Para evitar el interbloqueo se propone que un determinado filósofo empiece
// cogiendo el tenedor derecho antes que el izquierdo
if (id == 0) {
// Solicita tenedor derecho
cout << "Filosofo "<< id << " solicita tenedor derecho " << der << endl << flush;
MPI_Ssend(&peticion, 1, MPI_INT, der, 0, MPI_COMM_WORLD);
// Solicita tenedor izquierdo
cout << "Filosofo " << id << " solicita tenedor izquierdo " << izq << endl << flush;
MPI_Ssend(&peticion, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);
}
else {
// Solicita tenedor izquierdo
cout << "Filosofo " << id << " solicita tenedor izquierdo " << izq << endl << flush;
MPI_Ssend(&peticion, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);
// Solicita tenedor derecho
cout << "Filosofo "<< id << " solicita tenedor derecho " << der << endl << flush;
MPI_Ssend(&peticion, 1, MPI_INT, der, 0, MPI_COMM_WORLD);
}
cout << "Filosofo " << id << " COMIENDO..." << endl << flush;
sleep((rand() % 3) + 1);
// Suelta el tenedor izquierdo
cout << "Filosofo " << id << " suelta tenedor izquierdo " << izq << endl << flush;
MPI_Ssend(&depositar, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);
// Suelta el tenedor derecho
cout <<"Filosofo "<<id<< " suelta tenedor derecho " << der << endl << flush;
MPI_Ssend(&depositar, 1, MPI_INT, der, 0, MPI_COMM_WORLD);
// Piensa (espera bloqueada aleatorio del proceso)
cout << "Filosofo " << id << " PENSANDO..." << endl << flush;
// espera bloqueado durante un intervalo de tiempo aleatorio
// (entre una décima de segundo y un segundo)
usleep (1000U * (100U + (rand() % 900U)));
}
}
// ---------------------------------------------------------------------
void Tenedor(int id, int nprocesos)
{
int buf;
MPI_Status status;
int Filo;
while (true)
{
// Espera un peticion desde cualquier filosofo vecino
MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
// Recibe la peticion del filosofo
Filo = status.MPI_SOURCE;
MPI_Recv(&buf, 1, MPI_INT, Filo, 0, MPI_COMM_WORLD, &status);
cout << "Tenedor " << id << " recibe peticion de " << Filo << endl << flush;
// Espera a que el filosofo suelte el tenedor...
MPI_Recv(&buf, 1, MPI_INT, Filo, 0, MPI_COMM_WORLD, &status);
cout << "Tenedor " << id << " recibe liberacion de " << Filo << endl << flush;
}
}
<commit_msg>Updated<commit_after>/*****************************************************************************/
// Prácticas de Sistemas Concurrentes y Distribuidos
// Por David Vargas Carrillo, 2016
/*****************************************************************************/
#include <iostream>
#include <time.h> // incluye "time"
#include <unistd.h> // incluye "usleep"
#include <stdlib.h> // incluye "rand" y "srand"
#include <mpi.h>
using namespace std;
void Filosofo( int id, int nprocesos);
void Tenedor ( int id, int nprocesos);
// ---------------------------------------------------------------------
int main (int argc, char* argv[])
{
int rank, size;
srand(time(0));
MPI_Init (&argc, &argv);
MPI_Comm_rank (MPI_COMM_WORLD, &rank);
MPI_Comm_size (MPI_COMM_WORLD, &size);
if (size != 10)
{
if (rank == 0)
cout << "El numero de procesos debe ser 10" << endl << flush ;
MPI_Finalize( );
return 0;
}
if ((rank % 2) == 0)
Filosofo(rank, size); // Los pares son Filosofos
else
Tenedor(rank, size); // Los impares son Tenedores
MPI_Finalize();
return 0;
}
// ---------------------------------------------------------------------
void Filosofo (int id, int nprocesos)
{
int izq = (id + 1) % nprocesos; // Tenedor izquierdo
int der = ((id+nprocesos) - 1) % nprocesos; // Tenedor derecho
int peticion = 1; // Valor que se envía para pedir el tenedor
int depositar = 0; // Valor que se envía para depositar el tenedor
while (true)
{
// Para evitar el interbloqueo se propone que un determinado filósofo empiece
// cogiendo el tenedor derecho antes que el izquierdo
if (id == 0) {
// Solicita tenedor derecho
cout << "Filosofo "<< id << " solicita tenedor derecho " << der << endl << flush;
MPI_Ssend(&peticion, 1, MPI_INT, der, 0, MPI_COMM_WORLD);
// Solicita tenedor izquierdo
cout << "Filosofo " << id << " solicita tenedor izquierdo " << izq << endl << flush;
MPI_Ssend(&peticion, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);
}
else {
// Solicita tenedor izquierdo
cout << "Filosofo " << id << " solicita tenedor izquierdo " << izq << endl << flush;
MPI_Ssend(&peticion, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);
// Solicita tenedor derecho
cout << "Filosofo "<< id << " solicita tenedor derecho " << der << endl << flush;
MPI_Ssend(&peticion, 1, MPI_INT, der, 0, MPI_COMM_WORLD);
}
cout << "Filosofo " << id << " COMIENDO..." << endl << flush;
sleep((rand() % 3) + 1);
// Suelta el tenedor izquierdo
cout << "Filosofo " << id << " suelta tenedor izquierdo " << izq << endl << flush;
MPI_Ssend(&depositar, 1, MPI_INT, izq, 0, MPI_COMM_WORLD);
// Suelta el tenedor derecho
cout <<"Filosofo "<<id<< " suelta tenedor derecho " << der << endl << flush;
MPI_Ssend(&depositar, 1, MPI_INT, der, 0, MPI_COMM_WORLD);
// Piensa (espera bloqueada aleatorio del proceso)
cout << "Filosofo " << id << " PENSANDO..." << endl << flush;
// espera bloqueado durante un intervalo de tiempo aleatorio
// (entre una décima de segundo y un segundo)
usleep (1000U * (100U + (rand() % 900U)));
}
}
// ---------------------------------------------------------------------
void Tenedor(int id, int nprocesos)
{
int buf;
MPI_Status status;
int Filo;
while (true)
{
// Espera un peticion desde cualquier filosofo vecino
MPI_Probe(MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &status);
// Recibe la peticion del filosofo
Filo = status.MPI_SOURCE;
MPI_Recv(&buf, 1, MPI_INT, Filo, 0, MPI_COMM_WORLD, &status);
cout << "Tenedor " << id << " recibe peticion de " << Filo << endl << flush;
// Espera a que el filosofo suelte el tenedor...
MPI_Recv(&buf, 1, MPI_INT, Filo, 0, MPI_COMM_WORLD, &status);
cout << "Tenedor " << id << " recibe liberacion de " << Filo << endl << flush;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2002-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* XSEC
*
* XSECError := General include file for handling errors
*
* Author(s): Berin Lautenbach
*
* $Id$
*
*/
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/framework/XSECException.hpp>
/**
* @defgroup pubsig Main Signature API
* This section describes the main classes and interfaces necessary for
* programming with the XML-Security-C library.
* @{
*/
/**
* \brief Error strings
*
* An array that can be used to obtain an error string associated with
* an exception number.
*/
extern const char * XSECExceptionStrings [];
/** @} */
#if defined (_WIN32) && defined (_DEBUG) && defined (_XSEC_DO_MEMDEBUG_OLD)
# define XSECnew( a, b ) \
try {
if (( a = DEBUG_NEW b ) == NULL) { \
throw XSECException (XSECException::MemoryAllocationFail); \
}
} \
catch (XSECException &e) \
{\
throw XSECException (XSECException::InternalError, e.getMsg()); \
} \
catch (...) { \
throw XSECException (XSECException::MemoryAllocationFail); \
}
#else
# define XSECnew(a, b) \
try {\
if ((a = new b) == NULL) { \
throw XSECException (XSECException::MemoryAllocationFail); \
} \
} \
catch (XSECException &e) \
{\
throw XSECException (XSECException::InternalError, e.getMsg()); \
} \
catch (...) { \
throw XSECException (XSECException::MemoryAllocationFail); \
}
#endif
<commit_msg>Fix minor bug in old version of macro - it would never have worked without line escapes on *all* the lines<commit_after>/*
* Copyright 2002-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* XSEC
*
* XSECError := General include file for handling errors
*
* Author(s): Berin Lautenbach
*
* $Id$
*
*/
#include <xsec/framework/XSECDefs.hpp>
#include <xsec/framework/XSECException.hpp>
/**
* @defgroup pubsig Main Signature API
* This section describes the main classes and interfaces necessary for
* programming with the XML-Security-C library.
* @{
*/
/**
* \brief Error strings
*
* An array that can be used to obtain an error string associated with
* an exception number.
*/
extern const char * XSECExceptionStrings [];
/** @} */
#if defined (_WIN32) && defined (_DEBUG) && defined (_XSEC_DO_MEMDEBUG_OLD)
# define XSECnew( a, b ) \
try {\
if (( a = DEBUG_NEW b ) == NULL) { \
throw XSECException (XSECException::MemoryAllocationFail); \
}\
} \
catch (XSECException &e) \
{\
throw XSECException (XSECException::InternalError, e.getMsg()); \
} \
catch (...) { \
throw XSECException (XSECException::MemoryAllocationFail); \
}
#else
# define XSECnew(a, b) \
try {\
if ((a = new b) == NULL) { \
throw XSECException (XSECException::MemoryAllocationFail); \
} \
} \
catch (XSECException &e) \
{\
throw XSECException (XSECException::InternalError, e.getMsg()); \
} \
catch (...) { \
throw XSECException (XSECException::MemoryAllocationFail); \
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include "reliable_udp.hh"
#define GENERAL_PACKAGE (128)
namespace rudp {
struct message {
struct message* next;
uint8_t* buffer;
int sz;
int cap;
int id;
int tick;
};
struct message_queue {
struct message* head;
struct message* tail;
};
struct array {
int cap;
int n;
int* a;
};
struct rudp {
struct message_queue send_queue; // user packages will send
struct message_queue recv_queue; // the packages received
struct message_queue send_history; // user packages already send
struct rudp_package* send_package; // returns by rudp_update
struct message* free_list; // recycle message
struct array send_argain;
int corrupt;
int current_tick;
int last_send_tick;
int last_expired_tick;
int send_id;
int recv_id_min;
int recv_id_max;
int send_delay;
int expired;
};
static void clear_outpackage(struct rudp* u) {
struct rudp_package* package = u->send_package;
while (package) {
struct rudp_package* next_package = package->next;
free(package);
package = next_package;
}
u->send_package = nullptr;
}
static void free_message_list(struct message* m) {
while (m) {
struct message* next_message = m->next;
free(m);
m = next_message;
}
}
struct rudp* rudp_new(int send_delay, int expired_time) {
struct rudp* u = malloc(sizeof(*u));
memset(u, 0, sizeof(*u));
u->send_delay = send_delay;
u->expired = expired_time;
return u;
}
void rudp_delete(struct rudp* u) {
free_message_list(u->send_queue.head);
free_message_list(u->recv_queue.head);
free_message_list(u->send_history.head);
free_message_list(u->free_list);
clear_outpackage(u);
free(u->send_argain.a);
free(u);
}
}
<commit_msg>:construction: chore(rudp): updated the implementation of rudp<commit_after>// Copyright (c) 2020 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include <cassert>
#include <cstdlib>
#include <cstring>
#include <cstdint>
#include "reliable_udp.hh"
#define GENERAL_PACKAGE (128)
namespace rudp {
struct message {
struct message* next;
uint8_t* buffer;
int sz;
int cap;
int id;
int tick;
};
struct message_queue {
struct message* head;
struct message* tail;
};
static void queue_push(struct message_queue* mq, struct message* m) {
if (mq->head == nullptr) {
mq->head = mq->tail = m;
}
else {
mq->tail->next = m;
mq->tail = m;
}
}
static struct message* queue_pop(struct message_queue* mq, int id) {
if (mq->head == nullptr)
return nullptr;
struct message* m = mq->head;
if (m->id != id)
return nullptr;
mq->head = m->next;
m->next = nullptr;
if (mq->head == nullptr)
mq->tail = nullptr;
return m;
}
struct array {
int cap;
int n;
int* a;
};
static void array_insert(struct array* a, int id) {
int i{};
for (; i < a->n; ++i) {
if (a->a[i] == id)
return;
if (a->a[i] > id)
break;
}
// insert id before index [i]
if (a->n >= a->cap) {
if (a->cap == 0)
a->cap = 16;
else
a->cap *= 2;
a->a = (int*)realloc(a->a, sizeof(int) * a->cap);
}
for (int j = a->n; j > i; --j)
a->a[j] = a->a[j - 1];
a->a[i] = id;
++a->n;
}
struct rudp {
struct message_queue send_queue; // user packages will send
struct message_queue recv_queue; // the packages received
struct message_queue send_history; // user packages already send
struct rudp_package* send_package; // returns by rudp_update
struct message* free_list; // recycle message
struct array send_argain;
int corrupt;
int current_tick;
int last_send_tick;
int last_expired_tick;
int send_id;
int recv_id_min;
int recv_id_max;
int send_delay;
int expired;
};
static void clear_outpackage(struct rudp* u) {
struct rudp_package* package = u->send_package;
while (package) {
struct rudp_package* next_package = package->next;
free(package);
package = next_package;
}
u->send_package = nullptr;
}
static void free_message_list(struct message* m) {
while (m) {
struct message* next_message = m->next;
free(m);
m = next_message;
}
}
static struct message* new_message(struct rudp* u, const uint8_t* buffer, int sz) {
struct message* m = u->free_list;
if (m) {
u->free_list = m->next;
if (m->cap < sz) {
free(m);
m = nullptr;
}
}
if (m == nullptr) {
int cap = sz;
if (cap < GENERAL_PACKAGE)
cap = GENERAL_PACKAGE;
m = (struct message*)malloc(sizeof(*m) + cap);
if (m)
m->cap = cap;
}
if (m == nullptr)
return m;
m->sz = sz;
m->buffer = (uint8_t*)(m + 1);
if (sz > 0 && buffer)
memcpy(m->buffer, buffer, sz);
m->tick = 0;
m->id = 0;
m->next = nullptr;
return m;
}
static void delete_message(struct rudp* u, struct message* m) {
m->next = u->free_list;
u->free_list = m;
}
static void clear_send_expired(struct rudp* u, int tick) {
struct message* m = u->send_history.head;
struct message* last = nullptr;
while (m) {
if (m->tick >= tick)
break;
last = m;
m = m->next;
}
if (last) {
last->next = u->free_list;
u->free_list = u->send_history.head;
}
u->send_history.head = m;
if (m == nullptr)
u->send_history.tail = nullptr;
}
// rudp export methods
struct rudp* rudp_new(int send_delay, int expired_time) {
struct rudp* u = (struct rudp*)malloc(sizeof(*u));
if (u) {
memset(u, 0, sizeof(*u));
u->send_delay = send_delay;
u->expired = expired_time;
}
return u;
}
void rudp_delete(struct rudp* u) {
free_message_list(u->send_queue.head);
free_message_list(u->recv_queue.head);
free_message_list(u->send_history.head);
free_message_list(u->free_list);
clear_outpackage(u);
free(u->send_argain.a);
free(u);
}
void rudp_send(struct rudp* u, const char* buffer, int sz) {
assert(sz <= MAX_PACKAGE);
struct message* m = new_message(u, (const uint8_t*)buffer, sz);
m->id = u->send_id++;
m->tick = u->current_tick;
queue_push(&u->send_queue, m);
}
}
<|endoftext|> |
<commit_before>#pragma once
// `krbn::hid_grabber` can be used safely in a multi-threaded environment.
#include "boost_utility.hpp"
#include "dispatcher.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "thread_utility.hpp"
namespace krbn {
class hid_grabber final : public pqrs::dispatcher::dispatcher_client {
public:
struct signal2_combiner_call_while_grabbable {
typedef grabbable_state::state result_type;
template <typename input_iterator>
result_type operator()(input_iterator first_observer,
input_iterator last_observer) const {
result_type value = grabbable_state::state::grabbable;
for (;
first_observer != last_observer && value == grabbable_state::state::grabbable;
std::advance(first_observer, 1)) {
value = *first_observer;
}
return value;
}
};
// Signals
boost::signals2::signal<grabbable_state::state(void), signal2_combiner_call_while_grabbable> device_grabbing;
boost::signals2::signal<void(void)> device_grabbed;
boost::signals2::signal<void(void)> device_ungrabbed;
// Methods
hid_grabber(const hid_grabber&) = delete;
hid_grabber(std::weak_ptr<pqrs::dispatcher::dispatcher> weak_dispatcher,
std::weak_ptr<human_interface_device> weak_hid) : dispatcher_client(weak_dispatcher),
weak_hid_(weak_hid),
grabbed_(false) {
if (auto hid = weak_hid.lock()) {
// opened
{
auto c = hid->opened.connect([this] {
enqueue_to_dispatcher([this] {
if (auto hid = weak_hid_.lock()) {
grabbed_ = true;
device_grabbed();
hid->async_queue_start();
hid->async_schedule();
}
});
});
human_interface_device_connections_.push_back(c);
}
// open_failed
{
auto c = hid->open_failed.connect([this](auto&& error) {
enqueue_to_dispatcher([this, error] {
if (auto hid = weak_hid_.lock()) {
auto message = fmt::format("IOHIDDeviceOpen error: {0} ({1}) {2}",
iokit_utility::get_error_name(error),
error,
hid->get_name_for_log());
logger_unique_filter_.error(message);
}
});
});
human_interface_device_connections_.push_back(c);
}
// closed
{
auto c = hid->closed.connect([this] {
enqueue_to_dispatcher([this] {
if (auto hid = weak_hid_.lock()) {
device_ungrabbed();
}
});
});
human_interface_device_connections_.push_back(c);
}
// close_failed
{
auto c = hid->close_failed.connect([this](auto&& error) {
enqueue_to_dispatcher([this, error] {
if (auto hid = weak_hid_.lock()) {
auto message = fmt::format("IOHIDDeviceClose error: {0} ({1}) {2}",
iokit_utility::get_error_name(error),
error,
hid->get_name_for_log());
logger_unique_filter_.error(message);
device_ungrabbed();
}
});
});
human_interface_device_connections_.push_back(c);
}
}
}
virtual ~hid_grabber(void) {
detach_from_dispatcher([this] {
ungrab();
});
// Disconnect `human_interface_device_connections_`
if (auto hid = weak_hid_.lock()) {
hid->get_run_loop_thread()->enqueue(^{
human_interface_device_connections_.disconnect_all_connections();
});
} else {
human_interface_device_connections_.disconnect_all_connections();
}
human_interface_device_connections_.wait_disconnect_all_connections();
}
std::weak_ptr<human_interface_device> get_weak_hid(void) {
return weak_hid_;
}
grabbable_state::state make_grabbable_state(void) {
return device_grabbing();
}
void async_grab(void) {
enqueue_to_dispatcher([this] {
if (timer_) {
return;
}
logger_unique_filter_.reset();
timer_ = std::make_unique<thread_utility::timer>(
[](auto&& count) {
if (count == 0) {
return std::chrono::milliseconds(0);
} else {
return std::chrono::milliseconds(1000);
}
},
thread_utility::timer::mode::repeat,
[this] {
enqueue_to_dispatcher([this] {
if (!grabbed_) {
if (auto hid = weak_hid_.lock()) {
if (!hid->get_removed()) {
switch (make_grabbable_state()) {
case grabbable_state::state::grabbable:
hid->async_open(kIOHIDOptionsTypeSeizeDevice);
return;
case grabbable_state::state::none:
case grabbable_state::state::ungrabbable_temporarily:
case grabbable_state::state::device_error:
// Retry
return;
case grabbable_state::state::ungrabbable_permanently:
break;
}
}
}
}
timer_->cancel();
});
});
});
}
void async_ungrab(void) {
enqueue_to_dispatcher([this] {
ungrab();
});
}
private:
void ungrab(void) {
if (!timer_) {
return;
}
timer_->cancel();
timer_ = nullptr;
if (grabbed_) {
if (auto hid = weak_hid_.lock()) {
hid->async_unschedule();
hid->async_queue_stop();
hid->async_close();
}
grabbed_ = false;
}
}
std::weak_ptr<human_interface_device> weak_hid_;
boost_utility::signals2_connections human_interface_device_connections_;
bool grabbed_;
logger::unique_filter logger_unique_filter_;
std::unique_ptr<thread_utility::timer> timer_;
};
} // namespace krbn
<commit_msg>remove thread_utility::timer from hid_grabber<commit_after>#pragma once
// `krbn::hid_grabber` can be used safely in a multi-threaded environment.
#include "boost_utility.hpp"
#include "dispatcher.hpp"
#include "human_interface_device.hpp"
#include "logger.hpp"
#include "thread_utility.hpp"
namespace krbn {
class hid_grabber final : public pqrs::dispatcher::dispatcher_client {
public:
struct signal2_combiner_call_while_grabbable {
typedef grabbable_state::state result_type;
template <typename input_iterator>
result_type operator()(input_iterator first_observer,
input_iterator last_observer) const {
result_type value = grabbable_state::state::grabbable;
for (;
first_observer != last_observer && value == grabbable_state::state::grabbable;
std::advance(first_observer, 1)) {
value = *first_observer;
}
return value;
}
};
// Signals
boost::signals2::signal<grabbable_state::state(void), signal2_combiner_call_while_grabbable> device_grabbing;
boost::signals2::signal<void(void)> device_grabbed;
boost::signals2::signal<void(void)> device_ungrabbed;
// Methods
hid_grabber(const hid_grabber&) = delete;
hid_grabber(std::weak_ptr<pqrs::dispatcher::dispatcher> weak_dispatcher,
std::weak_ptr<human_interface_device> weak_hid) : dispatcher_client(weak_dispatcher),
weak_hid_(weak_hid),
enabled_(false),
grabbed_(false) {
if (auto hid = weak_hid.lock()) {
// opened
{
auto c = hid->opened.connect([this] {
enqueue_to_dispatcher([this] {
if (auto hid = weak_hid_.lock()) {
grabbed_ = true;
device_grabbed();
hid->async_queue_start();
hid->async_schedule();
}
});
});
human_interface_device_connections_.push_back(c);
}
// open_failed
{
auto c = hid->open_failed.connect([this](auto&& error) {
enqueue_to_dispatcher([this, error] {
if (auto hid = weak_hid_.lock()) {
auto message = fmt::format("IOHIDDeviceOpen error: {0} ({1}) {2}",
iokit_utility::get_error_name(error),
error,
hid->get_name_for_log());
logger_unique_filter_.error(message);
}
});
});
human_interface_device_connections_.push_back(c);
}
// closed
{
auto c = hid->closed.connect([this] {
enqueue_to_dispatcher([this] {
if (auto hid = weak_hid_.lock()) {
device_ungrabbed();
}
});
});
human_interface_device_connections_.push_back(c);
}
// close_failed
{
auto c = hid->close_failed.connect([this](auto&& error) {
enqueue_to_dispatcher([this, error] {
if (auto hid = weak_hid_.lock()) {
auto message = fmt::format("IOHIDDeviceClose error: {0} ({1}) {2}",
iokit_utility::get_error_name(error),
error,
hid->get_name_for_log());
logger_unique_filter_.error(message);
device_ungrabbed();
}
});
});
human_interface_device_connections_.push_back(c);
}
}
}
virtual ~hid_grabber(void) {
detach_from_dispatcher([this] {
ungrab();
});
// Disconnect `human_interface_device_connections_`
if (auto hid = weak_hid_.lock()) {
hid->get_run_loop_thread()->enqueue(^{
human_interface_device_connections_.disconnect_all_connections();
});
} else {
human_interface_device_connections_.disconnect_all_connections();
}
human_interface_device_connections_.wait_disconnect_all_connections();
}
std::weak_ptr<human_interface_device> get_weak_hid(void) {
return weak_hid_;
}
grabbable_state::state make_grabbable_state(void) {
return device_grabbing();
}
void async_grab(void) {
enqueue_to_dispatcher([this] {
enabled_ = true;
logger_unique_filter_.reset();
grab();
});
}
void async_ungrab(void) {
enqueue_to_dispatcher([this] {
enabled_ = false;
ungrab();
});
}
private:
void grab(void) {
if (!enabled_) {
return;
}
if (grabbed_) {
return;
}
if (!grabbed_) {
if (auto hid = weak_hid_.lock()) {
if (!hid->get_removed()) {
switch (make_grabbable_state()) {
case grabbable_state::state::grabbable:
hid->async_open(kIOHIDOptionsTypeSeizeDevice);
break;
case grabbable_state::state::none:
case grabbable_state::state::ungrabbable_temporarily:
case grabbable_state::state::device_error:
// Retry
break;
case grabbable_state::state::ungrabbable_permanently:
return;
}
}
}
}
enqueue_to_dispatcher(
[this] {
grab();
},
when_now() + std::chrono::milliseconds(1000));
}
void ungrab(void) {
if (grabbed_) {
if (auto hid = weak_hid_.lock()) {
hid->async_unschedule();
hid->async_queue_stop();
hid->async_close();
}
grabbed_ = false;
}
}
std::weak_ptr<human_interface_device> weak_hid_;
boost_utility::signals2_connections human_interface_device_connections_;
bool enabled_;
bool grabbed_;
logger::unique_filter logger_unique_filter_;
};
} // namespace krbn
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "restriction.hh"
#include "primary_key_restrictions.hh"
#include "exceptions/exceptions.hh"
#include "term_slice.hh"
#include "keys.hh"
class column_definition;
namespace cql3 {
namespace restrictions {
/**
* <code>Restriction</code> using the token function.
*/
class token_restriction: public primary_key_restrictions<partition_key> {
private:
/**
* The definition of the columns to which apply the token restriction.
*/
std::vector<const column_definition *> _column_definitions;
public:
token_restriction(std::vector<const column_definition *> c)
: _column_definitions(std::move(c)) {
}
bool is_on_token() const override {
return true;
}
std::vector<const column_definition*> get_column_defs() const override {
return _column_definitions;
}
#if 0
bool has_supporting_index(::shared_ptr<secondary_index_manager> index_manager) const override {
return false;
}
void add_index_expression_to(std::vector<::shared_ptr<index_expression>>& expressions,
const query_options& options) override {
throw exceptions::unsupported_operation_exception();
}
#endif
std::vector<partition_key> values_as_keys(const query_options& options) const override {
throw exceptions::unsupported_operation_exception();
}
std::vector<bounds_range_type> bounds_ranges(const query_options& options) const override {
auto get_token_bound = [this, &options](statements::bound b) {
if (!has_bound(b)) {
return is_start(b) ? dht::minimum_token() : dht::maximum_token();
}
auto buf= bounds(b, options).front();
if (!buf) {
throw exceptions::invalid_request_exception("Invalid null token value");
}
return dht::token(dht::token::kind::key, *buf);
};
const auto start_token = get_token_bound(statements::bound::START);
const auto end_token = get_token_bound(statements::bound::END);
const auto include_start = this->is_inclusive(statements::bound::START);
const auto include_end = this->is_inclusive(statements::bound::END);
/*
* If we ask SP.getRangeSlice() for (token(200), token(200)], it will happily return the whole ring.
* However, wrapping range doesn't really make sense for CQL, and we want to return an empty result in that
* case (CASSANDRA-5573). So special case to create a range that is guaranteed to be empty.
*
* In practice, we want to return an empty result set if either startToken > endToken, or both are equal but
* one of the bound is excluded (since [a, a] can contains something, but not (a, a], [a, a) or (a, a)).
*/
if (start_token > end_token
|| (start_token == end_token
&& (!include_start || !include_end))) {
return {query::partition_range::make_open_ended_both_sides()};
}
typedef typename bounds_range_type::bound bound;
auto start = bound(start_token, include_start);
auto end = bound(end_token, include_end);
return { bounds_range_type(start, end) };
}
class EQ;
class slice;
};
class token_restriction::EQ final : public token_restriction {
private:
::shared_ptr<term> _value;
public:
EQ(std::vector<const column_definition*> column_defs, ::shared_ptr<term> value)
: token_restriction(column_defs)
, _value(std::move(value))
{}
bool is_EQ() const {
return true;
}
bool uses_function(const sstring& ks_name, const sstring& function_name) const override {
return abstract_restriction::uses_function(_value, ks_name, function_name);
}
void merge_with(::shared_ptr<restriction>) override {
throw exceptions::invalid_request_exception(
join(", ", get_column_defs())
+ " cannot be restricted by more than one relation if it includes an Equal");
}
std::vector<bytes_opt> values(const query_options& options) const override {
return { _value->bind_and_get(options) };
}
sstring to_string() const override {
return sprint("EQ(%s)", _value->to_string());
}
};
class token_restriction::slice final : public token_restriction {
private:
term_slice _slice;
public:
slice(std::vector<const column_definition*> column_defs, statements::bound bound, bool inclusive, ::shared_ptr<term> term)
: token_restriction(column_defs)
, _slice(term_slice::new_instance(bound, inclusive, std::move(term)))
{}
bool is_slice() const override {
return true;
}
bool has_bound(statements::bound b) const override {
return _slice.has_bound(b);
}
std::vector<bytes_opt> values(const query_options& options) const override {
throw exceptions::unsupported_operation_exception();
}
std::vector<bytes_opt> bounds(statements::bound b, const query_options& options) const override {
return { _slice.bound(b)->bind_and_get(options) };
}
bool uses_function(const sstring& ks_name,
const sstring& function_name) const override {
return (_slice.has_bound(statements::bound::START)
&& abstract_restriction::uses_function(
_slice.bound(statements::bound::START), ks_name,
function_name))
|| (_slice.has_bound(statements::bound::END)
&& abstract_restriction::uses_function(
_slice.bound(statements::bound::END),
ks_name, function_name));
}
bool is_inclusive(statements::bound b) const override {
return _slice.is_inclusive(b);
}
void merge_with(::shared_ptr<restriction> restriction) override {
try {
if (!restriction->is_on_token()) {
throw exceptions::invalid_request_exception(
"Columns \"%s\" cannot be restricted by both a normal relation and a token relation");
}
if (!restriction->is_slice()) {
throw exceptions::invalid_request_exception(
"Columns \"%s\" cannot be restricted by both an equality and an inequality relation");
}
auto* other_slice = static_cast<slice *>(restriction.get());
if (has_bound(statements::bound::START)
&& other_slice->has_bound(statements::bound::START)) {
throw exceptions::invalid_request_exception(
"More than one restriction was found for the start bound on %s");
}
if (has_bound(statements::bound::END)
&& other_slice->has_bound(statements::bound::END)) {
throw exceptions::invalid_request_exception(
"More than one restriction was found for the end bound on %s");
}
_slice.merge(other_slice->_slice);
} catch (exceptions::invalid_request_exception & e) {
throw exceptions::invalid_request_exception(
sprint(e.what(), join(", ", get_column_defs())));
}
}
sstring to_string() const override {
return sprint("SLICE%s", _slice);
}
};
}
}
<commit_msg>cql: token_restriction: Fix range produced for contradicting restrictions<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* Copyright 2015 Cloudius Systems
*
* Modified by Cloudius Systems
*/
#pragma once
#include "restriction.hh"
#include "primary_key_restrictions.hh"
#include "exceptions/exceptions.hh"
#include "term_slice.hh"
#include "keys.hh"
class column_definition;
namespace cql3 {
namespace restrictions {
/**
* <code>Restriction</code> using the token function.
*/
class token_restriction: public primary_key_restrictions<partition_key> {
private:
/**
* The definition of the columns to which apply the token restriction.
*/
std::vector<const column_definition *> _column_definitions;
public:
token_restriction(std::vector<const column_definition *> c)
: _column_definitions(std::move(c)) {
}
bool is_on_token() const override {
return true;
}
std::vector<const column_definition*> get_column_defs() const override {
return _column_definitions;
}
#if 0
bool has_supporting_index(::shared_ptr<secondary_index_manager> index_manager) const override {
return false;
}
void add_index_expression_to(std::vector<::shared_ptr<index_expression>>& expressions,
const query_options& options) override {
throw exceptions::unsupported_operation_exception();
}
#endif
std::vector<partition_key> values_as_keys(const query_options& options) const override {
throw exceptions::unsupported_operation_exception();
}
std::vector<bounds_range_type> bounds_ranges(const query_options& options) const override {
auto get_token_bound = [this, &options](statements::bound b) {
if (!has_bound(b)) {
return is_start(b) ? dht::minimum_token() : dht::maximum_token();
}
auto buf= bounds(b, options).front();
if (!buf) {
throw exceptions::invalid_request_exception("Invalid null token value");
}
return dht::token(dht::token::kind::key, *buf);
};
const auto start_token = get_token_bound(statements::bound::START);
const auto end_token = get_token_bound(statements::bound::END);
const auto include_start = this->is_inclusive(statements::bound::START);
const auto include_end = this->is_inclusive(statements::bound::END);
/*
* If we ask SP.getRangeSlice() for (token(200), token(200)], it will happily return the whole ring.
* However, wrapping range doesn't really make sense for CQL, and we want to return an empty result in that
* case (CASSANDRA-5573). So special case to create a range that is guaranteed to be empty.
*
* In practice, we want to return an empty result set if either startToken > endToken, or both are equal but
* one of the bound is excluded (since [a, a] can contains something, but not (a, a], [a, a) or (a, a)).
*/
if (start_token > end_token
|| (start_token == end_token
&& (!include_start || !include_end))) {
return {};
}
typedef typename bounds_range_type::bound bound;
auto start = bound(start_token, include_start);
auto end = bound(end_token, include_end);
return { bounds_range_type(start, end) };
}
class EQ;
class slice;
};
class token_restriction::EQ final : public token_restriction {
private:
::shared_ptr<term> _value;
public:
EQ(std::vector<const column_definition*> column_defs, ::shared_ptr<term> value)
: token_restriction(column_defs)
, _value(std::move(value))
{}
bool is_EQ() const {
return true;
}
bool uses_function(const sstring& ks_name, const sstring& function_name) const override {
return abstract_restriction::uses_function(_value, ks_name, function_name);
}
void merge_with(::shared_ptr<restriction>) override {
throw exceptions::invalid_request_exception(
join(", ", get_column_defs())
+ " cannot be restricted by more than one relation if it includes an Equal");
}
std::vector<bytes_opt> values(const query_options& options) const override {
return { _value->bind_and_get(options) };
}
sstring to_string() const override {
return sprint("EQ(%s)", _value->to_string());
}
};
class token_restriction::slice final : public token_restriction {
private:
term_slice _slice;
public:
slice(std::vector<const column_definition*> column_defs, statements::bound bound, bool inclusive, ::shared_ptr<term> term)
: token_restriction(column_defs)
, _slice(term_slice::new_instance(bound, inclusive, std::move(term)))
{}
bool is_slice() const override {
return true;
}
bool has_bound(statements::bound b) const override {
return _slice.has_bound(b);
}
std::vector<bytes_opt> values(const query_options& options) const override {
throw exceptions::unsupported_operation_exception();
}
std::vector<bytes_opt> bounds(statements::bound b, const query_options& options) const override {
return { _slice.bound(b)->bind_and_get(options) };
}
bool uses_function(const sstring& ks_name,
const sstring& function_name) const override {
return (_slice.has_bound(statements::bound::START)
&& abstract_restriction::uses_function(
_slice.bound(statements::bound::START), ks_name,
function_name))
|| (_slice.has_bound(statements::bound::END)
&& abstract_restriction::uses_function(
_slice.bound(statements::bound::END),
ks_name, function_name));
}
bool is_inclusive(statements::bound b) const override {
return _slice.is_inclusive(b);
}
void merge_with(::shared_ptr<restriction> restriction) override {
try {
if (!restriction->is_on_token()) {
throw exceptions::invalid_request_exception(
"Columns \"%s\" cannot be restricted by both a normal relation and a token relation");
}
if (!restriction->is_slice()) {
throw exceptions::invalid_request_exception(
"Columns \"%s\" cannot be restricted by both an equality and an inequality relation");
}
auto* other_slice = static_cast<slice *>(restriction.get());
if (has_bound(statements::bound::START)
&& other_slice->has_bound(statements::bound::START)) {
throw exceptions::invalid_request_exception(
"More than one restriction was found for the start bound on %s");
}
if (has_bound(statements::bound::END)
&& other_slice->has_bound(statements::bound::END)) {
throw exceptions::invalid_request_exception(
"More than one restriction was found for the end bound on %s");
}
_slice.merge(other_slice->_slice);
} catch (exceptions::invalid_request_exception & e) {
throw exceptions::invalid_request_exception(
sprint(e.what(), join(", ", get_column_defs())));
}
}
sstring to_string() const override {
return sprint("SLICE%s", _slice);
}
};
}
}
<|endoftext|> |
<commit_before>#include "sequence.h"
#include "details/ir/isa/printer.inc.hpp"
#include "details/atom/atom.h"
#include <cstdlib>
using namespace Yuni;
namespace ny
{
namespace ir
{
Sequence::~Sequence()
{
free(m_body);
}
void Sequence::moveCursorFromBlueprintToEnd(const Instruction*& cursor) const
{
assert((*cursor).opcodes[0] == static_cast<uint32_t>(ir::ISA::Op::blueprint));
if ((*cursor).opcodes[0] == static_cast<uint32_t>(ir::ISA::Op::blueprint))
{
// next opcode, which should be blueprint.size
(cursor)++;
// getting the size and moving the cursor
auto& blueprintsize = (*cursor).to<ir::ISA::Op::pragma>();
assert(blueprintsize.opcode == (uint32_t) ir::ISA::Op::pragma);
assert(blueprintsize.value.blueprintsize >= 2);
cursor += blueprintsize.value.blueprintsize - 2; // -2: blueprint:class+blueprint:size
assert((*cursor).opcodes[0] == (uint32_t) ir::ISA::Op::end);
}
}
void Sequence::moveCursorFromBlueprintToEnd(Instruction*& cursor) const
{
assert((*cursor).opcodes[0] == static_cast<uint32_t>(ir::ISA::Op::blueprint));
if ((*cursor).opcodes[0] == static_cast<uint32_t>(ir::ISA::Op::blueprint))
{
// next opcode, which should be blueprint.size
(cursor)++;
// getting the size and moving the cursor
auto& blueprintsize = (*cursor).to<ir::ISA::Op::pragma>();
assert(blueprintsize.opcode == (uint32_t) ir::ISA::Op::pragma);
assert(blueprintsize.value.blueprintsize >= 2);
cursor += blueprintsize.value.blueprintsize - 2; // -2: blueprint:class+blueprint:size
assert((*cursor).opcodes[0] == (uint32_t) ir::ISA::Op::end);
}
}
void Sequence::clear()
{
m_size = 0;
stringrefs.clear();
free(m_body);
m_capacity = 0;
m_body = nullptr;
}
void Sequence::grow(uint32_t count)
{
assert(count > 0);
auto newcapa = m_capacity;
do { newcapa += 1000u; } while (newcapa < count);
auto* newbody = (Instruction*) realloc(m_body, sizeof(Instruction) * newcapa);
if (unlikely(nullptr == newbody))
throw std::bad_alloc();
m_body = newbody;
m_capacity = newcapa;
}
void Sequence::print(YString& out, const AtomMap* atommap, uint32_t offset) const
{
using namespace ir::ISA;
out.reserve(out.size() + (m_size * 100)); // arbitrary
Printer<String> printer{out, *this};
printer.atommap = atommap;
printer.offset = offset;
each(printer, offset);
}
namespace // anonymous
{
struct WalkerIncreaseLVID final
{
WalkerIncreaseLVID(ir::Sequence& sequence, uint32_t inc, uint32_t greaterThan)
: greaterThan(greaterThan)
, inc(inc)
, sequence(sequence)
{}
void visit(ir::ISA::Operand<ir::ISA::Op::stacksize>& operands)
{
operands.add += inc;
}
void visit(ir::ISA::Operand<ir::ISA::Op::blueprint>& operands)
{
auto kind = static_cast<ir::ISA::Blueprint>(operands.kind);
switch (kind)
{
case ir::ISA::Blueprint::funcdef:
case ir::ISA::Blueprint::classdef:
sequence.moveCursorFromBlueprintToEnd(*cursor);
break;
default:
operands.eachLVID(*this);
break;
}
}
void visit(ir::ISA::Operand<ir::ISA::Op::scope>&)
{
++depth;
}
void visit(ir::ISA::Operand<ir::ISA::Op::end>&)
{
if (depth-- == 0)
sequence.invalidateCursor(*cursor);
}
template<ir::ISA::Op O> void visit(ir::ISA::Operand<O>& operands)
{
// ask to the opcode datatype to update its own lvid
// (see operator() below)
operands.eachLVID(*this);
}
inline void operator () (uint32_t& lvid) const
{
if (lvid > greaterThan)
lvid += inc;
}
inline void operator () (uint32_t& lvid1, uint32_t& lvid2) const
{
if (lvid1 > greaterThan)
lvid1 += inc;
if (lvid2 > greaterThan)
lvid2 += inc;
}
inline void operator () (uint32_t& lvid1, uint32_t& lvid2, uint32_t& lvid3) const
{
if (lvid1 > greaterThan)
lvid1 += inc;
if (lvid2 > greaterThan)
lvid2 += inc;
if (lvid3 > greaterThan)
lvid3 += inc;
}
uint32_t greaterThan;
uint32_t inc;
uint32_t depth = 0;
Instruction** cursor = nullptr;
Sequence& sequence;
};
} // anonymous namespace
void Sequence::increaseAllLVID(uint32_t inc, uint32_t greaterThan, uint32_t offset)
{
assert(inc > 0 and "this method should not be called if nothing to do");
WalkerIncreaseLVID walker{*this, inc, greaterThan};
each(walker, offset);
}
} // namespace ir
} // namespace ny
<commit_msg>sequence: remove using namespace<commit_after>#include "sequence.h"
#include "details/ir/isa/printer.inc.hpp"
#include "details/atom/atom.h"
#include <cstdlib>
using namespace Yuni;
namespace ny
{
namespace ir
{
Sequence::~Sequence()
{
free(m_body);
}
void Sequence::moveCursorFromBlueprintToEnd(const Instruction*& cursor) const
{
assert((*cursor).opcodes[0] == static_cast<uint32_t>(ir::ISA::Op::blueprint));
if ((*cursor).opcodes[0] == static_cast<uint32_t>(ir::ISA::Op::blueprint))
{
// next opcode, which should be blueprint.size
(cursor)++;
// getting the size and moving the cursor
auto& blueprintsize = (*cursor).to<ir::ISA::Op::pragma>();
assert(blueprintsize.opcode == (uint32_t) ir::ISA::Op::pragma);
assert(blueprintsize.value.blueprintsize >= 2);
cursor += blueprintsize.value.blueprintsize - 2; // -2: blueprint:class+blueprint:size
assert((*cursor).opcodes[0] == (uint32_t) ir::ISA::Op::end);
}
}
void Sequence::moveCursorFromBlueprintToEnd(Instruction*& cursor) const
{
assert((*cursor).opcodes[0] == static_cast<uint32_t>(ir::ISA::Op::blueprint));
if ((*cursor).opcodes[0] == static_cast<uint32_t>(ir::ISA::Op::blueprint))
{
// next opcode, which should be blueprint.size
(cursor)++;
// getting the size and moving the cursor
auto& blueprintsize = (*cursor).to<ir::ISA::Op::pragma>();
assert(blueprintsize.opcode == (uint32_t) ir::ISA::Op::pragma);
assert(blueprintsize.value.blueprintsize >= 2);
cursor += blueprintsize.value.blueprintsize - 2; // -2: blueprint:class+blueprint:size
assert((*cursor).opcodes[0] == (uint32_t) ir::ISA::Op::end);
}
}
void Sequence::clear()
{
m_size = 0;
stringrefs.clear();
free(m_body);
m_capacity = 0;
m_body = nullptr;
}
void Sequence::grow(uint32_t count)
{
assert(count > 0);
auto newcapa = m_capacity;
do { newcapa += 1000u; } while (newcapa < count);
auto* newbody = (Instruction*) realloc(m_body, sizeof(Instruction) * newcapa);
if (unlikely(nullptr == newbody))
throw std::bad_alloc();
m_body = newbody;
m_capacity = newcapa;
}
void Sequence::print(YString& out, const AtomMap* atommap, uint32_t offset) const
{
out.reserve(out.size() + (m_size * 100)); // arbitrary
ir::ISA::Printer<String> printer{out, *this};
printer.atommap = atommap;
printer.offset = offset;
each(printer, offset);
}
namespace // anonymous
{
struct WalkerIncreaseLVID final
{
WalkerIncreaseLVID(ir::Sequence& sequence, uint32_t inc, uint32_t greaterThan)
: greaterThan(greaterThan)
, inc(inc)
, sequence(sequence)
{}
void visit(ir::ISA::Operand<ir::ISA::Op::stacksize>& operands)
{
operands.add += inc;
}
void visit(ir::ISA::Operand<ir::ISA::Op::blueprint>& operands)
{
auto kind = static_cast<ir::ISA::Blueprint>(operands.kind);
switch (kind)
{
case ir::ISA::Blueprint::funcdef:
case ir::ISA::Blueprint::classdef:
sequence.moveCursorFromBlueprintToEnd(*cursor);
break;
default:
operands.eachLVID(*this);
break;
}
}
void visit(ir::ISA::Operand<ir::ISA::Op::scope>&)
{
++depth;
}
void visit(ir::ISA::Operand<ir::ISA::Op::end>&)
{
if (depth-- == 0)
sequence.invalidateCursor(*cursor);
}
template<ir::ISA::Op O> void visit(ir::ISA::Operand<O>& operands)
{
// ask to the opcode datatype to update its own lvid
// (see operator() below)
operands.eachLVID(*this);
}
inline void operator () (uint32_t& lvid) const
{
if (lvid > greaterThan)
lvid += inc;
}
inline void operator () (uint32_t& lvid1, uint32_t& lvid2) const
{
if (lvid1 > greaterThan)
lvid1 += inc;
if (lvid2 > greaterThan)
lvid2 += inc;
}
inline void operator () (uint32_t& lvid1, uint32_t& lvid2, uint32_t& lvid3) const
{
if (lvid1 > greaterThan)
lvid1 += inc;
if (lvid2 > greaterThan)
lvid2 += inc;
if (lvid3 > greaterThan)
lvid3 += inc;
}
uint32_t greaterThan;
uint32_t inc;
uint32_t depth = 0;
Instruction** cursor = nullptr;
Sequence& sequence;
};
} // anonymous namespace
void Sequence::increaseAllLVID(uint32_t inc, uint32_t greaterThan, uint32_t offset)
{
assert(inc > 0 and "this method should not be called if nothing to do");
WalkerIncreaseLVID walker{*this, inc, greaterThan};
each(walker, offset);
}
} // namespace ir
} // namespace ny
<|endoftext|> |
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "norm_l2.hpp"
#include "norm_l1.hpp"
#include "norm_none.hpp"
<commit_msg>fix missing include guard in norm.hpp<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2011 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#ifndef JUBATUS_CORE_STORAGE_NORM_HPP_
#define JUBATUS_CORE_STORAGE_NORM_HPP_
#include "norm_l2.hpp"
#include "norm_l1.hpp"
#include "norm_none.hpp"
#endif // JUBATUS_CORE_STORAGE_NORM_HPP_
<|endoftext|> |
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/fastlib/text/unicodeutil.h>
#include "unicodeutil-charprops.cpp"
#include "unicodeutil-lowercase.cpp"
unsigned char Fast_UnicodeUtil::_utf8header[256];
namespace {
class Initialize
{
public:
Initialize() { Fast_UnicodeUtil::InitTables(); }
};
Initialize _G_Initializer;
}
void
Fast_UnicodeUtil::InitTables(void)
{
/**
* Hack for Katakana accent marks (torgeir)
*/
_compCharProps[(0xFF9E >> 8)][(0xFF9E & 255)] |= 32;
_compCharProps[(0xFF9F >> 8)][(0xFF9F & 255)] |= 32;
for (uint32_t i = 0; i < 256; i++) { _utf8header[i] = 0; }
// Initialize _utf8header array
for (uint32_t i = 0x00; i <= 0x7F; i++) { _utf8header[i] = 1; }
for (uint32_t i = 0xC0; i <= 0xDF; i++) { _utf8header[i] = 2; }
for (uint32_t i = 0xE0; i <= 0xEF; i++) { _utf8header[i] = 3; }
for (uint32_t i = 0xF0; i <= 0xF7; i++) { _utf8header[i] = 4; }
for (uint32_t i = 0xF8; i <= 0xFB; i++) { _utf8header[i] = 5; }
for (uint32_t i = 0xFC; i <= 0xFD; i++) { _utf8header[i] = 6; }
}
char *
Fast_UnicodeUtil::utf8ncopy(char *dst, const ucs4_t *src,
int maxdst, int maxsrc)
{
char * p = dst;
char * edst = dst + maxdst;
for (const ucs4_t *esrc(src + maxsrc); (src < esrc) && (*src != 0) && (p < edst); src++) {
ucs4_t i(*src);
if (i < 128)
*p++ = i;
else if (i < 0x800) {
if (p + 1 >= edst)
break;
*p++ = (i >> 6) | 0xc0;
*p++ = (i & 63) | 0x80;
} else if (i < 0x10000) {
if (p + 2 >= edst)
break;
*p++ = (i >> 12) | 0xe0;
*p++ = ((i >> 6) & 63) | 0x80;
*p++ = (i & 63) | 0x80;
} else if (i < 0x200000) {
if (p + 3 >= edst)
break;
*p++ = (i >> 18) | 0xf0;
*p++ = ((i >> 12) & 63) | 0x80;
*p++ = ((i >> 6) & 63) | 0x80;
*p++ = (i & 63) | 0x80;
} else if (i < 0x4000000) {
if (p + 4 >= edst)
break;
*p++ = (i >> 24) | 0xf8;
*p++ = ((i >> 18) & 63) | 0x80;
*p++ = ((i >> 12) & 63) | 0x80;
*p++ = ((i >> 6) & 63) | 0x80;
*p++ = (i & 63) | 0x80;
} else {
if (p + 5 >= edst)
break;
*p++ = (i >> 30) | 0xfc;
*p++ = ((i >> 24) & 63) | 0x80;
*p++ = ((i >> 18) & 63) | 0x80;
*p++ = ((i >> 12) & 63) | 0x80;
*p++ = ((i >> 6) & 63) | 0x80;
*p++ = (i & 63) | 0x80;
}
}
if (p < edst)
*p = 0;
return p;
}
int
Fast_UnicodeUtil::utf8cmp(const char *s1, const ucs4_t *s2)
{
ucs4_t i1;
ucs4_t i2;
const unsigned char *ps1 = reinterpret_cast<const unsigned char *>(s1);
do {
i1 = GetUTF8Char(ps1);
i2 = *s2++;
} while (i1 != 0 && i1 == i2);
if (i1 > i2)
return 1;
if (i1 < i2)
return -1;
return 0;
}
size_t
Fast_UnicodeUtil::ucs4strlen(const ucs4_t *str)
{
const ucs4_t *p = str;
while (*p++ != 0) {
/* Do nothing */
}
return p - 1 - str;
}
ucs4_t *
Fast_UnicodeUtil::ucs4copy(ucs4_t *dst, const char *src)
{
ucs4_t i;
ucs4_t *p;
const unsigned char *psrc = reinterpret_cast<const unsigned char *>(src);
p = dst;
while ((i = GetUTF8Char(psrc)) != 0) {
if (i != _BadUTF8Char)
*p++ = i;
}
*p = 0;
return p;
}
char *
Fast_UnicodeUtil::strdupLAT1(const char *src)
{
char *res;
size_t reslen;
ucs4_t i;
const unsigned char *p;
char *q;
reslen = 0;
p = reinterpret_cast<const unsigned char *>(src);
while ((i = *p++) != 0) {
reslen += utf8clen(i);
}
res = static_cast<char *>(malloc(reslen + 1));
p = reinterpret_cast<const unsigned char *>(src);
q = res;
while ((i = *p++) != 0) {
q = utf8cput(q, i);
}
assert(q == res + reslen);
*q = 0;
return res;
}
ucs4_t
Fast_UnicodeUtil::GetUTF8CharNonAscii(unsigned const char *&src)
{
ucs4_t retval;
if (*src >= 0xc0) {
if (src[1] < 0x80 || src[1] >= 0xc0) {
src++;
return _BadUTF8Char;
}
if (*src >= 0xe0) { /* 0xe0..0xff */
if (src[2] < 0x80 || src[2] >= 0xc0) {
src += 2;
return _BadUTF8Char;
}
if (*src >= 0xf0) { /* 0xf0..0xff */
if (src[3] < 0x80 || src[3] >= 0xc0) {
src += 3;
return _BadUTF8Char;
}
if (*src >= 0xf8) { /* 0xf8..0xff */
if (src[4] < 0x80 || src[4] >= 0xc0) {
src += 4;
return _BadUTF8Char;
}
if (*src >= 0xfc) { /* 0xfc..0xff */
if (src[5] < 0x80 || src[5] >= 0xc0) {
src += 5;
return _BadUTF8Char;
}
if (*src >= 0xfe) { /* 0xfe..0xff: INVALID */
src += 5;
return _BadUTF8Char;
} else { /* 0xfc..0xfd: 6 bytes */
retval = ((src[0] & 1) << 30) |
((src[1] & 63) << 24) |
((src[2] & 63) << 18) |
((src[3] & 63) << 12) |
((src[4] & 63) << 6) |
(src[5] & 63);
if (retval < 0x4000000u) { /* 6 bytes: >= 0x4000000 */
retval = _BadUTF8Char;
}
src += 6;
return retval;
}
} else { /* 0xf8..0xfb: 5 bytes */
retval = ((src[0] & 3) << 24) |
((src[1] & 63) << 18) |
((src[2] & 63) << 12) |
((src[3] & 63) << 6) |
(src[4] & 63);
if (retval < 0x200000u) { /* 5 bytes: >= 0x200000 */
retval = _BadUTF8Char;
}
src += 5;
return retval;
}
} else { /* 0xf0..0xf7: 4 bytes */
retval = ((src[0] & 7) << 18) |
((src[1] & 63) << 12) |
((src[2] & 63) << 6) |
(src[3] & 63);
if (retval < 0x10000) { /* 4 bytes: >= 0x10000 */
retval = _BadUTF8Char;
}
src += 4;
return retval;
}
} else { /* 0xe0..0xef: 3 bytes */
retval = ((src[0] & 15) << 12) |
((src[1] & 63) << 6) |
(src[2] & 63);
if (retval < 0x800) { /* 3 bytes: >= 0x800 */
retval = _BadUTF8Char;
}
src += 3;
return retval;
}
} else { /* 0xc0..0xdf: 2 bytes */
retval = ((src[0] & 31) << 6) |
(src[1] & 63);
if (retval < 0x80) { /* 2 bytes: >= 0x80 */
retval = _BadUTF8Char;
}
src += 2;
return retval;
}
} else { /* 0x80..0xbf: INVALID */
src += 1;
return _BadUTF8Char;
}
}
ucs4_t
Fast_UnicodeUtil::GetUTF8Char(unsigned const char *&src)
{
return (*src >= 0x80)
? GetUTF8CharNonAscii(src)
: *src++;
}
/** Move forwards or backwards a number of characters within an UTF8 buffer
* Modify pos to yield new position if possible
* @param start A pointer to the start of the UTF8 buffer
* @param length The length of the UTF8 buffer
* @param pos A pointer to the current position within the UTF8 buffer,
* updated to reflect new position upon return. @param pos will
* point to the start of the offset'th character before or after the character
* currently pointed to.
* @param offset An offset (+/-) in number of UTF8 characters.
* Offset 0 consequently yields a move to the start of the current character.
* @return Number of bytes moved, or -1 if out of range.
* If -1 is returned, pos is unchanged.
*/
#define UTF8_STARTCHAR(c) (!((c) & 0x80) || ((c) & 0x40))
int Fast_UnicodeUtil::UTF8move(unsigned const char* start, size_t length,
unsigned const char*& pos, off_t offset)
{
int increment = offset > 0 ? 1 : -1;
unsigned const char* p = pos;
/* If running backward we first need to get to the start of
* the current character, that's an extra step.
* Similarly, if we are running forward an are at the start of a character,
* we count that character as a step.
*/
if (increment < 0)
{
// Already at start?
if (p < start) return -1;
if (!offset)
{
if (p > start + length) return -1;
}
else if (p == start) return -1;
// Initially pointing to the first invalid char?
if (p == start + length)
p += increment;
else
offset += increment;
}
else if (p >= start + length)
return -1;
else if (UTF8_STARTCHAR(*p))
offset += increment;
for (; p >= start && p < start+length; p += increment)
{
/** Are we at start of a character? (both highest bits or none of them set) */
if (UTF8_STARTCHAR(*p))
offset -= increment; // We have "eaten" another character (independent of dir)
if (offset == 0) break;
}
if (offset != 0)
{
offset -= increment;
if (increment < 0)
p -= increment;
}
if (offset == 0) // Enough room to make it..
{
int moved = abs(p - pos);
pos = p;
return moved;
}
else
return -1;
}
<commit_msg>use cmath<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include <vespa/fastlib/text/unicodeutil.h>
#include <cstdlib>
#include "unicodeutil-charprops.cpp"
#include "unicodeutil-lowercase.cpp"
unsigned char Fast_UnicodeUtil::_utf8header[256];
namespace {
class Initialize
{
public:
Initialize() { Fast_UnicodeUtil::InitTables(); }
};
Initialize _G_Initializer;
}
void
Fast_UnicodeUtil::InitTables(void)
{
/**
* Hack for Katakana accent marks (torgeir)
*/
_compCharProps[(0xFF9E >> 8)][(0xFF9E & 255)] |= 32;
_compCharProps[(0xFF9F >> 8)][(0xFF9F & 255)] |= 32;
for (uint32_t i = 0; i < 256; i++) { _utf8header[i] = 0; }
// Initialize _utf8header array
for (uint32_t i = 0x00; i <= 0x7F; i++) { _utf8header[i] = 1; }
for (uint32_t i = 0xC0; i <= 0xDF; i++) { _utf8header[i] = 2; }
for (uint32_t i = 0xE0; i <= 0xEF; i++) { _utf8header[i] = 3; }
for (uint32_t i = 0xF0; i <= 0xF7; i++) { _utf8header[i] = 4; }
for (uint32_t i = 0xF8; i <= 0xFB; i++) { _utf8header[i] = 5; }
for (uint32_t i = 0xFC; i <= 0xFD; i++) { _utf8header[i] = 6; }
}
char *
Fast_UnicodeUtil::utf8ncopy(char *dst, const ucs4_t *src,
int maxdst, int maxsrc)
{
char * p = dst;
char * edst = dst + maxdst;
for (const ucs4_t *esrc(src + maxsrc); (src < esrc) && (*src != 0) && (p < edst); src++) {
ucs4_t i(*src);
if (i < 128)
*p++ = i;
else if (i < 0x800) {
if (p + 1 >= edst)
break;
*p++ = (i >> 6) | 0xc0;
*p++ = (i & 63) | 0x80;
} else if (i < 0x10000) {
if (p + 2 >= edst)
break;
*p++ = (i >> 12) | 0xe0;
*p++ = ((i >> 6) & 63) | 0x80;
*p++ = (i & 63) | 0x80;
} else if (i < 0x200000) {
if (p + 3 >= edst)
break;
*p++ = (i >> 18) | 0xf0;
*p++ = ((i >> 12) & 63) | 0x80;
*p++ = ((i >> 6) & 63) | 0x80;
*p++ = (i & 63) | 0x80;
} else if (i < 0x4000000) {
if (p + 4 >= edst)
break;
*p++ = (i >> 24) | 0xf8;
*p++ = ((i >> 18) & 63) | 0x80;
*p++ = ((i >> 12) & 63) | 0x80;
*p++ = ((i >> 6) & 63) | 0x80;
*p++ = (i & 63) | 0x80;
} else {
if (p + 5 >= edst)
break;
*p++ = (i >> 30) | 0xfc;
*p++ = ((i >> 24) & 63) | 0x80;
*p++ = ((i >> 18) & 63) | 0x80;
*p++ = ((i >> 12) & 63) | 0x80;
*p++ = ((i >> 6) & 63) | 0x80;
*p++ = (i & 63) | 0x80;
}
}
if (p < edst)
*p = 0;
return p;
}
int
Fast_UnicodeUtil::utf8cmp(const char *s1, const ucs4_t *s2)
{
ucs4_t i1;
ucs4_t i2;
const unsigned char *ps1 = reinterpret_cast<const unsigned char *>(s1);
do {
i1 = GetUTF8Char(ps1);
i2 = *s2++;
} while (i1 != 0 && i1 == i2);
if (i1 > i2)
return 1;
if (i1 < i2)
return -1;
return 0;
}
size_t
Fast_UnicodeUtil::ucs4strlen(const ucs4_t *str)
{
const ucs4_t *p = str;
while (*p++ != 0) {
/* Do nothing */
}
return p - 1 - str;
}
ucs4_t *
Fast_UnicodeUtil::ucs4copy(ucs4_t *dst, const char *src)
{
ucs4_t i;
ucs4_t *p;
const unsigned char *psrc = reinterpret_cast<const unsigned char *>(src);
p = dst;
while ((i = GetUTF8Char(psrc)) != 0) {
if (i != _BadUTF8Char)
*p++ = i;
}
*p = 0;
return p;
}
char *
Fast_UnicodeUtil::strdupLAT1(const char *src)
{
char *res;
size_t reslen;
ucs4_t i;
const unsigned char *p;
char *q;
reslen = 0;
p = reinterpret_cast<const unsigned char *>(src);
while ((i = *p++) != 0) {
reslen += utf8clen(i);
}
res = static_cast<char *>(malloc(reslen + 1));
p = reinterpret_cast<const unsigned char *>(src);
q = res;
while ((i = *p++) != 0) {
q = utf8cput(q, i);
}
assert(q == res + reslen);
*q = 0;
return res;
}
ucs4_t
Fast_UnicodeUtil::GetUTF8CharNonAscii(unsigned const char *&src)
{
ucs4_t retval;
if (*src >= 0xc0) {
if (src[1] < 0x80 || src[1] >= 0xc0) {
src++;
return _BadUTF8Char;
}
if (*src >= 0xe0) { /* 0xe0..0xff */
if (src[2] < 0x80 || src[2] >= 0xc0) {
src += 2;
return _BadUTF8Char;
}
if (*src >= 0xf0) { /* 0xf0..0xff */
if (src[3] < 0x80 || src[3] >= 0xc0) {
src += 3;
return _BadUTF8Char;
}
if (*src >= 0xf8) { /* 0xf8..0xff */
if (src[4] < 0x80 || src[4] >= 0xc0) {
src += 4;
return _BadUTF8Char;
}
if (*src >= 0xfc) { /* 0xfc..0xff */
if (src[5] < 0x80 || src[5] >= 0xc0) {
src += 5;
return _BadUTF8Char;
}
if (*src >= 0xfe) { /* 0xfe..0xff: INVALID */
src += 5;
return _BadUTF8Char;
} else { /* 0xfc..0xfd: 6 bytes */
retval = ((src[0] & 1) << 30) |
((src[1] & 63) << 24) |
((src[2] & 63) << 18) |
((src[3] & 63) << 12) |
((src[4] & 63) << 6) |
(src[5] & 63);
if (retval < 0x4000000u) { /* 6 bytes: >= 0x4000000 */
retval = _BadUTF8Char;
}
src += 6;
return retval;
}
} else { /* 0xf8..0xfb: 5 bytes */
retval = ((src[0] & 3) << 24) |
((src[1] & 63) << 18) |
((src[2] & 63) << 12) |
((src[3] & 63) << 6) |
(src[4] & 63);
if (retval < 0x200000u) { /* 5 bytes: >= 0x200000 */
retval = _BadUTF8Char;
}
src += 5;
return retval;
}
} else { /* 0xf0..0xf7: 4 bytes */
retval = ((src[0] & 7) << 18) |
((src[1] & 63) << 12) |
((src[2] & 63) << 6) |
(src[3] & 63);
if (retval < 0x10000) { /* 4 bytes: >= 0x10000 */
retval = _BadUTF8Char;
}
src += 4;
return retval;
}
} else { /* 0xe0..0xef: 3 bytes */
retval = ((src[0] & 15) << 12) |
((src[1] & 63) << 6) |
(src[2] & 63);
if (retval < 0x800) { /* 3 bytes: >= 0x800 */
retval = _BadUTF8Char;
}
src += 3;
return retval;
}
} else { /* 0xc0..0xdf: 2 bytes */
retval = ((src[0] & 31) << 6) |
(src[1] & 63);
if (retval < 0x80) { /* 2 bytes: >= 0x80 */
retval = _BadUTF8Char;
}
src += 2;
return retval;
}
} else { /* 0x80..0xbf: INVALID */
src += 1;
return _BadUTF8Char;
}
}
ucs4_t
Fast_UnicodeUtil::GetUTF8Char(unsigned const char *&src)
{
return (*src >= 0x80)
? GetUTF8CharNonAscii(src)
: *src++;
}
/** Move forwards or backwards a number of characters within an UTF8 buffer
* Modify pos to yield new position if possible
* @param start A pointer to the start of the UTF8 buffer
* @param length The length of the UTF8 buffer
* @param pos A pointer to the current position within the UTF8 buffer,
* updated to reflect new position upon return. @param pos will
* point to the start of the offset'th character before or after the character
* currently pointed to.
* @param offset An offset (+/-) in number of UTF8 characters.
* Offset 0 consequently yields a move to the start of the current character.
* @return Number of bytes moved, or -1 if out of range.
* If -1 is returned, pos is unchanged.
*/
#define UTF8_STARTCHAR(c) (!((c) & 0x80) || ((c) & 0x40))
int Fast_UnicodeUtil::UTF8move(unsigned const char* start, size_t length,
unsigned const char*& pos, off_t offset)
{
int increment = offset > 0 ? 1 : -1;
unsigned const char* p = pos;
/* If running backward we first need to get to the start of
* the current character, that's an extra step.
* Similarly, if we are running forward an are at the start of a character,
* we count that character as a step.
*/
if (increment < 0)
{
// Already at start?
if (p < start) return -1;
if (!offset)
{
if (p > start + length) return -1;
}
else if (p == start) return -1;
// Initially pointing to the first invalid char?
if (p == start + length)
p += increment;
else
offset += increment;
}
else if (p >= start + length)
return -1;
else if (UTF8_STARTCHAR(*p))
offset += increment;
for (; p >= start && p < start+length; p += increment)
{
/** Are we at start of a character? (both highest bits or none of them set) */
if (UTF8_STARTCHAR(*p))
offset -= increment; // We have "eaten" another character (independent of dir)
if (offset == 0) break;
}
if (offset != 0)
{
offset -= increment;
if (increment < 0)
p -= increment;
}
if (offset == 0) // Enough room to make it..
{
int moved = std::abs(p - pos);
pos = p;
return moved;
}
else
return -1;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include <stdlib.h>
#include <wchar.h>
#include <math.h>
#include <ctime>
#include "XEngine.h"
#include "Renderer\Renderer.h"
#include "GameObjects\GameObject.h"
#include "GameObjects\Rect.h"
#include "Scenes\EngineScene.h"
XEngine* pDemoApp;
void XEngine::RunMessageLoop()
{
MSG msg;
msg.message = WM_NULL;
while (msg.message != WM_QUIT) {
if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else {
pDemoApp->Update();
pDemoApp->renderer->PreRender();
pDemoApp->currentScene->Render(m_hwnd, pDemoApp->renderer);
pDemoApp->renderer->EndRender();
}
}
}
XEngine::XEngine():
m_hwnd(NULL)
{
}
XEngine::~XEngine()
{
delete renderer;
}
HRESULT XEngine::Initialize(EngineScene* initialScene, float resolutionX, float resolutionY)
{
HRESULT hr;
currentScene = initialScene;
renderer = new Renderer();
// as the Direct2D factory.
hr = renderer->Initialize();
if (SUCCEEDED(hr))
{
// Register the window class.
WNDCLASSEX wcex = { sizeof(WNDCLASSEX) };
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = XEngine::WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = sizeof(LONG_PTR);
wcex.hInstance = HINST_THISCOMPONENT;
wcex.hbrBackground = NULL;
wcex.lpszMenuName = NULL;
wcex.hCursor = LoadCursor(NULL, IDI_APPLICATION);
wcex.lpszClassName = L"D2DDemoApp";
RegisterClassEx(&wcex);
// Because the CreateWindow function takes its size in pixels,
// obtain the system DPI and use it to scale the window size.
FLOAT dpiX, dpiY;
// The factory returns the current system DPI. This is also the value it will use
// to create its own windows.
renderer->GetDesktopDpi(&dpiX, &dpiY);
// Create the window.
m_hwnd = CreateWindow(
L"D2DDemoApp",
L"Direct2D Demo App",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
static_cast<UINT>(ceil(resolutionX * dpiX / 96.f)),
static_cast<UINT>(ceil(resolutionY * dpiY / 96.f)),
NULL,
NULL,
HINST_THISCOMPONENT,
this
);
hr = m_hwnd ? S_OK : E_FAIL;
if (SUCCEEDED(hr))
{
ShowWindow(m_hwnd, SW_SHOWNORMAL);
UpdateWindow(m_hwnd);
renderer->CreateDeviceResources(m_hwnd);
}
pDemoApp = this;
currentTime = GetTime();
dt = 1.f / 60.f;
currentScene->Preload();
currentScene->Start();
}
return hr;
}
void XEngine::Update() {
//Calculate semi-fixed deltaTime
newTime = GetTime();
double frameTime = (newTime - currentTime) * 0.001;
currentTime = newTime;
float deltaTime = (float) min(frameTime, dt);
currentScene->Update(deltaTime);
}
void XEngine::StartScene(EngineScene * sceneToStart)
{
currentScene->OnDestroy();
currentScene = sceneToStart;
currentScene->Preload();
currentScene->Start();
}
LRESULT CALLBACK XEngine::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
bool wasHandled = false;
if (pDemoApp)
{
switch (message)
{
case WM_SIZE:
{
UINT width = LOWORD(lParam);
UINT height = HIWORD(lParam);
pDemoApp->renderer->OnResize(width, height);
}
result = 0;
wasHandled = true;
break;
case WM_DISPLAYCHANGE:
{
InvalidateRect(hwnd, NULL, FALSE);
}
result = 0;
wasHandled = true;
break;
case WM_PAINT:
{
ValidateRect(hwnd, NULL);
pDemoApp->currentScene->Render(hwnd, pDemoApp->renderer);
}
result = 0;
wasHandled = true;
break;
case WM_DESTROY:
{
PostQuitMessage(0);
}
result = 1;
wasHandled = true;
break;
}
}
if (!wasHandled)
{
result = DefWindowProc(hwnd, message, wParam, lParam);
}
return result;
}<commit_msg>Call flush cache before start a new scene<commit_after>#include "stdafx.h"
#include <stdlib.h>
#include <wchar.h>
#include <math.h>
#include <ctime>
#include "XEngine.h"
#include "Renderer\Renderer.h"
#include "GameObjects\GameObject.h"
#include "GameObjects\Rect.h"
#include "Scenes\EngineScene.h"
XEngine* pDemoApp;
void XEngine::RunMessageLoop()
{
MSG msg;
msg.message = WM_NULL;
while (msg.message != WM_QUIT) {
if (PeekMessage(&msg, NULL, NULL, NULL, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else {
pDemoApp->Update();
pDemoApp->renderer->PreRender();
pDemoApp->currentScene->Render(m_hwnd, pDemoApp->renderer);
pDemoApp->renderer->EndRender();
}
}
}
XEngine::XEngine():
m_hwnd(NULL)
{
}
XEngine::~XEngine()
{
delete renderer;
}
HRESULT XEngine::Initialize(EngineScene* initialScene, float resolutionX, float resolutionY)
{
HRESULT hr;
currentScene = initialScene;
renderer = new Renderer();
// as the Direct2D factory.
hr = renderer->Initialize();
if (SUCCEEDED(hr))
{
// Register the window class.
WNDCLASSEX wcex = { sizeof(WNDCLASSEX) };
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = XEngine::WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = sizeof(LONG_PTR);
wcex.hInstance = HINST_THISCOMPONENT;
wcex.hbrBackground = NULL;
wcex.lpszMenuName = NULL;
wcex.hCursor = LoadCursor(NULL, IDI_APPLICATION);
wcex.lpszClassName = L"D2DDemoApp";
RegisterClassEx(&wcex);
// Because the CreateWindow function takes its size in pixels,
// obtain the system DPI and use it to scale the window size.
FLOAT dpiX, dpiY;
// The factory returns the current system DPI. This is also the value it will use
// to create its own windows.
renderer->GetDesktopDpi(&dpiX, &dpiY);
// Create the window.
m_hwnd = CreateWindow(
L"D2DDemoApp",
L"Direct2D Demo App",
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
static_cast<UINT>(ceil(resolutionX * dpiX / 96.f)),
static_cast<UINT>(ceil(resolutionY * dpiY / 96.f)),
NULL,
NULL,
HINST_THISCOMPONENT,
this
);
hr = m_hwnd ? S_OK : E_FAIL;
if (SUCCEEDED(hr))
{
ShowWindow(m_hwnd, SW_SHOWNORMAL);
UpdateWindow(m_hwnd);
renderer->CreateDeviceResources(m_hwnd);
}
pDemoApp = this;
currentTime = GetTime();
dt = 1.f / 60.f;
currentScene->Preload();
currentScene->Start();
}
return hr;
}
void XEngine::Update() {
//Calculate semi-fixed deltaTime
newTime = GetTime();
double frameTime = (newTime - currentTime) * 0.001;
currentTime = newTime;
float deltaTime = (float) min(frameTime, dt);
currentScene->Update(deltaTime);
}
void XEngine::StartScene(EngineScene * sceneToStart)
{
currentScene->OnDestroy();
CacheManager::GetInstance()->FlushCache();
currentScene = sceneToStart;
currentScene->Preload();
currentScene->Start();
}
LRESULT CALLBACK XEngine::WndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
bool wasHandled = false;
if (pDemoApp)
{
switch (message)
{
case WM_SIZE:
{
UINT width = LOWORD(lParam);
UINT height = HIWORD(lParam);
pDemoApp->renderer->OnResize(width, height);
}
result = 0;
wasHandled = true;
break;
case WM_DISPLAYCHANGE:
{
InvalidateRect(hwnd, NULL, FALSE);
}
result = 0;
wasHandled = true;
break;
case WM_PAINT:
{
ValidateRect(hwnd, NULL);
pDemoApp->currentScene->Render(hwnd, pDemoApp->renderer);
}
result = 0;
wasHandled = true;
break;
case WM_DESTROY:
{
PostQuitMessage(0);
}
result = 1;
wasHandled = true;
break;
}
}
if (!wasHandled)
{
result = DefWindowProc(hwnd, message, wParam, lParam);
}
return result;
}<|endoftext|> |
<commit_before>#ifndef Ancona_System_Android_Log_H_
#define Ancona_System_Android_Log_H_
#include <string>
namespace ild
{
/**
* @brief Log functions a platform must implement.
*
* @author Tucker Lein
*/
class LogControls
{
public:
/**
* @brief Used to implement the log macro, should not be used outside of this file.
*
* @param msg Message to print out
*/
static void _log(const std::string & msg);
};
}
#define ILD_Log(message) {\
ild::LogControls::_log(message);\
}
#endif
<commit_msg>Provide an overload for ILD_Log that can use an ostringstream instead of just a string<commit_after>#ifndef Ancona_System_Android_Log_H_
#define Ancona_System_Android_Log_H_
#include <string>
#include <sstream>
namespace ild
{
/**
* @brief Log functions a platform must implement.
*
* @author Tucker Lein
*/
class LogControls
{
public:
/**
* @brief Used to implement the log macro, should not be used outside of this file.
*
* @param msg Message to print out
*/
static void _log(const std::string & msg);
static void _log(const std::ostringstream & stream) {
_log(stream.str());
}
};
}
#define ILD_Log(message) {\
ild::LogControls::_log(message);\
}
#endif
<|endoftext|> |
<commit_before>/*-----------------------------------------------------------------------------
This source file is a part of Hopsan
Copyright (c) 2009 to present year, Hopsan Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
For license details and information about the Hopsan Group see the files
GPLv3 and HOPSANGROUP in the Hopsan source code root directory
For author and contributor information see the AUTHORS file
-----------------------------------------------------------------------------*/
//!
//! @file Ops.h
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2015-08-31
//!
//! @brief Contains the optimization worker class for the Complex-RF algorithm
//!
//$Id$
#include "OpsWorkerComplexRF.h"
#include "OpsEvaluator.h"
#include "OpsMessageHandler.h"
#include <math.h>
#include <sstream>
using namespace Ops;
WorkerComplexRF::WorkerComplexRF(Evaluator *pEvaluator, MessageHandler *pMessageHandler)
: WorkerSimplex(pEvaluator, pMessageHandler)
{
mRetractionCounter = 0;
}
AlgorithmT WorkerComplexRF::getAlgorithm()
{
return ComplexRF;
}
void WorkerComplexRF::initialize()
{
WorkerSimplex::initialize();
mKf = 1.0-pow(mAlpha/2.0, mGamma/mNumPoints);
}
void WorkerComplexRF::run()
{
mpMessageHandler->printMessage("Running optimization with Complex-RF algorithm.");
distributePoints();
mpEvaluator->evaluateAllPoints();
mpMessageHandler->objectivesChanged();
calculateBestAndWorstId();
//Run optimization loop
mIterationCounter=0;
for(; mIterationCounter<mnMaxIterations && !mpMessageHandler->aborted(); ++mIterationCounter)
{
//Check convergence
if(checkForConvergence()) break;
//Increase all objective values (forgetting principle)
applyForgettingFactor();
//Calculate best and worst point
calculateBestAndWorstId();
//Find geometrical center
findCentroidPoint();
//Reflect worst point
mCandidatePoints[0] = reflect(mPoints[mWorstId], mCentroidPoint, mAlpha);
mpMessageHandler->candidateChanged(0);
//std::vector<double> newPoint = mCandidatePoints[0]; //Remember the new point, in case we need to iterate below
//Evaluate new point
mpEvaluator->evaluateCandidate(0);
mPoints[mWorstId] = mCandidatePoints[0];
mObjectives[mWorstId] = mCandidateObjectives[0];
mpMessageHandler->pointChanged(mWorstId);
mpMessageHandler->objectiveChanged(mWorstId);
calculateBestAndWorstId();
//Retract until worst point is no longer the same
mRetractionCounter = 0;
bool doBreak = false;
while(mLastWorstId == mWorstId && !mpMessageHandler->aborted())
{
++mIterationCounter;
mpMessageHandler->stepCompleted(mIterationCounter);
if(mIterationCounter>=mnMaxIterations)
{
--mIterationCounter; //Needed because for-loop will increase it by one anyway
break;
}
if(retract())
{
doBreak = true;
break;
}
}
if(doBreak)
{
break;
}
mpMessageHandler->stepCompleted(mIterationCounter);
}
if(mpMessageHandler->aborted())
{
mpMessageHandler->printMessage("Optimization was aborted after "+std::to_string(mIterationCounter)+" iterations.");
}
else if(mIterationCounter == mnMaxIterations)
{
mpMessageHandler->printMessage(std::string("Optimization failed to converge after "+std::to_string(mIterationCounter)+" iterations"));
}
else
{
mpMessageHandler->printMessage("Optimization converged in parameter values after "+std::to_string(mIterationCounter)+" iterations.");
}
// Clean up
finalize();
return;
}
void WorkerComplexRF::setReflectionFactor(double value)
{
mAlpha = value;
}
void WorkerComplexRF::setForgettingFactor(double value)
{
mGamma = value;
}
bool WorkerComplexRF::retract()
{
std::vector<double> newPoint = mPoints[mWorstId];
//Move first reflected point
double a1 = 1.0-exp(-double(mRetractionCounter)/5.0);
for(size_t j=0; j<mNumParameters; ++j)
{
double best = mPoints[mBestId][j];
double maxDiff = getMaxPercentalParameterDiff()*10/(9.0+mRetractionCounter);
double r = opsRand();
mCandidatePoints[0][j] = (mCentroidPoint[j]*(1.0-a1) + best*a1 + newPoint[j])/2.0;
mCandidatePoints[0][j] += mRandomFactor*(mParameterMax[j]-mParameterMin[j])*maxDiff*(r-0.5);
mCandidatePoints[0][j] = std::min(mCandidatePoints[0][j], mParameterMax[j]);
mCandidatePoints[0][j] = std::max(mCandidatePoints[0][j], mParameterMin[j]);
}
mpMessageHandler->candidateChanged(0);
++mRetractionCounter;
//Evaluate new point
mpEvaluator->evaluateCandidate(0);
mPoints[mWorstId] = mCandidatePoints[0];
mObjectives[mWorstId] = mCandidateObjectives[0];
mpMessageHandler->pointChanged(mWorstId);
mpMessageHandler->objectiveChanged(mWorstId);
calculateBestAndWorstId();
mpMessageHandler->pointChanged(mWorstId);
mpMessageHandler->objectiveChanged(mWorstId);
return checkForConvergence();
}
void WorkerComplexRF::applyForgettingFactor()
{
double maxObj = mObjectives[0];
double minObj = mObjectives[0];
for(size_t i=0; i<mNumPoints; ++i)
{
double obj = mObjectives[i];
if(obj > maxObj) maxObj = obj;
if(obj < minObj) minObj = obj;
}
for(size_t i=0; i<mNumPoints; ++i)
{
mObjectives[i] = mObjectives[i]+(maxObj-minObj)*mKf;
}
mpMessageHandler->objectivesChanged();
}
<commit_msg>Fixed numbering of iterations in output from Ops.<commit_after>/*-----------------------------------------------------------------------------
This source file is a part of Hopsan
Copyright (c) 2009 to present year, Hopsan Group
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
For license details and information about the Hopsan Group see the files
GPLv3 and HOPSANGROUP in the Hopsan source code root directory
For author and contributor information see the AUTHORS file
-----------------------------------------------------------------------------*/
//!
//! @file Ops.h
//! @author Robert Braun <robert.braun@liu.se>
//! @date 2015-08-31
//!
//! @brief Contains the optimization worker class for the Complex-RF algorithm
//!
//$Id$
#include "OpsWorkerComplexRF.h"
#include "OpsEvaluator.h"
#include "OpsMessageHandler.h"
#include <math.h>
#include <sstream>
using namespace Ops;
WorkerComplexRF::WorkerComplexRF(Evaluator *pEvaluator, MessageHandler *pMessageHandler)
: WorkerSimplex(pEvaluator, pMessageHandler)
{
mRetractionCounter = 0;
}
AlgorithmT WorkerComplexRF::getAlgorithm()
{
return ComplexRF;
}
void WorkerComplexRF::initialize()
{
WorkerSimplex::initialize();
mKf = 1.0-pow(mAlpha/2.0, mGamma/mNumPoints);
}
void WorkerComplexRF::run()
{
mpMessageHandler->printMessage("Running optimization with Complex-RF algorithm.");
distributePoints();
mpEvaluator->evaluateAllPoints();
mpMessageHandler->objectivesChanged();
calculateBestAndWorstId();
//Run optimization loop
mIterationCounter=0;
for(; mIterationCounter<mnMaxIterations && !mpMessageHandler->aborted(); ++mIterationCounter)
{
//Check convergence
if(checkForConvergence()) break;
//Increase all objective values (forgetting principle)
applyForgettingFactor();
//Calculate best and worst point
calculateBestAndWorstId();
//Find geometrical center
findCentroidPoint();
//Reflect worst point
mCandidatePoints[0] = reflect(mPoints[mWorstId], mCentroidPoint, mAlpha);
mpMessageHandler->candidateChanged(0);
//std::vector<double> newPoint = mCandidatePoints[0]; //Remember the new point, in case we need to iterate below
//Evaluate new point
mpEvaluator->evaluateCandidate(0);
mPoints[mWorstId] = mCandidatePoints[0];
mObjectives[mWorstId] = mCandidateObjectives[0];
mpMessageHandler->pointChanged(mWorstId);
mpMessageHandler->objectiveChanged(mWorstId);
calculateBestAndWorstId();
mpMessageHandler->stepCompleted(mIterationCounter);
//Retract until worst point is no longer the same
mRetractionCounter = 0;
bool doBreak = false;
while(mLastWorstId == mWorstId && !mpMessageHandler->aborted())
{
// mpMessageHandler->stepCompleted(mIterationCounter);
++mIterationCounter;
mpMessageHandler->stepCompleted(mIterationCounter);
if(mIterationCounter>=mnMaxIterations)
{
--mIterationCounter; //Needed because for-loop will increase it by one anyway
break;
}
if(retract())
{
doBreak = true;
break;
}
}
if(doBreak)
{
break;
}
}
if(mpMessageHandler->aborted())
{
mpMessageHandler->printMessage("Optimization was aborted after "+std::to_string(mIterationCounter)+" iterations.");
}
else if(mIterationCounter == mnMaxIterations)
{
mpMessageHandler->printMessage(std::string("Optimization failed to converge after "+std::to_string(mIterationCounter)+" iterations"));
}
else
{
mpMessageHandler->printMessage("Optimization converged in parameter values after "+std::to_string(mIterationCounter)+" iterations.");
}
// Clean up
finalize();
return;
}
void WorkerComplexRF::setReflectionFactor(double value)
{
mAlpha = value;
}
void WorkerComplexRF::setForgettingFactor(double value)
{
mGamma = value;
}
bool WorkerComplexRF::retract()
{
std::vector<double> newPoint = mPoints[mWorstId];
//Move first reflected point
double a1 = 1.0-exp(-double(mRetractionCounter)/5.0);
for(size_t j=0; j<mNumParameters; ++j)
{
double best = mPoints[mBestId][j];
double maxDiff = getMaxPercentalParameterDiff()*10/(9.0+mRetractionCounter);
double r = opsRand();
mCandidatePoints[0][j] = (mCentroidPoint[j]*(1.0-a1) + best*a1 + newPoint[j])/2.0;
mCandidatePoints[0][j] += mRandomFactor*(mParameterMax[j]-mParameterMin[j])*maxDiff*(r-0.5);
mCandidatePoints[0][j] = std::min(mCandidatePoints[0][j], mParameterMax[j]);
mCandidatePoints[0][j] = std::max(mCandidatePoints[0][j], mParameterMin[j]);
}
mpMessageHandler->candidateChanged(0);
++mRetractionCounter;
//Evaluate new point
mpEvaluator->evaluateCandidate(0);
mPoints[mWorstId] = mCandidatePoints[0];
mObjectives[mWorstId] = mCandidateObjectives[0];
mpMessageHandler->pointChanged(mWorstId);
mpMessageHandler->objectiveChanged(mWorstId);
calculateBestAndWorstId();
mpMessageHandler->pointChanged(mWorstId);
mpMessageHandler->objectiveChanged(mWorstId);
return checkForConvergence();
}
void WorkerComplexRF::applyForgettingFactor()
{
double maxObj = mObjectives[0];
double minObj = mObjectives[0];
for(size_t i=0; i<mNumPoints; ++i)
{
double obj = mObjectives[i];
if(obj > maxObj) maxObj = obj;
if(obj < minObj) minObj = obj;
}
for(size_t i=0; i<mNumPoints; ++i)
{
mObjectives[i] = mObjectives[i]+(maxObj-minObj)*mKf;
}
mpMessageHandler->objectivesChanged();
}
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright © 2005 Jason Kivlighn <jkivlighn@gmail.com> *
* *
* 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. *
***************************************************************************/
#include <kapplication.h>
#include <KCmdLineArgs>
#include <KAboutData>
#include <QString>
#include <iostream>
using std::cout;
using std::endl;
#include "rezkonvimporter.h"
#include "rezkonvexporter.h"
#include "importertest.h"
#include "exportertest.h"
int
main(int argc, char *argv[])
{
KAboutData about("rezkonvtest", 0, ki18n("Rezkonvtest"), "1");
KCmdLineArgs::init(argc, argv, &about);
KApplication app;
printf("Creating RezkonvImporter.\n");
RezkonvImporter importer;
printf("Parsing rezkonvtest.txt.\n");
QStringList files; files << "rezkonvtest.txt";
importer.parseFiles(files);
Recipe recipe;
recipe.title = "Cookies_Test";
recipe.yield.amount = 2;
recipe.yield.amount_offset = 1;
recipe.yield.type = "dozen";
recipe.categoryList.append( Element("Snacks") );
recipe.categoryList.append( Element("Cookies & Squares") );
recipe.instructions =
"\n\nDrop by spoonful on greased cookie sheet. Bake in moderate oven.";
recipe.authorList.append( Element("Mona Beamer") );
recipe.authorList.append( Element("Colleen Beamer") );
Ingredient ing9;
ing9.name = "a";
ing9.amount = 1;
ing9.amount_offset = 0;
ing9.units.name = "cup";
IngredientData ing9_1;
ing9_1.name = "b";
ing9_1.amount = 2;
ing9_1.amount_offset = 0;
ing9_1.units.plural = "cups";
IngredientData ing9_2;
ing9_2.name = "c";
ing9_2.amount = 3;
ing9_2.amount_offset = 0;
ing9_2.units.plural = "cups";
ing9.substitutes.append(ing9_1);
ing9.substitutes.append(ing9_2);
recipe.ingList.append( ing9 );
Ingredient ing;
ing.name = "granulated sugar";
ing.amount = 0.75;
ing.amount_offset = 0.25;
ing.units.name = "c.";
ing.groupID = 0; ing.group = "Dry Ingredients";
recipe.ingList.append( ing );
Ingredient ing2;
ing2.name = "brown sugar";
ing2.amount = 1;
ing2.amount_offset = 0;
ing2.units.name = "c.";
ing2.groupID = 0; ing2.group = "Dry Ingredients";
recipe.ingList.append( ing2 );
Ingredient ing3;
ing3.name = "all-purpose flour";
ing3.amount = 2;
ing3.units.plural = "c.";
ing3.groupID = 0; ing3.group = "Dry Ingredients";
recipe.ingList.append( ing3 );
Ingredient ing4;
ing4.name = "baking soda";
ing4.amount = 1;
ing4.amount_offset = 0;
ing4.units.name = "tsp.";
ing4.groupID = 0; ing4.group = "Dry Ingredients";
recipe.ingList.append( ing4 );
Ingredient ing8;
ing8.name = "shortening";
ing8.amount = 1;
ing8.amount_offset = 0;
ing8.units.name = "c.";
ing8.prepMethodList.append( Element("softened") );
ing8.prepMethodList.append( Element("at room temperature") );
ing8.groupID = 1; ing8.group = "Fat & Liquids";
recipe.ingList.append( ing8 );
Ingredient ing6;
ing6.name = "peanut butter";
ing6.amount = 1;
ing6.amount_offset = 0;
ing6.units.name = "c.";
ing6.groupID = 1; ing6.group = "Fat & Liquids";
recipe.ingList.append( ing6 );
Ingredient ing5;
ing5.name = "eggs";
ing5.amount = 2;
ing5.amount_offset = 0;
ing5.units.plural = "";
ing5.groupID = 1; ing5.group = "Fat & Liquids";
recipe.ingList.append( ing5 );
Ingredient ing7;
ing7.name = "vanilla extract";
ing7.amount = 1;
ing7.amount_offset = 0;
ing7.units.name = "tsp.";
ing7.groupID = 1; ing7.group = "Fat & Liquids";
recipe.ingList.append( ing7 );
check( importer, recipe );
RecipeList recipeList;
recipeList.append(recipe);
recipeList.append(recipe);
printf("Creating RezkonvExporter.\n");
RezkonvExporter exporter("not needed",".rk");
check( exporter, recipeList );
printf("Successfully exported recipes to test.txt.\n");
printf("Creating RezkonvImporter to test exported recipes.\n");
RezkonvImporter importer2;
printf("Parsing test.txt.\n");
QStringList files2; files2 << "test.txt";
importer2.parseFiles(files2);
QFile::remove("test.txt");
check( importer2, recipe );
printf("Recipe export successful.\n");
printf("Done.\n");
}
<commit_msg>Amended instructions for the recipe in rezkonvtest.<commit_after>/***************************************************************************
* Copyright © 2005 Jason Kivlighn <jkivlighn@gmail.com> *
* *
* 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. *
***************************************************************************/
#include <kapplication.h>
#include <KCmdLineArgs>
#include <KAboutData>
#include <QString>
#include <iostream>
using std::cout;
using std::endl;
#include "rezkonvimporter.h"
#include "rezkonvexporter.h"
#include "importertest.h"
#include "exportertest.h"
int
main(int argc, char *argv[])
{
KAboutData about("rezkonvtest", 0, ki18n("Rezkonvtest"), "1");
KCmdLineArgs::init(argc, argv, &about);
KApplication app;
printf("Creating RezkonvImporter.\n");
RezkonvImporter importer;
printf("Parsing rezkonvtest.txt.\n");
QStringList files; files << "rezkonvtest.txt";
importer.parseFiles(files);
Recipe recipe;
recipe.title = "Cookies_Test";
recipe.yield.amount = 2;
recipe.yield.amount_offset = 1;
recipe.yield.type = "dozen";
recipe.categoryList.append( Element("Snacks") );
recipe.categoryList.append( Element("Cookies & Squares") );
recipe.instructions =
"Drop by spoonful on greased cookie sheet. Bake in moderate oven.";
recipe.authorList.append( Element("Mona Beamer") );
recipe.authorList.append( Element("Colleen Beamer") );
Ingredient ing9;
ing9.name = "a";
ing9.amount = 1;
ing9.amount_offset = 0;
ing9.units.name = "cup";
IngredientData ing9_1;
ing9_1.name = "b";
ing9_1.amount = 2;
ing9_1.amount_offset = 0;
ing9_1.units.plural = "cups";
IngredientData ing9_2;
ing9_2.name = "c";
ing9_2.amount = 3;
ing9_2.amount_offset = 0;
ing9_2.units.plural = "cups";
ing9.substitutes.append(ing9_1);
ing9.substitutes.append(ing9_2);
recipe.ingList.append( ing9 );
Ingredient ing;
ing.name = "granulated sugar";
ing.amount = 0.75;
ing.amount_offset = 0.25;
ing.units.name = "c.";
ing.groupID = 0; ing.group = "Dry Ingredients";
recipe.ingList.append( ing );
Ingredient ing2;
ing2.name = "brown sugar";
ing2.amount = 1;
ing2.amount_offset = 0;
ing2.units.name = "c.";
ing2.groupID = 0; ing2.group = "Dry Ingredients";
recipe.ingList.append( ing2 );
Ingredient ing3;
ing3.name = "all-purpose flour";
ing3.amount = 2;
ing3.units.plural = "c.";
ing3.groupID = 0; ing3.group = "Dry Ingredients";
recipe.ingList.append( ing3 );
Ingredient ing4;
ing4.name = "baking soda";
ing4.amount = 1;
ing4.amount_offset = 0;
ing4.units.name = "tsp.";
ing4.groupID = 0; ing4.group = "Dry Ingredients";
recipe.ingList.append( ing4 );
Ingredient ing8;
ing8.name = "shortening";
ing8.amount = 1;
ing8.amount_offset = 0;
ing8.units.name = "c.";
ing8.prepMethodList.append( Element("softened") );
ing8.prepMethodList.append( Element("at room temperature") );
ing8.groupID = 1; ing8.group = "Fat & Liquids";
recipe.ingList.append( ing8 );
Ingredient ing6;
ing6.name = "peanut butter";
ing6.amount = 1;
ing6.amount_offset = 0;
ing6.units.name = "c.";
ing6.groupID = 1; ing6.group = "Fat & Liquids";
recipe.ingList.append( ing6 );
Ingredient ing5;
ing5.name = "eggs";
ing5.amount = 2;
ing5.amount_offset = 0;
ing5.units.plural = "";
ing5.groupID = 1; ing5.group = "Fat & Liquids";
recipe.ingList.append( ing5 );
Ingredient ing7;
ing7.name = "vanilla extract";
ing7.amount = 1;
ing7.amount_offset = 0;
ing7.units.name = "tsp.";
ing7.groupID = 1; ing7.group = "Fat & Liquids";
recipe.ingList.append( ing7 );
check( importer, recipe );
RecipeList recipeList;
recipeList.append(recipe);
recipeList.append(recipe);
printf("Creating RezkonvExporter.\n");
RezkonvExporter exporter("not needed",".rk");
check( exporter, recipeList );
printf("Successfully exported recipes to test.txt.\n");
printf("Creating RezkonvImporter to test exported recipes.\n");
RezkonvImporter importer2;
printf("Parsing test.txt.\n");
QStringList files2; files2 << "test.txt";
importer2.parseFiles(files2);
QFile::remove("test.txt");
check( importer2, recipe );
printf("Recipe export successful.\n");
printf("Done.\n");
}
<|endoftext|> |
<commit_before>
#include "StringUtil.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
namespace VersionControl
{
bool StringUtil::endsWith(const std::string &from, const std::string &what)
{
if (from.length() < what.length())
return false;
std::string::const_reverse_iterator i1 = from.rbegin();
std::string::const_reverse_iterator i2 = what.rbegin();
for (; i2 != what.rend(); i2++, i1++)
{
if (*i1 != *i2)
return false;
}
return true;
}
bool StringUtil::startsWith(const std::string &from, const std::string &what)
{
if (from.length() < what.length())
return false;
std::string::const_iterator i1 = from.begin();
std::string::const_iterator i2 = what.begin();
for (; i2 != what.end(); i2++, i1++)
{
if (*i1 != *i2)
return false;
}
return true;
}
std::string StringUtil::SplitByLastOf(const std::string &s, const char lastOf, bool keepFirst)
{
size_t splitpos = s.find_last_of(lastOf);
if (splitpos == std::string::npos)
return s;
if (keepFirst)
return s.substr(0, splitpos);
else
return s.substr(splitpos + 1, s.length() - splitpos - 1);
}
std::string StringUtil::SplitByFirstOf(const std::string &s, const char firstOf, bool keepFirst)
{
size_t splitpos = s.find_first_of(firstOf);
if (splitpos == std::string::npos)
return s;
if (keepFirst)
return s.substr(0, splitpos);
else
return s.substr(splitpos + 1, s.length() - splitpos - 1);
}
bool StringUtil::Contains(const std::string &s, const std::string &string)
{
return (s.find(string) != std::string::npos);
}
std::string StringUtil::TrimEnd(const std::string &str, char c)
{
std::string::size_type i1 = str.length() - 1;
while (i1 >= 0 && str[i1] == c)
{
--i1;
}
if (i1 < 0)
return "";
return str.substr(0, i1 + 1);
}
std::string StringUtil::TrimStart(const std::string &str, char c)
{
std::string::size_type iend = str.length();
std::string::size_type i1 = 0;
while (i1 < iend && str[i1] == c)
{
++i1;
}
if (i1 >= iend)
return "";
return str.substr(i1);
}
std::string StringUtil::Trim(const std::string &str, char c)
{
return TrimStart(TrimEnd(str, c), c);
}
void StringUtil::Split(std::string &s, const char delim, std::vector<std::string> &out)
{
std::string::size_type lastPos = s.find_first_not_of(delim, 0);
std::string::size_type pos = s.find_first_of(delim, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
out.push_back(s.substr(lastPos, pos - lastPos));
lastPos = s.find_first_not_of(delim, pos);
pos = s.find_first_of(delim, lastPos);
}
}
bool StringUtil::IsPositiveNumber(const std::string &s)
{
return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit);
}
bool StringUtil::startsWithAndAssign(const std::string &line, const char *prefix, std::string &dest, bool trim)
{
if (StringUtil::startsWith(line, prefix))
{
dest = line.substr(strlen(prefix));
if (trim)
{
dest = TrimStart(dest, ' ');
dest = TrimStart(dest, '\t');
}
return true;
}
return false;
}
}<commit_msg>Added empty string check to trims<commit_after>
#include "StringUtil.hpp"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
namespace VersionControl
{
bool StringUtil::endsWith(const std::string &from, const std::string &what)
{
if (from.length() < what.length())
return false;
std::string::const_reverse_iterator i1 = from.rbegin();
std::string::const_reverse_iterator i2 = what.rbegin();
for (; i2 != what.rend(); i2++, i1++)
{
if (*i1 != *i2)
return false;
}
return true;
}
bool StringUtil::startsWith(const std::string &from, const std::string &what)
{
if (from.length() < what.length())
return false;
std::string::const_iterator i1 = from.begin();
std::string::const_iterator i2 = what.begin();
for (; i2 != what.end(); i2++, i1++)
{
if (*i1 != *i2)
return false;
}
return true;
}
std::string StringUtil::SplitByLastOf(const std::string &s, const char lastOf, bool keepFirst)
{
size_t splitpos = s.find_last_of(lastOf);
if (splitpos == std::string::npos)
return s;
if (keepFirst)
return s.substr(0, splitpos);
else
return s.substr(splitpos + 1, s.length() - splitpos - 1);
}
std::string StringUtil::SplitByFirstOf(const std::string &s, const char firstOf, bool keepFirst)
{
size_t splitpos = s.find_first_of(firstOf);
if (splitpos == std::string::npos)
return s;
if (keepFirst)
return s.substr(0, splitpos);
else
return s.substr(splitpos + 1, s.length() - splitpos - 1);
}
bool StringUtil::Contains(const std::string &s, const std::string &string)
{
return (s.find(string) != std::string::npos);
}
std::string StringUtil::TrimEnd(const std::string &str, char c)
{
if(str.empty())
{
return "";
}
std::string::size_type i1 = str.length() - 1;
while (i1 >= 0 && str[i1] == c)
{
--i1;
}
if(i1 < 0)
{
return "";
}
return str.substr(0, i1 + 1);
}
std::string StringUtil::TrimStart(const std::string &str, char c)
{
if(str.empty())
{
return "";
}
std::string::size_type iend = str.length();
std::string::size_type i1 = 0;
while (i1 < iend && str[i1] == c)
{
++i1;
}
if(i1 >= iend)
{
return "";
}
return str.substr(i1);
}
std::string StringUtil::Trim(const std::string &str, char c)
{
return TrimStart(TrimEnd(str, c), c);
}
void StringUtil::Split(std::string &s, const char delim, std::vector<std::string> &out)
{
std::string::size_type lastPos = s.find_first_not_of(delim, 0);
std::string::size_type pos = s.find_first_of(delim, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
out.push_back(s.substr(lastPos, pos - lastPos));
lastPos = s.find_first_not_of(delim, pos);
pos = s.find_first_of(delim, lastPos);
}
}
bool StringUtil::IsPositiveNumber(const std::string &s)
{
return !s.empty() && std::all_of(s.begin(), s.end(), ::isdigit);
}
bool StringUtil::startsWithAndAssign(const std::string &line, const char *prefix, std::string &dest, bool trim)
{
if (StringUtil::startsWith(line, prefix))
{
dest = line.substr(strlen(prefix));
if (trim)
{
dest = TrimStart(dest, ' ');
dest = TrimStart(dest, '\t');
}
return true;
}
return false;
}
}<|endoftext|> |
<commit_before>#include "Utility.h"
#include "TraceLog.h"
#include "RegKeyPrivilege.h"
#include <VersionHelpers.h>
#include <ShlObj.h>
#include <tchar.h>
#include <xl/Meta/xlScopeExit.h>
#include <xl/Win32/Registry/xlRegistry.h>
// Win8
#define REG_MSPY_ROOT_80 _T("SOFTWARE\\Microsoft\\CTF\\TIP\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35e}") // ·ҪȨ
// Win8.1
#define REG_MSPY_ROOT_81 _T("SOFTWARE\\Microsoft\\CTF\\TIP\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35f}") // ·
#define REG_MSPY_PATH_SF _T("\\LanguageProfile\\0x00000804\\{FA550B04-5AD7-411f-A5AC-CA038EC515D7}") // ƴƴעҪɾ
#define REG_MSPY_PATH_NE _T("\\LanguageProfile\\0x00000804\\{F3BA9077-6C7E-11D4-97FA-0080C882687E}") // ƴ
// ֧ Metro Ӧõ GUID http://msdn.microsoft.com/zh-cn/library/windows/apps/hh967425.aspx#SET_COMPATIBILITY_FLAG
#define REG_MSPY_PATH_CATEGORY_IMMERSIVESUPPORT _T("\\Category\\Category\\{13A016DF-560B-46CD-947A-4C3AF1E0E35D}\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35e}")
#define REG_MSPY_PATH_CATEGORY_ITEM_IMMERSIVESUPPORT _T("\\Category\\Item\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35e}\\{13A016DF-560B-46CD-947A-4C3AF1E0E35D}")
// ֧ͼ
#define REG_MSPY_PATH_CATEGORY_SYSTRAYSUPPORT _T("\\Category\\Category\\{25504FB4-7BAB-4BC1-9C69-CF81890F0EF5}\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35e}")
#define REG_MSPY_PATH_CATEGORY_ITEM_SYSTRAYSUPPORT _T("\\Category\\Item\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35e}\\{25504FB4-7BAB-4BC1-9C69-CF81890F0EF5}")
// Win8Win8.1
#define REG_MSPY_KEY_DESC _T("Display Description")
#define REG_MSPY_VALUE_DESC_NE _T("@%SystemRoot%\\SYSTEM32\\input.dll,-5091")
#define REG_MSPY_KEY_ICON _T("IconFile")
#define REG_MSPY_VALUE_ICON_NE _T("%SystemRoot%\\SYSTEM32\\InputMethod\\Shared\\ResourceDll.dll")
bool Utility::IsWow64()
{
typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(_T("kernel32")), "IsWow64Process");
BOOL bIsWow64 = FALSE;
if (fnIsWow64Process != nullptr)
{
if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
{
XL_ERROR(_T("Failed to call IsWow64Process."));
}
}
return !!bIsWow64;
}
OSVersion Utility::GetOSVersion()
{
XL_INFO_FUNCTION();
OSVersion osv = OSV_Other;
do
{
if (IsWindows8OrGreater())
{
osv = OSV_Win8;
}
if (IsWindows8Point1OrGreater())
{
osv = OSV_Win81;
}
if (IsWindowsVersionOrGreater(6, 4, 0) || IsWindowsVersionOrGreater(7, 0, 0))
{
osv = OSV_Other;
}
} while (false);
return osv;
}
bool Utility::SetPrivilege(LPCTSTR szPrivilegeName, bool bEnable)
{
XL_INFO_FUNCTION();
HANDLE hProcess = GetCurrentProcess();
HANDLE hToken = NULL;
if (!OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
XL_ERROR(_T("Failed to open current process token."));
return false;
}
XL_ON_BLOCK_EXIT(CloseHandle, hToken);
LUID luid = {};
if (!LookupPrivilegeValue(NULL, szPrivilegeName, &luid))
{
XL_ERROR(_T("Failed to look up privilege value."));
return false;
}
TOKEN_PRIVILEGES tp = {};
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if (bEnable)
{
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
}
else
{
tp.Privileges[0].Attributes = SE_PRIVILEGE_REMOVED;
}
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
{
XL_ERROR(_T("Failed to adjust token privileges."));
return false;
}
return true;
}
xl::String Utility::GetKnownDir(int csidl)
{
TCHAR szPath[MAX_PATH] = {};
if (FAILED(SHGetFolderPath(nullptr, csidl, nullptr, SHGFP_TYPE_CURRENT, szPath)))
{
XL_ERROR(_T("Failed to get known directory."));
return _T("");
}
return szPath;
}
xl::String Utility::GetSystemDir()
{
return GetKnownDir(CSIDL_SYSTEM);
}
xl::String Utility::GetSysWow64Dir()
{
TCHAR szPath[MAX_PATH] = {};
if (GetSystemWow64Directory(szPath, _countof(szPath)) == 0)
{
return _T("");
}
return szPath;
}
xl::String Utility::GetWinDir()
{
return GetKnownDir(CSIDL_WINDOWS);
}
xl::String Utility::GetExeDir()
{
xl::String strPath = GetExePath();
int iPos = strPath.LastIndexOf(_T("\\"));
return strPath.SubString(0, iPos);
}
xl::String Utility::GetExePath()
{
TCHAR szPath[MAX_PATH] = {};
if (GetModuleFileName(nullptr, szPath, _countof(szPath)) == 0)
{
XL_ERROR(_T("Failed to get exe directory."));
return _T("");
}
return szPath;
}
bool Utility::SHCopyDir(HWND hWnd, LPCTSTR lpszSourceDir, LPCTSTR lpszDestDir)
{
xl::String strSourceDir = lpszSourceDir;
xl::String strDestDir = lpszDestDir;
strSourceDir.AppendBack(_T('\0'));
strDestDir.AppendBack(_T('\0'));
SHFILEOPSTRUCT op = {};
op.hwnd = hWnd;
op.wFunc = FO_COPY;
op.pFrom = strSourceDir.GetAddress();
op.pTo = strDestDir.GetAddress();
int iErrorCode = SHFileOperation(&op);
if (iErrorCode != ERROR_SUCCESS)
{
return false;
}
return true;
}
bool Utility::RunProcess(LPCTSTR lpszCmdLine, bool bWait/* = true*/)
{
STARTUPINFOW si = { sizeof(STARTUPINFOW) };
PROCESS_INFORMATION pi = {};
int iLen = (int)_tcslen(lpszCmdLine) + 1;
xl::SharedArray<TCHAR> lp = new TCHAR[iLen];
_tcscpy_s(lp.RawPointer(), iLen, lpszCmdLine);
if (!CreateProcess(nullptr, lp.RawPointer(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi))
{
XL_ERROR(_T("Failed to create process with CmdLine: %s."), lpszCmdLine);
return false;
}
if (bWait)
{
WaitForSingleObject(pi.hProcess, INFINITE);
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return true;
}
bool Utility::RegisterComDll(LPCTSTR lpszFileName)
{
XL_INFO_FUNCTION();
xl::String strCmdLine = _T("regsvr32 /s ");
strCmdLine += _T("\"");
strCmdLine += lpszFileName;
strCmdLine += _T("\"");
if (!RunProcess(strCmdLine.GetAddress()))
{
return false;
}
return true;
}
bool Utility::MergeRegFile(LPCTSTR lpszFileName)
{
XL_INFO_FUNCTION();
xl::String strCmdLine = _T("regedit /s ");
strCmdLine += _T("\"");
strCmdLine += lpszFileName;
strCmdLine += _T("\"");
if (!RunProcess(strCmdLine.GetAddress()))
{
return false;
}
return true;
}
bool Utility::GetMspyForWin8()
{
RegKeyOwnerDaclAquireRestoreRec r(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_80);
xl::String strPath = Utility::GetSystemDir() + _T("\\IME\\IMESC\\IMSCTIP.dll");
if (!Utility::RegisterComDll(strPath.GetAddress()))
{
XL_ERROR(_T("Failed to register IMSCTIP.dll."));
return false;
}
#ifdef _WIN64
strPath = Utility::GetSysWow64Dir() + _T("\\IME\\IMESC\\IMSCTIP.dll");
if (!Utility::RegisterComDll(strPath.GetAddress()))
{
XL_ERROR(_T("Failed to register IMSCTIP.dll."));
return false;
}
#endif
if (!xl::Registry::SetExpandString(HKEY_LOCAL_MACHINE,
REG_MSPY_ROOT_80 REG_MSPY_PATH_NE,
REG_MSPY_KEY_DESC,
REG_MSPY_VALUE_DESC_NE))
{
XL_ERROR(_T("Failed to set IME display description."));
return false;
}
return true;
}
bool Utility::GetMspyForWin81()
{
xl::String strExePath = Utility::GetExeDir();
struct SourceDestFolder
{
xl::String strSource;
xl::String strDest;
};
SourceDestFolder folderMap[] =
{
{ strExePath + _T("\\Files\\Windows\\IME\\IMESC\0"), Utility::GetWinDir() + _T("\\IME\\\0") },
#ifdef _WIN64
{ strExePath + _T("\\Files\\Windows\\System32\\IME\\IMESC\0"), Utility::GetSystemDir() + _T("\\IME\\\0") },
{ strExePath + _T("\\Files\\Windows\\SysWOW64\\IME\\IMESC\0"), Utility::GetSysWow64Dir() + _T("\\IME\\\0") },
#else
{ strExePath + _T("\\Files\\Windows\\SysWOW64\\IME\\IMESC\0"), Utility::GetSystemDir() + _T("\\IME\\\0") },
#endif
};
for (int i = 0; i < _countof(folderMap); ++i)
{
if (!Utility::SHCopyDir(nullptr, folderMap[i].strSource.GetAddress(), folderMap[i].strDest.GetAddress()))
{
XL_ERROR(_T("Failed to copy folder %s."), folderMap[i].strSource.GetAddress());
return false;
}
}
LPCTSTR lpszDllFiles[] =
{
_T("\\ImSCCfg.dll"),
_T("\\ImSCCore.dll"),
_T("\\IMSCDICB.dll"),
_T("\\IMSCTIP.dll"),
_T("\\applets\\PINTLCSA.dll"),
_T("\\applets\\PINTLMBX.dll"),
};
xl::String strPath = Utility::GetSystemDir() + _T("\\IME\\IMESC");
for (int i = 0; i < _countof(lpszDllFiles); ++i)
{
if (!Utility::RegisterComDll((strPath + lpszDllFiles[i]).GetAddress()))
{
XL_ERROR(_T("Failed to register %s."), (strPath + lpszDllFiles[i]).GetAddress());
return false;
}
}
#ifdef _WIN64
strPath = Utility::GetSysWow64Dir() + _T("\\IME\\IMESC");
for (int i = 0; i < _countof(lpszDllFiles); ++i)
{
if (!Utility::RegisterComDll((strPath + lpszDllFiles[i]).GetAddress()))
{
XL_ERROR(_T("Failed to register %s."), (strPath + lpszDllFiles[i]).GetAddress());
return false;
}
}
#endif
if (!xl::Registry::DeleteKeyRecursion(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_SF))
{
XL_ERROR(_T("Failed to delete MSPY SimpleFast."));
}
if (!xl::Registry::SetExpandString(HKEY_LOCAL_MACHINE,
REG_MSPY_ROOT_81 REG_MSPY_PATH_NE,
REG_MSPY_KEY_DESC,
REG_MSPY_VALUE_DESC_NE))
{
XL_ERROR(_T("Failed to set IME display description."));
return false;
}
if (!xl::Registry::SetExpandString(HKEY_LOCAL_MACHINE,
REG_MSPY_ROOT_81 REG_MSPY_PATH_NE,
REG_MSPY_KEY_ICON,
REG_MSPY_VALUE_ICON_NE))
{
XL_ERROR(_T("Failed to set IME icon."));
return false;
}
if (!xl::Registry::CreateKey(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_CATEGORY_IMMERSIVESUPPORT) ||
!xl::Registry::CreateKey(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_CATEGORY_ITEM_IMMERSIVESUPPORT))
{
XL_WARNING(_T("Failed to declare Metro compatibility."));
}
if (!xl::Registry::CreateKey(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_CATEGORY_SYSTRAYSUPPORT) ||
!xl::Registry::CreateKey(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_CATEGORY_ITEM_SYSTRAYSUPPORT))
{
XL_WARNING(_T("Failed to declare systray support."));
}
if (!Utility::MergeRegFile((strExePath + _T("\\Files\\Dict.reg")).GetAddress()))
{
XL_WARNING(_T("Failed to register dictionaries."));
}
return true;
}
<commit_msg>bug. i am sb.<commit_after>#include "Utility.h"
#include "TraceLog.h"
#include "RegKeyPrivilege.h"
#include <VersionHelpers.h>
#include <ShlObj.h>
#include <tchar.h>
#include <xl/Meta/xlScopeExit.h>
#include <xl/Win32/Registry/xlRegistry.h>
// Win8
#define REG_MSPY_ROOT_80 _T("SOFTWARE\\Microsoft\\CTF\\TIP\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35e}") // ·ҪȨ
// Win8.1
#define REG_MSPY_ROOT_81 _T("SOFTWARE\\Microsoft\\CTF\\TIP\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35f}") // ·
#define REG_MSPY_PATH_SF _T("\\LanguageProfile\\0x00000804\\{FA550B04-5AD7-411f-A5AC-CA038EC515D7}") // ƴƴעҪɾ
#define REG_MSPY_PATH_NE _T("\\LanguageProfile\\0x00000804\\{F3BA9077-6C7E-11D4-97FA-0080C882687E}") // ƴ
// ֧ Metro Ӧõ GUID http://msdn.microsoft.com/zh-cn/library/windows/apps/hh967425.aspx#SET_COMPATIBILITY_FLAG
#define REG_MSPY_PATH_CATEGORY_IMMERSIVESUPPORT_NE _T("\\Category\\Category\\{13A016DF-560B-46CD-947A-4C3AF1E0E35D}\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35f}")
#define REG_MSPY_PATH_CATEGORY_ITEM_IMMERSIVESUPPORT_NE _T("\\Category\\Item\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35f}\\{13A016DF-560B-46CD-947A-4C3AF1E0E35D}")
// ֧ͼ
#define REG_MSPY_PATH_CATEGORY_SYSTRAYSUPPORT_NE _T("\\Category\\Category\\{25504FB4-7BAB-4BC1-9C69-CF81890F0EF5}\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35f}")
#define REG_MSPY_PATH_CATEGORY_ITEM_SYSTRAYSUPPORT_NE _T("\\Category\\Item\\{81d4e9c9-1d3b-41bc-9e6c-4b40bf79e35f}\\{25504FB4-7BAB-4BC1-9C69-CF81890F0EF5}")
// Win8Win8.1
#define REG_MSPY_KEY_DESC _T("Display Description")
#define REG_MSPY_VALUE_DESC_NE _T("@%SystemRoot%\\SYSTEM32\\input.dll,-5091")
#define REG_MSPY_KEY_ICON _T("IconFile")
#define REG_MSPY_VALUE_ICON_NE _T("%SystemRoot%\\SYSTEM32\\InputMethod\\Shared\\ResourceDll.dll")
bool Utility::IsWow64()
{
typedef BOOL(WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(GetModuleHandle(_T("kernel32")), "IsWow64Process");
BOOL bIsWow64 = FALSE;
if (fnIsWow64Process != nullptr)
{
if (!fnIsWow64Process(GetCurrentProcess(), &bIsWow64))
{
XL_ERROR(_T("Failed to call IsWow64Process."));
}
}
return !!bIsWow64;
}
OSVersion Utility::GetOSVersion()
{
XL_INFO_FUNCTION();
OSVersion osv = OSV_Other;
do
{
if (IsWindows8OrGreater())
{
osv = OSV_Win8;
}
if (IsWindows8Point1OrGreater())
{
osv = OSV_Win81;
}
if (IsWindowsVersionOrGreater(6, 4, 0) || IsWindowsVersionOrGreater(7, 0, 0))
{
osv = OSV_Other;
}
} while (false);
return osv;
}
bool Utility::SetPrivilege(LPCTSTR szPrivilegeName, bool bEnable)
{
XL_INFO_FUNCTION();
HANDLE hProcess = GetCurrentProcess();
HANDLE hToken = NULL;
if (!OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
{
XL_ERROR(_T("Failed to open current process token."));
return false;
}
XL_ON_BLOCK_EXIT(CloseHandle, hToken);
LUID luid = {};
if (!LookupPrivilegeValue(NULL, szPrivilegeName, &luid))
{
XL_ERROR(_T("Failed to look up privilege value."));
return false;
}
TOKEN_PRIVILEGES tp = {};
tp.PrivilegeCount = 1;
tp.Privileges[0].Luid = luid;
if (bEnable)
{
tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
}
else
{
tp.Privileges[0].Attributes = SE_PRIVILEGE_REMOVED;
}
if (!AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL, (PDWORD)NULL))
{
XL_ERROR(_T("Failed to adjust token privileges."));
return false;
}
return true;
}
xl::String Utility::GetKnownDir(int csidl)
{
TCHAR szPath[MAX_PATH] = {};
if (FAILED(SHGetFolderPath(nullptr, csidl, nullptr, SHGFP_TYPE_CURRENT, szPath)))
{
XL_ERROR(_T("Failed to get known directory."));
return _T("");
}
return szPath;
}
xl::String Utility::GetSystemDir()
{
return GetKnownDir(CSIDL_SYSTEM);
}
xl::String Utility::GetSysWow64Dir()
{
TCHAR szPath[MAX_PATH] = {};
if (GetSystemWow64Directory(szPath, _countof(szPath)) == 0)
{
return _T("");
}
return szPath;
}
xl::String Utility::GetWinDir()
{
return GetKnownDir(CSIDL_WINDOWS);
}
xl::String Utility::GetExeDir()
{
xl::String strPath = GetExePath();
int iPos = strPath.LastIndexOf(_T("\\"));
return strPath.SubString(0, iPos);
}
xl::String Utility::GetExePath()
{
TCHAR szPath[MAX_PATH] = {};
if (GetModuleFileName(nullptr, szPath, _countof(szPath)) == 0)
{
XL_ERROR(_T("Failed to get exe directory."));
return _T("");
}
return szPath;
}
bool Utility::SHCopyDir(HWND hWnd, LPCTSTR lpszSourceDir, LPCTSTR lpszDestDir)
{
xl::String strSourceDir = lpszSourceDir;
xl::String strDestDir = lpszDestDir;
strSourceDir.AppendBack(_T('\0'));
strDestDir.AppendBack(_T('\0'));
SHFILEOPSTRUCT op = {};
op.hwnd = hWnd;
op.wFunc = FO_COPY;
op.pFrom = strSourceDir.GetAddress();
op.pTo = strDestDir.GetAddress();
int iErrorCode = SHFileOperation(&op);
if (iErrorCode != ERROR_SUCCESS)
{
return false;
}
return true;
}
bool Utility::RunProcess(LPCTSTR lpszCmdLine, bool bWait/* = true*/)
{
STARTUPINFOW si = { sizeof(STARTUPINFOW) };
PROCESS_INFORMATION pi = {};
int iLen = (int)_tcslen(lpszCmdLine) + 1;
xl::SharedArray<TCHAR> lp = new TCHAR[iLen];
_tcscpy_s(lp.RawPointer(), iLen, lpszCmdLine);
if (!CreateProcess(nullptr, lp.RawPointer(), nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi))
{
XL_ERROR(_T("Failed to create process with CmdLine: %s."), lpszCmdLine);
return false;
}
if (bWait)
{
WaitForSingleObject(pi.hProcess, INFINITE);
}
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
return true;
}
bool Utility::RegisterComDll(LPCTSTR lpszFileName)
{
XL_INFO_FUNCTION();
xl::String strCmdLine = _T("regsvr32 /s ");
strCmdLine += _T("\"");
strCmdLine += lpszFileName;
strCmdLine += _T("\"");
if (!RunProcess(strCmdLine.GetAddress()))
{
return false;
}
return true;
}
bool Utility::MergeRegFile(LPCTSTR lpszFileName)
{
XL_INFO_FUNCTION();
xl::String strCmdLine = _T("regedit /s ");
strCmdLine += _T("\"");
strCmdLine += lpszFileName;
strCmdLine += _T("\"");
if (!RunProcess(strCmdLine.GetAddress()))
{
return false;
}
return true;
}
bool Utility::GetMspyForWin8()
{
RegKeyOwnerDaclAquireRestoreRec r(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_80);
xl::String strPath = Utility::GetSystemDir() + _T("\\IME\\IMESC\\IMSCTIP.dll");
if (!Utility::RegisterComDll(strPath.GetAddress()))
{
XL_ERROR(_T("Failed to register IMSCTIP.dll."));
return false;
}
#ifdef _WIN64
strPath = Utility::GetSysWow64Dir() + _T("\\IME\\IMESC\\IMSCTIP.dll");
if (!Utility::RegisterComDll(strPath.GetAddress()))
{
XL_ERROR(_T("Failed to register IMSCTIP.dll."));
return false;
}
#endif
if (!xl::Registry::SetExpandString(HKEY_LOCAL_MACHINE,
REG_MSPY_ROOT_80 REG_MSPY_PATH_NE,
REG_MSPY_KEY_DESC,
REG_MSPY_VALUE_DESC_NE))
{
XL_ERROR(_T("Failed to set IME display description."));
return false;
}
return true;
}
bool Utility::GetMspyForWin81()
{
xl::String strExePath = Utility::GetExeDir();
struct SourceDestFolder
{
xl::String strSource;
xl::String strDest;
};
SourceDestFolder folderMap[] =
{
{ strExePath + _T("\\Files\\Windows\\IME\\IMESC\0"), Utility::GetWinDir() + _T("\\IME\\\0") },
#ifdef _WIN64
{ strExePath + _T("\\Files\\Windows\\System32\\IME\\IMESC\0"), Utility::GetSystemDir() + _T("\\IME\\\0") },
{ strExePath + _T("\\Files\\Windows\\SysWOW64\\IME\\IMESC\0"), Utility::GetSysWow64Dir() + _T("\\IME\\\0") },
#else
{ strExePath + _T("\\Files\\Windows\\SysWOW64\\IME\\IMESC\0"), Utility::GetSystemDir() + _T("\\IME\\\0") },
#endif
};
for (int i = 0; i < _countof(folderMap); ++i)
{
if (!Utility::SHCopyDir(nullptr, folderMap[i].strSource.GetAddress(), folderMap[i].strDest.GetAddress()))
{
XL_ERROR(_T("Failed to copy folder %s."), folderMap[i].strSource.GetAddress());
return false;
}
}
LPCTSTR lpszDllFiles[] =
{
_T("\\ImSCCfg.dll"),
_T("\\ImSCCore.dll"),
_T("\\IMSCDICB.dll"),
_T("\\IMSCTIP.dll"),
_T("\\applets\\PINTLCSA.dll"),
_T("\\applets\\PINTLMBX.dll"),
};
xl::String strPath = Utility::GetSystemDir() + _T("\\IME\\IMESC");
for (int i = 0; i < _countof(lpszDllFiles); ++i)
{
if (!Utility::RegisterComDll((strPath + lpszDllFiles[i]).GetAddress()))
{
XL_ERROR(_T("Failed to register %s."), (strPath + lpszDllFiles[i]).GetAddress());
return false;
}
}
#ifdef _WIN64
strPath = Utility::GetSysWow64Dir() + _T("\\IME\\IMESC");
for (int i = 0; i < _countof(lpszDllFiles); ++i)
{
if (!Utility::RegisterComDll((strPath + lpszDllFiles[i]).GetAddress()))
{
XL_ERROR(_T("Failed to register %s."), (strPath + lpszDllFiles[i]).GetAddress());
return false;
}
}
#endif
if (!xl::Registry::DeleteKeyRecursion(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_SF))
{
XL_ERROR(_T("Failed to delete MSPY SimpleFast."));
}
if (!xl::Registry::SetExpandString(HKEY_LOCAL_MACHINE,
REG_MSPY_ROOT_81 REG_MSPY_PATH_NE,
REG_MSPY_KEY_DESC,
REG_MSPY_VALUE_DESC_NE))
{
XL_ERROR(_T("Failed to set IME display description."));
return false;
}
if (!xl::Registry::SetExpandString(HKEY_LOCAL_MACHINE,
REG_MSPY_ROOT_81 REG_MSPY_PATH_NE,
REG_MSPY_KEY_ICON,
REG_MSPY_VALUE_ICON_NE))
{
XL_ERROR(_T("Failed to set IME icon."));
return false;
}
if (!xl::Registry::CreateKey(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_CATEGORY_IMMERSIVESUPPORT_NE) ||
!xl::Registry::CreateKey(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_CATEGORY_ITEM_IMMERSIVESUPPORT_NE))
{
XL_WARNING(_T("Failed to declare Metro compatibility."));
}
if (!xl::Registry::CreateKey(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_CATEGORY_SYSTRAYSUPPORT_NE) ||
!xl::Registry::CreateKey(HKEY_LOCAL_MACHINE, REG_MSPY_ROOT_81 REG_MSPY_PATH_CATEGORY_ITEM_SYSTRAYSUPPORT_NE))
{
XL_WARNING(_T("Failed to declare systray support."));
}
if (!Utility::MergeRegFile((strExePath + _T("\\Files\\Dict.reg")).GetAddress()))
{
XL_WARNING(_T("Failed to register dictionaries."));
}
return true;
}
<|endoftext|> |
<commit_before>//Tested on:
// Solaris 11.2 (g++)
#include "netstat.hpp"
#include <cstdlib>
#include <stdexcept>
#include <iomanip>
#include <iostream>
#include <string>
#include <stdint.h>
#include <sstream>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stropts.h>
#include <cstring>
#include <sys/tihdr.h>
#include <inet/mib2.h>
#include "netstat_util.hpp"
#include "string_util.hpp"
class buffer_t
{
public:
char buffer[512];
strbuf buf;
buffer_t()
{
memset(buffer,0,512);
buf.buf=(char*)buffer;
buf.len=512;
}
};
struct request_t
{
public:
request_t()
{
req_header.PRIM_type=T_SVR4_OPTMGMT_REQ;
req_header.OPT_length=sizeof(opt_header);
req_header.OPT_offset=offsetof(request_t,opt_header);
req_header.MGMT_flags=T_CURRENT;
opt_header.level=MIB2_IP;
opt_header.name=0;
opt_header.len=0;
}
T_optmgmt_req req_header;
opthdr opt_header;
};
struct reply_t
{
T_optmgmt_ack ack_header;
opthdr opt_header;
};
static std::string state_int_to_string(const uint32_t state)
{
if(state==MIB2_TCP_established)
return "ESTABLISHED";
if(state==MIB2_TCP_synSent)
return "SYN_SENT";
if(state==MIB2_TCP_synReceived)
return "SYN_RECV";
if(state==MIB2_TCP_finWait1)
return "FIN_WAIT1";
if(state==MIB2_TCP_finWait2)
return "FIN_WAIT2";
if(state==MIB2_TCP_timeWait)
return "TIME_WAIT";
if(state==MIB2_TCP_closed)
return "CLOSE";
if(state==MIB2_TCP_closeWait)
return "CLOSE_WAIT";
if(state==MIB2_TCP_lastAck)
return "LAST_ACK";
if(state==MIB2_TCP_listen)
return "LISTEN";
if(state==MIB2_TCP_closing||state==MIB2_TCP_deleteTCB)
return "CLOSING";
return "UNKNOWN";
}
netstat_list_t netstat()
{
int fd=open("/dev/arp",O_RDWR);
if(fd==-1)
throw std::runtime_error("netstat_solaris() - Could not find /dev/arp.");
if(ioctl(fd,I_PUSH,"tcp")==-1)
throw std::runtime_error("netstat_solaris() - Could not push module tcp into /dev/arp.");
if(ioctl(fd,I_PUSH,"udp")==-1)
throw std::runtime_error("netstat_solaris() - Could not push module udp into /dev/arp.");
request_t request;
strbuf buf;
buf.len=sizeof(request);
buf.buf=(char*)&request;
if(putmsg(fd,&buf,NULL,0)<0)
throw std::runtime_error("netstat_solaris() - putmsg failed for /dev/arp.");
netstat_list_t tcp4;
netstat_list_t tcp6;
netstat_list_t udp4;
netstat_list_t udp6;
while(true)
{
strbuf buf2;
int flags=0;
reply_t reply;
buf2.maxlen=sizeof(reply);
buf2.buf=(char*)&reply;
int ret=getmsg(fd,&buf2,NULL,&flags);
if(ret<0)
throw std::runtime_error("netstat_solaris() - getmsg failed for /dev/arp.");
if(ret!=MOREDATA)
break;
if(reply.ack_header.PRIM_type!=T_OPTMGMT_ACK)
throw std::runtime_error("netstat_solaris() - Invalid acknowledgement header primative type from getmsg.");
if((size_t)buf2.len<sizeof(reply.ack_header))
throw std::runtime_error("netstat_solaris() - Invalid buffer length received from getmsg.");
if((size_t)reply.ack_header.OPT_length<sizeof(reply.opt_header))
throw std::runtime_error("netstat_solaris() - Invalid option length received from getmsg.");
std::vector<uint8_t> data;
data.resize(reply.opt_header.len);
buf2.maxlen=reply.opt_header.len;
buf2.buf=(char*)&data[0];
flags=0;
if(getmsg(fd,NULL,&buf2,&flags)>=0)
{
if(reply.opt_header.level==MIB2_TCP&&reply.opt_header.name==MIB2_TCP_CONN)
{
for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_tcpConnEntry_t))
{
mib2_tcpConnEntry_t* entry=(mib2_tcpConnEntry_t*)((char*)&data[0]+ii);
netstat_t netstat;
netstat.proto="tcp4";
netstat.laddr=u32_to_ipv4(entry->tcpConnLocalAddress);
netstat.faddr=u32_to_ipv4(entry->tcpConnRemAddress);
netstat.lport=u16_to_port(htons(entry->tcpConnLocalPort));
netstat.fport=u16_to_port(htons(entry->tcpConnRemPort));
netstat.state=state_int_to_string(entry->tcpConnState);
netstat.pid="-";
if(netstat.state!="TIME_WAIT")
netstat.pid=to_string(entry->tcpConnCreationProcess);
tcp4.push_back(netstat);
}
}
#if(defined(MIB2_TCP6))
if(reply.opt_header.level==MIB2_TCP6&&reply.opt_header.name==MIB2_TCP6_CONN)
{
for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_tcp6ConnEntry_t))
{
mib2_tcp6ConnEntry_t* entry=(mib2_tcp6ConnEntry_t*)((char*)&data[0]+ii);
netstat_t netstat;
netstat.proto="tcp6";
netstat.laddr=u8x16_to_ipv6(entry->tcp6ConnLocalAddress.s6_addr);
netstat.faddr=u8x16_to_ipv6(entry->tcp6ConnRemAddress.s6_addr);
netstat.lport=u16_to_port(htons(entry->tcp6ConnLocalPort));
netstat.fport=u16_to_port(htons(entry->tcp6ConnRemPort));
netstat.state=state_int_to_string(entry->tcp6ConnState);
netstat.pid="-";
if(netstat.state!="TIME_WAIT")
netstat.pid=to_string(entry->tcp6ConnCreationProcess);
tcp6.push_back(netstat);
}
}
#endif
if(reply.opt_header.level==MIB2_UDP&&reply.opt_header.name==MIB2_UDP_ENTRY)
{
for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_udpEntry_t))
{
mib2_udpEntry_t* entry=(mib2_udpEntry_t*)((char*)&data[0]+ii);
netstat_t netstat;
netstat.proto="udp4";
netstat.laddr=u32_to_ipv4(entry->udpLocalAddress);
netstat.faddr="0.0.0.0";
netstat.lport=u16_to_port(htons(entry->udpLocalPort));
netstat.fport=0;
netstat.state="-";
netstat.pid="-";
if(netstat.state!="TIME_WAIT")
netstat.pid=to_string(entry->udpCreationProcess);
udp4.push_back(netstat);
}
}
#if(defined(MIB2_UDP6))
if(reply.opt_header.level==MIB2_UDP6&&reply.opt_header.name==MIB2_UDP6_ENTRY)
{
for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_udp6Entry_t))
{
mib2_udp6Entry_t* entry=(mib2_udp6Entry_t*)((char*)&data[0]+ii);
netstat_t netstat;
netstat.proto="udp6";
netstat.laddr=u8x16_to_ipv6(entry->udp6LocalAddress.s6_addr);
netstat.faddr="0000:0000:0000:0000:0000:0000:0000:0000";
netstat.lport=u16_to_port(htons(entry->udp6LocalPort));
netstat.fport=0;
netstat.state="-";
netstat.pid="-";
if(netstat.state!="TIME_WAIT")
netstat.pid=to_string(entry->udp6CreationProcess);
udp6.push_back(netstat);
}
}
#endif
}
}
netstat_list_t netstats;
for(size_t ii=0;ii<tcp4.size();++ii)
netstats.push_back(tcp4[ii]);
for(size_t ii=0;ii<tcp6.size();++ii)
netstats.push_back(tcp6[ii]);
for(size_t ii=0;ii<udp4.size();++ii)
netstats.push_back(udp4[ii]);
for(size_t ii=0;ii<udp6.size();++ii)
netstats.push_back(udp6[ii]);
return netstats;
}
<commit_msg>Added pid ifdef for old versions of solaris...<commit_after>//Tested on:
// Solaris 11.2 (g++)
#include "netstat.hpp"
#include <cstdlib>
#include <stdexcept>
#include <iomanip>
#include <iostream>
#include <string>
#include <stdint.h>
#include <sstream>
#include <vector>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stropts.h>
#include <cstring>
#include <sys/tihdr.h>
#include <inet/mib2.h>
#include "netstat_util.hpp"
#include "string_util.hpp"
class buffer_t
{
public:
char buffer[512];
strbuf buf;
buffer_t()
{
memset(buffer,0,512);
buf.buf=(char*)buffer;
buf.len=512;
}
};
struct request_t
{
public:
request_t()
{
req_header.PRIM_type=T_SVR4_OPTMGMT_REQ;
req_header.OPT_length=sizeof(opt_header);
req_header.OPT_offset=offsetof(request_t,opt_header);
req_header.MGMT_flags=T_CURRENT;
opt_header.level=MIB2_IP;
opt_header.name=0;
opt_header.len=0;
}
T_optmgmt_req req_header;
opthdr opt_header;
};
struct reply_t
{
T_optmgmt_ack ack_header;
opthdr opt_header;
};
static std::string state_int_to_string(const uint32_t state)
{
if(state==MIB2_TCP_established)
return "ESTABLISHED";
if(state==MIB2_TCP_synSent)
return "SYN_SENT";
if(state==MIB2_TCP_synReceived)
return "SYN_RECV";
if(state==MIB2_TCP_finWait1)
return "FIN_WAIT1";
if(state==MIB2_TCP_finWait2)
return "FIN_WAIT2";
if(state==MIB2_TCP_timeWait)
return "TIME_WAIT";
if(state==MIB2_TCP_closed)
return "CLOSE";
if(state==MIB2_TCP_closeWait)
return "CLOSE_WAIT";
if(state==MIB2_TCP_lastAck)
return "LAST_ACK";
if(state==MIB2_TCP_listen)
return "LISTEN";
if(state==MIB2_TCP_closing||state==MIB2_TCP_deleteTCB)
return "CLOSING";
return "UNKNOWN";
}
netstat_list_t netstat()
{
int fd=open("/dev/arp",O_RDWR);
if(fd==-1)
throw std::runtime_error("netstat_solaris() - Could not find /dev/arp.");
if(ioctl(fd,I_PUSH,"tcp")==-1)
throw std::runtime_error("netstat_solaris() - Could not push module tcp into /dev/arp.");
if(ioctl(fd,I_PUSH,"udp")==-1)
throw std::runtime_error("netstat_solaris() - Could not push module udp into /dev/arp.");
request_t request;
strbuf buf;
buf.len=sizeof(request);
buf.buf=(char*)&request;
if(putmsg(fd,&buf,NULL,0)<0)
throw std::runtime_error("netstat_solaris() - putmsg failed for /dev/arp.");
netstat_list_t tcp4;
netstat_list_t tcp6;
netstat_list_t udp4;
netstat_list_t udp6;
while(true)
{
strbuf buf2;
int flags=0;
reply_t reply;
buf2.maxlen=sizeof(reply);
buf2.buf=(char*)&reply;
int ret=getmsg(fd,&buf2,NULL,&flags);
if(ret<0)
throw std::runtime_error("netstat_solaris() - getmsg failed for /dev/arp.");
if(ret!=MOREDATA)
break;
if(reply.ack_header.PRIM_type!=T_OPTMGMT_ACK)
throw std::runtime_error("netstat_solaris() - Invalid acknowledgement header primative type from getmsg.");
if((size_t)buf2.len<sizeof(reply.ack_header))
throw std::runtime_error("netstat_solaris() - Invalid buffer length received from getmsg.");
if((size_t)reply.ack_header.OPT_length<sizeof(reply.opt_header))
throw std::runtime_error("netstat_solaris() - Invalid option length received from getmsg.");
std::vector<uint8_t> data;
data.resize(reply.opt_header.len);
buf2.maxlen=reply.opt_header.len;
buf2.buf=(char*)&data[0];
flags=0;
if(getmsg(fd,NULL,&buf2,&flags)>=0)
{
if(reply.opt_header.level==MIB2_TCP&&reply.opt_header.name==MIB2_TCP_CONN)
{
for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_tcpConnEntry_t))
{
mib2_tcpConnEntry_t* entry=(mib2_tcpConnEntry_t*)((char*)&data[0]+ii);
netstat_t netstat;
netstat.proto="tcp4";
netstat.laddr=u32_to_ipv4(entry->tcpConnLocalAddress);
netstat.faddr=u32_to_ipv4(entry->tcpConnRemAddress);
netstat.lport=u16_to_port(htons(entry->tcpConnLocalPort));
netstat.fport=u16_to_port(htons(entry->tcpConnRemPort));
netstat.state=state_int_to_string(entry->tcpConnState);
netstat.pid="-";
if(netstat.state!="TIME_WAIT")
netstat.pid=to_string(entry->tcpConnCreationProcess);
tcp4.push_back(netstat);
}
}
#if(defined(MIB2_TCP6))
if(reply.opt_header.level==MIB2_TCP6&&reply.opt_header.name==MIB2_TCP6_CONN)
{
for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_tcp6ConnEntry_t))
{
mib2_tcp6ConnEntry_t* entry=(mib2_tcp6ConnEntry_t*)((char*)&data[0]+ii);
netstat_t netstat;
netstat.proto="tcp6";
netstat.laddr=u8x16_to_ipv6(entry->tcp6ConnLocalAddress.s6_addr);
netstat.faddr=u8x16_to_ipv6(entry->tcp6ConnRemAddress.s6_addr);
netstat.lport=u16_to_port(htons(entry->tcp6ConnLocalPort));
netstat.fport=u16_to_port(htons(entry->tcp6ConnRemPort));
netstat.state=state_int_to_string(entry->tcp6ConnState);
netstat.pid="-";
if(netstat.state!="TIME_WAIT")
netstat.pid=to_string(entry->tcp6ConnCreationProcess);
tcp6.push_back(netstat);
}
}
#endif
if(reply.opt_header.level==MIB2_UDP&&reply.opt_header.name==MIB2_UDP_ENTRY)
{
for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_udpEntry_t))
{
mib2_udpEntry_t* entry=(mib2_udpEntry_t*)((char*)&data[0]+ii);
netstat_t netstat;
netstat.proto="udp4";
netstat.laddr=u32_to_ipv4(entry->udpLocalAddress);
netstat.faddr="0.0.0.0";
netstat.lport=u16_to_port(htons(entry->udpLocalPort));
netstat.fport=0;
netstat.state="-";
netstat.pid="-";
#if(defined(NEW_MIB_COMPLIANT)||defined(_KERNEL))
if(netstat.state!="TIME_WAIT")
netstat.pid=to_string(entry->udpCreationProcess);
#endif
udp4.push_back(netstat);
}
}
#if(defined(MIB2_UDP6))
if(reply.opt_header.level==MIB2_UDP6&&reply.opt_header.name==MIB2_UDP6_ENTRY)
{
for(int ii=0;ii<buf2.len;ii+=sizeof(mib2_udp6Entry_t))
{
mib2_udp6Entry_t* entry=(mib2_udp6Entry_t*)((char*)&data[0]+ii);
netstat_t netstat;
netstat.proto="udp6";
netstat.laddr=u8x16_to_ipv6(entry->udp6LocalAddress.s6_addr);
netstat.faddr="0000:0000:0000:0000:0000:0000:0000:0000";
netstat.lport=u16_to_port(htons(entry->udp6LocalPort));
netstat.fport=0;
netstat.state="-";
netstat.pid="-";
#if(defined(NEW_MIB_COMPLIANT)||defined(_KERNEL))
if(netstat.state!="TIME_WAIT")
netstat.pid=to_string(entry->udp6CreationProcess);
#endif
udp6.push_back(netstat);
}
}
#endif
}
}
netstat_list_t netstats;
for(size_t ii=0;ii<tcp4.size();++ii)
netstats.push_back(tcp4[ii]);
for(size_t ii=0;ii<tcp6.size();++ii)
netstats.push_back(tcp6[ii]);
for(size_t ii=0;ii<udp4.size();++ii)
netstats.push_back(udp4[ii]);
for(size_t ii=0;ii<udp6.size();++ii)
netstats.push_back(udp6[ii]);
return netstats;
}
<|endoftext|> |
<commit_before>#ifndef BUCKET_BUCKET_HPP
#define BUCKET_BUCKET_HPP
#include <map>
#include <vector>
namespace bucket {
/**
* @brief A (magical) bucket to store stuff inside
* @details Stores an object together with a key.
*
* @tparam T What to put in the bucket
*/
template <typename T>
class Bucket {
private:
using Key = size_t;
using Collection = std::map<Key, T>;
using Content = std::pair<Key, T>;
public:
Bucket();
/**
* @brief Capture something inside the bucket.
* @details Add to the map and assign a unqiue key
*
* @param Something to capture
* @return The given ID to the captured something
*/
Key capture(T&);
/**
* @brief Uses black magic to spawn a new something inside the bucket.
* @details Call emplace on the underlying map, while also assigning a unique key.
*
* @param Constructor args to something
* @return The created something
*/
template <typename... Args>
T& spawn(Args&&...);
/**
* @brief Pick up the something with the given key inside the bucket.
* @details Using key to find the object inside the map. Throws if not found
*
* @param The key to the something
* @return (Hopefully) the something with the given key.
*/
T& pick_up(const Key);
/**
* @brief Abandon/release the something with the given key
* @details Calls earse on the underlying map
*
* @param The key to the something.
* @return Wheter something was abandoned or not.
*/
bool abandon(const Key);
/**
* @brief Lineup everything inside the bucket.
* @details Builds a vector with only the values from the underlying map.
* @return A vector with all the content inside the bucket.
*/
std::vector<T> lineup() const;
private:
Key idx;
Collection bucket_;
};
template <typename T>
Bucket<T>::Bucket() : idx(1), bucket_()
{
}
template <typename T>
size_t Bucket<T>::capture(T& obj) {
obj.key = idx++;
bucket_.insert({obj.key, obj});
return obj.key;
}
template <typename T>
template <typename... Args>
T& Bucket<T>::spawn(Args&&... args) {
Key id = idx++;
bucket_.emplace(id, T{args...});
auto& obj = bucket_[id];
obj.key = id;
return obj;
}
template <typename T>
T& Bucket<T>::pick_up(const Key key) {
auto it = bucket_.find(key);
if(it != bucket_.end())
return it->second;
throw "not found";
}
template <typename T>
bool Bucket<T>::abandon(const Key key) {
return bucket_.erase(key);
}
template <typename T>
std::vector<T> Bucket<T>::lineup() const {
std::vector<T> vec;
vec.reserve(bucket_.size());
for(auto content : bucket_)
vec.push_back(content.second);
assert(vec.size() == bucket_.size());
return vec;
}
}; // < namespace bucket
#endif
<commit_msg>Made use of RapidJson for json handling<commit_after>#ifndef BUCKET_BUCKET_HPP
#define BUCKET_BUCKET_HPP
#include <map>
#include <vector>
namespace bucket {
/**
* @brief A (magical) bucket to store stuff inside
* @details Stores an object together with a key.
*
* @tparam T What to put in the bucket
*/
template <typename T>
class Bucket {
private:
using Key = size_t;
using Collection = std::map<Key, T>;
using Content = std::pair<Key, T>;
public:
Bucket();
/**
* @brief Capture something inside the bucket.
* @details Add to the map and assign a unqiue key
*
* @param Something to capture
* @return The given ID to the captured something
*/
Key capture(T&);
/**
* @brief Uses black magic to spawn a new something inside the bucket.
* @details Call emplace on the underlying map, while also assigning a unique key.
*
* @param Constructor args to something
* @return The created something
*/
template <typename... Args>
T& spawn(Args&&...);
/**
* @brief Pick up the something with the given key inside the bucket.
* @details Using key to find the object inside the map. Throws if not found
*
* @param The key to the something
* @return (Hopefully) the something with the given key.
*/
T& pick_up(const Key);
/**
* @brief Abandon/release the something with the given key
* @details Calls earse on the underlying map
*
* @param The key to the something.
* @return Wheter something was abandoned or not.
*/
bool abandon(const Key);
/**
* @brief Lineup everything inside the bucket.
* @details Builds a vector with only the values from the underlying map.
* @return A vector with all the content inside the bucket.
*/
std::vector<T> lineup() const;
template <typename Writer>
void serialize(Writer& writer) const;
private:
Key idx;
Collection bucket_;
};
template <typename T>
Bucket<T>::Bucket() : idx(1), bucket_()
{
}
template <typename T>
size_t Bucket<T>::capture(T& obj) {
obj.key = idx++;
bucket_.insert({obj.key, obj});
return obj.key;
}
template <typename T>
template <typename... Args>
T& Bucket<T>::spawn(Args&&... args) {
Key id = idx++;
bucket_.emplace(id, T{args...});
auto& obj = bucket_[id];
obj.key = id;
return obj;
}
template <typename T>
T& Bucket<T>::pick_up(const Key key) {
auto it = bucket_.find(key);
if(it != bucket_.end())
return it->second;
throw "not found";
}
template <typename T>
bool Bucket<T>::abandon(const Key key) {
return bucket_.erase(key);
}
template <typename T>
std::vector<T> Bucket<T>::lineup() const {
std::vector<T> vec;
vec.reserve(bucket_.size());
for(auto content : bucket_)
vec.push_back(content.second);
assert(vec.size() == bucket_.size());
return vec;
}
template <typename T>
template <typename Writer>
void Bucket<T>::serialize(Writer& writer) const {
writer.start_array();
for(auto content : bucket_)
content.second.serialize(writer);
writer.end_array();
}
}; // < namespace bucket
#endif
<|endoftext|> |
<commit_before>#ifndef GCL_TMP_H_
# define GCL_TMP_H_
#include <array>
#include <bitset>
namespace gcl
{
struct mp
{ // C++17
template <typename ... ts>
struct type_pack
{ // constexpr type that has variadic parameter
// use this instead of std::tuple for viariadic-as-std-tuple-parameter,
// if your optimization level does not skip unused variables
};
template <typename ... ts>
struct super : ts...
{};
template <template <typename...> class trait_type, typename ... ts>
struct partial_template
{
template <typename ... us>
using type = trait_type<ts..., us...>;
template <typename ... us>
static constexpr bool value = trait_type<ts..., us...>::value;
};
template <typename T, template <typename> class ... traits>
constexpr static bool meet_requirement = (traits<T>::value && ...);
template <template <typename> class ... constraint_type>
struct require
{
template <typename T>
static constexpr void on()
{
(check_constraint<constraint_type, T>(), ...);
}
template <typename T>
static inline constexpr
std::array<bool, sizeof...(constraint_type)>
values_on{ std::move(constraint_type<T>::value)... };
private:
template <template <typename> class constraint_type, typename T>
static constexpr void check_constraint()
{
static_assert(constraint_type<T>::value, "constraint failed to apply. see template context for more infos");
}
};
template <typename T, typename ... ts>
static constexpr inline bool contains = std::disjunction<std::is_same<T, ts>...>::value;
template <typename to_find, typename ... ts>
constexpr auto get_index()
{
return index_of<to_find, ts...>;
// [C++20] constexpr => std::count, std::find
/*static_assert(contains<to_find, ts...>);
constexpr auto result = gcl::mp::require
<
gcl::mp::partial_template<std::is_same, ts>::type
...
>::values_on<to_find>;
auto count = std::count(std::cbegin(result), std::cend(result), true);
if (count > 1)
throw std::runtime_error("get_index : duplicate type");
if (count == 0)
throw std::out_of_range("get_index : no match");
return std::distance
(
std::cbegin(result),
std::find(std::cbegin(result), std::cend(result), true)
);*/
}
// C++17 constexpr index_of. Use recursion. remove when C++20 is ready. see get_index comments for more infos.
template <typename T, typename ...ts>
static constexpr inline auto index_of = index_of_impl<T, ts...>();
template <size_t N, typename ...ts>
// better than std::decay_t<decltype(std::get<index>(std::tuple<ts...>{}))>
// because one or more types in ts... may not be default constructible
using type_at = typename std::tuple_element<N, std::tuple<ts...>>::type;
template <typename T, typename ... ts>
constexpr static bool is_unique()
{
constexpr std::size_t remain_index = gcl::mp::index_of<T, ts...> + 1;
return is_unique_impl<remain_index, T, ts...>(std::make_index_sequence<sizeof...(ts) - remain_index>());
}
template <typename T, typename ... ts>
constexpr static bool inline is_unique_v = is_unique<T, ts...>();
template <typename ... ts>
constexpr static inline bool are_unique = are_unique_impl<ts...>(std::make_index_sequence<sizeof...(ts)>());
struct filter
{ // allow filtering operation on variadic type,
// using gcl::mp::contains and std::bitset
// or_as_bitset impl is :
// { T0, T1, T2 } | {T4, T1, T5} => 010
using std_bitset_initializer_type = unsigned long long; // not typedef in std::bitset
static_assert(std::is_constructible_v<std::bitset<8>, std_bitset_initializer_type>);
struct disjunction
{
};
template <typename ... ts, typename ... us>
constexpr static auto or_as_bitset_initializer(type_pack<ts...>, type_pack<us...>)
{
std_bitset_initializer_type value{ 0 };
return ~
(
((value |= std_bitset_initializer_type{ gcl::mp::contains<ts, us...> }) << 1),
...
);
}
template <typename ... ts, typename ... us>
constexpr static auto or_as_bitset(type_pack<ts...>, type_pack<us...>)
{
const auto initializer = or_as_bitset_initializer(type_pack<ts...>{}, type_pack<us...>{});
return std::bitset<sizeof...(ts)>{initializer};
}
};
private:
template <typename T, typename T_it = void, typename... ts>
static constexpr std::size_t index_of_impl()
{
if constexpr (std::is_same_v<T, T_it>)
return 0;
if constexpr (sizeof...(ts) == 0)
throw 0; // "index_of : no match found";
return 1 + index_of_impl<T, ts...>();
}
template <std::size_t remain_index, typename T, typename ... ts, std::size_t ...indexes>
constexpr static bool is_unique_impl(std::index_sequence<indexes...>)
{
return not contains
<
T,
gcl::mp::type_at<remain_index + indexes, ts...> ...
>;
}
template <typename ... ts, std::size_t ... indexes>
constexpr static bool are_unique_impl(std::index_sequence<indexes...>)
{
return (gcl::mp::is_unique_v<gcl::mp::type_at<indexes, ts...>, ts...> && ...);
}
};
}
namespace gcl::deprecated::mp
{ // C++98
template <class T, class ... T_Classes>
struct super
{
struct Type : T, super<T_Classes...>::Type
{};
};
template <class T>
struct super<T>
{
using Type = T;
};
// constexpr if
template <bool condition, typename _THEN, typename _ELSE> struct IF
{};
template <typename _THEN, typename _ELSE> struct IF<true, _THEN, _ELSE>
{
using _Type = _THEN;
};
template <typename _THEN, typename _ELSE> struct IF<false, _THEN, _ELSE>
{
using _Type = _ELSE;
};
struct out_of_range {};
template <size_t N_id = 0>
struct list
{
static constexpr size_t id = N_id;
using type_t = list<id>;
using next = list<id + 1>;
using previous = mp::IF<(id == 0), out_of_range, list<id - 1> >;
constexpr static const bool is_head = mp::IF<(id == 0), true, false>;
};
template <template <typename> class T_trait>
struct apply_trait
{
template <typename T>
static constexpr bool value = T_trait<T>::value;
};
template <template <typename> class T_Constraint>
struct require
{
template <typename T>
static constexpr void on()
{
static_assert(T_Constraint<T>::value, "gcl::mp::apply_constraint : constraint not matched");
}
};
template <typename ... T> struct for_each;
template <typename T0, typename ... T> struct for_each<T0, T...>
{
for_each() = delete;
for_each(const for_each &) = delete;
for_each(const for_each &&) = delete;
template <template <typename> class T_Constraint>
struct require
{
T_Constraint<T0> _check; // Check by generation, not value
typename for_each<T...>::template require<T_Constraint> _next;
};
template <template <typename> class T_Functor>
static void call(void)
{
T_Functor<T0>::call();
for_each<T...>::call<T_Functor>();
}
template <template <typename> class T_Functor, size_t N = 0>
static void call_at(const size_t pos)
{
if (N == pos) T_Functor<T0>::call();
else for_each<T...>::call_at<T_Functor, (N + 1)>(pos);
}
template <template <typename> class T_Functor, size_t N = 0>
static typename T_Functor<T0>::return_type call_at_with_return_value(const size_t pos)
{
if (N == pos) return T_Functor<T0>::call();
else return for_each<T...>::call_at_with_return_value<T_Functor, (N + 1)>(pos);
}
};
template <> struct for_each<>
{
for_each() = delete;
for_each(const for_each &) = delete;
for_each(const for_each &&) = delete;
template <template <typename> class T_Constraint>
struct require
{};
template <template <typename> class T_Functor>
static void call(void)
{}
template <template <typename> class T_Functor, size_t N = 0>
static void call_at(const size_t pos)
{
throw std::out_of_range("template <typename ... T> struct for_each::call_at");
}
template <template <typename> class T_Functor, size_t N = 0>
static typename T_Functor<void>::return_type call_at_with_return_value(const size_t pos)
{
throw std::out_of_range("template <typename ... T> struct for_each::call_at_with_return_value");
}
};
}
#endif // GCL_TMP_H_
<commit_msg>gcl::mp::filter : cleaner code<commit_after>#ifndef GCL_TMP_H_
# define GCL_TMP_H_
#include <array>
#include <bitset>
namespace gcl
{
struct mp
{ // C++17
template <typename ... ts>
struct type_pack
{ // constexpr type that has variadic parameter
// use this instead of std::tuple for viariadic-as-std-tuple-parameter,
// if your optimization level does not skip unused variables
};
template <typename ... ts>
struct super : ts...
{};
template <template <typename...> class trait_type, typename ... ts>
struct partial_template
{
template <typename ... us>
using type = trait_type<ts..., us...>;
template <typename ... us>
static constexpr bool value = trait_type<ts..., us...>::value;
};
template <typename T, template <typename> class ... traits>
constexpr static bool meet_requirement = (traits<T>::value && ...);
template <template <typename> class ... constraint_type>
struct require
{
template <typename T>
static constexpr void on()
{
(check_constraint<constraint_type, T>(), ...);
}
template <typename T>
static inline constexpr
std::array<bool, sizeof...(constraint_type)>
values_on{ std::move(constraint_type<T>::value)... };
private:
template <template <typename> class constraint_type, typename T>
static constexpr void check_constraint()
{
static_assert(constraint_type<T>::value, "constraint failed to apply. see template context for more infos");
}
};
template <typename T, typename ... ts>
static constexpr inline bool contains = std::disjunction<std::is_same<T, ts>...>::value;
template <typename to_find, typename ... ts>
constexpr auto get_index()
{
return index_of<to_find, ts...>;
// [C++20] constexpr => std::count, std::find
/*static_assert(contains<to_find, ts...>);
constexpr auto result = gcl::mp::require
<
gcl::mp::partial_template<std::is_same, ts>::type
...
>::values_on<to_find>;
auto count = std::count(std::cbegin(result), std::cend(result), true);
if (count > 1)
throw std::runtime_error("get_index : duplicate type");
if (count == 0)
throw std::out_of_range("get_index : no match");
return std::distance
(
std::cbegin(result),
std::find(std::cbegin(result), std::cend(result), true)
);*/
}
// C++17 constexpr index_of. Use recursion. remove when C++20 is ready. see get_index comments for more infos.
template <typename T, typename ...ts>
static constexpr inline auto index_of = index_of_impl<T, ts...>();
template <size_t N, typename ...ts>
// better than std::decay_t<decltype(std::get<index>(std::tuple<ts...>{}))>
// because one or more types in ts... may not be default constructible
using type_at = typename std::tuple_element<N, std::tuple<ts...>>::type;
template <typename T, typename ... ts>
constexpr static bool is_unique()
{
constexpr std::size_t remain_index = gcl::mp::index_of<T, ts...> + 1;
return is_unique_impl<remain_index, T, ts...>(std::make_index_sequence<sizeof...(ts) - remain_index>());
}
template <typename T, typename ... ts>
constexpr static bool inline is_unique_v = is_unique<T, ts...>();
template <typename ... ts>
constexpr static inline bool are_unique = are_unique_impl<ts...>(std::make_index_sequence<sizeof...(ts)>());
struct filter
{ // allow filtering operation on variadic type,
// using gcl::mp::contains and std::bitset
// or_as_bitset impl is :
// { T0, T1, T2 } | {T1, T4, T5} => 010
using std_bitset_initializer_type = unsigned long long; // not type-alias in std::bitset for constexpr constructor parameter
static_assert(std::is_constructible_v<std::bitset<8>, std_bitset_initializer_type>);
template <typename ... ts, typename ... us>
constexpr static auto as_bitset_initializer(type_pack<ts...>, type_pack<us...>)
{
std_bitset_initializer_type value{ 0 };
return ~
(
((value |= gcl::mp::contains<ts, us...> ) << 1),
...
);
}
template <typename ... ts, typename ... us>
constexpr static auto as_bitset(type_pack<ts...>, type_pack<us...>)
{
const auto initializer = as_bitset_initializer(type_pack<ts...>{}, type_pack<us...>{});
return std::bitset<sizeof...(ts)>{initializer};
}
};
private:
template <typename T, typename T_it = void, typename... ts>
static constexpr std::size_t index_of_impl()
{
if constexpr (std::is_same_v<T, T_it>)
return 0;
if constexpr (sizeof...(ts) == 0)
throw 0; // "index_of : no match found";
return 1 + index_of_impl<T, ts...>();
}
template <std::size_t remain_index, typename T, typename ... ts, std::size_t ...indexes>
constexpr static bool is_unique_impl(std::index_sequence<indexes...>)
{
return not contains
<
T,
gcl::mp::type_at<remain_index + indexes, ts...> ...
>;
}
template <typename ... ts, std::size_t ... indexes>
constexpr static bool are_unique_impl(std::index_sequence<indexes...>)
{
return (gcl::mp::is_unique_v<gcl::mp::type_at<indexes, ts...>, ts...> && ...);
}
};
}
namespace gcl::deprecated::mp
{ // C++98
template <class T, class ... T_Classes>
struct super
{
struct Type : T, super<T_Classes...>::Type
{};
};
template <class T>
struct super<T>
{
using Type = T;
};
// constexpr if
template <bool condition, typename _THEN, typename _ELSE> struct IF
{};
template <typename _THEN, typename _ELSE> struct IF<true, _THEN, _ELSE>
{
using _Type = _THEN;
};
template <typename _THEN, typename _ELSE> struct IF<false, _THEN, _ELSE>
{
using _Type = _ELSE;
};
struct out_of_range {};
template <size_t N_id = 0>
struct list
{
static constexpr size_t id = N_id;
using type_t = list<id>;
using next = list<id + 1>;
using previous = mp::IF<(id == 0), out_of_range, list<id - 1> >;
constexpr static const bool is_head = mp::IF<(id == 0), true, false>;
};
template <template <typename> class T_trait>
struct apply_trait
{
template <typename T>
static constexpr bool value = T_trait<T>::value;
};
template <template <typename> class T_Constraint>
struct require
{
template <typename T>
static constexpr void on()
{
static_assert(T_Constraint<T>::value, "gcl::mp::apply_constraint : constraint not matched");
}
};
template <typename ... T> struct for_each;
template <typename T0, typename ... T> struct for_each<T0, T...>
{
for_each() = delete;
for_each(const for_each &) = delete;
for_each(const for_each &&) = delete;
template <template <typename> class T_Constraint>
struct require
{
T_Constraint<T0> _check; // Check by generation, not value
typename for_each<T...>::template require<T_Constraint> _next;
};
template <template <typename> class T_Functor>
static void call(void)
{
T_Functor<T0>::call();
for_each<T...>::call<T_Functor>();
}
template <template <typename> class T_Functor, size_t N = 0>
static void call_at(const size_t pos)
{
if (N == pos) T_Functor<T0>::call();
else for_each<T...>::call_at<T_Functor, (N + 1)>(pos);
}
template <template <typename> class T_Functor, size_t N = 0>
static typename T_Functor<T0>::return_type call_at_with_return_value(const size_t pos)
{
if (N == pos) return T_Functor<T0>::call();
else return for_each<T...>::call_at_with_return_value<T_Functor, (N + 1)>(pos);
}
};
template <> struct for_each<>
{
for_each() = delete;
for_each(const for_each &) = delete;
for_each(const for_each &&) = delete;
template <template <typename> class T_Constraint>
struct require
{};
template <template <typename> class T_Functor>
static void call(void)
{}
template <template <typename> class T_Functor, size_t N = 0>
static void call_at(const size_t pos)
{
throw std::out_of_range("template <typename ... T> struct for_each::call_at");
}
template <template <typename> class T_Functor, size_t N = 0>
static typename T_Functor<void>::return_type call_at_with_return_value(const size_t pos)
{
throw std::out_of_range("template <typename ... T> struct for_each::call_at_with_return_value");
}
};
}
#endif // GCL_TMP_H_
<|endoftext|> |
<commit_before>#include <utility>
#include <iostream>
#include <map>
template<
typename Key_t,
typename Value_t,
typename Predicate_t = std::less<Key_t> >
class non_copyable_map : public std::map<Key_t,Value_t,Predicate_t>
{
typedef std::map<Key_t,Value_t,Predicate_t> BaseType;
public:
non_copyable_map() { }
non_copyable_map(non_copyable_map&& t) : BaseType(std::move(t))
{
}
non_copyable_map& operator = (non_copyable_map&& t)
{
if ( this != &t )
{
std::swap<BaseType>(*this,t);
}
return *this;
}
private:
non_copyable_map(const non_copyable_map&) = delete;
non_copyable_map& operator = (const non_copyable_map&) = delete;
};
int main(int argc, char* argv[])
{
non_copyable_map<int, non_copyable_map<int, int> > nestedMap;
non_copyable_map<int,int> inner;
inner[3]=4;
nestedMap[2] = std::move(inner);
auto find_inner = nestedMap.find(2);
if ( find_inner != nestedMap.end() )
{
std::cout << "Found inner map " << std::endl;
auto find_value = find_inner->second.find(3);
//This HAS to be a reference otherwise compilation fails
//Failing to compile when accidentally copying maps is the aim
auto& giveMeAMap = find_inner->second;
giveMeAMap[4] = 7;
if ( find_value != find_inner->second.end() )
{
std::cout << "Found value " << find_value->second << std::endl;
}
}
}
<commit_msg>removed 'delete' as MSVS2010 does not like it<commit_after>#include <utility>
#include <iostream>
#include <map>
template<
typename Key_t,
typename Value_t,
typename Predicate_t = std::less<Key_t> >
class non_copyable_map : public std::map<Key_t,Value_t,Predicate_t>
{
typedef std::map<Key_t,Value_t,Predicate_t> BaseType;
public:
non_copyable_map() { }
non_copyable_map(non_copyable_map&& t) : BaseType(std::move(t))
{
}
non_copyable_map& operator = (non_copyable_map&& t)
{
if ( this != &t )
{
std::swap<BaseType>(*this,t);
}
return *this;
}
private:
non_copyable_map(const non_copyable_map&);
non_copyable_map& operator = (const non_copyable_map&);
};
int main(int argc, char* argv[])
{
non_copyable_map<int, non_copyable_map<int, int> > nestedMap;
non_copyable_map<int,int> inner;
inner[3]=4;
nestedMap[2] = std::move(inner);
auto find_inner = nestedMap.find(2);
if ( find_inner != nestedMap.end() )
{
std::cout << "Found inner map " << std::endl;
auto find_value = find_inner->second.find(3);
//This HAS to be a reference otherwise compilation fails
//Failing to compile when accidentally copying maps is the aim
auto& giveMeAMap = find_inner->second;
giveMeAMap[4] = 7;
if ( find_value != find_inner->second.end() )
{
std::cout << "Found value " << find_value->second << std::endl;
}
}
}
<|endoftext|> |
<commit_before>{
gSystem->Load("libHFE.so");
// Set the include paths
gROOT->ProcessLine(".include HFE");
}<commit_msg>update<commit_after>{
gSystem->Load("libPWG3hfe.so");
// Set the include paths
gROOT->ProcessLine(".include PWG3hfe");
}
<|endoftext|> |
<commit_before>// ---------------------------------------------------------------------------
//
// This file is part of the <kortex> library suite
//
// Copyright (C) 2013 Engin Tola
//
// See LICENSE file for license information.
//
// author: Engin Tola
// e-mail: engintola@gmail.com
// web : http://www.engintola.com
//
// ---------------------------------------------------------------------------
#include <algorithm>
#include <climits>
#include <kortex/rect2.h>
namespace kortex {
bool Rect2f::is_inside(float x, float y) const {
if( y>=ly && y<uy && x>=lx && x<ux ) return true;
else return false;
}
bool Rect2f::is_inside_y(float y) const {
if( y>=ly && y<uy ) return true;
else return false;
}
bool Rect2f::is_inside_x(float x) const {
if( x>=lx && x<ux ) return true;
else return false;
}
bool Rect2f::is_inside(int x, int y) const {
if( y>=ly && y<uy && x>=lx && x<ux ) return true;
else return false;
}
bool Rect2f::is_inside_y(int y) const {
if( y>=ly && y<uy ) return true;
else return false;
}
bool Rect2f::is_inside_x(int x) const {
if( x>=lx && x<ux ) return true;
else return false;
}
void Rect2f::print() const {
printf( "Boundary: [x %f %f ] [y %f %f] [sz %f %f]\n",
lx, ux, ly, uy, dx, dy );
}
//
//
//
void Rect2i::reset_max_region() {
init( INT_MIN, INT_MAX, INT_MIN, INT_MAX );
id = 0;
}
bool Rect2i::is_inside(int x, int y) const {
if( x>=lx && x<ux && y>=ly && y<uy ) return true;
else return false;
}
bool Rect2i::is_inside_x(int x) const {
if( x>=lx && x<ux ) return true;
else return false;
}
bool Rect2i::is_inside_y(int y) const {
if( y>=ly && y<uy ) return true;
else return false;
}
//
void rect_move( const Rect2i& irect, int mx, int my, Rect2i& orect ) {
orect.init( mx+irect.lx, mx+irect.ux, my+irect.ly, my+irect.uy );
orect.id = irect.id;
}
void rect_union( const Rect2i& r0, const Rect2i& r1, Rect2i& out ) {
out = r0;
out.update( r1.lx, r1.ly );
out.update( r1.ux, r1.uy );
}
bool rect_intersect( const Rect2i& r0, const Rect2i& r1, Rect2i& out ) {
if( r1.lx > r0.ux ) return false;
if( r0.lx > r1.ux ) return false;
if( r1.ly > r0.uy ) return false;
if( r0.ly > r1.uy ) return false;
int olx = std::max( r0.lx, r1.lx );
int oux = std::min( r0.ux, r1.ux );
int oly = std::max( r0.ly, r1.ly );
int ouy = std::min( r0.uy, r1.uy );
out.init(olx, oux, oly, ouy);
return true;
}
}
<commit_msg>added warning message for a possible bug<commit_after>// ---------------------------------------------------------------------------
//
// This file is part of the <kortex> library suite
//
// Copyright (C) 2013 Engin Tola
//
// See LICENSE file for license information.
//
// author: Engin Tola
// e-mail: engintola@gmail.com
// web : http://www.engintola.com
//
// ---------------------------------------------------------------------------
#include <algorithm>
#include <climits>
#include <kortex/rect2.h>
#include <kortex/check.h>
namespace kortex {
bool Rect2f::is_inside(float x, float y) const {
if( y>=ly && y<uy && x>=lx && x<ux ) return true;
else return false;
}
bool Rect2f::is_inside_y(float y) const {
if( y>=ly && y<uy ) return true;
else return false;
}
bool Rect2f::is_inside_x(float x) const {
if( x>=lx && x<ux ) return true;
else return false;
}
bool Rect2f::is_inside(int x, int y) const {
if( y>=ly && y<uy && x>=lx && x<ux ) return true;
else return false;
}
bool Rect2f::is_inside_y(int y) const {
if( y>=ly && y<uy ) return true;
else return false;
}
bool Rect2f::is_inside_x(int x) const {
if( x>=lx && x<ux ) return true;
else return false;
}
void Rect2f::print() const {
printf( "Boundary: [x %f %f ] [y %f %f] [sz %f %f]\n",
lx, ux, ly, uy, dx, dy );
}
//
//
//
void Rect2i::reset_max_region() {
logman_warning( "there is a possible bug here - below min/max should be flipped" );
init( INT_MIN, INT_MAX, INT_MIN, INT_MAX );
id = 0;
}
bool Rect2i::is_inside(int x, int y) const {
if( x>=lx && x<ux && y>=ly && y<uy ) return true;
else return false;
}
bool Rect2i::is_inside_x(int x) const {
if( x>=lx && x<ux ) return true;
else return false;
}
bool Rect2i::is_inside_y(int y) const {
if( y>=ly && y<uy ) return true;
else return false;
}
//
void rect_move( const Rect2i& irect, int mx, int my, Rect2i& orect ) {
orect.init( mx+irect.lx, mx+irect.ux, my+irect.ly, my+irect.uy );
orect.id = irect.id;
}
void rect_union( const Rect2i& r0, const Rect2i& r1, Rect2i& out ) {
out = r0;
out.update( r1.lx, r1.ly );
out.update( r1.ux, r1.uy );
}
bool rect_intersect( const Rect2i& r0, const Rect2i& r1, Rect2i& out ) {
if( r1.lx > r0.ux ) return false;
if( r0.lx > r1.ux ) return false;
if( r1.ly > r0.uy ) return false;
if( r0.ly > r1.uy ) return false;
int olx = std::max( r0.lx, r1.lx );
int oux = std::min( r0.ux, r1.ux );
int oly = std::max( r0.ly, r1.ly );
int ouy = std::min( r0.uy, r1.uy );
out.init(olx, oux, oly, ouy);
return true;
}
}
<|endoftext|> |
<commit_before>#ifndef regex_hh_INCLUDED
#define regex_hh_INCLUDED
#include "string.hh"
#include "exception.hh"
#include "utf8_iterator.hh"
#include <boost/regex.hpp>
namespace Kakoune
{
struct regex_error : runtime_error
{
regex_error(StringView desc)
: runtime_error{format("regex error: '{}'", desc)}
{}
};
using RegexBase = boost::basic_regex<wchar_t, boost::c_regex_traits<wchar_t>>;
// Regex that keeps track of its string representation
struct Regex : RegexBase
{
Regex() = default;
explicit Regex(StringView re, flag_type flags = ECMAScript);
bool empty() const { return m_str.empty(); }
bool operator==(const Regex& other) const { return m_str == other.m_str; }
bool operator!=(const Regex& other) const { return m_str != other.m_str; }
const String& str() const { return m_str; }
static constexpr const char* option_type_name = "regex";
private:
String m_str;
};
template<typename It>
using RegexUtf8It = utf8::iterator<It, wchar_t, ssize_t>;
template<typename It>
using RegexIteratorBase = boost::regex_iterator<RegexUtf8It<It>, wchar_t,
boost::c_regex_traits<wchar_t>>;
namespace RegexConstant = boost::regex_constants;
template<typename Iterator>
struct MatchResults : boost::match_results<RegexUtf8It<Iterator>>
{
using ParentType = boost::match_results<RegexUtf8It<Iterator>>;
struct SubMatch : std::pair<Iterator, Iterator>
{
SubMatch() = default;
SubMatch(const boost::sub_match<RegexUtf8It<Iterator>>& m)
: std::pair<Iterator, Iterator>{m.first.base(), m.second.base()},
matched{m.matched}
{}
bool matched = false;
};
struct iterator : boost::match_results<RegexUtf8It<Iterator>>::iterator
{
using ParentType = typename boost::match_results<RegexUtf8It<Iterator>>::iterator;
iterator(const ParentType& it) : ParentType(it) {}
SubMatch operator*() const { return {ParentType::operator*()}; }
};
iterator begin() const { return {ParentType::begin()}; }
iterator cbegin() const { return {ParentType::cbegin()}; }
iterator end() const { return {ParentType::end()}; }
iterator cend() const { return {ParentType::cend()}; }
SubMatch operator[](size_t s) const { return {ParentType::operator[](s)}; }
};
template<typename Iterator>
struct RegexIterator : RegexIteratorBase<Iterator>
{
using Utf8It = RegexUtf8It<Iterator>;
using ValueType = MatchResults<Iterator>;
RegexIterator() = default;
RegexIterator(Iterator begin, Iterator end, const Regex& re,
RegexConstant::match_flag_type flags = RegexConstant::match_default)
: RegexIteratorBase<Iterator>{Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags} {}
const ValueType& operator*() const { return *reinterpret_cast<const ValueType*>(&RegexIteratorBase<Iterator>::operator*()); }
const ValueType* operator->() const { return reinterpret_cast<const ValueType*>(RegexIteratorBase<Iterator>::operator->()); }
};
inline RegexConstant::match_flag_type match_flags(bool bol, bool eol, bool bow, bool eow)
{
return (bol ? RegexConstant::match_default : RegexConstant::match_not_bol) |
(eol ? RegexConstant::match_default : RegexConstant::match_not_eol) |
(bow ? RegexConstant::match_default : RegexConstant::match_not_bow) |
(eow ? RegexConstant::match_default : RegexConstant::match_not_eow);
}
template<typename It>
bool regex_match(It begin, It end, const Regex& re)
{
using Utf8It = RegexUtf8It<It>;
return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re);
}
template<typename It>
bool regex_match(It begin, It end, MatchResults<It>& res, const Regex& re)
{
using Utf8It = RegexUtf8It<It>;
return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re);
}
template<typename It>
bool regex_search(It begin, It end, const Regex& re,
RegexConstant::match_flag_type flags = RegexConstant::match_default)
{
using Utf8It = RegexUtf8It<It>;
return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re);
}
template<typename It>
bool regex_search(It begin, It end, MatchResults<It>& res, const Regex& re,
RegexConstant::match_flag_type flags = RegexConstant::match_default)
{
using Utf8It = RegexUtf8It<It>;
return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re);
}
String option_to_string(const Regex& re);
void option_from_string(StringView str, Regex& re);
}
#endif // regex_hh_INCLUDED
<commit_msg>Do not let boost regex errors propagate, convert them to Kakoune errors.<commit_after>#ifndef regex_hh_INCLUDED
#define regex_hh_INCLUDED
#include "string.hh"
#include "exception.hh"
#include "utf8_iterator.hh"
#include <boost/regex.hpp>
namespace Kakoune
{
struct regex_error : runtime_error
{
regex_error(StringView desc)
: runtime_error{format("regex error: '{}'", desc)}
{}
};
using RegexBase = boost::basic_regex<wchar_t, boost::c_regex_traits<wchar_t>>;
// Regex that keeps track of its string representation
struct Regex : RegexBase
{
Regex() = default;
explicit Regex(StringView re, flag_type flags = ECMAScript);
bool empty() const { return m_str.empty(); }
bool operator==(const Regex& other) const { return m_str == other.m_str; }
bool operator!=(const Regex& other) const { return m_str != other.m_str; }
const String& str() const { return m_str; }
static constexpr const char* option_type_name = "regex";
private:
String m_str;
};
template<typename It>
using RegexUtf8It = utf8::iterator<It, wchar_t, ssize_t>;
template<typename It>
using RegexIteratorBase = boost::regex_iterator<RegexUtf8It<It>, wchar_t,
boost::c_regex_traits<wchar_t>>;
namespace RegexConstant = boost::regex_constants;
template<typename Iterator>
struct MatchResults : boost::match_results<RegexUtf8It<Iterator>>
{
using ParentType = boost::match_results<RegexUtf8It<Iterator>>;
struct SubMatch : std::pair<Iterator, Iterator>
{
SubMatch() = default;
SubMatch(const boost::sub_match<RegexUtf8It<Iterator>>& m)
: std::pair<Iterator, Iterator>{m.first.base(), m.second.base()},
matched{m.matched}
{}
bool matched = false;
};
struct iterator : boost::match_results<RegexUtf8It<Iterator>>::iterator
{
using ParentType = typename boost::match_results<RegexUtf8It<Iterator>>::iterator;
iterator(const ParentType& it) : ParentType(it) {}
SubMatch operator*() const { return {ParentType::operator*()}; }
};
iterator begin() const { return {ParentType::begin()}; }
iterator cbegin() const { return {ParentType::cbegin()}; }
iterator end() const { return {ParentType::end()}; }
iterator cend() const { return {ParentType::cend()}; }
SubMatch operator[](size_t s) const { return {ParentType::operator[](s)}; }
};
template<typename Iterator>
struct RegexIterator : RegexIteratorBase<Iterator>
{
using Utf8It = RegexUtf8It<Iterator>;
using ValueType = MatchResults<Iterator>;
RegexIterator() = default;
RegexIterator(Iterator begin, Iterator end, const Regex& re,
RegexConstant::match_flag_type flags = RegexConstant::match_default)
: RegexIteratorBase<Iterator>{Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re, flags} {}
const ValueType& operator*() const { return *reinterpret_cast<const ValueType*>(&RegexIteratorBase<Iterator>::operator*()); }
const ValueType* operator->() const { return reinterpret_cast<const ValueType*>(RegexIteratorBase<Iterator>::operator->()); }
};
inline RegexConstant::match_flag_type match_flags(bool bol, bool eol, bool bow, bool eow)
{
return (bol ? RegexConstant::match_default : RegexConstant::match_not_bol) |
(eol ? RegexConstant::match_default : RegexConstant::match_not_eol) |
(bow ? RegexConstant::match_default : RegexConstant::match_not_bow) |
(eow ? RegexConstant::match_default : RegexConstant::match_not_eow);
}
template<typename It>
bool regex_match(It begin, It end, const Regex& re)
{
using Utf8It = RegexUtf8It<It>;
try
{
return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re);
}
catch (std::runtime_error& err)
{
throw runtime_error{format("Regex matching error: {}", err.what())};
}
}
template<typename It>
bool regex_match(It begin, It end, MatchResults<It>& res, const Regex& re)
{
using Utf8It = RegexUtf8It<It>;
try
{
return boost::regex_match(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re);
}
catch (std::runtime_error& err)
{
throw runtime_error{format("Regex matching error: {}", err.what())};
}
}
template<typename It>
bool regex_search(It begin, It end, const Regex& re,
RegexConstant::match_flag_type flags = RegexConstant::match_default)
{
using Utf8It = RegexUtf8It<It>;
try
{
return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, re);
}
catch (std::runtime_error& err)
{
throw runtime_error{format("Regex searching error: {}", err.what())};
}
}
template<typename It>
bool regex_search(It begin, It end, MatchResults<It>& res, const Regex& re,
RegexConstant::match_flag_type flags = RegexConstant::match_default)
{
using Utf8It = RegexUtf8It<It>;
try
{
return boost::regex_search(Utf8It{begin, begin, end}, Utf8It{end, begin, end}, res, re);
}
catch (std::runtime_error& err)
{
throw runtime_error{format("Regex searching error: {}", err.what())};
}
}
String option_to_string(const Regex& re);
void option_from_string(StringView str, Regex& re);
}
#endif // regex_hh_INCLUDED
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
* Copyright (c) 2014, RadiantBlue Technologies, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PCL_SEGMENTATION_APPROXIMATE_PROGRESSIVE_MORPHOLOGICAL_FILTER_HPP_
#define PCL_SEGMENTATION_APPROXIMATE_PROGRESSIVE_MORPHOLOGICAL_FILTER_HPP_
#include <pcl/common/common.h>
#include <pcl/common/io.h>
#include <pcl/filters/morphological_filter.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/segmentation/approximate_progressive_morphological_filter.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::ApproximateProgressiveMorphologicalFilter<PointT>::ApproximateProgressiveMorphologicalFilter () :
max_window_size_ (33),
slope_ (0.7f),
max_distance_ (10.0f),
initial_distance_ (0.15f),
cell_size_ (1.0f),
base_ (2.0f),
exponential_ (true),
threads_ (0)
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::ApproximateProgressiveMorphologicalFilter<PointT>::~ApproximateProgressiveMorphologicalFilter ()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::ApproximateProgressiveMorphologicalFilter<PointT>::extract (std::vector<int>& ground)
{
bool segmentation_is_possible = initCompute ();
if (!segmentation_is_possible)
{
deinitCompute ();
return;
}
// Compute the series of window sizes and height thresholds
std::vector<float> height_thresholds;
std::vector<float> window_sizes;
std::vector<int> half_sizes;
int iteration = 0;
int half_size = 0.0f;
float window_size = 0.0f;
float height_threshold = 0.0f;
while (window_size < max_window_size_)
{
// Determine the initial window size.
if (exponential_)
half_size = static_cast<int> (std::pow (static_cast<float> (base_), iteration));
else
half_size = (iteration+1) * base_;
window_size = 2 * half_size + 1;
// Calculate the height threshold to be used in the next iteration.
if (iteration == 0)
height_threshold = initial_distance_;
else
height_threshold = slope_ * (window_size - window_sizes[iteration-1]) * cell_size_ + initial_distance_;
// Enforce max distance on height threshold
if (height_threshold > max_distance_)
height_threshold = max_distance_;
half_sizes.push_back (half_size);
window_sizes.push_back (window_size);
height_thresholds.push_back (height_threshold);
iteration++;
}
// setup grid based on scale and extents
Eigen::Vector4f global_max, global_min;
pcl::getMinMax3D<PointT> (*input_, global_min, global_max);
float xextent = global_max.x () - global_min.x ();
float yextent = global_max.y () - global_min.y ();
int rows = static_cast<int> (std::floor (yextent / cell_size_) + 1);
int cols = static_cast<int> (std::floor (xextent / cell_size_) + 1);
Eigen::MatrixXf A (rows, cols);
A.setConstant (std::numeric_limits<float>::quiet_NaN ());
Eigen::MatrixXf Z (rows, cols);
Z.setConstant (std::numeric_limits<float>::quiet_NaN ());
Eigen::MatrixXf Zf (rows, cols);
Zf.setConstant (std::numeric_limits<float>::quiet_NaN ());
#ifdef _OPENMP
#pragma omp parallel for num_threads(threads_)
#endif
for (size_t i = 0; i < input_->points.size (); ++i)
{
// ...then test for lower points within the cell
PointT p = input_->points[i];
int row = std::floor(p.y - global_min.y ());
int col = std::floor(p.x - global_min.x ());
if (p.z < A (row, col) || pcl_isnan (A (row, col)))
{
A (row, col) = p.z;
}
}
// Ground indices are initially limited to those points in the input cloud we
// wish to process
ground = *indices_;
// Progressively filter ground returns using morphological open
for (size_t i = 0; i < window_sizes.size (); ++i)
{
PCL_DEBUG (" Iteration %d (height threshold = %f, window size = %f, half size = %d)...",
i, height_thresholds[i], window_sizes[i], half_sizes[i]);
// Limit filtering to those points currently considered ground returns
typename pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>);
pcl::copyPointCloud<PointT> (*input_, ground, *cloud);
// Apply the morphological opening operation at the current window size.
#ifdef _OPENMP
#pragma omp parallel for num_threads(threads_)
#endif
for (int row = 0; row < rows; ++row)
{
int rs, re;
rs = ((row - half_sizes[i]) < 0) ? 0 : row - half_sizes[i];
re = ((row + half_sizes[i]) > (rows-1)) ? (rows-1) : row + half_sizes[i];
for (int col = 0; col < cols; ++col)
{
int cs, ce;
cs = ((col - half_sizes[i]) < 0) ? 0 : col - half_sizes[i];
ce = ((col + half_sizes[i]) > (cols-1)) ? (cols-1) : col + half_sizes[i];
float min_coeff = std::numeric_limits<float>::max ();
for (int j = rs; j < (re + 1); ++j)
{
for (int k = cs; k < (ce + 1); ++k)
{
if (A (j, k) != std::numeric_limits<float>::quiet_NaN ())
{
if (A (j, k) < min_coeff)
min_coeff = A (j, k);
}
}
}
if (min_coeff != std::numeric_limits<float>::max ())
Z(row, col) = min_coeff;
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(threads_)
#endif
for (int row = 0; row < rows; ++row)
{
int rs, re;
rs = ((row - half_sizes[i]) < 0) ? 0 : row - half_sizes[i];
re = ((row + half_sizes[i]) > (rows-1)) ? (rows-1) : row + half_sizes[i];
for (int col = 0; col < cols; ++col)
{
int cs, ce;
cs = ((col - half_sizes[i]) < 0) ? 0 : col - half_sizes[i];
ce = ((col + half_sizes[i]) > (cols-1)) ? (cols-1) : col + half_sizes[i];
float max_coeff = -std::numeric_limits<float>::max ();
for (int j = rs; j < (re + 1); ++j)
{
for (int k = cs; k < (ce + 1); ++k)
{
if (Z (j, k) != std::numeric_limits<float>::quiet_NaN ())
{
if (Z (j, k) > max_coeff)
max_coeff = Z (j, k);
}
}
}
if (max_coeff != -std::numeric_limits<float>::max ())
Zf (row, col) = max_coeff;
}
}
// Find indices of the points whose difference between the source and
// filtered point clouds is less than the current height threshold.
std::vector<int> pt_indices;
for (size_t p_idx = 0; p_idx < ground.size (); ++p_idx)
{
PointT p = cloud->points[p_idx];
int erow = static_cast<int> (std::floor ((p.y - global_min.y ()) / cell_size_));
int ecol = static_cast<int> (std::floor ((p.x - global_min.x ()) / cell_size_));
float diff = p.z - Zf (erow, ecol);
if (diff < height_thresholds[i])
pt_indices.push_back (ground[p_idx]);
}
A.swap (Zf);
// Ground is now limited to pt_indices
ground.swap (pt_indices);
PCL_DEBUG ("ground now has %d points\n", ground.size ());
}
deinitCompute ();
}
#define PCL_INSTANTIATE_ApproximateProgressiveMorphologicalFilter(T) template class pcl::ApproximateProgressiveMorphologicalFilter<T>;
#endif // PCL_SEGMENTATION_APPROXIMATE_PROGRESSIVE_MORPHOLOGICAL_FILTER_HPP_
<commit_msg>fix for MSVC build (OpenMP parallelized for-loop does not accept size_t variable)<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
* Copyright (c) 2014, RadiantBlue Technologies, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the copyright holder(s) 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef PCL_SEGMENTATION_APPROXIMATE_PROGRESSIVE_MORPHOLOGICAL_FILTER_HPP_
#define PCL_SEGMENTATION_APPROXIMATE_PROGRESSIVE_MORPHOLOGICAL_FILTER_HPP_
#include <pcl/common/common.h>
#include <pcl/common/io.h>
#include <pcl/filters/morphological_filter.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/segmentation/approximate_progressive_morphological_filter.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::ApproximateProgressiveMorphologicalFilter<PointT>::ApproximateProgressiveMorphologicalFilter () :
max_window_size_ (33),
slope_ (0.7f),
max_distance_ (10.0f),
initial_distance_ (0.15f),
cell_size_ (1.0f),
base_ (2.0f),
exponential_ (true),
threads_ (0)
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT>
pcl::ApproximateProgressiveMorphologicalFilter<PointT>::~ApproximateProgressiveMorphologicalFilter ()
{
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointT> void
pcl::ApproximateProgressiveMorphologicalFilter<PointT>::extract (std::vector<int>& ground)
{
bool segmentation_is_possible = initCompute ();
if (!segmentation_is_possible)
{
deinitCompute ();
return;
}
// Compute the series of window sizes and height thresholds
std::vector<float> height_thresholds;
std::vector<float> window_sizes;
std::vector<int> half_sizes;
int iteration = 0;
int half_size = 0.0f;
float window_size = 0.0f;
float height_threshold = 0.0f;
while (window_size < max_window_size_)
{
// Determine the initial window size.
if (exponential_)
half_size = static_cast<int> (std::pow (static_cast<float> (base_), iteration));
else
half_size = (iteration+1) * base_;
window_size = 2 * half_size + 1;
// Calculate the height threshold to be used in the next iteration.
if (iteration == 0)
height_threshold = initial_distance_;
else
height_threshold = slope_ * (window_size - window_sizes[iteration-1]) * cell_size_ + initial_distance_;
// Enforce max distance on height threshold
if (height_threshold > max_distance_)
height_threshold = max_distance_;
half_sizes.push_back (half_size);
window_sizes.push_back (window_size);
height_thresholds.push_back (height_threshold);
iteration++;
}
// setup grid based on scale and extents
Eigen::Vector4f global_max, global_min;
pcl::getMinMax3D<PointT> (*input_, global_min, global_max);
float xextent = global_max.x () - global_min.x ();
float yextent = global_max.y () - global_min.y ();
int rows = static_cast<int> (std::floor (yextent / cell_size_) + 1);
int cols = static_cast<int> (std::floor (xextent / cell_size_) + 1);
Eigen::MatrixXf A (rows, cols);
A.setConstant (std::numeric_limits<float>::quiet_NaN ());
Eigen::MatrixXf Z (rows, cols);
Z.setConstant (std::numeric_limits<float>::quiet_NaN ());
Eigen::MatrixXf Zf (rows, cols);
Zf.setConstant (std::numeric_limits<float>::quiet_NaN ());
#ifdef _OPENMP
#pragma omp parallel for num_threads(threads_)
#endif
for (int i = 0; i < (int)input_->points.size (); ++i)
{
// ...then test for lower points within the cell
PointT p = input_->points[i];
int row = std::floor(p.y - global_min.y ());
int col = std::floor(p.x - global_min.x ());
if (p.z < A (row, col) || pcl_isnan (A (row, col)))
{
A (row, col) = p.z;
}
}
// Ground indices are initially limited to those points in the input cloud we
// wish to process
ground = *indices_;
// Progressively filter ground returns using morphological open
for (size_t i = 0; i < window_sizes.size (); ++i)
{
PCL_DEBUG (" Iteration %d (height threshold = %f, window size = %f, half size = %d)...",
i, height_thresholds[i], window_sizes[i], half_sizes[i]);
// Limit filtering to those points currently considered ground returns
typename pcl::PointCloud<PointT>::Ptr cloud (new pcl::PointCloud<PointT>);
pcl::copyPointCloud<PointT> (*input_, ground, *cloud);
// Apply the morphological opening operation at the current window size.
#ifdef _OPENMP
#pragma omp parallel for num_threads(threads_)
#endif
for (int row = 0; row < rows; ++row)
{
int rs, re;
rs = ((row - half_sizes[i]) < 0) ? 0 : row - half_sizes[i];
re = ((row + half_sizes[i]) > (rows-1)) ? (rows-1) : row + half_sizes[i];
for (int col = 0; col < cols; ++col)
{
int cs, ce;
cs = ((col - half_sizes[i]) < 0) ? 0 : col - half_sizes[i];
ce = ((col + half_sizes[i]) > (cols-1)) ? (cols-1) : col + half_sizes[i];
float min_coeff = std::numeric_limits<float>::max ();
for (int j = rs; j < (re + 1); ++j)
{
for (int k = cs; k < (ce + 1); ++k)
{
if (A (j, k) != std::numeric_limits<float>::quiet_NaN ())
{
if (A (j, k) < min_coeff)
min_coeff = A (j, k);
}
}
}
if (min_coeff != std::numeric_limits<float>::max ())
Z(row, col) = min_coeff;
}
}
#ifdef _OPENMP
#pragma omp parallel for num_threads(threads_)
#endif
for (int row = 0; row < rows; ++row)
{
int rs, re;
rs = ((row - half_sizes[i]) < 0) ? 0 : row - half_sizes[i];
re = ((row + half_sizes[i]) > (rows-1)) ? (rows-1) : row + half_sizes[i];
for (int col = 0; col < cols; ++col)
{
int cs, ce;
cs = ((col - half_sizes[i]) < 0) ? 0 : col - half_sizes[i];
ce = ((col + half_sizes[i]) > (cols-1)) ? (cols-1) : col + half_sizes[i];
float max_coeff = -std::numeric_limits<float>::max ();
for (int j = rs; j < (re + 1); ++j)
{
for (int k = cs; k < (ce + 1); ++k)
{
if (Z (j, k) != std::numeric_limits<float>::quiet_NaN ())
{
if (Z (j, k) > max_coeff)
max_coeff = Z (j, k);
}
}
}
if (max_coeff != -std::numeric_limits<float>::max ())
Zf (row, col) = max_coeff;
}
}
// Find indices of the points whose difference between the source and
// filtered point clouds is less than the current height threshold.
std::vector<int> pt_indices;
for (size_t p_idx = 0; p_idx < ground.size (); ++p_idx)
{
PointT p = cloud->points[p_idx];
int erow = static_cast<int> (std::floor ((p.y - global_min.y ()) / cell_size_));
int ecol = static_cast<int> (std::floor ((p.x - global_min.x ()) / cell_size_));
float diff = p.z - Zf (erow, ecol);
if (diff < height_thresholds[i])
pt_indices.push_back (ground[p_idx]);
}
A.swap (Zf);
// Ground is now limited to pt_indices
ground.swap (pt_indices);
PCL_DEBUG ("ground now has %d points\n", ground.size ());
}
deinitCompute ();
}
#define PCL_INSTANTIATE_ApproximateProgressiveMorphologicalFilter(T) template class pcl::ApproximateProgressiveMorphologicalFilter<T>;
#endif // PCL_SEGMENTATION_APPROXIMATE_PROGRESSIVE_MORPHOLOGICAL_FILTER_HPP_
<|endoftext|> |
<commit_before>/*
* qiaffine.cpp
*
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <iostream>
#include "itkImageIOFactory.h"
#include "itkVersor.h"
#include "itkVersorRigid3DTransform.h"
#include "itkCenteredAffineTransform.h"
#include "itkTransformFileWriter.h"
#include "itkPermuteAxesImageFilter.h"
#include "itkFlipImageFilter.h"
#include "itkImageMomentsCalculator.h"
#include "Util.h"
#include "ImageIO.h"
#include "Args.h"
using namespace std;
/*
* Declare arguments here so they are available to pipeline
*/
args::ArgumentParser parser("Applies simple affine transformations to images by manipulating the header\n"
"transforms. If an output file is not specified, the input file will be\n"
"overwritten.\n"
"http://github.com/spinicist/QUIT");
args::Positional<std::string> source_path(parser, "SOURCE", "Source file");
args::Positional<std::string> dest_path(parser, "DEST", "Destination file");
args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
args::ValueFlag<std::string> center(parser, "CENTER", "Set the origin to geometric center (geo) or (cog)", {'c', "center"});
args::ValueFlag<std::string> tfm_path(parser, "TFM", "Write out the transformation to a file", {'t', "tfm"});
args::ValueFlag<double> scale(parser, "SCALE", "Scale by a constant", {'s', "scale"});
args::ValueFlag<double> offX(parser, "OFF_X", "Translate origin in X direction", {"offX"});
args::ValueFlag<double> offY(parser, "OFF_Y", "Translate origin in Y direction", {"offY"});
args::ValueFlag<double> offZ(parser, "OFF_Z", "Translate origin in Z direction", {"offZ"});
args::ValueFlag<double> rotX(parser, "ROT_X", "Rotate about X-axis by angle (degrees)", {"rotX"});
args::ValueFlag<double> rotY(parser, "ROT_Y", "Rotate about Y-axis by angle (degrees)", {"rotY"});
args::ValueFlag<double> rotZ(parser, "ROT_Z", "Rotate about Z-axis by angle (degrees)", {"rotZ"});
args::ValueFlag<std::string> permute(parser, "PERMUTE", "Permute axes, e.g. 2,0,1. Negative values mean flip as well", {"permute"});
args::ValueFlag<std::string> flip(parser, "FLIP", "Flip an axis, e.g. 0,1,0. Occurs AFTER any permutation.", {"flip"});
template<typename TImage>
int Pipeline() {
auto image = QI::ReadImage<TImage>(QI::CheckPos(source_path));
// Permute if required
if (permute) {
auto permute_filter = itk::PermuteAxesImageFilter<TImage>::New();
itk::FixedArray<unsigned int, TImage::ImageDimension> permute_order;
std::istringstream iss(permute.Get());
std::string el;
for (int i = 0; i < 3; i++) {
std::getline(iss, el, ',');
permute_order[i] = std::stoi(el);
}
for (int i = 3; i < TImage::ImageDimension; i++) {
permute_order[i] = i;
}
if (!iss)
QI_FAIL("Failed to read permutation order: " << permute.Get());
permute_filter->SetInput(image);
permute_filter->SetOrder(permute_order);
permute_filter->Update();
image = permute_filter->GetOutput();
image->DisconnectPipeline();
}
// Flip if required
if (flip) {
auto flip_filter = itk::FlipImageFilter<TImage>::New();
itk::FixedArray<bool, TImage::ImageDimension> flip_axes; // Save this
std::istringstream iss(flip.Get());
std::string el;
for (int i = 0; i < 3; i++) {
std::getline(iss, el, ',');
flip_axes[i] = (std::stoi(el) > 0);
}
for (int i = 3; i < TImage::ImageDimension; i++) {
flip_axes[i] = false;
}
if (!iss)
QI_FAIL("Failed to read flip: " << flip.Get());
if (verbose) std::cout << "Flipping: " << flip_axes << std::endl;
flip_filter->SetInput(image);
flip_filter->SetFlipAxes(flip_axes);
flip_filter->SetFlipAboutOrigin(false);
flip_filter->Update();
image = flip_filter->GetOutput();
image->DisconnectPipeline();
}
typename TImage::DirectionType fullDir = image->GetDirection();
typename TImage::SpacingType fullSpacing = image->GetSpacing();
typename TImage::PointType fullOrigin = image->GetOrigin();
typename TImage::SizeType fullSize = image->GetLargestPossibleRegion().GetSize();
QI::VolumeF::DirectionType direction;
QI::VolumeF::SpacingType spacing;
typedef itk::CenteredAffineTransform<double, 3> TAffine;
TAffine::OutputVectorType origin;
QI::VolumeF::SizeType size;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
direction[i][j] = fullDir[i][j];
}
origin[i] = fullOrigin[i];
spacing[i] = fullSpacing[i];
size[i] = fullSize[i];
}
auto img_tfm = TAffine::New();
img_tfm->SetMatrix(direction);
img_tfm->Scale(spacing);
img_tfm->Translate(origin);
if (verbose) std::cout << "Start transform:\n" << img_tfm->GetMatrix() << std::endl;
auto tfm = TAffine::New();
if (scale) {
if (verbose) cout << "Scaling by factor " << scale.Get() << endl;
tfm->Scale(scale.Get());
}
if (rotX != 0.0) {
if (verbose) cout << "Rotating image by " << rotX.Get() << " around X axis." << endl;
tfm->Rotate(1,2,rotX.Get() * M_PI / 180.0);
}
if (rotY != 0.0) {
if (verbose) cout << "Rotating image by " << rotY.Get() << " around X axis." << endl;
tfm->Rotate(2,0,rotY.Get() * M_PI / 180.0);
}
if (rotZ != 0.0) {
if (verbose) cout << "Rotating image by " << rotZ.Get() << " around X axis." << endl;
tfm->Rotate(0,1,rotZ.Get() * M_PI / 180.0);
}
itk::Versor<double>::VectorType offset; offset.Fill(0);
if (center) {
if (center.Get() == "geo") {
if (verbose) std::cout << "Setting geometric center" << std::endl;
for (int i = 0; i < 3; i++) {
offset[i] = origin[i]-spacing[i]*size[i] / 2;
}
} else if (center.Get() == "cog") {
if (verbose) std::cout << "Setting center to center of gravity" << std::endl;
auto moments = itk::ImageMomentsCalculator<TImage>::New();
moments->SetImage(image);
moments->Compute();
// ITK seems to put a negative sign on the CoG
for (int i = 0; i < 3; i++) {
offset[i] = moments->GetCenterOfGravity()[i];
}
}
std::cout << "Translation will be: " << offset << std::endl;
tfm->Translate(-offset);
} else if (offX || offY || offZ) {
offset[0] = offX.Get();
offset[1] = offY.Get();
offset[2] = offZ.Get();
if (verbose) std::cout << "Translating by: " << offset << std::endl;
tfm->Translate(-offset);
}
if (tfm_path) { // Output the transform file
auto writer = itk::TransformFileWriterTemplate<double>::New();
writer->SetInput(tfm);
writer->SetFileName(tfm_path.Get());
writer->Update();
}
img_tfm->Compose(tfm);
itk::CenteredAffineTransform<double, 3>::MatrixType fmat = img_tfm->GetMatrix();
if (verbose) std::cout << "Final transform:\n" << fmat << std::endl;
for (int i = 0; i < 3; i++) {
fullOrigin[i] = img_tfm->GetOffset()[i];
}
for (int j = 0; j < 3; j++) {
double scale = 0.;
for (int i = 0; i < 3; i++) {
scale += fmat[i][j]*fmat[i][j];
}
scale = sqrt(scale);
fullSpacing[j] = scale;
for (int i = 0; i < 3; i++) {
fullDir[i][j] = fmat[i][j] / scale;
}
}
image->SetDirection(fullDir);
image->SetOrigin(fullOrigin);
image->SetSpacing(fullSpacing);
// Write out the edited file
if (dest_path) {
if (verbose) std::cout << "Writing: " << dest_path.Get() << std::endl;
QI::WriteImage(image, dest_path.Get());
} else {
if (verbose) std::cout << "Writing: " << source_path.Get() << std::endl;
QI::WriteImage(image, source_path.Get());
}
return EXIT_SUCCESS;
}
int main(int argc, char **argv) {
QI::ParseArgs(parser, argc, argv, verbose);
if (verbose) std::cout << "Reading header for: " << QI::CheckPos(source_path) << std::endl;
auto header = itk::ImageIOFactory::CreateImageIO(QI::CheckPos(source_path).c_str(), itk::ImageIOFactory::ReadMode);
if (!header) {
QI_EXCEPTION("Failed to read header from: " << source_path.Get());
}
header->SetFileName(source_path.Get());
header->ReadImageInformation();
auto dims = header->GetNumberOfDimensions();
auto dtype = header->GetComponentType();
if (verbose) std::cout << "Datatype is " << header->GetComponentTypeAsString( dtype ) << std::endl;
#define DIM_SWITCH( TYPE ) \
switch (dims) { \
case 3: return Pipeline<itk::Image< TYPE , 3 >>(); \
case 4: return Pipeline<itk::Image< TYPE , 4 >>(); \
default: QI_FAIL("Unsupported dimension: " << dims); return EXIT_FAILURE; \
}
switch (dtype) {
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: QI_FAIL("Unknown component type in image " << source_path);
/*case itk::ImageIOBase::UCHAR: DIM_SWITCH( unsigned char ); break;
case itk::ImageIOBase::CHAR: DIM_SWITCH( char ); break;
case itk::ImageIOBase::USHORT: DIM_SWITCH( unsigned short ); break;
case itk::ImageIOBase::SHORT: DIM_SWITCH( short ); break;
case itk::ImageIOBase::UINT: DIM_SWITCH( unsigned int ); break;
case itk::ImageIOBase::INT: DIM_SWITCH( int ); break;
case itk::ImageIOBase::ULONG: DIM_SWITCH( unsigned long ); break;
case itk::ImageIOBase::LONG: DIM_SWITCH( long ); break;
case itk::ImageIOBase::LONGLONG: DIM_SWITCH( long long ); break;
case itk::ImageIOBase::ULONGLONG: DIM_SWITCH( unsigned long long ); break;*/
case itk::ImageIOBase::FLOAT: DIM_SWITCH( float ); break;
case itk::ImageIOBase::DOUBLE: DIM_SWITCH( double ); break;
default: QI_FAIL("Unimplemented component type: " << dtype << " in image " << source_path);
}
}
<commit_msg>BUG: qiaffine was mangling non-isotropic voxel spacings<commit_after>/*
* qiaffine.cpp
*
* Copyright (c) 2015 Tobias Wood.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
#include <iostream>
#include "itkImageIOFactory.h"
#include "itkVersor.h"
#include "itkVersorRigid3DTransform.h"
#include "itkCenteredAffineTransform.h"
#include "itkEuler3DTransform.h"
#include "itkTransformFileWriter.h"
#include "itkPermuteAxesImageFilter.h"
#include "itkFlipImageFilter.h"
#include "itkImageMomentsCalculator.h"
#include "Util.h"
#include "ImageIO.h"
#include "Args.h"
/*
* Declare arguments here so they are available to pipeline
*/
args::ArgumentParser parser("Applies simple affine transformations to images by manipulating the header\n"
"transforms. If an output file is not specified, the input file will be\n"
"overwritten.\n"
"http://github.com/spinicist/QUIT");
args::Positional<std::string> source_path(parser, "SOURCE", "Source file");
args::Positional<std::string> dest_path(parser, "DEST", "Destination file");
args::HelpFlag help(parser, "HELP", "Show this help menu", {'h', "help"});
args::Flag verbose(parser, "VERBOSE", "Print more information", {'v', "verbose"});
args::ValueFlag<std::string> center(parser, "CENTER", "Set the origin to geometric center (geo) or (cog)", {'c', "center"});
args::ValueFlag<std::string> tfm_path(parser, "TFM", "Write out the transformation to a file", {'t', "tfm"});
args::ValueFlag<std::string> permute(parser, "PERMUTE", "Permute axes in data-space, e.g. 2,0,1. Negative values mean flip as well", {"permute"});
args::ValueFlag<std::string> flip(parser, "FLIP", "Flip axes in data-space, e.g. 0,1,0. Occurs AFTER any permutation.", {"flip"});
args::ValueFlag<double> scale(parser, "SCALE", "Scale by a constant", {'s', "scale"});
args::ValueFlag<std::string> translate(parser, "TRANSLATE", "Translate image by X,Y,Z (mm)", {"trans"}, "0,0,0");
args::ValueFlag<std::string> rotate(parser, "ROTATE", "Rotate by Euler angles around X,Y,Z (degrees).", {"rotate"}, "0,0,0");
template<typename TImage>
int Pipeline() {
auto image = QI::ReadImage<TImage>(QI::CheckPos(source_path));
// Permute if required
if (permute) {
auto permute_filter = itk::PermuteAxesImageFilter<TImage>::New();
itk::FixedArray<unsigned int, TImage::ImageDimension> permute_order;
std::istringstream iss(permute.Get());
std::string el;
for (int i = 0; i < 3; i++) {
std::getline(iss, el, ',');
permute_order[i] = std::stoi(el);
}
for (int i = 3; i < TImage::ImageDimension; i++) {
permute_order[i] = i;
}
if (!iss)
QI_FAIL("Failed to read permutation order: " << permute.Get());
permute_filter->SetInput(image);
permute_filter->SetOrder(permute_order);
permute_filter->Update();
image = permute_filter->GetOutput();
image->DisconnectPipeline();
}
// Flip if required
if (flip) {
auto flip_filter = itk::FlipImageFilter<TImage>::New();
itk::FixedArray<bool, TImage::ImageDimension> flip_axes; // Save this
std::istringstream iss(flip.Get());
std::string el;
for (int i = 0; i < 3; i++) {
std::getline(iss, el, ',');
flip_axes[i] = (std::stoi(el) > 0);
}
for (int i = 3; i < TImage::ImageDimension; i++) {
flip_axes[i] = false;
}
if (!iss)
QI_FAIL("Failed to read flip: " << flip.Get());
if (verbose) std::cout << "Flipping: " << flip_axes << std::endl;
flip_filter->SetInput(image);
flip_filter->SetFlipAxes(flip_axes);
flip_filter->SetFlipAboutOrigin(false);
flip_filter->Update();
image = flip_filter->GetOutput();
image->DisconnectPipeline();
}
typename TImage::DirectionType fullDir = image->GetDirection();
typename TImage::SpacingType fullSpacing = image->GetSpacing();
typename TImage::PointType fullOrigin = image->GetOrigin();
typename TImage::SizeType fullSize = image->GetLargestPossibleRegion().GetSize();
QI::VolumeF::DirectionType direction;
QI::VolumeF::SpacingType spacing;
using Affine = itk::CenteredAffineTransform<double, 3>;
using Euler = itk::Euler3DTransform<double>;
Affine::OutputVectorType origin;
QI::VolumeF::SizeType size;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
direction[i][j] = fullDir[i][j];
}
origin[i] = fullOrigin[i];
spacing[i] = fullSpacing[i];
size[i] = fullSize[i];
}
auto img_tfm = Affine::New();
img_tfm->SetMatrix(direction);
img_tfm->Scale(spacing);
img_tfm->Translate(origin);
if (scale) {
if (verbose) std::cout << "Scaling by factor " << scale.Get() << std::endl;
img_tfm->Scale(scale.Get());
}
auto tfm = Euler::New();
if (rotate) {
Eigen::Array3d angles; QI::ArrayArg<Eigen::Array3d, 3>(rotate.Get(), angles);
tfm->SetRotation(angles[0]*M_PI/180., angles[1]*M_PI/180., angles[2]*M_PI/180.);
if (verbose) std::cout << "Rotation by: " << angles.transpose() << std::endl;
}
if (translate) {
Euler::OffsetType offset; QI::ArrayArg<Euler::OffsetType, 3>(translate.Get(), offset);
tfm->Translate(-offset);
if (verbose) std::cout << "Translate by: " << offset << std::endl;
}
if (center) {
Euler::OffsetType offset; offset.Fill(0.);
if (center.Get() == "geo") {
if (verbose) std::cout << "Setting geometric center" << std::endl;
for (int i = 0; i < 3; i++) {
offset[i] = origin[i]-spacing[i]*size[i] / 2;
}
} else if (center.Get() == "cog") {
if (verbose) std::cout << "Setting center to center of gravity" << std::endl;
auto moments = itk::ImageMomentsCalculator<TImage>::New();
moments->SetImage(image);
moments->Compute();
// ITK seems to put a negative sign on the CoG
for (int i = 0; i < 3; i++) {
offset[i] = moments->GetCenterOfGravity()[i];
}
}
std::cout << "Translation will be: " << offset << std::endl;
tfm->Translate(-offset);
}
if (tfm_path) { // Output the transform file
auto writer = itk::TransformFileWriterTemplate<double>::New();
writer->SetInput(tfm);
writer->SetFileName(tfm_path.Get());
if (verbose) std::cout << "Writing transform file: " << tfm_path.Get() << std::endl;
writer->Update();
}
img_tfm->Compose(tfm);
itk::CenteredAffineTransform<double, 3>::MatrixType fmat = img_tfm->GetMatrix();
if (verbose) std::cout << "Final transform:\n" << fmat << std::endl;
for (int i = 0; i < 3; i++) {
fullOrigin[i] = img_tfm->GetOffset()[i];
}
for (int j = 0; j < 3; j++) {
double scale = 0.;
for (int i = 0; i < 3; i++) {
scale += fmat[i][j]*fmat[i][j];
}
scale = sqrt(scale);
for (int i = 0; i < 3; i++) {
fullDir[i][j] = fmat[i][j] / scale;
}
}
image->SetDirection(fullDir);
image->SetOrigin(fullOrigin);
image->SetSpacing(fullSpacing);
// Write out the edited file
if (dest_path) {
if (verbose) std::cout << "Writing: " << dest_path.Get() << std::endl;
QI::WriteImage(image, dest_path.Get());
} else {
if (verbose) std::cout << "Writing: " << source_path.Get() << std::endl;
QI::WriteImage(image, source_path.Get());
}
return EXIT_SUCCESS;
}
int main(int argc, char **argv) {
QI::ParseArgs(parser, argc, argv, verbose);
if (verbose) std::cout << "Reading header for: " << QI::CheckPos(source_path) << std::endl;
auto header = itk::ImageIOFactory::CreateImageIO(QI::CheckPos(source_path).c_str(), itk::ImageIOFactory::ReadMode);
if (!header) {
QI_EXCEPTION("Failed to read header from: " << source_path.Get());
}
header->SetFileName(source_path.Get());
header->ReadImageInformation();
auto dims = header->GetNumberOfDimensions();
auto dtype = header->GetComponentType();
if (verbose) std::cout << "Datatype is " << header->GetComponentTypeAsString( dtype ) << std::endl;
#define DIM_SWITCH( TYPE ) \
switch (dims) { \
case 3: return Pipeline<itk::Image< TYPE , 3 >>(); \
case 4: return Pipeline<itk::Image< TYPE , 4 >>(); \
default: QI_FAIL("Unsupported dimension: " << dims); return EXIT_FAILURE; \
}
switch (dtype) {
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: QI_FAIL("Unknown component type in image " << source_path);
/*case itk::ImageIOBase::UCHAR: DIM_SWITCH( unsigned char ); break;
case itk::ImageIOBase::CHAR: DIM_SWITCH( char ); break;
case itk::ImageIOBase::USHORT: DIM_SWITCH( unsigned short ); break;
case itk::ImageIOBase::SHORT: DIM_SWITCH( short ); break;
case itk::ImageIOBase::UINT: DIM_SWITCH( unsigned int ); break;
case itk::ImageIOBase::INT: DIM_SWITCH( int ); break;
case itk::ImageIOBase::ULONG: DIM_SWITCH( unsigned long ); break;
case itk::ImageIOBase::LONG: DIM_SWITCH( long ); break;
case itk::ImageIOBase::LONGLONG: DIM_SWITCH( long long ); break;
case itk::ImageIOBase::ULONGLONG: DIM_SWITCH( unsigned long long ); break;*/
case itk::ImageIOBase::FLOAT: DIM_SWITCH( float ); break;
case itk::ImageIOBase::DOUBLE: DIM_SWITCH( double ); break;
default: QI_FAIL("Unimplemented component type: " << dtype << " in image " << source_path);
}
}
<|endoftext|> |
<commit_before>#include <QDebug>
#include "helpwindow.h"
#include "ui_helpwindow.h"
HelpWindow* HelpWindow::self = 0;
HelpWindow::HelpWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::HelpWindow)
{
ui->setupUi(this);
m_helpEngine = new QHelpEngineCore("SavvyCAN.qhc", this);
if (!m_helpEngine->setupData()) {
delete m_helpEngine;
m_helpEngine = 0;
qDebug() << "Could not load help file!";
}
readSettings();
}
HelpWindow::~HelpWindow()
{
writeSettings();
delete ui;
}
void HelpWindow::closeEvent(QCloseEvent *event)
{
Q_UNUSED(event);
writeSettings();
}
void HelpWindow::readSettings()
{
QSettings settings;
if (settings.value("Main/SaveRestorePositions", false).toBool())
{
resize(settings.value("HelpViewer/WindowSize", QSize(600, 700)).toSize());
move(settings.value("HelpViewer/WindowPos", QPoint(50, 50)).toPoint());
}
}
void HelpWindow::writeSettings()
{
QSettings settings;
if (settings.value("Main/SaveRestorePositions", false).toBool())
{
settings.setValue("HelpViewer/WindowSize", size());
settings.setValue("HelpViewer/WindowPos", pos());
}
}
HelpWindow* HelpWindow::getRef()
{
if (!self)
{
self = new HelpWindow();
}
return self;
}
void HelpWindow::showHelp(QString help)
{
if (m_helpEngine) {
qDebug() << "Searching for " << help;
QByteArray helpData = m_helpEngine->fileData(QUrl("qthelp://org.sphinx.savvycan.181/doc/" + help));
ui->textHelp->setText(helpData);
}
else
{
qDebug() << "Help engine not loaded!";
}
readSettings();
self->show();
}
/*
QVariant HelpBrowser::loadResource(int type, const QUrl &name)
{
QByteArray ba;
if (type < 4 && m_helpEngine) {
QUrl url(name);
if (name.isRelative())
url = source().resolved(url);
ba = m_helpEngine->fileData(url);
}
return ba;
}
*/
<commit_msg>Fix to loading of online help system.<commit_after>#include <QDebug>
#include "helpwindow.h"
#include "ui_helpwindow.h"
HelpWindow* HelpWindow::self = 0;
HelpWindow::HelpWindow(QWidget *parent) :
QDialog(parent),
ui(new Ui::HelpWindow)
{
ui->setupUi(this);
m_helpEngine = new QHelpEngineCore(QApplication::applicationDirPath() +"/SavvyCAN.qhc", this);
if (!m_helpEngine->setupData()) {
delete m_helpEngine;
m_helpEngine = 0;
qDebug() << "Could not load help file!";
}
readSettings();
}
HelpWindow::~HelpWindow()
{
writeSettings();
delete ui;
}
void HelpWindow::closeEvent(QCloseEvent *event)
{
Q_UNUSED(event);
writeSettings();
}
void HelpWindow::readSettings()
{
QSettings settings;
if (settings.value("Main/SaveRestorePositions", false).toBool())
{
resize(settings.value("HelpViewer/WindowSize", QSize(600, 700)).toSize());
move(settings.value("HelpViewer/WindowPos", QPoint(50, 50)).toPoint());
}
}
void HelpWindow::writeSettings()
{
QSettings settings;
if (settings.value("Main/SaveRestorePositions", false).toBool())
{
settings.setValue("HelpViewer/WindowSize", size());
settings.setValue("HelpViewer/WindowPos", pos());
}
}
HelpWindow* HelpWindow::getRef()
{
if (!self)
{
self = new HelpWindow();
}
return self;
}
void HelpWindow::showHelp(QString help)
{
if (m_helpEngine) {
QString url = "qthelp://org.sphinx.savvycan.181/doc/" + help;
qDebug() << "Searching for " << url;
QByteArray helpData = m_helpEngine->fileData(QUrl(url));
qDebug() << "Help file size: " << helpData.length();
ui->textHelp->setText(helpData);
}
else
{
qDebug() << "Help engine not loaded!";
}
readSettings();
self->show();
}
<|endoftext|> |
<commit_before>
// (c) COPYRIGHT URI/MIT 1996
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
// jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)
// This is the source to `geturl'; a simple tool to exercise the Connect
// class. It can be used to get naked URLs as well as the DODS DAS and DDS
// objects. jhrg.
// $Log: getdap.cc,v $
// Revision 1.15 1996/11/27 22:12:33 jimg
// Expanded help to include all the verbose options.
// Added PERF macros to code around request_data() call.
//
// Revision 1.14 1996/11/20 00:37:47 jimg
// Modified -D option to correctly process the Asynchronous option.
//
// Revision 1.13 1996/11/16 00:20:47 jimg
// Fixed a bug where multiple urls failed.
//
// Revision 1.12 1996/10/31 22:24:05 jimg
// Fix the help message so that -D is not described as -A...
//
// Revision 1.11 1996/10/08 17:13:09 jimg
// Added test for the -D option so that a Ce can be supplied either with the
// -c option or using a ? at the end of the URL.
//
// Revision 1.10 1996/09/19 16:53:35 jimg
// Added code to process sequences correctly when given the -D (get data)
// option.
//
// Revision 1.9 1996/09/05 16:28:06 jimg
// Added a new option to geturl, -D, which uses the Connect::request_data
// member function to get data. Thus -a, -d and -D can be used to get the
// das, dds and data from a DODS server. Because the request_data member
// function requires a constraint expression I also added the option -c; this
// option takes as a single argument a constraint expression and passes it to
// the request_data member function. You must use -c <expr> with -D.
//
// Revision 1.8 1996/08/13 20:13:36 jimg
// Added __unused__ to definition of char rcsid[].
// Added code so that local `URLs' are skipped.
//
// Revision 1.7 1996/06/22 00:11:20 jimg
// Modified to accomodate the new Gui class.
//
// Revision 1.6 1996/06/18 23:55:33 jimg
// Added support for the GUI progress indicator.
//
// Revision 1.5 1996/06/08 00:18:38 jimg
// Initialized vcode to null.
//
// Revision 1.4 1996/05/29 22:05:57 jimg
// Fixed up the copyright header.
//
// Revision 1.3 1996/05/28 17:35:40 jimg
// Fixed verbose arguments.
//
// Revision 1.2 1996/05/28 15:49:55 jimg
// Removed code that read from the stream after the das/dds parser built the
// internal object (since there was nothing in that stream after the parse
// geturl would always crash).
//
// Revision 1.1 1996/05/22 23:34:21 jimg
// First version. Built to test the new WWW code in the class Connect.
//
#include "config_dap.h"
static char rcsid[] __unused__ = {"$Id: getdap.cc,v 1.15 1996/11/27 22:12:33 jimg Exp $"};
#include <stdio.h>
#include <assert.h>
#include <GetOpt.h>
#include <String.h>
#include "Connect.h"
void
usage(String name)
{
cerr << "Usage: " << name
<< "[AdDa] [c <expr>] [v <codes>] [m <num>] <url> [<url> ...]"
<< endl;
cerr << " " << "A: Use Connect's asynchronous mode." << endl;
cerr << " " << "d: For each URL, get the DODS DDS." << endl;
cerr << " " << "a: For each URL, get the DODS DAS." << endl;
cerr << " " << "D: For each URL, get the DODS Data." << endl;
cerr << " " << "g: Show the progress GUI." << endl;
cerr << " " << "c: <expr> is a contraint expression. Used with -D."
<< endl;
<< " " << " NB: You can use a `?' for the CE also."
<< endl;
cerr << " " << "v: <options> Verbose output; use -vd for default."
<< endl;
cerr << " " << " a: show_anchor_trace." << endl;
cerr << " " << " b: show_bind_trace." << endl;
cerr << " " << " c: show_cache_trace." << endl;
cerr << " " << " l: show_sgml_trace." << endl;
cerr << " " << " m: show_mem_trace." << endl;
cerr << " " << " p: show_protocol_trace." << endl;
cerr << " " << " s: show_stream_trace." << endl;
cerr << " " << " t: show_thread_trace." << endl;
cerr << " " << " u: show_uri_trace." << endl;
cerr << " " << "m: Request the same URL <num> times." << endl;
cerr << " " << "Without A, use the synchronous mode." << endl;
cerr << " " << "Without d or a, print the URL." << endl;
}
bool
read_data(FILE *fp)
{
char c;
if (!fp) {
cerr <<"Whoa!!! Null stream pointer." << endl;
return false;
}
// Changed from a loop that used getc() to one that uses fread(). getc()
// worked fine for transfers of text information, but *not* for binary
// transfers. fread() will handle both.
while (fread(&c, 1, 1, fp))
printf("%c", c); // stick with stdio
return true;
}
int
main(int argc, char * argv[])
{
GetOpt getopt (argc, argv, "AdaDgc:v:m:");
int option_char;
bool async = false;
bool get_das = false;
bool get_dds = false;
bool get_data = false;
bool gui = false;
bool cexpr = false;
bool verbose = false;
bool multi = false;
int times = 1;
char *vcode = NULL;
char *expr = NULL;
int vopts = 0;
while ((option_char = getopt()) != EOF)
switch (option_char)
{
case 'A': async = true; break;
case 'd': get_dds = true; break;
case 'a': get_das = true; break;
case 'D': get_data = true; break;
case 'g': gui = true; break;
case 'c':
cexpr = true; expr = getopt.optarg; break;
case 'v':
verbose = true;
vopts = strlen(getopt.optarg);
if (vopts) {
vcode = new char[vopts + 1];
strcpy(vcode, getopt.optarg);
}
break;
case 'm': multi = true; times = atoi(getopt.optarg); break;
case 'h':
case '?':
default:
usage(argv[0]); exit(1); break;
}
char c, *cc = vcode;
if (verbose && vopts > 0)
while ((c = *cc++))
switch (c) {
case 'a': WWWTRACE |= SHOW_ANCHOR_TRACE; break;
case 'b': WWWTRACE |= SHOW_BIND_TRACE; break;
case 'c': WWWTRACE |= SHOW_CACHE_TRACE; break;
case 'l': WWWTRACE |= SHOW_SGML_TRACE; break;
case 'm': WWWTRACE |= SHOW_MEM_TRACE; break;
case 'p': WWWTRACE |= SHOW_PROTOCOL_TRACE; break;
case 's': WWWTRACE |= SHOW_STREAM_TRACE; break;
case 't': WWWTRACE |= SHOW_THREAD_TRACE; break;
case 'u': WWWTRACE |= SHOW_URI_TRACE; break;
case 'd': break;
default:
cerr << "Unrecognized verbose option: `" << c << "'" << endl;
break;
}
delete vcode;
for (int i = getopt.optind; i < argc; ++i) {
if (verbose)
cerr << "Fetching " << argv[i] << ":" << endl;
String name = argv[i];
Connect url(name);
if (url.is_local()) {
cerr << "Skipping the URL `" << argv[i]
<< "' because it lacks the `http' access protocol."
<< endl;
continue;
}
if (get_das) {
for (int j = 0; j < times; ++j) {
if (!url.request_das(gui))
exit(1);
if (verbose)
cerr << "DAS:" << endl;
url.das().print();
}
}
if (get_dds) {
for (int j = 0; j < times; ++j) {
if (!url.request_dds(gui))
exit(1);
if (verbose)
cerr << "DDS:" << endl;
url.dds().print();
}
}
if (get_data) {
if (!(expr || name.contains("?"))) {
cerr << "Must supply a constraint expression with -D."
<< endl;
exit(1);
}
for (int j = 0; j < times; ++j) {
DDS &dds = url.request_data(expr, gui, async);
cout << "The data:" << endl;
for (Pix q = dds.first_var(); q; dds.next_var(q)) {
BaseType *v = dds.var(q);
switch (v->type()) {
// Sequences present a special case because I let
// their semantics get out of hand... jhrg 9/12/96
case dods_sequence_c:
((Sequence *)v)->print_all_vals(cout, url.source());
break;
default:
PERF(cerr << "Deserializing: " << dds.var(q).name() \
<< endl);
if (async && !dds.var(q)->deserialize(url.source())) {
cerr << "Asynchronous read failure." << endl;
exit(1);
}
PERF(cerr << "Deserializing complete" << endl);
dds.var(q)->print_val(cout);
break;
}
}
}
}
if (!get_das && !get_dds && !get_data) {
if (gui)
url.gui()->show_gui(gui);
String url_string = argv[i];
for (int j = 0; j < times; ++j) {
if (!url.fetch_url(url_string, async))
exit(1);
FILE *fp = url.output();
if (!read_data(fp))
exit(1);
fclose(fp);
}
}
}
}
<commit_msg>Tried to fix the online help - maybe I succeeded?<commit_after>
// (c) COPYRIGHT URI/MIT 1996
// Please read the full copyright statement in the file COPYRIGH.
//
// Authors:
// jhrg,jimg James Gallagher (jgallagher@gso.uri.edu)
// This is the source to `geturl'; a simple tool to exercise the Connect
// class. It can be used to get naked URLs as well as the DODS DAS and DDS
// objects. jhrg.
// $Log: getdap.cc,v $
// Revision 1.16 1996/12/18 18:43:32 jimg
// Tried to fix the online help - maybe I succeeded?
//
// Revision 1.15 1996/11/27 22:12:33 jimg
// Expanded help to include all the verbose options.
// Added PERF macros to code around request_data() call.
//
// Revision 1.14 1996/11/20 00:37:47 jimg
// Modified -D option to correctly process the Asynchronous option.
//
// Revision 1.13 1996/11/16 00:20:47 jimg
// Fixed a bug where multiple urls failed.
//
// Revision 1.12 1996/10/31 22:24:05 jimg
// Fix the help message so that -D is not described as -A...
//
// Revision 1.11 1996/10/08 17:13:09 jimg
// Added test for the -D option so that a Ce can be supplied either with the
// -c option or using a ? at the end of the URL.
//
// Revision 1.10 1996/09/19 16:53:35 jimg
// Added code to process sequences correctly when given the -D (get data)
// option.
//
// Revision 1.9 1996/09/05 16:28:06 jimg
// Added a new option to geturl, -D, which uses the Connect::request_data
// member function to get data. Thus -a, -d and -D can be used to get the
// das, dds and data from a DODS server. Because the request_data member
// function requires a constraint expression I also added the option -c; this
// option takes as a single argument a constraint expression and passes it to
// the request_data member function. You must use -c <expr> with -D.
//
// Revision 1.8 1996/08/13 20:13:36 jimg
// Added __unused__ to definition of char rcsid[].
// Added code so that local `URLs' are skipped.
//
// Revision 1.7 1996/06/22 00:11:20 jimg
// Modified to accomodate the new Gui class.
//
// Revision 1.6 1996/06/18 23:55:33 jimg
// Added support for the GUI progress indicator.
//
// Revision 1.5 1996/06/08 00:18:38 jimg
// Initialized vcode to null.
//
// Revision 1.4 1996/05/29 22:05:57 jimg
// Fixed up the copyright header.
//
// Revision 1.3 1996/05/28 17:35:40 jimg
// Fixed verbose arguments.
//
// Revision 1.2 1996/05/28 15:49:55 jimg
// Removed code that read from the stream after the das/dds parser built the
// internal object (since there was nothing in that stream after the parse
// geturl would always crash).
//
// Revision 1.1 1996/05/22 23:34:21 jimg
// First version. Built to test the new WWW code in the class Connect.
//
#include "config_dap.h"
static char rcsid[] __unused__ = {"$Id: getdap.cc,v 1.16 1996/12/18 18:43:32 jimg Exp $"};
#include <stdio.h>
#include <assert.h>
#include <GetOpt.h>
#include <String.h>
#include "Connect.h"
void
usage(String name)
{
cerr << "Usage: " << name
<< "[AdDa] [c <expr>] [v <codes>] [m <num>] <url> [<url> ...]"
<< endl;
cerr << " " << "A: Use Connect's asynchronous mode." << endl;
cerr << " " << "d: For each URL, get the DODS DDS." << endl;
cerr << " " << "a: For each URL, get the DODS DAS." << endl;
cerr << " " << "D: For each URL, get the DODS Data." << endl;
cerr << " " << "g: Show the progress GUI." << endl;
cerr << " " << "c: <expr> is a contraint expression. Used with -D."
<< endl;
cerr << " " << " NB: You can use a `?' for the CE also." << endl;
cerr << " " << "v: <options> Verbose output; use -vd for default."
<< endl;
cerr << " " << " a: show_anchor_trace." << endl;
cerr << " " << " b: show_bind_trace." << endl;
cerr << " " << " c: show_cache_trace." << endl;
cerr << " " << " l: show_sgml_trace." << endl;
cerr << " " << " m: show_mem_trace." << endl;
cerr << " " << " p: show_protocol_trace." << endl;
cerr << " " << " s: show_stream_trace." << endl;
cerr << " " << " t: show_thread_trace." << endl;
cerr << " " << " u: show_uri_trace." << endl;
cerr << " " << "m: Request the same URL <num> times." << endl;
cerr << " " << "Without A, use the synchronous mode." << endl;
cerr << " " << "Without d or a, print the URL." << endl;
}
bool
read_data(FILE *fp)
{
char c;
if (!fp) {
cerr <<"Whoa!!! Null stream pointer." << endl;
return false;
}
// Changed from a loop that used getc() to one that uses fread(). getc()
// worked fine for transfers of text information, but *not* for binary
// transfers. fread() will handle both.
while (fread(&c, 1, 1, fp))
printf("%c", c); // stick with stdio
return true;
}
int
main(int argc, char * argv[])
{
GetOpt getopt (argc, argv, "AdaDgc:v:m:");
int option_char;
bool async = false;
bool get_das = false;
bool get_dds = false;
bool get_data = false;
bool gui = false;
bool cexpr = false;
bool verbose = false;
bool multi = false;
int times = 1;
char *vcode = NULL;
char *expr = NULL;
int vopts = 0;
while ((option_char = getopt()) != EOF)
switch (option_char)
{
case 'A': async = true; break;
case 'd': get_dds = true; break;
case 'a': get_das = true; break;
case 'D': get_data = true; break;
case 'g': gui = true; break;
case 'c':
cexpr = true; expr = getopt.optarg; break;
case 'v':
verbose = true;
vopts = strlen(getopt.optarg);
if (vopts) {
vcode = new char[vopts + 1];
strcpy(vcode, getopt.optarg);
}
break;
case 'm': multi = true; times = atoi(getopt.optarg); break;
case 'h':
case '?':
default:
usage(argv[0]); exit(1); break;
}
char c, *cc = vcode;
if (verbose && vopts > 0)
while ((c = *cc++))
switch (c) {
case 'a': WWWTRACE |= SHOW_ANCHOR_TRACE; break;
case 'b': WWWTRACE |= SHOW_BIND_TRACE; break;
case 'c': WWWTRACE |= SHOW_CACHE_TRACE; break;
case 'l': WWWTRACE |= SHOW_SGML_TRACE; break;
case 'm': WWWTRACE |= SHOW_MEM_TRACE; break;
case 'p': WWWTRACE |= SHOW_PROTOCOL_TRACE; break;
case 's': WWWTRACE |= SHOW_STREAM_TRACE; break;
case 't': WWWTRACE |= SHOW_THREAD_TRACE; break;
case 'u': WWWTRACE |= SHOW_URI_TRACE; break;
case 'd': break;
default:
cerr << "Unrecognized verbose option: `" << c << "'" << endl;
break;
}
delete vcode;
for (int i = getopt.optind; i < argc; ++i) {
if (verbose)
cerr << "Fetching " << argv[i] << ":" << endl;
String name = argv[i];
Connect url(name);
if (url.is_local()) {
cerr << "Skipping the URL `" << argv[i]
<< "' because it lacks the `http' access protocol."
<< endl;
continue;
}
if (get_das) {
for (int j = 0; j < times; ++j) {
if (!url.request_das(gui))
exit(1);
if (verbose)
cerr << "DAS:" << endl;
url.das().print();
}
}
if (get_dds) {
for (int j = 0; j < times; ++j) {
if (!url.request_dds(gui))
exit(1);
if (verbose)
cerr << "DDS:" << endl;
url.dds().print();
}
}
if (get_data) {
if (!(expr || name.contains("?"))) {
cerr << "Must supply a constraint expression with -D."
<< endl;
exit(1);
}
for (int j = 0; j < times; ++j) {
DDS &dds = url.request_data(expr, gui, async);
cout << "The data:" << endl;
for (Pix q = dds.first_var(); q; dds.next_var(q)) {
BaseType *v = dds.var(q);
switch (v->type()) {
// Sequences present a special case because I let
// their semantics get out of hand... jhrg 9/12/96
case dods_sequence_c:
((Sequence *)v)->print_all_vals(cout, url.source());
break;
default:
PERF(cerr << "Deserializing: " << dds.var(q).name() \
<< endl);
if (async && !dds.var(q)->deserialize(url.source())) {
cerr << "Asynchronous read failure." << endl;
exit(1);
}
PERF(cerr << "Deserializing complete" << endl);
dds.var(q)->print_val(cout);
break;
}
}
}
}
if (!get_das && !get_dds && !get_data) {
if (gui)
url.gui()->show_gui(gui);
String url_string = argv[i];
for (int j = 0; j < times; ++j) {
if (!url.fetch_url(url_string, async))
exit(1);
FILE *fp = url.output();
if (!read_data(fp))
exit(1);
fclose(fp);
}
}
}
}
<|endoftext|> |
<commit_before>#include <feed.h>
int main(){
auto x = feed("http://www.forbes.com/feeds/popstories.xml");
x.fetch();
std::cout<<x.json;
x.parse();
x.fetch_data();
}
<commit_msg>Compiles now. Able to link archive<commit_after>#include <Feedparser/feed.h>
int main(){
auto x = feed("http://www.forbes.com/feeds/popstories.xml");
x.fetch();
std::cout<<x.json;
x.parse();
x.fetch_data();
}
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* helloSstWriter.cpp
*
* Created on: Aug 17, 2017
* Author: Greg Eisenhauer
*/
#include <iostream>
#include <vector>
#include <adios2.h>
#if ADIOS2_USE_MPI
#include <mpi.h>
#endif
int main(int argc, char *argv[])
{
int rank;
int size;
#if ADIOS2_USE_MPI
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
#else
rank = 0;
size = 1;
#define MPI_COMM_WORLD 0
#endif
std::vector<float> myFloats = {
(float)10.0 * rank + 0, (float)10.0 * rank + 1, (float)10.0 * rank + 2,
(float)10.0 * rank + 3, (float)10.0 * rank + 4, (float)10.0 * rank + 5,
(float)10.0 * rank + 6, (float)10.0 * rank + 7, (float)10.0 * rank + 8,
(float)10.0 * rank + 9};
const std::size_t Nx = myFloats.size();
try
{
adios2::ADIOS adios(MPI_COMM_WORLD);
adios2::IO sstIO = adios.DeclareIO("myIO");
sstIO.SetEngine("Sst");
// Define variable and local size
auto bpFloats = sstIO.DefineVariable<float>("bpFloats", {size * Nx},
{rank * Nx}, {Nx});
// Create engine smart pointer to Sst Engine due to polymorphism,
// Open returns a smart pointer to Engine containing the Derived class
adios2::Engine sstWriter = sstIO.Open("helloSst", adios2::Mode::Write);
sstWriter.BeginStep();
sstWriter.Put<float>(bpFloats, myFloats.data());
sstWriter.EndStep();
sstWriter.Close();
}
catch (std::invalid_argument &e)
{
std::cout << "Invalid argument exception, STOPPING PROGRAM from rank "
<< rank << "\n";
std::cout << e.what() << "\n";
}
catch (std::ios_base::failure &e)
{
std::cout
<< "IO System base failure exception, STOPPING PROGRAM from rank "
<< rank << "\n";
std::cout << e.what() << "\n";
}
catch (std::exception &e)
{
std::cout << "Exception, STOPPING PROGRAM from rank " << rank << "\n";
std::cout << e.what() << "\n";
}
#if ADIOS2_USE_MPI
MPI_Finalize();
#endif
return 0;
}
<commit_msg>examples: Fix helloSstWriter to avoid MPI constructor in serial build<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* helloSstWriter.cpp
*
* Created on: Aug 17, 2017
* Author: Greg Eisenhauer
*/
#include <iostream>
#include <vector>
#include <adios2.h>
#if ADIOS2_USE_MPI
#include <mpi.h>
#endif
int main(int argc, char *argv[])
{
int rank;
int size;
#if ADIOS2_USE_MPI
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
#else
rank = 0;
size = 1;
#endif
std::vector<float> myFloats = {
(float)10.0 * rank + 0, (float)10.0 * rank + 1, (float)10.0 * rank + 2,
(float)10.0 * rank + 3, (float)10.0 * rank + 4, (float)10.0 * rank + 5,
(float)10.0 * rank + 6, (float)10.0 * rank + 7, (float)10.0 * rank + 8,
(float)10.0 * rank + 9};
const std::size_t Nx = myFloats.size();
try
{
#if ADIOS2_USE_MPI
adios2::ADIOS adios(MPI_COMM_WORLD);
#else
adios2::ADIOS adios;
#endif
adios2::IO sstIO = adios.DeclareIO("myIO");
sstIO.SetEngine("Sst");
// Define variable and local size
auto bpFloats = sstIO.DefineVariable<float>("bpFloats", {size * Nx},
{rank * Nx}, {Nx});
// Create engine smart pointer to Sst Engine due to polymorphism,
// Open returns a smart pointer to Engine containing the Derived class
adios2::Engine sstWriter = sstIO.Open("helloSst", adios2::Mode::Write);
sstWriter.BeginStep();
sstWriter.Put<float>(bpFloats, myFloats.data());
sstWriter.EndStep();
sstWriter.Close();
}
catch (std::invalid_argument &e)
{
std::cout << "Invalid argument exception, STOPPING PROGRAM from rank "
<< rank << "\n";
std::cout << e.what() << "\n";
}
catch (std::ios_base::failure &e)
{
std::cout
<< "IO System base failure exception, STOPPING PROGRAM from rank "
<< rank << "\n";
std::cout << e.what() << "\n";
}
catch (std::exception &e)
{
std::cout << "Exception, STOPPING PROGRAM from rank " << rank << "\n";
std::cout << e.what() << "\n";
}
#if ADIOS2_USE_MPI
MPI_Finalize();
#endif
return 0;
}
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "DeclarationVisitor.h"
#include "ExpressionVisitor.h"
#include "StatementVisitor.h"
#include "ElementVisitor.h"
#include "OOModel/src/declarations/Project.h"
#include "OOModel/src/declarations/Module.h"
#include "OOModel/src/declarations/Class.h"
#include "OOModel/src/declarations/Declaration.h"
#include "OOModel/src/declarations/Method.h"
#include "OOModel/src/declarations/NameImport.h"
#include "OOModel/src/declarations/VariableDeclaration.h"
#include "OOModel/src/declarations/ExplicitTemplateInstantiation.h"
#include "OOModel/src/declarations/TypeAlias.h"
#include "Export/src/tree/SourceDir.h"
#include "Export/src/tree/SourceFile.h"
#include "Export/src/tree/CompositeFragment.h"
#include "Export/src/tree/TextFragment.h"
#include "Comments/src/nodes/CommentNode.h"
using namespace Export;
using namespace OOModel;
namespace CppExport {
SourceFragment* DeclarationVisitor::visit(Declaration* declaration)
{
if (auto castDeclaration = DCast<Method>(declaration)) return visit(castDeclaration);
if (auto castDeclaration = DCast<Class>(declaration)) return visit(castDeclaration);
if (auto castDeclaration = DCast<VariableDeclaration>(declaration)) return visit(castDeclaration);
if (auto castDeclaration = DCast<TypeAlias>(declaration)) return visit(castDeclaration);
notAllowed(declaration);
// TODO: handle comments
auto fragment = new CompositeFragment(declaration);
*fragment << "Invalid Declaration";
return fragment;
}
SourceDir* DeclarationVisitor::visitProject(Project* project, SourceDir* parent)
{
auto projectDir = parent ? &parent->subDir(project->name()) : new SourceDir(nullptr, "src");
for (auto node : *project->projects()) visitProject(node, projectDir);
for (auto node : *project->modules()) visitModule(node, projectDir);
for (auto node : *project->classes()) visitTopLevelClass(node, projectDir);
notAllowed(project->methods());
notAllowed(project->fields());
return projectDir;
}
SourceDir* DeclarationVisitor::visitModule(Module* module, SourceDir* parent)
{
Q_ASSERT(parent);
auto moduleDir = &parent->subDir(module->name());
for (auto node : *module->modules()) visitModule(node, moduleDir);
for (auto node : *module->classes()) visitTopLevelClass(node, moduleDir);
notAllowed(module->methods());
notAllowed(module->fields());
return moduleDir;
}
SourceFile* DeclarationVisitor::visitTopLevelClass(Class* classs, SourceDir* parent)
{
Q_ASSERT(parent);
auto classFile = &parent->file(classs->name() + ".cpp");
auto fragment = classFile->append(new CompositeFragment(classs, "sections"));
auto imports = fragment->append(new CompositeFragment(classs, "vertical"));
for (auto node : *classs->subDeclarations())
{
if (auto ni = DCast<NameImport>(node)) *imports << visit(ni);
else notAllowed(node);
}
*fragment << visit(classs);
return classFile;
}
SourceFragment* DeclarationVisitor::visitTopLevelClass(Class* classs)
{
if (!headerVisitor()) return visit(classs);
auto fragment = new CompositeFragment(classs, "spacedSections");
*fragment << visit(classs);
auto filter = [](Method* method) { return !method->typeArguments()->isEmpty(); };
*fragment << list(classs->methods(), DeclarationVisitor(SOURCE_VISITOR), "spacedSections", filter);
return fragment;
}
SourceFragment* DeclarationVisitor::visit(Class* classs)
{
auto fragment = new CompositeFragment(classs);
if (!headerVisitor())
{
//TODO
auto sections = fragment->append( new CompositeFragment(classs, "sections"));
*sections << list(classs->enumerators(), ElementVisitor(data()), "enumerators");
*sections << list(classs->classes(), this, "sections");
auto filter = [](Method* method) { return method->typeArguments()->isEmpty(); };
*sections << list(classs->methods(), this, "spacedSections", filter);
*sections << list(classs->fields(), this, "vertical");
}
else
{
if (!classs->typeArguments()->isEmpty())
*fragment << list(classs->typeArguments(), ElementVisitor(data()), "templateArgsList");
*fragment << printAnnotationsAndModifiers(classs);
if (Class::ConstructKind::Class == classs->constructKind()) *fragment << "class ";
else if (Class::ConstructKind::Struct == classs->constructKind()) *fragment << "struct ";
else if (Class::ConstructKind::Enum == classs->constructKind()) *fragment << "enum ";
else notAllowed(classs);
if (auto namespaceModule = classs->firstAncestorOfType<Module>())
*fragment << namespaceModule->name().toUpper() + "_API ";
*fragment << classs->nameNode();
if (!classs->baseClasses()->isEmpty())
// TODO: inheritance modifiers like private, virtual... (not only public)
*fragment << list(classs->baseClasses(), ExpressionVisitor(data()), "baseClasses");
notAllowed(classs->friends());
auto sections = fragment->append( new CompositeFragment(classs, "bodySections"));
if (classs->enumerators()->size() > 0)
error(classs->enumerators(), "Enum unhandled"); // TODO
auto publicSection = new CompositeFragment(classs, "accessorSections");
auto publicFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Public); };
bool hasPublicSection = addMemberDeclarations(classs, publicSection, publicFilter);
if (hasPublicSection)
{
*sections << "public:";
sections->append(publicSection);
}
auto protectedSection = new CompositeFragment(classs, "accessorSections");
auto protectedFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Protected); };
bool hasProtectedSection = addMemberDeclarations(classs, protectedSection, protectedFilter);
if (hasProtectedSection)
{
if (hasPublicSection) *sections << "\n"; // add newline between two accessor sections
*sections << "protected:";
sections->append(protectedSection);
}
auto privateSection = new CompositeFragment(classs, "accessorSections");
auto privateFilter = [](Declaration* declaration) { return !declaration->modifiers()->isSet(Modifier::Public) &&
!declaration->modifiers()->isSet(Modifier::Protected); };
bool hasPrivateSection = addMemberDeclarations(classs, privateSection, privateFilter);
if (hasPrivateSection)
{
if (hasPublicSection || hasProtectedSection) *sections << "\n"; // add newline between two accessor sections
*sections << "private:";
sections->append(privateSection);
}
*fragment << ";";
}
return fragment;
}
template<typename Predicate>
bool DeclarationVisitor::addMemberDeclarations(Class* classs, CompositeFragment* section, Predicate filter)
{
auto subDeclarations = list(classs->subDeclarations(), this, "sections", filter);
auto fields = list(classs->fields(), this, "vertical", filter);
auto classes = list(classs->classes(), this, "sections", filter);
auto methods = list(classs->methods(), this, "sections", filter);
*section << subDeclarations << fields << classes << methods;
return !subDeclarations->fragments().empty() ||
!fields->fragments().empty() ||
!classes->fragments().empty() ||
!methods->fragments().empty();
}
SourceFragment* DeclarationVisitor::visit(Method* method)
{
auto fragment = new CompositeFragment(method);
if (headerVisitor())
if (auto comment = DCast<Comments::CommentNode>(method->comment()))
for (auto line : *(comment->lines()))
*fragment << line->get() << "\n";
if (!method->typeArguments()->isEmpty())
*fragment << list(method->typeArguments(), ElementVisitor(data()), "templateArgsList");
if (headerVisitor())
*fragment << printAnnotationsAndModifiers(method);
else
if (method->modifiers()->isSet(Modifier::Inline))
*fragment << new TextFragment(method->modifiers(), "inline") << " ";
if (method->results()->size() > 1)
error(method->results(), "Cannot have more than one return value in C++");
if (method->methodKind() != Method::MethodKind::Constructor &&
method->methodKind() != Method::MethodKind::Destructor)
{
if (!method->results()->isEmpty())
*fragment << expression(method->results()->at(0)->typeExpression()) << " ";
else
*fragment << "void ";
}
if (!headerVisitor())
if (auto parentClass = method->firstAncestorOfType<Class>())
*fragment << parentClass->name() << "::";
if (method->methodKind() == Method::MethodKind::Destructor && !method->name().startsWith("~")) *fragment << "~";
*fragment << method->nameNode();
*fragment << list(method->arguments(), ElementVisitor(data()), "argsList");
if (method->modifiers()->isSet(Modifier::Const))
*fragment << " " << new TextFragment(method->modifiers(), "const");
if (!headerVisitor())
if (!method->memberInitializers()->isEmpty())
*fragment << " : " << list(method->memberInitializers(), ElementVisitor(data()));
if (!method->throws()->isEmpty())
{
*fragment << " throw (";
*fragment << list(method->throws(), ExpressionVisitor(data()), "comma");
*fragment << ")";
}
if (headerVisitor())
{
if (method->modifiers()->isSet(Modifier::Override))
*fragment << " " << new TextFragment(method->modifiers(), "override");
*fragment << ";";
}
else
*fragment << list(method->items(), StatementVisitor(data()), "body");
notAllowed(method->subDeclarations());
notAllowed(method->memberInitializers());
return fragment;
}
SourceFragment* DeclarationVisitor::visit(VariableDeclaration* variableDeclaration)
{
auto fragment = new CompositeFragment(variableDeclaration);
if (headerVisitor())
{
*fragment << printAnnotationsAndModifiers(variableDeclaration);
*fragment << expression(variableDeclaration->typeExpression()) << " " << variableDeclaration->nameNode();
if (variableDeclaration->initialValue())
*fragment << " = " << expression(variableDeclaration->initialValue());
if (!DCast<Expression>(variableDeclaration->parent())) *fragment << ";";
}
else
{
bool isField = DCast<Field>(variableDeclaration);
if (!isField || variableDeclaration->modifiers()->isSet(Modifier::Static))
{
*fragment << printAnnotationsAndModifiers(variableDeclaration);
*fragment << expression(variableDeclaration->typeExpression()) << " ";
if (isField)
if (auto parentClass = variableDeclaration->firstAncestorOfType<Class>())
*fragment << parentClass->name() << "::";
*fragment << variableDeclaration->nameNode();
if (variableDeclaration->initialValue())
*fragment << " = " << expression(variableDeclaration->initialValue());
if (!DCast<Expression>(variableDeclaration->parent())) *fragment << ";";
}
}
return fragment;
}
SourceFragment* DeclarationVisitor::printAnnotationsAndModifiers(Declaration* declaration)
{
auto fragment = new CompositeFragment(declaration, "vertical");
if (!declaration->annotations()->isEmpty()) // avoid an extra new line if there are no annotations
*fragment << list(declaration->annotations(), StatementVisitor(data()), "vertical");
auto header = fragment->append(new CompositeFragment(declaration, "space"));
if (declaration->modifiers()->isSet(Modifier::Static))
*header << new TextFragment(declaration->modifiers(), "static");
if (declaration->modifiers()->isSet(Modifier::Final))
*header << new TextFragment(declaration->modifiers(), "final");
if (declaration->modifiers()->isSet(Modifier::Abstract))
*header << new TextFragment(declaration->modifiers(), "abstract");
if (declaration->modifiers()->isSet(Modifier::Virtual))
*header << new TextFragment(declaration->modifiers(), "virtual");
return fragment;
}
SourceFragment* DeclarationVisitor::visit(NameImport* nameImport)
{
auto fragment = new CompositeFragment(nameImport);
notAllowed(nameImport->annotations());
*fragment << "import " << expression(nameImport->importedName());
if (nameImport->importAll()) *fragment << ".*";
*fragment << ";";
return fragment;
}
SourceFragment* DeclarationVisitor::visit(ExplicitTemplateInstantiation* eti)
{
notAllowed(eti);
return new TextFragment(eti);
}
SourceFragment* DeclarationVisitor::visit(TypeAlias* typeAlias)
{
auto fragment = new CompositeFragment(typeAlias);
*fragment << "using " << typeAlias->nameNode() << " = " << expression(typeAlias->typeExpression()) << ";";
return fragment;
}
}
<commit_msg>move inline method output to header file<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products
** derived from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
**********************************************************************************************************************/
#include "DeclarationVisitor.h"
#include "ExpressionVisitor.h"
#include "StatementVisitor.h"
#include "ElementVisitor.h"
#include "OOModel/src/declarations/Project.h"
#include "OOModel/src/declarations/Module.h"
#include "OOModel/src/declarations/Class.h"
#include "OOModel/src/declarations/Declaration.h"
#include "OOModel/src/declarations/Method.h"
#include "OOModel/src/declarations/NameImport.h"
#include "OOModel/src/declarations/VariableDeclaration.h"
#include "OOModel/src/declarations/ExplicitTemplateInstantiation.h"
#include "OOModel/src/declarations/TypeAlias.h"
#include "Export/src/tree/SourceDir.h"
#include "Export/src/tree/SourceFile.h"
#include "Export/src/tree/CompositeFragment.h"
#include "Export/src/tree/TextFragment.h"
#include "Comments/src/nodes/CommentNode.h"
using namespace Export;
using namespace OOModel;
namespace CppExport {
SourceFragment* DeclarationVisitor::visit(Declaration* declaration)
{
if (auto castDeclaration = DCast<Method>(declaration)) return visit(castDeclaration);
if (auto castDeclaration = DCast<Class>(declaration)) return visit(castDeclaration);
if (auto castDeclaration = DCast<VariableDeclaration>(declaration)) return visit(castDeclaration);
if (auto castDeclaration = DCast<TypeAlias>(declaration)) return visit(castDeclaration);
notAllowed(declaration);
// TODO: handle comments
auto fragment = new CompositeFragment(declaration);
*fragment << "Invalid Declaration";
return fragment;
}
SourceDir* DeclarationVisitor::visitProject(Project* project, SourceDir* parent)
{
auto projectDir = parent ? &parent->subDir(project->name()) : new SourceDir(nullptr, "src");
for (auto node : *project->projects()) visitProject(node, projectDir);
for (auto node : *project->modules()) visitModule(node, projectDir);
for (auto node : *project->classes()) visitTopLevelClass(node, projectDir);
notAllowed(project->methods());
notAllowed(project->fields());
return projectDir;
}
SourceDir* DeclarationVisitor::visitModule(Module* module, SourceDir* parent)
{
Q_ASSERT(parent);
auto moduleDir = &parent->subDir(module->name());
for (auto node : *module->modules()) visitModule(node, moduleDir);
for (auto node : *module->classes()) visitTopLevelClass(node, moduleDir);
notAllowed(module->methods());
notAllowed(module->fields());
return moduleDir;
}
SourceFile* DeclarationVisitor::visitTopLevelClass(Class* classs, SourceDir* parent)
{
Q_ASSERT(parent);
auto classFile = &parent->file(classs->name() + ".cpp");
auto fragment = classFile->append(new CompositeFragment(classs, "sections"));
auto imports = fragment->append(new CompositeFragment(classs, "vertical"));
for (auto node : *classs->subDeclarations())
{
if (auto ni = DCast<NameImport>(node)) *imports << visit(ni);
else notAllowed(node);
}
*fragment << visit(classs);
return classFile;
}
SourceFragment* DeclarationVisitor::visitTopLevelClass(Class* classs)
{
if (!headerVisitor()) return visit(classs);
auto fragment = new CompositeFragment(classs, "spacedSections");
*fragment << visit(classs);
auto filter = [](Method* method) { return !method->typeArguments()->isEmpty() ||
method->modifiers()->isSet(OOModel::Modifier::Inline); };
*fragment << list(classs->methods(), DeclarationVisitor(SOURCE_VISITOR), "spacedSections", filter);
return fragment;
}
SourceFragment* DeclarationVisitor::visit(Class* classs)
{
auto fragment = new CompositeFragment(classs);
if (!headerVisitor())
{
//TODO
auto sections = fragment->append( new CompositeFragment(classs, "sections"));
*sections << list(classs->enumerators(), ElementVisitor(data()), "enumerators");
*sections << list(classs->classes(), this, "sections");
auto filter = [](Method* method) { return method->typeArguments()->isEmpty() &&
!method->modifiers()->isSet(OOModel::Modifier::Inline); };
*sections << list(classs->methods(), this, "spacedSections", filter);
*sections << list(classs->fields(), this, "vertical");
}
else
{
if (!classs->typeArguments()->isEmpty())
*fragment << list(classs->typeArguments(), ElementVisitor(data()), "templateArgsList");
*fragment << printAnnotationsAndModifiers(classs);
if (Class::ConstructKind::Class == classs->constructKind()) *fragment << "class ";
else if (Class::ConstructKind::Struct == classs->constructKind()) *fragment << "struct ";
else if (Class::ConstructKind::Enum == classs->constructKind()) *fragment << "enum ";
else notAllowed(classs);
if (auto namespaceModule = classs->firstAncestorOfType<Module>())
*fragment << namespaceModule->name().toUpper() + "_API ";
*fragment << classs->nameNode();
if (!classs->baseClasses()->isEmpty())
// TODO: inheritance modifiers like private, virtual... (not only public)
*fragment << list(classs->baseClasses(), ExpressionVisitor(data()), "baseClasses");
notAllowed(classs->friends());
auto sections = fragment->append( new CompositeFragment(classs, "bodySections"));
if (classs->enumerators()->size() > 0)
error(classs->enumerators(), "Enum unhandled"); // TODO
auto publicSection = new CompositeFragment(classs, "accessorSections");
auto publicFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Public); };
bool hasPublicSection = addMemberDeclarations(classs, publicSection, publicFilter);
if (hasPublicSection)
{
*sections << "public:";
sections->append(publicSection);
}
auto protectedSection = new CompositeFragment(classs, "accessorSections");
auto protectedFilter = [](Declaration* declaration) { return declaration->modifiers()->isSet(Modifier::Protected); };
bool hasProtectedSection = addMemberDeclarations(classs, protectedSection, protectedFilter);
if (hasProtectedSection)
{
if (hasPublicSection) *sections << "\n"; // add newline between two accessor sections
*sections << "protected:";
sections->append(protectedSection);
}
auto privateSection = new CompositeFragment(classs, "accessorSections");
auto privateFilter = [](Declaration* declaration) { return !declaration->modifiers()->isSet(Modifier::Public) &&
!declaration->modifiers()->isSet(Modifier::Protected); };
bool hasPrivateSection = addMemberDeclarations(classs, privateSection, privateFilter);
if (hasPrivateSection)
{
if (hasPublicSection || hasProtectedSection) *sections << "\n"; // add newline between two accessor sections
*sections << "private:";
sections->append(privateSection);
}
*fragment << ";";
}
return fragment;
}
template<typename Predicate>
bool DeclarationVisitor::addMemberDeclarations(Class* classs, CompositeFragment* section, Predicate filter)
{
auto subDeclarations = list(classs->subDeclarations(), this, "sections", filter);
auto fields = list(classs->fields(), this, "vertical", filter);
auto classes = list(classs->classes(), this, "sections", filter);
auto methods = list(classs->methods(), this, "sections", filter);
*section << subDeclarations << fields << classes << methods;
return !subDeclarations->fragments().empty() ||
!fields->fragments().empty() ||
!classes->fragments().empty() ||
!methods->fragments().empty();
}
SourceFragment* DeclarationVisitor::visit(Method* method)
{
auto fragment = new CompositeFragment(method);
if (headerVisitor())
if (auto comment = DCast<Comments::CommentNode>(method->comment()))
for (auto line : *(comment->lines()))
*fragment << line->get() << "\n";
if (!method->typeArguments()->isEmpty())
*fragment << list(method->typeArguments(), ElementVisitor(data()), "templateArgsList");
if (headerVisitor())
*fragment << printAnnotationsAndModifiers(method);
else
if (method->modifiers()->isSet(Modifier::Inline))
*fragment << new TextFragment(method->modifiers(), "inline") << " ";
if (method->results()->size() > 1)
error(method->results(), "Cannot have more than one return value in C++");
if (method->methodKind() != Method::MethodKind::Constructor &&
method->methodKind() != Method::MethodKind::Destructor)
{
if (!method->results()->isEmpty())
*fragment << expression(method->results()->at(0)->typeExpression()) << " ";
else
*fragment << "void ";
}
if (!headerVisitor())
if (auto parentClass = method->firstAncestorOfType<Class>())
*fragment << parentClass->name() << "::";
if (method->methodKind() == Method::MethodKind::Destructor && !method->name().startsWith("~")) *fragment << "~";
*fragment << method->nameNode();
*fragment << list(method->arguments(), ElementVisitor(data()), "argsList");
if (method->modifiers()->isSet(Modifier::Const))
*fragment << " " << new TextFragment(method->modifiers(), "const");
if (!headerVisitor())
if (!method->memberInitializers()->isEmpty())
*fragment << " : " << list(method->memberInitializers(), ElementVisitor(data()));
if (!method->throws()->isEmpty())
{
*fragment << " throw (";
*fragment << list(method->throws(), ExpressionVisitor(data()), "comma");
*fragment << ")";
}
if (headerVisitor())
{
if (method->modifiers()->isSet(Modifier::Override))
*fragment << " " << new TextFragment(method->modifiers(), "override");
*fragment << ";";
}
else
*fragment << list(method->items(), StatementVisitor(data()), "body");
notAllowed(method->subDeclarations());
notAllowed(method->memberInitializers());
return fragment;
}
SourceFragment* DeclarationVisitor::visit(VariableDeclaration* variableDeclaration)
{
auto fragment = new CompositeFragment(variableDeclaration);
if (headerVisitor())
{
*fragment << printAnnotationsAndModifiers(variableDeclaration);
*fragment << expression(variableDeclaration->typeExpression()) << " " << variableDeclaration->nameNode();
if (variableDeclaration->initialValue())
*fragment << " = " << expression(variableDeclaration->initialValue());
if (!DCast<Expression>(variableDeclaration->parent())) *fragment << ";";
}
else
{
bool isField = DCast<Field>(variableDeclaration);
if (!isField || variableDeclaration->modifiers()->isSet(Modifier::Static))
{
*fragment << printAnnotationsAndModifiers(variableDeclaration);
*fragment << expression(variableDeclaration->typeExpression()) << " ";
if (isField)
if (auto parentClass = variableDeclaration->firstAncestorOfType<Class>())
*fragment << parentClass->name() << "::";
*fragment << variableDeclaration->nameNode();
if (variableDeclaration->initialValue())
*fragment << " = " << expression(variableDeclaration->initialValue());
if (!DCast<Expression>(variableDeclaration->parent())) *fragment << ";";
}
}
return fragment;
}
SourceFragment* DeclarationVisitor::printAnnotationsAndModifiers(Declaration* declaration)
{
auto fragment = new CompositeFragment(declaration, "vertical");
if (!declaration->annotations()->isEmpty()) // avoid an extra new line if there are no annotations
*fragment << list(declaration->annotations(), StatementVisitor(data()), "vertical");
auto header = fragment->append(new CompositeFragment(declaration, "space"));
if (declaration->modifiers()->isSet(Modifier::Static))
*header << new TextFragment(declaration->modifiers(), "static");
if (declaration->modifiers()->isSet(Modifier::Final))
*header << new TextFragment(declaration->modifiers(), "final");
if (declaration->modifiers()->isSet(Modifier::Abstract))
*header << new TextFragment(declaration->modifiers(), "abstract");
if (declaration->modifiers()->isSet(Modifier::Virtual))
*header << new TextFragment(declaration->modifiers(), "virtual");
return fragment;
}
SourceFragment* DeclarationVisitor::visit(NameImport* nameImport)
{
auto fragment = new CompositeFragment(nameImport);
notAllowed(nameImport->annotations());
*fragment << "import " << expression(nameImport->importedName());
if (nameImport->importAll()) *fragment << ".*";
*fragment << ";";
return fragment;
}
SourceFragment* DeclarationVisitor::visit(ExplicitTemplateInstantiation* eti)
{
notAllowed(eti);
return new TextFragment(eti);
}
SourceFragment* DeclarationVisitor::visit(TypeAlias* typeAlias)
{
auto fragment = new CompositeFragment(typeAlias);
*fragment << "using " << typeAlias->nameNode() << " = " << expression(typeAlias->typeExpression()) << ";";
return fragment;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vclstatusindicator.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2006-06-19 11:20:36 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef __FRAMEWORK_HELPER_VCLSTATUSINDICATOR_HXX_
#include <helper/vclstatusindicator.hxx>
#endif
//-----------------------------------------------
// includes of own modules
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
//-----------------------------------------------
// includes of interfaces
//-----------------------------------------------
// includes of external modules
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//-----------------------------------------------
// namespace
namespace framework {
//-----------------------------------------------
// definitions
//-----------------------------------------------
DEFINE_XINTERFACE_1(VCLStatusIndicator ,
OWeakObject ,
DIRECT_INTERFACE(css::task::XStatusIndicator))
//-----------------------------------------------
VCLStatusIndicator::VCLStatusIndicator(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::awt::XWindow >& xParentWindow)
: ThreadHelpBase (&Application::GetSolarMutex())
, ::cppu::OWeakObject( )
, m_xSMGR (xSMGR )
, m_xParentWindow (xParentWindow )
, m_pStatusBar (0 )
, m_nRange (0 )
, m_nValue (0 )
{
if (!m_xParentWindow.is())
throw css::uno::RuntimeException(
::rtl::OUString::createFromAscii("Cant work without a parent window!"),
static_cast< css::task::XStatusIndicator* >(this));
}
//-----------------------------------------------
VCLStatusIndicator::~VCLStatusIndicator()
{
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::start(const ::rtl::OUString& sText ,
sal_Int32 nRange)
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::awt::XWindow > xParentWindow = m_xParentWindow;
aReadLock.unlock();
// <- SAFE ----------------------------------
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
Window* pParentWindow = VCLUnoHelper::GetWindow(xParentWindow);
if (!m_pStatusBar)
m_pStatusBar = new StatusBar(pParentWindow, WB_3DLOOK|WB_BORDER);
VCLStatusIndicator::impl_recalcLayout(m_pStatusBar, pParentWindow);
m_pStatusBar->Show();
m_pStatusBar->StartProgressMode(sText);
m_pStatusBar->SetProgressValue(0);
// force repaint!
pParentWindow->Show();
pParentWindow->Invalidate(INVALIDATE_CHILDREN);
pParentWindow->Flush();
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
m_sText = sText;
m_nRange = nRange;
m_nValue = 0;
aWriteLock.unlock();
// <- SAFE ----------------------------------
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::reset()
throw(css::uno::RuntimeException)
{
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
if (m_pStatusBar)
{
m_pStatusBar->SetProgressValue(0);
m_pStatusBar->SetText(String());
}
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::end()
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
m_sText = ::rtl::OUString();
m_nRange = 0;
m_nValue = 0;
aWriteLock.unlock();
// <- SAFE ----------------------------------
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
if (m_pStatusBar)
{
m_pStatusBar->EndProgressMode();
m_pStatusBar->Show(sal_False);
delete m_pStatusBar;
m_pStatusBar = 0;
}
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::setText(const ::rtl::OUString& sText)
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
m_sText = sText;
aWriteLock.unlock();
// <- SAFE ----------------------------------
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
if (m_pStatusBar)
m_pStatusBar->SetText(sText);
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::setValue(sal_Int32 nValue)
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
if (nValue <= m_nRange)
m_nValue = nValue;
else
m_nValue = m_nRange;
sal_Int32 nRange = m_nRange;
nValue = m_nValue;
aWriteLock.unlock();
// <- SAFE ----------------------------------
// normalize value to fit the range of 0-100 %
sal_Int32 nPercent = ::std::min(((nValue*100) / ::std::max(nRange,(sal_Int32)1)), (sal_Int32)100);
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
if (m_pStatusBar)
m_pStatusBar->SetProgressValue(nPercent);
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
}
//-----------------------------------------------
void VCLStatusIndicator::impl_recalcLayout(Window* pStatusBar ,
Window* pParentWindow)
{
if (
(!pStatusBar ) ||
(!pParentWindow)
)
return;
Size aParentSize = pParentWindow->GetSizePixel();
pStatusBar->SetPosSizePixel(0,
0,
aParentSize.Width(),
aParentSize.Height());
}
} // namespace framework
<commit_msg>INTEGRATION: CWS pchfix02 (1.4.52); FILE MERGED 2006/09/01 17:29:12 kaib 1.4.52.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: vclstatusindicator.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: obo $ $Date: 2006-09-16 14:01:41 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
#ifndef __FRAMEWORK_HELPER_VCLSTATUSINDICATOR_HXX_
#include <helper/vclstatusindicator.hxx>
#endif
//-----------------------------------------------
// includes of own modules
#ifndef __FRAMEWORK_THREADHELP_READGUARD_HXX_
#include <threadhelp/readguard.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_WRITEGUARD_HXX_
#include <threadhelp/writeguard.hxx>
#endif
//-----------------------------------------------
// includes of interfaces
//-----------------------------------------------
// includes of external modules
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/unohlp.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//-----------------------------------------------
// namespace
namespace framework {
//-----------------------------------------------
// definitions
//-----------------------------------------------
DEFINE_XINTERFACE_1(VCLStatusIndicator ,
OWeakObject ,
DIRECT_INTERFACE(css::task::XStatusIndicator))
//-----------------------------------------------
VCLStatusIndicator::VCLStatusIndicator(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR ,
const css::uno::Reference< css::awt::XWindow >& xParentWindow)
: ThreadHelpBase (&Application::GetSolarMutex())
, ::cppu::OWeakObject( )
, m_xSMGR (xSMGR )
, m_xParentWindow (xParentWindow )
, m_pStatusBar (0 )
, m_nRange (0 )
, m_nValue (0 )
{
if (!m_xParentWindow.is())
throw css::uno::RuntimeException(
::rtl::OUString::createFromAscii("Cant work without a parent window!"),
static_cast< css::task::XStatusIndicator* >(this));
}
//-----------------------------------------------
VCLStatusIndicator::~VCLStatusIndicator()
{
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::start(const ::rtl::OUString& sText ,
sal_Int32 nRange)
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
ReadGuard aReadLock(m_aLock);
css::uno::Reference< css::awt::XWindow > xParentWindow = m_xParentWindow;
aReadLock.unlock();
// <- SAFE ----------------------------------
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
Window* pParentWindow = VCLUnoHelper::GetWindow(xParentWindow);
if (!m_pStatusBar)
m_pStatusBar = new StatusBar(pParentWindow, WB_3DLOOK|WB_BORDER);
VCLStatusIndicator::impl_recalcLayout(m_pStatusBar, pParentWindow);
m_pStatusBar->Show();
m_pStatusBar->StartProgressMode(sText);
m_pStatusBar->SetProgressValue(0);
// force repaint!
pParentWindow->Show();
pParentWindow->Invalidate(INVALIDATE_CHILDREN);
pParentWindow->Flush();
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
m_sText = sText;
m_nRange = nRange;
m_nValue = 0;
aWriteLock.unlock();
// <- SAFE ----------------------------------
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::reset()
throw(css::uno::RuntimeException)
{
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
if (m_pStatusBar)
{
m_pStatusBar->SetProgressValue(0);
m_pStatusBar->SetText(String());
}
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::end()
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
m_sText = ::rtl::OUString();
m_nRange = 0;
m_nValue = 0;
aWriteLock.unlock();
// <- SAFE ----------------------------------
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
if (m_pStatusBar)
{
m_pStatusBar->EndProgressMode();
m_pStatusBar->Show(sal_False);
delete m_pStatusBar;
m_pStatusBar = 0;
}
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::setText(const ::rtl::OUString& sText)
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
m_sText = sText;
aWriteLock.unlock();
// <- SAFE ----------------------------------
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
if (m_pStatusBar)
m_pStatusBar->SetText(sText);
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
}
//-----------------------------------------------
void SAL_CALL VCLStatusIndicator::setValue(sal_Int32 nValue)
throw(css::uno::RuntimeException)
{
// SAFE -> ----------------------------------
WriteGuard aWriteLock(m_aLock);
if (nValue <= m_nRange)
m_nValue = nValue;
else
m_nValue = m_nRange;
sal_Int32 nRange = m_nRange;
nValue = m_nValue;
aWriteLock.unlock();
// <- SAFE ----------------------------------
// normalize value to fit the range of 0-100 %
sal_Int32 nPercent = ::std::min(((nValue*100) / ::std::max(nRange,(sal_Int32)1)), (sal_Int32)100);
// SOLAR SAFE -> ----------------------------
::vos::OClearableGuard aSolarLock(Application::GetSolarMutex());
if (m_pStatusBar)
m_pStatusBar->SetProgressValue(nPercent);
aSolarLock.clear();
// <- SOLAR SAFE ----------------------------
}
//-----------------------------------------------
void VCLStatusIndicator::impl_recalcLayout(Window* pStatusBar ,
Window* pParentWindow)
{
if (
(!pStatusBar ) ||
(!pParentWindow)
)
return;
Size aParentSize = pParentWindow->GetSizePixel();
pStatusBar->SetPosSizePixel(0,
0,
aParentSize.Width(),
aParentSize.Height());
}
} // namespace framework
<|endoftext|> |
<commit_before><commit_msg>Replace char[] by OUStringBuffer/OUString<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// FILE HEADER
#include "ktx-loader.h"
// EXTERNAL INCLUDES
#include <dali/devel-api/adaptor-framework/file-stream.h>
#include <dali/integration-api/debug.h>
#include <memory.h>
#include <stdint.h>
#include <stdio.h>
namespace PbrDemo
{
struct KtxFileHeader
{
char identifier[12];
uint32_t endianness;
uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.)
uint32_t glTypeSize;
uint32_t glFormat; //(RGB, RGBA, BGRA, etc.)
uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D
uint32_t glBaseInternalFormat;
uint32_t pixelWidth;
uint32_t pixelHeight;
uint32_t pixelDepth;
uint32_t numberOfArrayElements;
uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z.
uint32_t numberOfMipmapLevels;
uint32_t bytesOfKeyValueData;
};
/**
* Convert KTX format to Dali::Pixel::Format
*/
bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Dali::Pixel::Format& format)
{
switch(ktxPixelFormat)
{
case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4_KHR
{
format = Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR;
break;
}
case 0x881B: // GL_RGB16F
{
format = Dali::Pixel::RGB16F;
break;
}
case 0x8815: // GL_RGB32F
{
format = Dali::Pixel::RGB32F;
break;
}
case 0x8C3A: // GL_R11F_G11F_B10F
{
format = Dali::Pixel::RGB32F;
break;
}
case 0x8D7C: // GL_RGBA8UI
{
format = Dali::Pixel::RGBA8888;
break;
}
case 0x8D7D: // GL_RGB8UI
{
format = Dali::Pixel::RGB888;
break;
}
default:
{
return false;
}
}
return true;
}
bool LoadCubeMapFromKtxFile(const std::string& path, CubeData& cubedata)
{
std::unique_ptr<FILE, void (*)(FILE*)> fp(fopen(path.c_str(), "rb"), [](FILE* fp) {
if(fp)
{
fclose(fp);
}
});
if(!fp)
{
return false;
}
KtxFileHeader header;
int result = fread(&header, sizeof(KtxFileHeader), 1u, fp.get());
if(0 == result)
{
return false;
}
// Skip the key-values:
if(fseek(fp.get(), header.bytesOfKeyValueData, SEEK_CUR))
{
return false;
}
cubedata.img.resize(header.numberOfFaces);
for(unsigned int face = 0; face < header.numberOfFaces; ++face) //array_element must be 0 or 1
{
cubedata.img[face].resize(header.numberOfMipmapLevels);
}
if(0 == header.numberOfMipmapLevels)
{
header.numberOfMipmapLevels = 1u;
}
if(0 == header.numberOfArrayElements)
{
header.numberOfArrayElements = 1u;
}
if(0 == header.pixelDepth)
{
header.pixelDepth = 1u;
}
if(0 == header.pixelHeight)
{
header.pixelHeight = 1u;
}
Dali::Pixel::Format daliformat = Pixel::RGB888;
ConvertPixelFormat(header.glInternalFormat, daliformat);
for(unsigned int mipmapLevel = 0; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel)
{
uint32_t byteSize = 0;
if(fread(&byteSize, sizeof(byteSize), 1u, fp.get()) != 1)
{
return false;
}
if(0 != byteSize % 4u)
{
byteSize += 4u - byteSize % 4u;
}
for(unsigned int arrayElement = 0; arrayElement < header.numberOfArrayElements; ++arrayElement) // arrayElement must be 0 or 1
{
for(unsigned int face = 0; face < header.numberOfFaces; ++face)
{
std::unique_ptr<uint8_t, void (*)(void*)> img(static_cast<unsigned char*>(malloc(byteSize)), free); // resources will be freed when the PixelData is destroyed.
if(fread(img.get(), byteSize, 1u, fp.get()) != 1)
{
return false;
}
cubedata.img[face][mipmapLevel] = PixelData::New(img.release(), byteSize, header.pixelWidth, header.pixelHeight, daliformat, PixelData::FREE);
}
}
header.pixelHeight /= 2u;
header.pixelWidth /= 2u;
}
return true;
}
} // namespace PbrDemo
<commit_msg>Use dali-adaptor api to read files from inside apk<commit_after>/*
* Copyright (c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// FILE HEADER
#include "ktx-loader.h"
// EXTERNAL INCLUDES
#include <dali/devel-api/adaptor-framework/file-stream.h>
#include <dali/integration-api/debug.h>
#include <memory.h>
#include <stdint.h>
#include <stdio.h>
namespace PbrDemo
{
struct KtxFileHeader
{
char identifier[12];
uint32_t endianness;
uint32_t glType; //(UNSIGNED_BYTE, UNSIGNED_SHORT_5_6_5, etc.)
uint32_t glTypeSize;
uint32_t glFormat; //(RGB, RGBA, BGRA, etc.)
uint32_t glInternalFormat; //For uncompressed textures, specifies the internalformat parameter passed to glTexStorage*D or glTexImage*D
uint32_t glBaseInternalFormat;
uint32_t pixelWidth;
uint32_t pixelHeight;
uint32_t pixelDepth;
uint32_t numberOfArrayElements;
uint32_t numberOfFaces; //Cube map faces are stored in the order: +X, -X, +Y, -Y, +Z, -Z.
uint32_t numberOfMipmapLevels;
uint32_t bytesOfKeyValueData;
};
/**
* Convert KTX format to Dali::Pixel::Format
*/
bool ConvertPixelFormat(const uint32_t ktxPixelFormat, Dali::Pixel::Format& format)
{
switch(ktxPixelFormat)
{
case 0x93B0: // GL_COMPRESSED_RGBA_ASTC_4x4_KHR
{
format = Dali::Pixel::COMPRESSED_RGBA_ASTC_4x4_KHR;
break;
}
case 0x881B: // GL_RGB16F
{
format = Dali::Pixel::RGB16F;
break;
}
case 0x8815: // GL_RGB32F
{
format = Dali::Pixel::RGB32F;
break;
}
case 0x8C3A: // GL_R11F_G11F_B10F
{
format = Dali::Pixel::RGB32F;
break;
}
case 0x8D7C: // GL_RGBA8UI
{
format = Dali::Pixel::RGBA8888;
break;
}
case 0x8D7D: // GL_RGB8UI
{
format = Dali::Pixel::RGB888;
break;
}
default:
{
return false;
}
}
return true;
}
bool LoadCubeMapFromKtxFile(const std::string& path, CubeData& cubedata)
{
Dali::FileStream daliFileStream(path);
FILE* fp(daliFileStream.GetFile());
if(!fp)
{
return false;
}
KtxFileHeader header;
int result = fread(&header, sizeof(KtxFileHeader), 1u, fp);
if(0 == result)
{
return false;
}
// Skip the key-values:
if(fseek(fp, header.bytesOfKeyValueData, SEEK_CUR))
{
return false;
}
cubedata.img.resize(header.numberOfFaces);
for(unsigned int face = 0; face < header.numberOfFaces; ++face) //array_element must be 0 or 1
{
cubedata.img[face].resize(header.numberOfMipmapLevels);
}
if(0 == header.numberOfMipmapLevels)
{
header.numberOfMipmapLevels = 1u;
}
if(0 == header.numberOfArrayElements)
{
header.numberOfArrayElements = 1u;
}
if(0 == header.pixelDepth)
{
header.pixelDepth = 1u;
}
if(0 == header.pixelHeight)
{
header.pixelHeight = 1u;
}
Dali::Pixel::Format daliformat = Pixel::RGB888;
ConvertPixelFormat(header.glInternalFormat, daliformat);
for(unsigned int mipmapLevel = 0; mipmapLevel < header.numberOfMipmapLevels; ++mipmapLevel)
{
uint32_t byteSize = 0;
if(fread(&byteSize, sizeof(byteSize), 1u, fp) != 1)
{
return false;
}
if(0 != byteSize % 4u)
{
byteSize += 4u - byteSize % 4u;
}
for(unsigned int arrayElement = 0; arrayElement < header.numberOfArrayElements; ++arrayElement) // arrayElement must be 0 or 1
{
for(unsigned int face = 0; face < header.numberOfFaces; ++face)
{
std::unique_ptr<uint8_t, void (*)(void*)> img(static_cast<unsigned char*>(malloc(byteSize)), free); // resources will be freed when the PixelData is destroyed.
if(fread(img.get(), byteSize, 1u, fp) != 1)
{
return false;
}
cubedata.img[face][mipmapLevel] = PixelData::New(img.release(), byteSize, header.pixelWidth, header.pixelHeight, daliformat, PixelData::FREE);
}
}
header.pixelHeight /= 2u;
header.pixelWidth /= 2u;
}
return true;
}
} // namespace PbrDemo
<|endoftext|> |
<commit_before>#ifndef VIENNAGRID_STORAGE_ID_GENERATOR_HPP
#define VIENNAGRID_STORAGE_ID_GENERATOR_HPP
#include "viennagrid/meta/typelist.hpp"
namespace viennagrid
{
namespace storage
{
template<typename typelist, typename id_type>
class continuous_id_generator_layer_t;
template<typename head, typename tail, typename id_type>
class continuous_id_generator_layer_t<viennameta::typelist_t<head, tail>, id_type> : public continuous_id_generator_layer_t<tail, id_type>
{
typedef continuous_id_generator_layer_t<tail, id_type> base;
public:
continuous_id_generator_layer_t() : base(), last_id(0) {}
using base::operator();
id_type operator()( viennameta::tag<head> )
{
return last_id++;
}
private:
id_type last_id;
};
template<typename id_type>
class continuous_id_generator_layer_t<viennameta::null_type, id_type>
{
public:
id_type operator()();
};
template<typename typelist, typename id_type>
class continuous_id_generator_t : public continuous_id_generator_layer_t<typelist, id_type>
{
typedef continuous_id_generator_layer_t<typelist, id_type> base;
public:
using base::operator();
};
namespace result_of
{
template<typename typelist, typename id_type = int>
struct continuous_id_generator_layer
{
typedef continuous_id_generator_t<
typename viennameta::typelist::result_of::no_duplicates< typelist >::type,
id_type
> type;
};
}
}
}
#endif<commit_msg>renamed class (_layer was a typo)<commit_after>#ifndef VIENNAGRID_STORAGE_ID_GENERATOR_HPP
#define VIENNAGRID_STORAGE_ID_GENERATOR_HPP
#include "viennagrid/meta/typelist.hpp"
namespace viennagrid
{
namespace storage
{
template<typename typelist, typename id_type>
class continuous_id_generator_layer_t;
template<typename head, typename tail, typename id_type>
class continuous_id_generator_layer_t<viennameta::typelist_t<head, tail>, id_type> : public continuous_id_generator_layer_t<tail, id_type>
{
typedef continuous_id_generator_layer_t<tail, id_type> base;
public:
continuous_id_generator_layer_t() : base(), last_id(0) {}
using base::operator();
id_type operator()( viennameta::tag<head> )
{
return last_id++;
}
private:
id_type last_id;
};
template<typename id_type>
class continuous_id_generator_layer_t<viennameta::null_type, id_type>
{
public:
id_type operator()();
};
template<typename typelist, typename id_type>
class continuous_id_generator_t : public continuous_id_generator_layer_t<typelist, id_type>
{
typedef continuous_id_generator_layer_t<typelist, id_type> base;
public:
using base::operator();
};
namespace result_of
{
template<typename typelist, typename id_type = int>
struct continuous_id_generator
{
typedef viennagrid::storage::continuous_id_generator_t<
typename viennameta::typelist::result_of::no_duplicates< typelist >::type,
id_type
> type;
};
}
}
}
#endif<|endoftext|> |
<commit_before><commit_msg>update<commit_after><|endoftext|> |
<commit_before>#include <cmath>
#include <gmpxx.h>
#include <iostream>
#include <vector>
#include <sstream>
#define SUCCESS 0
#define FAILURE 1
#define MAX_ARR_SIZE 16777216
#define MAX_PRECISION 65536
#define LOG_INFO
using namespace std;
mpf_class meanVal(const mpf_class* arr, size_t size, size_t acc) {
mpf_class sum(0, acc), length(size, acc), result(0, acc);
for (int i=0;i<length;i++)
{
sum += arr[i];
}
result = sum/length;
return result;
}
mpf_class varVal(const mpf_class* arr, const size_t& size, const size_t& acc,
const mpf_class& meanValue) {
mpf_class sum2(0, acc), length(size, acc), result(0, acc);
mpf_class temp(0, acc);
for (int i=0; i< length; i++) {
temp = arr[i] - meanValue;
mpf_pow_ui(temp.get_mpf_t(), temp.get_mpf_t(), 2);
sum2 += temp;
}
result = (sum2/length);
return result;
}
mpf_class periodVal(const mpf_class* arr, size_t size, size_t acc) {
mpf_class sum(0, acc), sum2(0, acc), length(size, acc), result(0, acc);
for (int i=0; i< length; i++)
sum += arr[i];
sum = (sum / length);
for (int i=0; i< length; i++) {
mpf_class temp(0, acc);
temp = arr[i] - sum;
sum2 += temp * temp;
}
result = (sum2/length);
return result;
}
const vector<mpf_class> getStream(size_t acc) {
vector<mpf_class> vec;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
while (true)
{
mpf_class input_val;
if(!(lineStream >> input_val)) break;
input_val.set_prec(acc);
vec.push_back(input_val);
}
return vec;
}
mpf_class* getArrStream(size_t acc, size_t& size) {
mpf_class* arr = new mpf_class[MAX_ARR_SIZE];
size_t i = 0;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
while (true)
{
mpf_class input_val;
if(!(lineStream >> input_val)) break;
input_val.set_prec(acc);
arr[i] = input_val;
i++;
}
size = i;
return arr;
}
void debugPrintArr(const mpf_class* arr, long size) {
cout << "Debug array print:" << endl;
for (long i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void printUsage(char **argv) {
cout <<"usage: "<< argv[0] <<" <accuracy>\n";
}
int main (int argc, char **argv) {
// Cin && cout optimization.
std::ios_base::sync_with_stdio(false);
// Max acc: 2^16 = 65536
// Max size of array: 2^24 = 16777216
// Max elem | value |: 2^64 = 18446744073709551616
int accuracy = MAX_PRECISION; // Default accuracy.
if ( argc > 1 ) {
if (!strcmp(argv[1], "-h")) {
printUsage(argv);
return SUCCESS;
}
accuracy = atoi(argv[1]);
if (accuracy < 1 && accuracy > MAX_PRECISION)
return FAILURE;
}
mpf_class meanValue(0, accuracy);
mpf_class varianceVal(0, accuracy);
mpf_class periodicVal(0, accuracy);
mpf_class sum(0, accuracy);
// Our array.
mpf_class* arr = new mpf_class[MAX_ARR_SIZE];
size_t i = 0;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
mpf_class input_val;
input_val.set_prec(accuracy);
while (true)
{
if(!(lineStream >> input_val)) break;
sum += input_val;
arr[i] = input_val;
i++;
}
meanValue = sum / i;
#ifdef LOG_INFO
cout << "Starting prog" << endl;
#endif
//debugPrintArr(&vec[0], vec.size());
cout.precision(accuracy);
cout << meanValue << endl;
cout << varVal(arr, i, accuracy, meanValue) << endl;
//cout << varVal(arr, i, accuracy, meanValue) << endl;
delete[](arr);
return 0;
}
<commit_msg>prokopp: Good performance improvement. TODO: REFACTOR it<commit_after>#include <gmpxx.h>
#include <iostream>
#include <sstream>
#define SUCCESS 0
#define FAILURE 1
#define MAX_ARR_SIZE 16777216
#define MAX_PRECISION 65536
#define LOG_INFO
using namespace std;
/**
* Calc mean Vak
*/
mpf_class meanVal(const mpf_class* arr, size_t size, size_t acc) {
mpf_class sum(0, acc), length(size, acc), result(0, acc);
for (int i=0;i<length;i++)
{
sum += arr[i];
}
result = sum/length;
return result;
}
mpf_class varVal(const mpf_class* arr, const size_t& size, const size_t& acc,
const mpf_class& meanValueSquare) {
mpf_class sum2(0, acc), length(size, acc), result(0, acc);
mpf_class temp(0, acc);
for (int i=0; i< length; i++) {
temp = arr[i] - meanValueSquare;
sum2 += temp;
}
result = (sum2/length);
return result;
}
mpf_class periodVal(const mpf_class* arr, size_t size, size_t acc) {
mpf_class sum(0, acc), sum2(0, acc), length(size, acc), result(0, acc);
for (int i=0; i< length; i++)
sum += arr[i];
sum = (sum / length);
for (int i=0; i< length; i++) {
mpf_class temp(0, acc);
temp = arr[i] - sum;
sum2 += temp * temp;
}
result = (sum2/length);
return result;
}
const vector<mpf_class> getStream(size_t acc) {
vector<mpf_class> vec;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
while (true)
{
mpf_class input_val;
if(!(lineStream >> input_val)) break;
input_val.set_prec(acc);
vec.push_back(input_val);
}
return vec;
}
mpf_class* getArrStream(size_t acc, size_t& size) {
mpf_class* arr = new mpf_class[MAX_ARR_SIZE];
size_t i = 0;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
while (true)
{
mpf_class input_val;
if(!(lineStream >> input_val)) break;
input_val.set_prec(acc);
arr[i] = input_val;
i++;
}
size = i;
return arr;
}
void debugPrintArr(const mpf_class* arr, long size) {
cout << "Debug array print:" << endl;
for (long i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
void printUsage(char **argv) {
cout <<"usage: "<< argv[0] <<" <accuracy>\n";
}
int main (int argc, char **argv) {
// Cin && cout optimization.
std::ios_base::sync_with_stdio(false);
// Max acc: 2^16 = 65536
// Max size of array: 2^24 = 16777216
// Max elem | value |: 2^64 = 18446744073709551616
int accuracy = MAX_PRECISION; // Default accuracy.
if ( argc > 1 ) {
if (!strcmp(argv[1], "-h")) {
printUsage(argv);
return SUCCESS;
}
accuracy = atoi(argv[1]);
if (accuracy < 1 && accuracy > MAX_PRECISION)
return FAILURE;
}
mpf_class meanValue(0, accuracy);
mpf_class varianceVal(0, accuracy);
mpf_class periodicVal(0, accuracy);
mpf_class meanValueSquare(0, accuracy);
mpf_class sum(0, accuracy);
// Our array.
mpf_class* arr = new mpf_class[MAX_ARR_SIZE];
size_t i = 0;
string line;
#ifdef LOG_INFO
cout << "Enter input in one line:" << endl;
#endif
std::getline(cin, line);
stringstream lineStream(line);
mpf_class input_val;
input_val.set_prec(accuracy);
while (true)
{
if(!(lineStream >> input_val)) break;
sum += input_val;
arr[i] = input_val*input_val;
i++;
}
meanValue = sum / i;
meanValueSquare = meanValue * meanValue;
#ifdef LOG_INFO
cout << "Starting prog" << endl;
#endif
//debugPrintArr(&vec[0], vec.size());
cout.precision(accuracy);
cout << meanValue << endl;
cout << varVal(arr, i, accuracy, meanValueSquare) << endl;
//cout << varVal(arr, i, accuracy, meanValue) << endl;
delete[](arr);
return 0;
}
<|endoftext|> |
<commit_before>#include <random>
#include <array>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include <chrono>
//Chrono typedefs
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds milliseconds;
static const std::size_t REPEAT = 1;
/* Fill back */
template<typename Container>
void fill_back(std::size_t size){
Container container;
for(std::size_t i = 0; i < size; ++i){
container.push_back(i);
}
}
void fill_back_vector(std::size_t size){
std::vector<std::size_t> container(size);
for(std::size_t i = 0; i < size; ++i){
container[i] = i;
}
}
/* Fill front */
void fill_front_list(std::size_t size){
std::list<std::size_t> container;
for(std::size_t i = 0; i < size; ++i){
container.push_front(i);
}
}
void fill_front_vector(std::size_t size){
std::list<std::size_t> container;
for(std::size_t i = 0; i < size; ++i){
container.insert(container.begin(), i);
}
}
/* Find */
template<typename Container>
void find(std::size_t size, Container& container){
std::mt19937 generator;
std::uniform_int_distribution<std::size_t> distribution(0, size);
for(std::size_t i = 0; i < 1000; ++i){
std::find(container.begin(), container.end(), distribution(generator));
}
}
/* Insert */
template<typename Container>
void insert(std::size_t size, Container& container){
std::mt19937 generator;
std::uniform_int_distribution<std::size_t> distribution(0, size - 1);
for(std::size_t i = 0; i < 1000; ++i){
auto it = std::find(container.begin(), container.end(), distribution(generator));
container.insert(it, size + i);
}
}
/* Remove */
template<typename Container>
void remove(std::size_t size, Container& container){
std::mt19937 generator;
std::uniform_int_distribution<std::size_t> distribution(0, size - 1);
for(std::size_t i = 0; i < 1000; ++i){
auto it = std::find(container.begin(), container.end(), distribution(generator));
if(it != container.end()){
container.erase(it);
}
}
}
/* Sort */
void sort_vector(std::vector<std::size_t>& container){
std::sort(container.begin(), container.end());
}
void sort_list(std::list<std::size_t>& container){
container.sort();
}
/* Bench functions */
template<typename Function>
void bench(Function function, const std::string& type){
std::vector<std::size_t> sizes = {1000, 10000, 100000, 1000000/*, 10000000*/};
for(auto size : sizes){
Clock::time_point t0 = Clock::now();
for(std::size_t i = 0; i < REPEAT; ++i){
function(size);
}
Clock::time_point t1 = Clock::now();
milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
std::cout << type << ":" << size << ":" << ms.count() << "ms" << std::endl;
}
}
template<typename Container, typename Function>
void bench_pre(Function function, const std::string& type){
std::vector<std::size_t> sizes = {1000, 10000, 100000, 1000000/*, 10000000*/};
for(auto size : sizes){
Container container;
for(std::size_t i = 0; i < size; ++i){
container.push_back(i);
}
Clock::time_point t0 = Clock::now();
for(std::size_t i = 0; i < REPEAT; ++i){
function(size, container);
}
Clock::time_point t1 = Clock::now();
milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
std::cout << type << ":" << size << ":" << ms.count() << "ms" << std::endl;
}
}
template<typename Container, typename Function>
void bench_sort(Function function, const std::string& type){
std::vector<std::size_t> sizes = {1000, 10000, 100000, 1000000/*, 10000000*/};
for(auto size : sizes){
std::vector<std::size_t> temp(size);
for(std::size_t i = 0; i < size; ++i){
temp.push_back(i);
}
std::random_shuffle(temp.begin(), temp.end());
milliseconds ms_tot;
Container container;
for(std::size_t i = 0; i < REPEAT; ++i){
container.clear();
container.insert(container.begin(), temp.begin(), temp.end());
Clock::time_point t0 = Clock::now();
function(container);
Clock::time_point t1 = Clock::now();
milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
ms_tot += ms;
}
std::cout << type << ":" << size << ":" << ms_tot.count() << "ms" << std::endl;
}
}
int main(){
std::cout << "Fill back" << std::endl;
bench(fill_back_vector, "vector_pre");
bench(fill_back<std::vector<std::size_t>>, "vector");
bench(fill_back<std::list<std::size_t>>, "list");
std::cout << "Fill front" << std::endl;
bench(fill_front_vector, "vector");
bench(fill_front_list, "list");
std::cout << "Find all" << std::endl;
bench_pre<std::vector<std::size_t>>(find<std::vector<std::size_t>>, "vector");
bench_pre<std::list<std::size_t>>(find<std::list<std::size_t>>, "list");
std::cout << "Insert" << std::endl;
bench_pre<std::vector<std::size_t>>(insert<std::vector<std::size_t>>, "vector");
bench_pre<std::list<std::size_t>>(insert<std::list<std::size_t>>, "list");
std::cout << "Remove" << std::endl;
bench_pre<std::vector<std::size_t>>(remove<std::vector<std::size_t>>, "vector");
bench_pre<std::list<std::size_t>>(remove<std::list<std::size_t>>, "list");
std::cout << "Sort" << std::endl;
bench_sort<std::vector<std::size_t>>(sort_vector, "vector");
bench_sort<std::list<std::size_t>>(sort_list, "list");
return 0;
}
<commit_msg>Adapt the code to change the size of the data type<commit_after>#include <random>
#include <array>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include <chrono>
//Chrono typedefs
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds milliseconds;
static const std::size_t REPEAT = 1;
struct Small {
std::size_t a = 0;
Small(){}
Small(std::size_t a) : a(a){}
};
bool operator==(const Small& s1, const Small& s2){
return s1.a == s2.a;
}
bool operator<(const Small& s1, const Small& s2){
return s1.a < s2.a;
}
/* Fill back */
template<typename Container>
void fill_back(std::size_t size){
Container container;
for(std::size_t i = 0; i < size; ++i){
container.push_back({i});
}
}
template<typename T>
void fill_back_vector(std::size_t size){
std::vector<T> container(size);
for(std::size_t i = 0; i < size; ++i){
container[i] = {i};
}
}
/* Fill front */
template<typename T>
void fill_front_list(std::size_t size){
std::list<T> container;
for(std::size_t i = 0; i < size; ++i){
container.push_front({i});
}
}
template<typename T>
void fill_front_vector(std::size_t size){
std::list<T> container;
for(std::size_t i = 0; i < size; ++i){
container.insert(container.begin(), {i});
}
}
/* Find */
template<typename Container>
void find(std::size_t size, Container& container){
std::mt19937 generator;
std::uniform_int_distribution<std::size_t> distribution(0, size);
for(std::size_t i = 0; i < 1000; ++i){
typename Container::value_type v = {distribution(generator)};
std::find(container.begin(), container.end(), v);
}
}
/* Insert */
template<typename Container>
void insert(std::size_t size, Container& container){
std::mt19937 generator;
std::uniform_int_distribution<std::size_t> distribution(0, size - 1);
for(std::size_t i = 0; i < 1000; ++i){
typename Container::value_type v = {distribution(generator)};
auto it = std::find(container.begin(), container.end(), v);
container.insert(it, {size + i});
}
}
/* Remove */
template<typename Container>
void remove(std::size_t size, Container& container){
std::mt19937 generator;
std::uniform_int_distribution<std::size_t> distribution(0, size - 1);
for(std::size_t i = 0; i < 1000; ++i){
typename Container::value_type v = {distribution(generator)};
auto it = std::find(container.begin(), container.end(), v);
if(it != container.end()){
container.erase(it);
}
}
}
/* Sort */
template<typename T>
void sort_vector(std::vector<T>& container){
std::sort(container.begin(), container.end());
}
template<typename T>
void sort_list(std::list<T>& container){
container.sort();
}
/* Bench functions */
template<typename Function>
void bench(Function function, const std::string& type){
std::vector<std::size_t> sizes = {1000, 10000, 100000, 1000000/*, 10000000*/};
for(auto size : sizes){
Clock::time_point t0 = Clock::now();
for(std::size_t i = 0; i < REPEAT; ++i){
function(size);
}
Clock::time_point t1 = Clock::now();
milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
std::cout << type << ":" << size << ":" << ms.count() << "ms" << std::endl;
}
}
template<typename Container, typename Function>
void bench_pre(Function function, const std::string& type){
std::vector<std::size_t> sizes = {1000, 10000, 100000, 1000000/*, 10000000*/};
for(auto size : sizes){
Container container;
for(std::size_t i = 0; i < size; ++i){
container.push_back({i});
}
Clock::time_point t0 = Clock::now();
for(std::size_t i = 0; i < REPEAT; ++i){
function(size, container);
}
Clock::time_point t1 = Clock::now();
milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
std::cout << type << ":" << size << ":" << ms.count() << "ms" << std::endl;
}
}
template<typename Container, typename Function>
void bench_sort(Function function, const std::string& type){
std::vector<std::size_t> sizes = {1000, 10000, 100000, 1000000/*, 10000000*/};
for(auto size : sizes){
std::vector<typename Container::value_type> temp(size);
for(std::size_t i = 0; i < size; ++i){
temp.push_back({i});
}
std::random_shuffle(temp.begin(), temp.end());
milliseconds ms_tot;
Container container;
for(std::size_t i = 0; i < REPEAT; ++i){
container.clear();
container.insert(container.begin(), temp.begin(), temp.end());
Clock::time_point t0 = Clock::now();
function(container);
Clock::time_point t1 = Clock::now();
milliseconds ms = std::chrono::duration_cast<milliseconds>(t1 - t0);
ms_tot += ms;
}
std::cout << type << ":" << size << ":" << ms_tot.count() << "ms" << std::endl;
}
}
template<typename T>
void bench(){
std::cout << "Bench " << sizeof(T) << std::endl;
std::cout << "Fill back" << std::endl;
bench(fill_back_vector<T>, "vector_pre");
bench(fill_back<std::vector<T>>, "vector");
bench(fill_back<std::list<T>>, "list");
std::cout << "Fill front" << std::endl;
bench(fill_front_vector<T>, "vector");
bench(fill_front_list<T>, "list");
std::cout << "Find all" << std::endl;
bench_pre<std::vector<T>>(find<std::vector<T>>, "vector");
bench_pre<std::list<T>>(find<std::list<T>>, "list");
std::cout << "Insert" << std::endl;
bench_pre<std::vector<T>>(insert<std::vector<T>>, "vector");
bench_pre<std::list<T>>(insert<std::list<T>>, "list");
std::cout << "Remove" << std::endl;
bench_pre<std::vector<T>>(remove<std::vector<T>>, "vector");
bench_pre<std::list<T>>(remove<std::list<T>>, "list");
std::cout << "Sort" << std::endl;
bench_sort<std::vector<T>>(sort_vector<T>, "vector");
bench_sort<std::list<T>>(sort_list<T>, "list");
}
int main(){
bench<Small>();
return 0;
}
<|endoftext|> |
<commit_before>#ifndef VIENNAMATERIALS_KERNELS_PUGIXML_HPP
#define VIENNAMATERIALS_KERNELS_PUGIXML_HPP
/* =============================================================================
Copyright (c) 2013, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaMaterials - The Vienna Materials Library
-----------------
authors: Josef Weinbub weinbub@iue.tuwien.ac.at
license: see file LICENSE in the base directory
============================================================================= */
#include "viennautils/xml.hpp"
#include "viennautils/file.hpp"
#ifdef HAVE_VIENNAIPD
extern "C" {
#include "ipd.h"
}
#endif
namespace vmat {
namespace tag {
struct pugixml {};
} // tag
namespace kernel {
struct PugiXML
{
typedef viennautils::xml<viennautils::tag::pugixml>::type MaterialDatabase;
typedef MaterialDatabase::NodeSet Entries;
typedef MaterialDatabase::Node Entry;
typedef MaterialDatabase::NodeIterator EntryIterator;
typedef double Numeric;
typedef bool Boolean;
typedef std::string String;
PugiXML()
{
// setup variables used as placeholdes in the precompiled queries
vars.add(vmat::key::id.c_str(), pugi::xpath_type_string);
vars.add(vmat::key::category.c_str(), pugi::xpath_type_string);
vars.add(vmat::key::parameter.c_str(), pugi::xpath_type_string);
// precompile the various query strings - use placeholders for run-time parameters
std::string material_query_string = "/materials/material[id = string($"+vmat::key::id+")]";
query_material = new pugi::xpath_query(material_query_string.c_str(), &vars);
std::string category_query_string = "/materials/material[category = string($"+vmat::key::category+")]";
query_category = new pugi::xpath_query(category_query_string.c_str(), &vars);
std::string parameter_query_string = "/materials/material[id = string($"+vmat::key::id+")]/parameters/parameter[name = string($"+vmat::key::parameter+")]";
query_parameter = new pugi::xpath_query(parameter_query_string.c_str(), &vars);
std::string parameter_value_query_string = "/materials/material[id = string($"+vmat::key::id+")]/parameters/parameter[name = string($"+vmat::key::parameter+")]/value";
query_parameter_value = new pugi::xpath_query(parameter_value_query_string.c_str(), &vars);
std::string parameter_unit_query_string = "/materials/material[id = string($"+vmat::key::id+")]/parameters/parameter[name = string($"+vmat::key::parameter+")]/unit";
query_parameter_unit = new pugi::xpath_query(parameter_unit_query_string.c_str(), &vars);
std::string parameter_note_query_string = "/materials/material[id = string($"+vmat::key::id+")]/parameters/parameter[name = string($"+vmat::key::parameter+")]/note";
query_parameter_note = new pugi::xpath_query(parameter_note_query_string.c_str(), &vars);
}
~PugiXML()
{
// the xpath queries are due to pugixml's impelmentation required to be allocated
// on the heap ..
delete query_material;
delete query_category;
delete query_parameter;
delete query_parameter_value;
delete query_parameter_unit;
delete query_parameter_note;
}
bool load(std::string const& filename)
{
#ifdef HAVE_LIBXML2
if(!vmat::check(filename))
{
return false;
}
#endif
if(!viennautils::file_exists(filename))
{
throw XMLFileLoadError();
return false;
}
if(viennautils::file_extension(filename) == "xml") // native
{
mdb.read(filename);
return true;
}
#ifdef HAVE_VIENNAIPD
else if(viennautils::file_extension(filename) == "ipd") // conversion required
{
ipdInit(NULL, NULL);
// todo:
std::cout << "IPD support is not yet implemented .." << std::endl;
return true;
}
#endif
else return false;
}
void dump(std::ostream& stream = std::cout)
{
mdb.dump(stream);
}
void dump(std::ostream& stream = std::cout) const
{
mdb.dump(stream);
}
Entries query(std::string const& expr)
{
return mdb.query_raw(expr);
}
Entries query(std::string const& expr) const
{
return mdb.query_raw(expr);
}
Entries getSemiconductors()
{
vars.set(vmat::key::category.c_str(), vmat::key::semiconductor.c_str());
return query_category->evaluate_node_set(mdb.xml);
}
// Entries getSemiconductors() const
// {
// vars.set(vmat::key::category.c_str(), vmat::key::semiconductor.c_str());
// return query_category->evaluate_node_set(mdb.xml);
// }
bool hasSemiconductors()
{
return !(this->getSemiconductors().empty());
}
// bool hasSemiconductors() const
// {
// return !(this->getSemiconductors().empty());
// }
Entries getMetals()
{
vars.set(vmat::key::category.c_str(), vmat::key::metal.c_str());
return query_category->evaluate_node_set(mdb.xml);
}
// Entries getMetals() const
// {
// vars.set(vmat::key::category.c_str(), vmat::key::metal.c_str());
// return query_category->evaluate_node_set(mdb.xml);
// }
bool hasMetals()
{
return !(this->getMetals().empty());
}
Entries getOxides()
{
vars.set(vmat::key::category.c_str(), vmat::key::oxide.c_str());
return query_category->evaluate_node_set(mdb.xml);
}
bool hasOxides()
{
return !(this->getOxides().empty());
}
Entries getMaterialsOfCategory(std::string const& category_id)
{
vars.set(vmat::key::category.c_str(), category_id.c_str());
return query_category->evaluate_node_set(mdb.xml);
}
bool hasMaterialsOfCategory(std::string const& category_id)
{
return !(this->getMaterialsOfCategory(category_id).empty());
}
// -- Material Accessors -----------------------------------------------------
private:
Entries queryMaterial(std::string const& material_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
return query_material->evaluate_node_set(mdb.xml);
}
public:
Entry getMaterial(std::string const& material_id)
{
pugi::xpath_node_set const& result = this->queryMaterial(material_id);
if(result.size() > 1) // there must be only one material with this id
{
throw vmat::NonUniqueMaterialException(material_id);
return Entry();
}
else if (result.size() == 0) return Entry();
else return result.first(); // if success, return only a single xpath_node
}
bool hasMaterial(std::string const& material_id)
{
pugi::xpath_node_set const& result = this->queryMaterial(material_id);
if(result.size() > 1) // there must be only one material with this id
{
throw vmat::NonUniqueMaterialException(material_id);
return false;
}
else if (result.size() == 0) return false;
else return true;
}
// ---------------------------------------------------------------------------
// -- Parameter Accessors ----------------------------------------------------
private:
Entries queryParameter(std::string const& material_id, std::string const& parameter_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter->evaluate_node_set(mdb.xml);
}
public:
Entry getParameter(std::string const& material_id, std::string const& parameter_id)
{
pugi::xpath_node_set const& result = this->queryParameter(material_id, parameter_id);
if(result.size() > 1) // there must be only one parameter with this id
{
throw vmat::NonUniqueParameterException(parameter_id);
return Entry();
}
else if (result.size() == 0) return Entry();
else return result.first(); // if success, return only a single xpath_node
}
bool hasParameter(std::string const& material_id, std::string const& parameter_id)
{
pugi::xpath_node_set const& result = this->queryParameter(material_id, parameter_id);
if(result.size() > 1) // there must be only one material with this id
{
throw vmat::NonUniqueParameterException(parameter_id);
return false;
}
else if (result.size() == 0) return false;
else return true;
}
Numeric getParameterValue(std::string const& material_id, std::string const& parameter_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter_value->evaluate_number(mdb.xml);
}
String getParameterUnit(std::string const& material_id, std::string const& parameter_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter_unit->evaluate_string(mdb.xml);
}
String getParameterNote(std::string const& material_id, std::string const& parameter_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter_note->evaluate_string(mdb.xml);
}
// ---------------------------------------------------------------------------
private:
MaterialDatabase mdb;
pugi::xpath_variable_set vars;
pugi::xpath_query *query_material;
pugi::xpath_query *query_category;
pugi::xpath_query *query_parameter;
pugi::xpath_query *query_parameter_value;
pugi::xpath_query *query_parameter_unit;
pugi::xpath_query *query_parameter_note;
};
} // kernel
template<>
struct Library <vmat::tag::pugixml>
{
typedef vmat::kernel::PugiXML type;
};
// TOOLS -----------------------------------------------------------------------
inline void printToStream(vmat::kernel::PugiXML::Entries const& nodeset, std::ostream& stream = std::cout)
{
for(size_t i = 0; i < nodeset.size(); i++)
nodeset[i].node().print(stream, " ");
}
inline void printToStream(vmat::kernel::PugiXML::Entry const& node, std::ostream& stream = std::cout)
{
node.node().print(stream, " ");
}
inline vmat::kernel::PugiXML::Entries query(vmat::kernel::PugiXML::Entry const& entry, std::string const& query)
{
return entry.node().select_nodes(query.c_str());
}
inline bool isParameter(vmat::kernel::PugiXML::Entry const& entry)
{
if(std::string(entry.node().name()) == vmat::key::parameter)
return true;
else return false;
}
inline bool isMaterial(vmat::kernel::PugiXML::Entry const& entry)
{
if(std::string(entry.node().name()) == vmat::key::material)
return true;
else return false;
}
inline vmat::kernel::PugiXML::Numeric value(vmat::kernel::PugiXML::Entry const& entry)
{
return pugi::xpath_query("value").evaluate_number(entry);
}
inline vmat::kernel::PugiXML::String name(vmat::kernel::PugiXML::Entry const& entry)
{
return pugi::xpath_query("name").evaluate_string(entry);
}
inline vmat::kernel::PugiXML::String unit(vmat::kernel::PugiXML::Entry const& entry)
{
return pugi::xpath_query("unit").evaluate_string(entry);
}
inline vmat::kernel::PugiXML::String note(vmat::kernel::PugiXML::Entry const& entry)
{
return pugi::xpath_query("note").evaluate_string(entry);
}
// -----------------------------------------------------------------------------
struct ParameterExtractor
{
typedef vmat::kernel::PugiXML::Entries Entries;
typedef vmat::kernel::PugiXML::Entry Entry;
public:
ParameterExtractor()
{
vars.add(vmat::key::parameter.c_str(), pugi::xpath_type_string);
std::string parameter_query_string = ".//parameters/parameter[name = string($"+vmat::key::parameter+")]";
query_parameter = new pugi::xpath_query(parameter_query_string.c_str(), &vars);
}
~ParameterExtractor()
{
delete query_parameter;
}
Entry operator()(Entry const& material, std::string const& parameter_id)
{
pugi::xpath_node_set const& result = this->queryParameter(material, parameter_id);
if(result.size() > 1) // there must be only one parameter with this id
{
throw vmat::NonUniqueParameterException(parameter_id);
return Entry();
}
else if (result.size() == 0) return Entry();
else return result.first(); // if success, return only a single xpath_node
}
bool hasParameter(Entry const& material, std::string const& parameter_id)
{
pugi::xpath_node_set const& result = this->queryParameter(material, parameter_id);
if(result.size() > 1) // there must be only one material with this id
{
throw vmat::NonUniqueParameterException(parameter_id);
return false;
}
else if (result.size() == 0) return false;
else return true;
}
private:
Entries queryParameter(Entry const& material, std::string const& parameter_id)
{
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter->evaluate_node_set(material.node());
}
pugi::xpath_variable_set vars;
pugi::xpath_query *query_parameter;
};
inline vmat::kernel::PugiXML::Entry getParameter(vmat::kernel::PugiXML::Entry const& material, std::string const& parameter_id)
{
return vmat::ParameterExtractor()(material, parameter_id);
}
inline bool hasParameter(vmat::kernel::PugiXML::Entry const& material, std::string const& parameter_id)
{
return vmat::ParameterExtractor().hasParameter(material, parameter_id);
}
} // vmat
#endif
<commit_msg>added vmat::id(Entry) function<commit_after>#ifndef VIENNAMATERIALS_KERNELS_PUGIXML_HPP
#define VIENNAMATERIALS_KERNELS_PUGIXML_HPP
/* =============================================================================
Copyright (c) 2013, Institute for Microelectronics, TU Wien
http://www.iue.tuwien.ac.at
-----------------
ViennaMaterials - The Vienna Materials Library
-----------------
authors: Josef Weinbub weinbub@iue.tuwien.ac.at
license: see file LICENSE in the base directory
============================================================================= */
#include "viennautils/xml.hpp"
#include "viennautils/file.hpp"
#ifdef HAVE_VIENNAIPD
extern "C" {
#include "ipd.h"
}
#endif
namespace vmat {
namespace tag {
struct pugixml {};
} // tag
namespace kernel {
struct PugiXML
{
typedef viennautils::xml<viennautils::tag::pugixml>::type MaterialDatabase;
typedef MaterialDatabase::NodeSet Entries;
typedef MaterialDatabase::Node Entry;
typedef MaterialDatabase::NodeIterator EntryIterator;
typedef double Numeric;
typedef bool Boolean;
typedef std::string String;
PugiXML()
{
// setup variables used as placeholdes in the precompiled queries
vars.add(vmat::key::id.c_str(), pugi::xpath_type_string);
vars.add(vmat::key::category.c_str(), pugi::xpath_type_string);
vars.add(vmat::key::parameter.c_str(), pugi::xpath_type_string);
// precompile the various query strings - use placeholders for run-time parameters
std::string material_query_string = "/materials/material[id = string($"+vmat::key::id+")]";
query_material = new pugi::xpath_query(material_query_string.c_str(), &vars);
std::string category_query_string = "/materials/material[category = string($"+vmat::key::category+")]";
query_category = new pugi::xpath_query(category_query_string.c_str(), &vars);
std::string parameter_query_string = "/materials/material[id = string($"+vmat::key::id+")]/parameters/parameter[name = string($"+vmat::key::parameter+")]";
query_parameter = new pugi::xpath_query(parameter_query_string.c_str(), &vars);
std::string parameter_value_query_string = "/materials/material[id = string($"+vmat::key::id+")]/parameters/parameter[name = string($"+vmat::key::parameter+")]/value";
query_parameter_value = new pugi::xpath_query(parameter_value_query_string.c_str(), &vars);
std::string parameter_unit_query_string = "/materials/material[id = string($"+vmat::key::id+")]/parameters/parameter[name = string($"+vmat::key::parameter+")]/unit";
query_parameter_unit = new pugi::xpath_query(parameter_unit_query_string.c_str(), &vars);
std::string parameter_note_query_string = "/materials/material[id = string($"+vmat::key::id+")]/parameters/parameter[name = string($"+vmat::key::parameter+")]/note";
query_parameter_note = new pugi::xpath_query(parameter_note_query_string.c_str(), &vars);
}
~PugiXML()
{
// the xpath queries are due to pugixml's impelmentation required to be allocated
// on the heap ..
delete query_material;
delete query_category;
delete query_parameter;
delete query_parameter_value;
delete query_parameter_unit;
delete query_parameter_note;
}
bool load(std::string const& filename)
{
#ifdef HAVE_LIBXML2
if(!vmat::check(filename))
{
return false;
}
#endif
if(!viennautils::file_exists(filename))
{
throw XMLFileLoadError();
return false;
}
if(viennautils::file_extension(filename) == "xml") // native
{
mdb.read(filename);
return true;
}
#ifdef HAVE_VIENNAIPD
else if(viennautils::file_extension(filename) == "ipd") // conversion required
{
ipdInit(NULL, NULL);
// todo:
std::cout << "IPD support is not yet implemented .." << std::endl;
return true;
}
#endif
else return false;
}
bool load(std::stringstream & stream)
{
mdb.read(stream);
}
void dump(std::ostream& stream = std::cout)
{
mdb.dump(stream);
}
void dump(std::ostream& stream = std::cout) const
{
mdb.dump(stream);
}
Entries query(std::string const& expr)
{
return mdb.query_raw(expr);
}
Entries query(std::string const& expr) const
{
return mdb.query_raw(expr);
}
Entries getSemiconductors()
{
vars.set(vmat::key::category.c_str(), vmat::key::semiconductor.c_str());
return query_category->evaluate_node_set(mdb.xml);
}
// Entries getSemiconductors() const
// {
// vars.set(vmat::key::category.c_str(), vmat::key::semiconductor.c_str());
// return query_category->evaluate_node_set(mdb.xml);
// }
bool hasSemiconductors()
{
return !(this->getSemiconductors().empty());
}
// bool hasSemiconductors() const
// {
// return !(this->getSemiconductors().empty());
// }
Entries getMetals()
{
vars.set(vmat::key::category.c_str(), vmat::key::metal.c_str());
return query_category->evaluate_node_set(mdb.xml);
}
// Entries getMetals() const
// {
// vars.set(vmat::key::category.c_str(), vmat::key::metal.c_str());
// return query_category->evaluate_node_set(mdb.xml);
// }
bool hasMetals()
{
return !(this->getMetals().empty());
}
Entries getOxides()
{
vars.set(vmat::key::category.c_str(), vmat::key::oxide.c_str());
return query_category->evaluate_node_set(mdb.xml);
}
bool hasOxides()
{
return !(this->getOxides().empty());
}
Entries getMaterialsOfCategory(std::string const& category_id)
{
vars.set(vmat::key::category.c_str(), category_id.c_str());
return query_category->evaluate_node_set(mdb.xml);
}
bool hasMaterialsOfCategory(std::string const& category_id)
{
return !(this->getMaterialsOfCategory(category_id).empty());
}
// -- Material Accessors -----------------------------------------------------
private:
Entries queryMaterial(std::string const& material_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
return query_material->evaluate_node_set(mdb.xml);
}
public:
Entry getMaterial(std::string const& material_id)
{
pugi::xpath_node_set const& result = this->queryMaterial(material_id);
if(result.size() > 1) // there must be only one material with this id
{
throw vmat::NonUniqueMaterialException(material_id);
return Entry();
}
else if (result.size() == 0) return Entry();
else return result.first(); // if success, return only a single xpath_node
}
bool hasMaterial(std::string const& material_id)
{
pugi::xpath_node_set const& result = this->queryMaterial(material_id);
if(result.size() > 1) // there must be only one material with this id
{
throw vmat::NonUniqueMaterialException(material_id);
return false;
}
else if (result.size() == 0) return false;
else return true;
}
// ---------------------------------------------------------------------------
// -- Parameter Accessors ----------------------------------------------------
private:
Entries queryParameter(std::string const& material_id, std::string const& parameter_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter->evaluate_node_set(mdb.xml);
}
public:
Entry getParameter(std::string const& material_id, std::string const& parameter_id)
{
pugi::xpath_node_set const& result = this->queryParameter(material_id, parameter_id);
if(result.size() > 1) // there must be only one parameter with this id
{
throw vmat::NonUniqueParameterException(parameter_id);
return Entry();
}
else if (result.size() == 0) return Entry();
else return result.first(); // if success, return only a single xpath_node
}
bool hasParameter(std::string const& material_id, std::string const& parameter_id)
{
pugi::xpath_node_set const& result = this->queryParameter(material_id, parameter_id);
if(result.size() > 1) // there must be only one material with this id
{
throw vmat::NonUniqueParameterException(parameter_id);
return false;
}
else if (result.size() == 0) return false;
else return true;
}
Numeric getParameterValue(std::string const& material_id, std::string const& parameter_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter_value->evaluate_number(mdb.xml);
}
String getParameterUnit(std::string const& material_id, std::string const& parameter_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter_unit->evaluate_string(mdb.xml);
}
String getParameterNote(std::string const& material_id, std::string const& parameter_id)
{
vars.set(vmat::key::id.c_str(), material_id.c_str());
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter_note->evaluate_string(mdb.xml);
}
// ---------------------------------------------------------------------------
private:
MaterialDatabase mdb;
pugi::xpath_variable_set vars;
pugi::xpath_query *query_material;
pugi::xpath_query *query_category;
pugi::xpath_query *query_parameter;
pugi::xpath_query *query_parameter_value;
pugi::xpath_query *query_parameter_unit;
pugi::xpath_query *query_parameter_note;
};
} // kernel
template<>
struct Library <vmat::tag::pugixml>
{
typedef vmat::kernel::PugiXML type;
};
// TOOLS -----------------------------------------------------------------------
inline void printToStream(vmat::kernel::PugiXML::Entries const& nodeset, std::ostream& stream = std::cout)
{
for(size_t i = 0; i < nodeset.size(); i++)
nodeset[i].node().print(stream, " ");
}
inline void printToStream(vmat::kernel::PugiXML::Entry const& node, std::ostream& stream = std::cout)
{
node.node().print(stream, " ");
}
inline vmat::kernel::PugiXML::Entries query(vmat::kernel::PugiXML::Entry const& entry, std::string const& query)
{
return entry.node().select_nodes(query.c_str());
}
inline bool isParameter(vmat::kernel::PugiXML::Entry const& entry)
{
if(std::string(entry.node().name()) == vmat::key::parameter)
return true;
else return false;
}
inline bool isMaterial(vmat::kernel::PugiXML::Entry const& entry)
{
if(std::string(entry.node().name()) == vmat::key::material)
return true;
else return false;
}
inline vmat::kernel::PugiXML::Numeric value(vmat::kernel::PugiXML::Entry const& entry)
{
return pugi::xpath_query("value").evaluate_number(entry);
}
inline vmat::kernel::PugiXML::String name(vmat::kernel::PugiXML::Entry const& entry)
{
return pugi::xpath_query("name").evaluate_string(entry);
}
inline vmat::kernel::PugiXML::String id(vmat::kernel::PugiXML::Entry const& entry)
{
return pugi::xpath_query("id").evaluate_string(entry);
}
inline vmat::kernel::PugiXML::String unit(vmat::kernel::PugiXML::Entry const& entry)
{
return pugi::xpath_query("unit").evaluate_string(entry);
}
inline vmat::kernel::PugiXML::String note(vmat::kernel::PugiXML::Entry const& entry)
{
return pugi::xpath_query("note").evaluate_string(entry);
}
// -----------------------------------------------------------------------------
struct ParameterExtractor
{
typedef vmat::kernel::PugiXML::Entries Entries;
typedef vmat::kernel::PugiXML::Entry Entry;
public:
ParameterExtractor()
{
vars.add(vmat::key::parameter.c_str(), pugi::xpath_type_string);
std::string parameter_query_string = ".//parameters/parameter[name = string($"+vmat::key::parameter+")]";
query_parameter = new pugi::xpath_query(parameter_query_string.c_str(), &vars);
}
~ParameterExtractor()
{
delete query_parameter;
}
Entry operator()(Entry const& material, std::string const& parameter_id)
{
pugi::xpath_node_set const& result = this->queryParameter(material, parameter_id);
if(result.size() > 1) // there must be only one parameter with this id
{
throw vmat::NonUniqueParameterException(parameter_id);
return Entry();
}
else if (result.size() == 0) return Entry();
else return result.first(); // if success, return only a single xpath_node
}
bool hasParameter(Entry const& material, std::string const& parameter_id)
{
pugi::xpath_node_set const& result = this->queryParameter(material, parameter_id);
if(result.size() > 1) // there must be only one material with this id
{
throw vmat::NonUniqueParameterException(parameter_id);
return false;
}
else if (result.size() == 0) return false;
else return true;
}
private:
Entries queryParameter(Entry const& material, std::string const& parameter_id)
{
vars.set(vmat::key::parameter.c_str(), parameter_id.c_str());
return query_parameter->evaluate_node_set(material.node());
}
pugi::xpath_variable_set vars;
pugi::xpath_query *query_parameter;
};
inline vmat::kernel::PugiXML::Entry getParameter(vmat::kernel::PugiXML::Entry const& material, std::string const& parameter_id)
{
return vmat::ParameterExtractor()(material, parameter_id);
}
inline bool hasParameter(vmat::kernel::PugiXML::Entry const& material, std::string const& parameter_id)
{
return vmat::ParameterExtractor().hasParameter(material, parameter_id);
}
} // vmat
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: services.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2004-08-02 15:16:43 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _DBA_REGHELPER_HXX_
#include "dba_reghelper.hxx"
#endif
/********************************************************************************************/
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
//***************************************************************************************
//
// registry functions
extern "C" void SAL_CALL createRegistryInfo_ODatabaseContext();
extern "C" void SAL_CALL createRegistryInfo_ODatabaseSource();
// extern "C" void SAL_CALL createRegistryInfo_ODocumentDefinition();
extern "C" void SAL_CALL createRegistryInfo_OCommandDefinition();
extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition();
extern "C" void SAL_CALL createRegistryInfo_ORowSet();
//***************************************************************************************
//
// Die vorgeschriebene C-Api muss erfuellt werden!
// Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.
//
extern "C" void SAL_CALL createRegistryInfo_DBA()
{
static sal_Bool bInit = sal_False;
if (!bInit)
{
createRegistryInfo_ODatabaseContext();
createRegistryInfo_ODatabaseSource();
// createRegistryInfo_ODocumentDefinition();
createRegistryInfo_OCommandDefinition();
createRegistryInfo_OComponentDefinition();
createRegistryInfo_ORowSet();
bInit = sal_True;
}
}
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment **ppEnv
)
{
createRegistryInfo_DBA();
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* pServiceManager,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
return ::dbaccess::OModuleRegistration::writeComponentInfos(
static_cast<XMultiServiceFactory*>(pServiceManager),
static_cast<XRegistryKey*>(pRegistryKey));
}
catch (InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "DBA::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* pRegistryKey)
{
Reference< XInterface > xRet;
if (pServiceManager && pImplementationName)
{
xRet = ::dbaccess::OModuleRegistration::getComponentFactory(
::rtl::OUString::createFromAscii(pImplementationName),
static_cast< XMultiServiceFactory* >(pServiceManager));
}
if (xRet.is())
xRet->acquire();
return xRet.get();
};
<commit_msg>INTEGRATION: CWS dba24 (1.7.80); FILE MERGED 2005/02/28 08:48:10 oj 1.7.80.2: #i43628# #i43627# check impl and reinvent service datasource 2005/02/18 12:25:30 oj 1.7.80.1: #i42460# changes for the separation of datasource and database document(model)<commit_after>/*************************************************************************
*
* $RCSfile: services.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: vg $ $Date: 2005-03-10 16:38:14 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CPPUHELPER_FACTORY_HXX_
#include <cppuhelper/factory.hxx>
#endif
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _DBA_REGHELPER_HXX_
#include "dba_reghelper.hxx"
#endif
/********************************************************************************************/
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::com::sun::star::registry;
//***************************************************************************************
//
// registry functions
extern "C" void SAL_CALL createRegistryInfo_ODatabaseContext();
// extern "C" void SAL_CALL createRegistryInfo_ODocumentDefinition();
extern "C" void SAL_CALL createRegistryInfo_OCommandDefinition();
extern "C" void SAL_CALL createRegistryInfo_OComponentDefinition();
extern "C" void SAL_CALL createRegistryInfo_ORowSet();
extern "C" void SAL_CALL createRegistryInfo_ODatabaseDocument();
extern "C" void SAL_CALL createRegistryInfo_ODatabaseSource();
//***************************************************************************************
//
// Die vorgeschriebene C-Api muss erfuellt werden!
// Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.
//
extern "C" void SAL_CALL createRegistryInfo_DBA()
{
static sal_Bool bInit = sal_False;
if (!bInit)
{
createRegistryInfo_ODatabaseContext();
// createRegistryInfo_ODocumentDefinition();
createRegistryInfo_OCommandDefinition();
createRegistryInfo_OComponentDefinition();
createRegistryInfo_ORowSet();
createRegistryInfo_ODatabaseDocument();
createRegistryInfo_ODatabaseSource();
bInit = sal_True;
}
}
//---------------------------------------------------------------------------------------
extern "C" void SAL_CALL component_getImplementationEnvironment(
const sal_Char **ppEnvTypeName,
uno_Environment **ppEnv
)
{
createRegistryInfo_DBA();
*ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;
}
//---------------------------------------------------------------------------------------
extern "C" sal_Bool SAL_CALL component_writeInfo(
void* pServiceManager,
void* pRegistryKey
)
{
if (pRegistryKey)
try
{
return ::dbaccess::OModuleRegistration::writeComponentInfos(
static_cast<XMultiServiceFactory*>(pServiceManager),
static_cast<XRegistryKey*>(pRegistryKey));
}
catch (InvalidRegistryException& )
{
OSL_ENSURE(sal_False, "DBA::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !");
}
return sal_False;
}
//---------------------------------------------------------------------------------------
extern "C" void* SAL_CALL component_getFactory(
const sal_Char* pImplementationName,
void* pServiceManager,
void* pRegistryKey)
{
Reference< XInterface > xRet;
if (pServiceManager && pImplementationName)
{
xRet = ::dbaccess::OModuleRegistration::getComponentFactory(
::rtl::OUString::createFromAscii(pImplementationName),
static_cast< XMultiServiceFactory* >(pServiceManager));
}
if (xRet.is())
xRet->acquire();
return xRet.get();
};
<|endoftext|> |
<commit_before>
#include "stdafx.h"
#include "node.h"
#include "editmanager.h"
#include "../external/NodeEditor/imgui_node_editor_internal.h"
using namespace framework;
using namespace vprog;
cNode::cNode(int id, const StrId &name
, ImColor color //= ImColor(255, 255, 255)
)
: m_id(id)
, m_name(name)
, m_desc(name)
, m_color(color)
, m_type(eNodeType::Function)
, m_size(0, 0)
{
}
cNode::~cNode()
{
Clear();
}
// render visual programming node
bool cNode::Render(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin* newLinkPin //= nullptr
)
{
if (m_type != eNodeType::Function
&& m_type != eNodeType::Operator
&& m_type != eNodeType::Event
&& m_type != eNodeType::Control
&& m_type != eNodeType::Macro
&& m_type != eNodeType::Variable)
return true;
const auto isSimple = (m_type == eNodeType::Variable)
|| (m_type == eNodeType::Operator);
bool hasOutputDelegates = false;
for (auto& output : m_outputs)
{
if (output.type == ePinType::Delegate)
hasOutputDelegates = true;
}
builder.Begin(m_id);
if (!isSimple)
{
builder.Header(m_color);
ImGui::Spring(0);
ImGui::TextUnformatted(m_name.c_str());
ImGui::Spring(1);
ImGui::Dummy(ImVec2(0, 28));
if (hasOutputDelegates)
{
ImGui::BeginVertical("delegates", ImVec2(0, 28));
ImGui::Spring(1, 0);
for (auto& output : m_outputs)
{
if (output.type != ePinType::Delegate)
continue;
auto alpha = ImGui::GetStyle().Alpha;
if (newLinkPin && !CanCreateLink(newLinkPin, &output) && &output != newLinkPin)
alpha = alpha * (48.0f / 255.0f);
ed::BeginPin(output.id, ed::ePinKind::Output);
ed::PinPivotAlignment(ImVec2(1.0f, 0.5f));
ed::PinPivotSize(ImVec2(0, 0));
ImGui::BeginHorizontal(output.id.AsPointer());
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha);
if (!output.name.empty())
{
ImGui::TextUnformatted(output.name.c_str());
ImGui::Spring(0);
}
DrawPinIcon(output, editMgr.IsPinLinked(output.id), (int)(alpha * 255));
ImGui::Spring(0, ImGui::GetStyle().ItemSpacing.x / 2);
ImGui::EndHorizontal();
ImGui::PopStyleVar();
ed::EndPin();
//DrawItemRect(ImColor(255, 0, 0));
}
ImGui::Spring(1, 0);
ImGui::EndVertical();
ImGui::Spring(0, ImGui::GetStyle().ItemSpacing.x / 2);
}
else
ImGui::Spring(0);
builder.EndHeader();
}
for (auto& input : m_inputs)
{
auto alpha = ImGui::GetStyle().Alpha;
if (newLinkPin && !CanCreateLink(newLinkPin, &input) && &input != newLinkPin)
alpha = alpha * (48.0f / 255.0f);
builder.Input(input.id);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha);
DrawPinIcon(input, editMgr.IsPinLinked(input.id), (int)(alpha * 255));
ImGui::Spring(0);
switch (input.type)
{
case ePinType::NotDef:
// set variable node?
if (m_name == "Set")
{
RenderSetInputPin(editMgr, builder, input, newLinkPin);
}
else
{
if (!input.name.empty())
{
ImGui::TextUnformatted(input.name.c_str());
ImGui::Spring(0);
}
}
break;
//case ePinType::Bool:
// todo: check or combo
//ImGui::Spring(0);
//break;
default:
if (!input.name.empty())
{
ImGui::TextUnformatted(input.name.c_str());
ImGui::Spring(0);
}
break;
}
ImGui::PopStyleVar();
builder.EndInput();
} //~input
if (isSimple)
{
if (eNodeType::Operator == m_type)
{
builder.Middle();
ImGui::Spring(1, 0);
ImGui::TextUnformatted(m_name.c_str());
ImGui::Spring(1, 0);
}
else
{
builder.Middle();
ImGui::Spring(1, 0);
ImGui::TextUnformatted(" ");
ImGui::Spring(1, 0);
}
}
for (auto& output : m_outputs)
{
if (!isSimple && output.type == ePinType::Delegate)
continue;
auto alpha = ImGui::GetStyle().Alpha;
if (newLinkPin && !CanCreateLink(newLinkPin, &output) && &output != newLinkPin)
alpha = alpha * (48.0f / 255.0f);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha);
builder.Output(output.id);
if (eNodeType::Variable == m_type)
{
switch (output.type)
{
case ePinType::String:
RenderStringPin(editMgr, builder, output, newLinkPin);
break;
case ePinType::Enums:
RenderEnumPin(editMgr, builder, output, newLinkPin);
break;
}
}
if (!output.name.empty())
{
ImGui::Spring(0);
ImGui::TextUnformatted(output.name.c_str());
}
ImGui::Spring(0);
DrawPinIcon(output, editMgr.IsPinLinked(output.id), (int)(alpha * 255));
ImGui::PopStyleVar();
builder.EndOutput();
} //~output
if ((eNodeType::Control == m_type) && (m_desc == "Switch"))
RenderSwitchCaseNode(editMgr, builder, newLinkPin);
else if ((eNodeType::Control == m_type) && (m_desc == "Sequence"))
RenderSequenceNode(editMgr, builder, newLinkPin);
builder.End();
return true;
}
// render Set node input pin
// render input variable combo box
bool cNode::RenderSetInputPin(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin &pin
, sPin* newLinkPin //= nullptr
)
{
char *prevStr = "Empty";
// enum selection combo
ImGui::PushItemWidth(100);
const ImVec2 offset = ed::GetCurrentViewTransformPosition();
const float scale = 1.f / ed::GetCurrentZoom();
if (ImGui::BeginCombo2("##enum combo", prevStr, scale, offset))
{
ed::Suspend();
for (auto &kv : editMgr.m_symbTable.m_vars)
{
const string &scopeName = kv.first;
for (auto &kv2 : kv.second)
{
const string &name = kv2.first;
sPin *varPin = editMgr.FindPin(scopeName, name);
if (!varPin)
continue;
if (ImGui::Selectable(varPin->name.c_str()))
{
// update pin information
pin.name = varPin->name;
pin.type = varPin->type;
pin.typeStr = varPin->typeStr;
cNode *node = editMgr.FindContainNode(pin.id);
node->m_desc = scopeName;
}
}
}
ed::Resume();
ImGui::EndCombo();
}
ImGui::PopItemWidth();
//~combo
ImGui::Spring(0);
return true;
}
// render string pin
bool cNode::RenderStringPin(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin &pin
, sPin* newLinkPin //= nullptr
)
{
const string scopeName =
common::script::cSymbolTable::MakeScopeName(
m_name.c_str(), m_id.Get());
common::script::cSymbolTable::sVar *varInfo =
editMgr.m_symbTable.FindVarInfo(scopeName, pin.name.c_str());
if (!varInfo)
return true;
Str128 buffer = common::variant2str(varInfo->var);
static bool wasActive = false;
ImGui::PushItemWidth(100.0f);
if (ImGui::InputText("##edit", buffer.m_str, buffer.SIZE))
{
common::clearvariant(varInfo->var);
varInfo->var = common::str2variant(VT_BSTR, buffer.c_str());
}
ImGui::PopItemWidth();
if (ImGui::IsItemActive() && !wasActive)
{
ed::EnableShortcuts(false);
wasActive = true;
}
else if (!ImGui::IsItemActive() && wasActive)
{
ed::EnableShortcuts(true);
wasActive = false;
}
ImGui::Spring(0);
return true;
}
// render enumeration pin
bool cNode::RenderEnumPin(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin &pin
, sPin* newLinkPin //= nullptr
)
{
const string scopeName =
common::script::cSymbolTable::MakeScopeName(
m_name.c_str(), m_id.Get());
common::script::cSymbolTable::sVar *varInfo =
editMgr.m_symbTable.FindVarInfo(scopeName, pin.name.c_str());
if (!varInfo)
return true;
auto *type = editMgr.m_symbTable.FindSymbol(m_name.c_str());
if (!type)
return true;
auto &var = varInfo->var;
const char *prevStr = nullptr;
if (type->enums.size() > (uint)var.intVal)
prevStr = type->enums[var.intVal].name.c_str();
else
prevStr = type->enums[0].name.c_str();
// enum selection combo
ImGui::PushItemWidth(200);
const ImVec2 offset = ed::GetCurrentViewTransformPosition();
const float scale = 1.f / ed::GetCurrentZoom();
if (ImGui::BeginCombo2("##enum combo", prevStr, scale, offset))
{
ed::Suspend();
for (uint i = 0; i < type->enums.size(); ++i)
{
auto &e = type->enums[i];
if (ImGui::Selectable(e.name.c_str()))
var.intVal = (int)i;
}
ed::Resume();
ImGui::EndCombo();
}
ImGui::PopItemWidth();
//~combo
ImGui::Spring(0);
return true;
}
// render switch case, default type
bool cNode::RenderSwitchCaseNode(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin* newLinkPin //= nullptr
)
{
// check int selection type?
ePinType::Enum pinType = ePinType::COUNT;
for (uint i = 0; i < m_inputs.size(); ++i)
{
auto &pin = m_inputs[i];
if (pin.name == "Selection")
{
pinType = pin.type;
break;
}
}
// int type switch case
// render + Add pin Button
if (ePinType::Int == pinType)
{
static int val = 0;
ImGui::Spring(0);
ImGui::PushItemWidth(35);
ImGui::InputInt("##val", &val, 0);
ImGui::PopItemWidth();
ImGui::SameLine();
if (ImGui::Button("Add Pin+"))
{
// check same value?
auto it = find_if(m_outputs.begin(), m_outputs.end()
, [&](const auto &a) { return a.value == val; });
if (it == m_outputs.end())
{
// insert case, before Default case
StrId text;
text.Format("%d", val);
vprog::sPin pin(editMgr.GetUniqueId(), text.c_str(), ePinType::Flow);
pin.typeStr = "Flow";
pin.nodeId = m_id;
pin.kind = ePinKind::Output;
pin.value = val;
m_outputs.push_back(pin);
// find default iterator?
auto it2 = find_if(m_outputs.begin(), m_outputs.end()
, [](const auto &a) { return a.name == "Default"; });
if (m_outputs.end() != it)
{
std::swap(*it2, m_outputs.back());
}
}
}
//ImGui::Spring(0);
}
return true;
}
// render button "Add pin+"
bool cNode::RenderSequenceNode(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin* newLinkPin //= nullptr
)
{
ImGui::Spring(0);
if (ImGui::Button("Add Pin+"))
{
StrId text;
text.Format("Then %d", m_outputs.size());
vprog::sPin pin(editMgr.GetUniqueId(), text.c_str(), ePinType::Flow);
pin.typeStr = "Flow";
pin.nodeId = m_id;
pin.kind = ePinKind::Output;
pin.value = 0;
m_outputs.push_back(pin);
}
return true;
}
void cNode::Clear()
{
m_id = 0;
m_name.clear();
m_desc.clear();
m_inputs.clear();
m_outputs.clear();
}
<commit_msg>update symboltable compile error<commit_after>
#include "stdafx.h"
#include "node.h"
#include "editmanager.h"
#include "../external/NodeEditor/imgui_node_editor_internal.h"
using namespace framework;
using namespace vprog;
cNode::cNode(int id, const StrId &name
, ImColor color //= ImColor(255, 255, 255)
)
: m_id(id)
, m_name(name)
, m_desc(name)
, m_color(color)
, m_type(eNodeType::Function)
, m_size(0, 0)
{
}
cNode::~cNode()
{
Clear();
}
// render visual programming node
bool cNode::Render(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin* newLinkPin //= nullptr
)
{
if (m_type != eNodeType::Function
&& m_type != eNodeType::Operator
&& m_type != eNodeType::Event
&& m_type != eNodeType::Control
&& m_type != eNodeType::Macro
&& m_type != eNodeType::Variable)
return true;
const auto isSimple = (m_type == eNodeType::Variable)
|| (m_type == eNodeType::Operator);
bool hasOutputDelegates = false;
for (auto& output : m_outputs)
{
if (output.type == ePinType::Delegate)
hasOutputDelegates = true;
}
builder.Begin(m_id);
if (!isSimple)
{
builder.Header(m_color);
ImGui::Spring(0);
ImGui::TextUnformatted(m_name.c_str());
ImGui::Spring(1);
ImGui::Dummy(ImVec2(0, 28));
if (hasOutputDelegates)
{
ImGui::BeginVertical("delegates", ImVec2(0, 28));
ImGui::Spring(1, 0);
for (auto& output : m_outputs)
{
if (output.type != ePinType::Delegate)
continue;
auto alpha = ImGui::GetStyle().Alpha;
if (newLinkPin && !CanCreateLink(newLinkPin, &output) && &output != newLinkPin)
alpha = alpha * (48.0f / 255.0f);
ed::BeginPin(output.id, ed::ePinKind::Output);
ed::PinPivotAlignment(ImVec2(1.0f, 0.5f));
ed::PinPivotSize(ImVec2(0, 0));
ImGui::BeginHorizontal(output.id.AsPointer());
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha);
if (!output.name.empty())
{
ImGui::TextUnformatted(output.name.c_str());
ImGui::Spring(0);
}
DrawPinIcon(output, editMgr.IsPinLinked(output.id), (int)(alpha * 255));
ImGui::Spring(0, ImGui::GetStyle().ItemSpacing.x / 2);
ImGui::EndHorizontal();
ImGui::PopStyleVar();
ed::EndPin();
//DrawItemRect(ImColor(255, 0, 0));
}
ImGui::Spring(1, 0);
ImGui::EndVertical();
ImGui::Spring(0, ImGui::GetStyle().ItemSpacing.x / 2);
}
else
ImGui::Spring(0);
builder.EndHeader();
}
for (auto& input : m_inputs)
{
auto alpha = ImGui::GetStyle().Alpha;
if (newLinkPin && !CanCreateLink(newLinkPin, &input) && &input != newLinkPin)
alpha = alpha * (48.0f / 255.0f);
builder.Input(input.id);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha);
DrawPinIcon(input, editMgr.IsPinLinked(input.id), (int)(alpha * 255));
ImGui::Spring(0);
switch (input.type)
{
case ePinType::NotDef:
// set variable node?
if (m_name == "Set")
{
RenderSetInputPin(editMgr, builder, input, newLinkPin);
}
else
{
if (!input.name.empty())
{
ImGui::TextUnformatted(input.name.c_str());
ImGui::Spring(0);
}
}
break;
//case ePinType::Bool:
// todo: check or combo
//ImGui::Spring(0);
//break;
default:
if (!input.name.empty())
{
ImGui::TextUnformatted(input.name.c_str());
ImGui::Spring(0);
}
break;
}
ImGui::PopStyleVar();
builder.EndInput();
} //~input
if (isSimple)
{
if (eNodeType::Operator == m_type)
{
builder.Middle();
ImGui::Spring(1, 0);
ImGui::TextUnformatted(m_name.c_str());
ImGui::Spring(1, 0);
}
else
{
builder.Middle();
ImGui::Spring(1, 0);
ImGui::TextUnformatted(" ");
ImGui::Spring(1, 0);
}
}
for (auto& output : m_outputs)
{
if (!isSimple && output.type == ePinType::Delegate)
continue;
auto alpha = ImGui::GetStyle().Alpha;
if (newLinkPin && !CanCreateLink(newLinkPin, &output) && &output != newLinkPin)
alpha = alpha * (48.0f / 255.0f);
ImGui::PushStyleVar(ImGuiStyleVar_Alpha, alpha);
builder.Output(output.id);
if (eNodeType::Variable == m_type)
{
switch (output.type)
{
case ePinType::String:
RenderStringPin(editMgr, builder, output, newLinkPin);
break;
case ePinType::Enums:
RenderEnumPin(editMgr, builder, output, newLinkPin);
break;
}
}
if (!output.name.empty())
{
ImGui::Spring(0);
ImGui::TextUnformatted(output.name.c_str());
}
ImGui::Spring(0);
DrawPinIcon(output, editMgr.IsPinLinked(output.id), (int)(alpha * 255));
ImGui::PopStyleVar();
builder.EndOutput();
} //~output
if ((eNodeType::Control == m_type) && (m_desc == "Switch"))
RenderSwitchCaseNode(editMgr, builder, newLinkPin);
else if ((eNodeType::Control == m_type) && (m_desc == "Sequence"))
RenderSequenceNode(editMgr, builder, newLinkPin);
builder.End();
return true;
}
// render Set node input pin
// render input variable combo box
bool cNode::RenderSetInputPin(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin &pin
, sPin* newLinkPin //= nullptr
)
{
char *prevStr = "Empty";
// enum selection combo
ImGui::PushItemWidth(100);
const ImVec2 offset = ed::GetCurrentViewTransformPosition();
const float scale = 1.f / ed::GetCurrentZoom();
if (ImGui::BeginCombo2("##enum combo", prevStr, scale, offset))
{
ed::Suspend();
for (auto &kv : editMgr.m_symbTable.m_vars)
{
const string &scopeName = kv.first;
for (auto &kv2 : kv.second)
{
const string &name = kv2.first;
sPin *varPin = editMgr.FindPin(scopeName, name);
if (!varPin)
continue;
if (ImGui::Selectable(varPin->name.c_str()))
{
// update pin information
pin.name = varPin->name;
pin.type = varPin->type;
pin.typeStr = varPin->typeStr;
cNode *node = editMgr.FindContainNode(pin.id);
node->m_desc = scopeName;
}
}
}
ed::Resume();
ImGui::EndCombo();
}
ImGui::PopItemWidth();
//~combo
ImGui::Spring(0);
return true;
}
// render string pin
bool cNode::RenderStringPin(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin &pin
, sPin* newLinkPin //= nullptr
)
{
const string scopeName =
common::script::cSymbolTable::MakeScopeName(
m_name.c_str(), m_id.Get());
common::script::sVariable *varInfo =
editMgr.m_symbTable.FindVarInfo(scopeName, pin.name.c_str());
if (!varInfo)
return true;
Str128 buffer = common::variant2str(varInfo->var);
static bool wasActive = false;
ImGui::PushItemWidth(100.0f);
if (ImGui::InputText("##edit", buffer.m_str, buffer.SIZE))
{
common::clearvariant(varInfo->var);
varInfo->var = common::str2variant(VT_BSTR, buffer.c_str());
}
ImGui::PopItemWidth();
if (ImGui::IsItemActive() && !wasActive)
{
ed::EnableShortcuts(false);
wasActive = true;
}
else if (!ImGui::IsItemActive() && wasActive)
{
ed::EnableShortcuts(true);
wasActive = false;
}
ImGui::Spring(0);
return true;
}
// render enumeration pin
bool cNode::RenderEnumPin(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin &pin
, sPin* newLinkPin //= nullptr
)
{
const string scopeName =
common::script::cSymbolTable::MakeScopeName(
m_name.c_str(), m_id.Get());
common::script::sVariable *varInfo =
editMgr.m_symbTable.FindVarInfo(scopeName, pin.name.c_str());
if (!varInfo)
return true;
auto *type = editMgr.m_symbTable.FindSymbol(m_name.c_str());
if (!type)
return true;
auto &var = varInfo->var;
const char *prevStr = nullptr;
if (type->enums.size() > (uint)var.intVal)
prevStr = type->enums[var.intVal].name.c_str();
else
prevStr = type->enums[0].name.c_str();
// enum selection combo
ImGui::PushItemWidth(200);
const ImVec2 offset = ed::GetCurrentViewTransformPosition();
const float scale = 1.f / ed::GetCurrentZoom();
if (ImGui::BeginCombo2("##enum combo", prevStr, scale, offset))
{
ed::Suspend();
for (uint i = 0; i < type->enums.size(); ++i)
{
auto &e = type->enums[i];
if (ImGui::Selectable(e.name.c_str()))
var.intVal = (int)i;
}
ed::Resume();
ImGui::EndCombo();
}
ImGui::PopItemWidth();
//~combo
ImGui::Spring(0);
return true;
}
// render switch case, default type
bool cNode::RenderSwitchCaseNode(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin* newLinkPin //= nullptr
)
{
// check int selection type?
ePinType::Enum pinType = ePinType::COUNT;
for (uint i = 0; i < m_inputs.size(); ++i)
{
auto &pin = m_inputs[i];
if (pin.name == "Selection")
{
pinType = pin.type;
break;
}
}
// int type switch case
// render + Add pin Button
if (ePinType::Int == pinType)
{
static int val = 0;
ImGui::Spring(0);
ImGui::PushItemWidth(35);
ImGui::InputInt("##val", &val, 0);
ImGui::PopItemWidth();
ImGui::SameLine();
if (ImGui::Button("Add Pin+"))
{
// check same value?
auto it = find_if(m_outputs.begin(), m_outputs.end()
, [&](const auto &a) { return a.value == val; });
if (it == m_outputs.end())
{
// insert case, before Default case
StrId text;
text.Format("%d", val);
vprog::sPin pin(editMgr.GetUniqueId(), text.c_str(), ePinType::Flow);
pin.typeStr = "Flow";
pin.nodeId = m_id;
pin.kind = ePinKind::Output;
pin.value = val;
m_outputs.push_back(pin);
// find default iterator?
auto it2 = find_if(m_outputs.begin(), m_outputs.end()
, [](const auto &a) { return a.name == "Default"; });
if (m_outputs.end() != it)
{
std::swap(*it2, m_outputs.back());
}
}
}
//ImGui::Spring(0);
}
return true;
}
// render button "Add pin+"
bool cNode::RenderSequenceNode(cEditManager &editMgr
, util::BlueprintNodeBuilder &builder
, sPin* newLinkPin //= nullptr
)
{
ImGui::Spring(0);
if (ImGui::Button("Add Pin+"))
{
StrId text;
text.Format("Then %d", m_outputs.size());
vprog::sPin pin(editMgr.GetUniqueId(), text.c_str(), ePinType::Flow);
pin.typeStr = "Flow";
pin.nodeId = m_id;
pin.kind = ePinKind::Output;
pin.value = 0;
m_outputs.push_back(pin);
}
return true;
}
void cNode::Clear()
{
m_id = 0;
m_name.clear();
m_desc.clear();
m_inputs.clear();
m_outputs.clear();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: TableWindow.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: oj $ $Date: 2002-11-08 09:27:39 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_TABLEWINDOW_HXX
#define DBAUI_TABLEWINDOW_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef DBAUI_TABLEWINDOWTITLE_HXX
#include "TableWindowTitle.hxx"
#endif
#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif
#ifndef DBAUI_TABLEWINDOWDATA_HXX
#include "TableWindowData.hxx"
#endif
#include <vector>
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
class SvLBoxEntry;
namespace dbaui
{
//////////////////////////////////////////////////////////////////////////
// Flags fuer die Groessenanpassung der SbaJoinTabWins
const UINT16 SIZING_NONE = 0x0000;
const UINT16 SIZING_TOP = 0x0001;
const UINT16 SIZING_BOTTOM = 0x0002;
const UINT16 SIZING_LEFT = 0x0004;
const UINT16 SIZING_RIGHT = 0x0008;
class OTableWindowListBox;
class OJoinDesignView;
class OJoinTableView;
class IAccessibleHelper;
class OTableWindow : public Window,
public ::utl::OEventListenerAdapter
{
friend class OTableWindowTitle;
friend class OTableWindowListBox;
mutable ::osl::Mutex m_aMutex;
protected:
// und die Tabelle selber (brauche ich, da ich sie locken will, solange das Fenster lebt)
OTableWindowTitle m_aTitle;
OTableWindowListBox* m_pListBox;
IAccessibleHelper* m_pAccessible;
private:
// the columns of the table
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xTable;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xColumns;
OTableWindowData* m_pData;
::rtl::OUString m_strInitialWinName;
sal_Int32 m_nMoveCount; // how often the arrow keys was pressed
sal_Int32 m_nMoveIncrement; // how many pixel we should move
UINT16 m_nSizingFlags;
BOOL m_bActive;
void Draw3DBorder( const Rectangle& rRect );
protected:
virtual void Resize();
virtual void Paint( const Rectangle& rRect );
virtual void MouseMove( const MouseEvent& rEvt );
virtual void MouseButtonDown( const MouseEvent& rEvt );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual OTableWindowListBox* CreateListBox();
// wird im ERSTEN Init aufgerufen
BOOL FillListBox();
// wird in JEDEM Init aufgerufen
virtual void OnEntryDoubleClicked(SvLBoxEntry* pEntry) { }
// wird aus dem DoubleClickHdl der ListBox heraus aufgerufen
/** HandleKeyInput triues to handle the KeyEvent. Movement or deletion
@param rEvt
The KEyEvent
@return
<TRUE/> when the table could handle the keyevent.
*/
BOOL HandleKeyInput( const KeyEvent& rEvt );
/** delete the user data with the equal type as created within createUserData
@param _pUserData
The user data store in the listbox entries. Created with a call to createUserData.
_pUserData may be <NULL/>. _pUserData will be set to <NULL/> after call.
*/
virtual void deleteUserData(void*& _pUserData);
/** creates user information that will be append at the ListBoxentry
@param _xColumn
The corresponding column, can be <NULL/>.
@param _bPrimaryKey
<TRUE/> when the column belongs to the primary key
@return
the user data which will be append at the listbox entry, may be <NULL/>
*/
virtual void* createUserData(const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet>& _xColumn,
bool _bPrimaryKey);
OTableWindow( Window* pParent, OTableWindowData* pTabWinData);
public:
TYPEINFO();
virtual ~OTableWindow();
// spaeter Constructor, siehe auch CreateListbox und FillListbox
virtual BOOL Init();
OJoinTableView* getTableView();
const OJoinTableView* getTableView() const;
OJoinDesignView* getDesignView();
void SetPosPixel( const Point& rNewPos );
void SetSizePixel( const Size& rNewSize );
void SetPosSizePixel( const Point& rNewPos, const Size& rNewSize );
void SetTitle( const ::rtl::OUString& rTit );
String getTitle() const;
void SetBoldTitle( BOOL bBold );
void setActive(sal_Bool _bActive = sal_True);
void Remove();
BOOL IsActive(){ return m_bActive; }
::rtl::OUString GetTableName() const { return m_pData->GetTableName(); }
::rtl::OUString GetWinName() const { return m_pData->GetWinName(); }
::rtl::OUString GetComposedName() const { return m_pData->GetComposedName(); }
OTableWindowListBox* GetListBox() const { return m_pListBox; }
OTableWindowData* GetData() const { return m_pData; }
/** returns the name which should be used when displaying join or relations
@return
The composed name or the window name.
*/
virtual ::rtl::OUString GetName() const = 0;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> GetOriginalColumns() const { ::osl::MutexGuard aGuard( m_aMutex ); return m_xColumns; }
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> GetTable() const { ::osl::MutexGuard aGuard( m_aMutex ); return m_xTable; }
UINT16 GetSizingFlags() const { return m_nSizingFlags; }
/** set the sizing flag to the direction
@param _rPos
The EndPosition after resizing.
*/
void setSizingFlag(const Point& _rPos);
/** set the rsizing flag to NONE.
*/
void resetSizingFlag() { m_nSizingFlags = SIZING_NONE; }
/** returns the new sizing
*/
Rectangle getSizingRect(const Point& _rPos,const Size& _rOutputSize) const;
// window override
virtual void StateChanged( StateChangedType nStateChange );
virtual void GetFocus();
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void Command(const CommandEvent& rEvt);
// Accessibility
virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > CreateAccessible();
// Linien neu zeichnen
void InvalidateLines();
// habe ich Connections nach aussen ?
BOOL ExistsAConn() const;
virtual void EnumValidFields(::std::vector< ::rtl::OUString>& arrstrFields);
// OEventListenerAdapter
virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );
/** clears the listbox inside. Must be called be the dtor is called.
*/
void clearListBox();
};
}
#endif //DBAUI_TABLEWINDOW_HXX
<commit_msg>#105538# new method to access the fixedtext<commit_after>/*************************************************************************
*
* $RCSfile: TableWindow.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: oj $ $Date: 2002-11-26 12:47:48 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the License); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an AS IS basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef DBAUI_TABLEWINDOW_HXX
#define DBAUI_TABLEWINDOW_HXX
#ifndef _COM_SUN_STAR_CONTAINER_XNAMEACCESS_HPP_
#include <com/sun/star/container/XNameAccess.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef DBAUI_TABLEWINDOWTITLE_HXX
#include "TableWindowTitle.hxx"
#endif
#ifndef _RTTI_HXX
#include <tools/rtti.hxx>
#endif
#ifndef DBAUI_TABLEWINDOWDATA_HXX
#include "TableWindowData.hxx"
#endif
#include <vector>
#ifndef _SV_WINDOW_HXX
#include <vcl/window.hxx>
#endif
#ifndef _UNOTOOLS_EVENTLISTENERADAPTER_HXX_
#include <unotools/eventlisteneradapter.hxx>
#endif
class SvLBoxEntry;
namespace dbaui
{
//////////////////////////////////////////////////////////////////////////
// Flags fuer die Groessenanpassung der SbaJoinTabWins
const UINT16 SIZING_NONE = 0x0000;
const UINT16 SIZING_TOP = 0x0001;
const UINT16 SIZING_BOTTOM = 0x0002;
const UINT16 SIZING_LEFT = 0x0004;
const UINT16 SIZING_RIGHT = 0x0008;
class OTableWindowListBox;
class OJoinDesignView;
class OJoinTableView;
class IAccessibleHelper;
class OTableWindow : public Window,
public ::utl::OEventListenerAdapter
{
friend class OTableWindowTitle;
friend class OTableWindowListBox;
mutable ::osl::Mutex m_aMutex;
protected:
// und die Tabelle selber (brauche ich, da ich sie locken will, solange das Fenster lebt)
OTableWindowTitle m_aTitle;
OTableWindowListBox* m_pListBox;
IAccessibleHelper* m_pAccessible;
private:
// the columns of the table
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> m_xTable;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> m_xColumns;
OTableWindowData* m_pData;
::rtl::OUString m_strInitialWinName;
sal_Int32 m_nMoveCount; // how often the arrow keys was pressed
sal_Int32 m_nMoveIncrement; // how many pixel we should move
UINT16 m_nSizingFlags;
BOOL m_bActive;
void Draw3DBorder( const Rectangle& rRect );
protected:
virtual void Resize();
virtual void Paint( const Rectangle& rRect );
virtual void MouseMove( const MouseEvent& rEvt );
virtual void MouseButtonDown( const MouseEvent& rEvt );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual OTableWindowListBox* CreateListBox();
// wird im ERSTEN Init aufgerufen
BOOL FillListBox();
// wird in JEDEM Init aufgerufen
virtual void OnEntryDoubleClicked(SvLBoxEntry* pEntry) { }
// wird aus dem DoubleClickHdl der ListBox heraus aufgerufen
/** HandleKeyInput triues to handle the KeyEvent. Movement or deletion
@param rEvt
The KEyEvent
@return
<TRUE/> when the table could handle the keyevent.
*/
BOOL HandleKeyInput( const KeyEvent& rEvt );
/** delete the user data with the equal type as created within createUserData
@param _pUserData
The user data store in the listbox entries. Created with a call to createUserData.
_pUserData may be <NULL/>. _pUserData will be set to <NULL/> after call.
*/
virtual void deleteUserData(void*& _pUserData);
/** creates user information that will be append at the ListBoxentry
@param _xColumn
The corresponding column, can be <NULL/>.
@param _bPrimaryKey
<TRUE/> when the column belongs to the primary key
@return
the user data which will be append at the listbox entry, may be <NULL/>
*/
virtual void* createUserData(const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet>& _xColumn,
bool _bPrimaryKey);
OTableWindow( Window* pParent, OTableWindowData* pTabWinData);
public:
TYPEINFO();
virtual ~OTableWindow();
// spaeter Constructor, siehe auch CreateListbox und FillListbox
virtual BOOL Init();
OJoinTableView* getTableView();
const OJoinTableView* getTableView() const;
OJoinDesignView* getDesignView();
void SetPosPixel( const Point& rNewPos );
void SetSizePixel( const Size& rNewSize );
void SetPosSizePixel( const Point& rNewPos, const Size& rNewSize );
void SetTitle( const ::rtl::OUString& rTit );
String getTitle() const;
void SetBoldTitle( BOOL bBold );
void setActive(sal_Bool _bActive = sal_True);
void Remove();
BOOL IsActive(){ return m_bActive; }
::rtl::OUString GetTableName() const { return m_pData->GetTableName(); }
::rtl::OUString GetWinName() const { return m_pData->GetWinName(); }
::rtl::OUString GetComposedName() const { return m_pData->GetComposedName(); }
OTableWindowListBox* GetListBox() const { return m_pListBox; }
OTableWindowData* GetData() const { return m_pData; }
OTableWindowTitle* GetTitleCtrl() { return &m_aTitle; }
/** returns the name which should be used when displaying join or relations
@return
The composed name or the window name.
*/
virtual ::rtl::OUString GetName() const = 0;
::com::sun::star::uno::Reference< ::com::sun::star::container::XNameAccess> GetOriginalColumns() const { ::osl::MutexGuard aGuard( m_aMutex ); return m_xColumns; }
::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySet> GetTable() const { ::osl::MutexGuard aGuard( m_aMutex ); return m_xTable; }
UINT16 GetSizingFlags() const { return m_nSizingFlags; }
/** set the sizing flag to the direction
@param _rPos
The EndPosition after resizing.
*/
void setSizingFlag(const Point& _rPos);
/** set the rsizing flag to NONE.
*/
void resetSizingFlag() { m_nSizingFlags = SIZING_NONE; }
/** returns the new sizing
*/
Rectangle getSizingRect(const Point& _rPos,const Size& _rOutputSize) const;
// window override
virtual void StateChanged( StateChangedType nStateChange );
virtual void GetFocus();
virtual long PreNotify( NotifyEvent& rNEvt );
virtual void Command(const CommandEvent& rEvt);
// Accessibility
virtual ::com::sun::star::uno::Reference< ::drafts::com::sun::star::accessibility::XAccessible > CreateAccessible();
// Linien neu zeichnen
void InvalidateLines();
// habe ich Connections nach aussen ?
BOOL ExistsAConn() const;
virtual void EnumValidFields(::std::vector< ::rtl::OUString>& arrstrFields);
// OEventListenerAdapter
virtual void _disposing( const ::com::sun::star::lang::EventObject& _rSource );
/** clears the listbox inside. Must be called be the dtor is called.
*/
void clearListBox();
};
}
#endif //DBAUI_TABLEWINDOW_HXX
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2013
\file app/rdo_studio/plugins/game5/src/graph_widget.cpp
\author Чернов Алексей (ChernovAlexeyOlegovich@gmail.com)
\date 22.09.2013
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include "utils/src/common/warning_disable.h"
#include <math.h>
#include <QGridLayout>
#include <QAction>
#include <QMenu>
#include "utils/src/common/warning_enable.h"
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio/plugins/game5/src/graph_widget.h"
// --------------------------------------------------------------------------------
namespace
{
const double MAX_FACTOR = 10;
const double MIN_FACTOR = 0.1;
const double SCALE_SPEED = 1/2400.;
const double MANUAL_SCALE_FACTOR = 40 * SCALE_SPEED;
} // end anonymous namespace
GraphWidget::GraphWidget(QWidget* pParent)
: QGraphicsView(pParent)
, m_graphInfo(this)
, m_autoScale(true)
{
QGraphicsScene* pScene = new QGraphicsScene(this);
pScene->setItemIndexMethod(QGraphicsScene::NoIndex);
setScene(pScene);
QGridLayout* graphWidgetLayout = new QGridLayout(this);
graphWidgetLayout->setContentsMargins(0, 0, 0, 0);
QSpacerItem* verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum , QSizePolicy::Expanding);
QSpacerItem* horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
graphWidgetLayout->addWidget(&m_graphInfo , 0, 0, 1, 1);
graphWidgetLayout->addItem (verticalSpacer , 1, 0, 1, 1);
graphWidgetLayout->addItem (horizontalSpacer, 0, 1, 2, 1);
setCacheMode(CacheBackground);
setViewportUpdateMode(BoundingRectViewportUpdate);
setRenderHint(QPainter::Antialiasing);
setTransformationAnchor(AnchorUnderMouse);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &QWidget::customContextMenuRequested, this, &GraphWidget::callContextMenu);
zoomInAct = new QAction("Zoom In", this);
zoomInAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Plus));
zoomInAct->setStatusTip("Приблизить");
connect(zoomInAct, &QAction::triggered, this, &GraphWidget::zoomIn);
zoomOutAct = new QAction("Zoom Out", this);
zoomOutAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Minus));
zoomOutAct->setStatusTip("Отдалить");
connect(zoomOutAct, &QAction::triggered, this, &GraphWidget::zoomOut);
zoomFitAct = new QAction("Zoom Fit", this);
zoomFitAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_9));
zoomFitAct->setStatusTip("Вписать граф в окно");
connect(zoomFitAct, &QAction::triggered, this, &GraphWidget::zoomFit);
normalSizeAct = new QAction("Normal Size", this);
normalSizeAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0));
normalSizeAct->setStatusTip("Вернуть масштаб 1:1");
connect(normalSizeAct, &QAction::triggered, this, &GraphWidget::normalSize);
addAction(zoomInAct);
addAction(zoomOutAct);
addAction(zoomFitAct);
addAction(normalSizeAct);
}
GraphWidget::~GraphWidget()
{}
void GraphWidget::updateGraphInfo(const QString& solutionCost, const QString& numberOfOpenNodes, const QString& totalNumberOfNodes)
{
m_graphInfo.update(solutionCost, numberOfOpenNodes, totalNumberOfNodes);
}
void GraphWidget::zoomIn()
{
scaleView(pow(2., MANUAL_SCALE_FACTOR));
}
void GraphWidget::zoomOut()
{
scaleView(pow(2., -MANUAL_SCALE_FACTOR));
}
void GraphWidget::zoomFit()
{
m_autoScale = true;
fitInView(scene()->itemsBoundingRect(), Qt::KeepAspectRatio);
const double factor = transform().mapRect(QRectF(0, 0, 1, 1)).width();
if (factor > MAX_FACTOR)
{
scale(MAX_FACTOR / factor, MAX_FACTOR / factor);
}
if (factor < MIN_FACTOR)
{
scale(MIN_FACTOR / factor, MIN_FACTOR / factor);
}
}
void GraphWidget::normalSize()
{
m_autoScale = false;
setTransform(QTransform());
}
void GraphWidget::wheelEvent(QWheelEvent* wEvent)
{
if (wEvent->modifiers() & Qt::SHIFT)
{
scaleView(pow(2., wEvent->delta() * SCALE_SPEED));
}
else
{
QGraphicsView::wheelEvent(wEvent);
}
}
void GraphWidget::keyPressEvent(QKeyEvent* kEvent)
{
QGraphicsView::keyPressEvent(kEvent);
if (kEvent->key() == Qt::Key_Control)
{
setDragMode(ScrollHandDrag);
setInteractive(false);
m_dragModeCtrl = true;
}
}
void GraphWidget::keyReleaseEvent(QKeyEvent* kEvent)
{
QGraphicsView::keyReleaseEvent(kEvent);
if (kEvent->key() == Qt::Key_Control)
{
if (!m_dragModeClick)
{
setDragMode(NoDrag);
setInteractive(true);
}
m_dragModeCtrl = false;
}
}
void GraphWidget::mousePressEvent(QMouseEvent* mEvent)
{
if (mEvent->button() == Qt::MouseButton::LeftButton && !itemAt(mEvent->pos()))
{
setDragMode(ScrollHandDrag);
m_dragModeClick = true;
}
QGraphicsView::mousePressEvent(mEvent);
}
void GraphWidget::mouseReleaseEvent(QMouseEvent* mEvent)
{
if (mEvent->button() == Qt::MouseButton::LeftButton)
{
if (!m_dragModeCtrl)
{
setDragMode(NoDrag);
}
m_dragModeClick = false;
}
QGraphicsView::mouseReleaseEvent(mEvent);
}
void GraphWidget::scaleView(double scaleFactor)
{
m_autoScale = false;
const double factor = transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width();
if (MIN_FACTOR < factor && factor < MAX_FACTOR)
{
scale(scaleFactor, scaleFactor);
}
}
void GraphWidget::resizeEvent(QResizeEvent* event)
{
if (m_autoScale)
{
zoomFit();
}
QGraphicsView::resizeEvent(event);
}
void GraphWidget::callContextMenu(const QPoint& pos)
{
QMenu* menu = new QMenu;
menu->addAction(zoomInAct);
menu->addAction(zoomOutAct);
menu->addAction(zoomFitAct);
menu->addAction(normalSizeAct);
menu->exec(viewport()->mapToGlobal(pos));
}
<commit_msg>#18 уменьшен минимальный масштаб<commit_after>/*!
\copyright (c) RDO-Team, 2013
\file app/rdo_studio/plugins/game5/src/graph_widget.cpp
\author Чернов Алексей (ChernovAlexeyOlegovich@gmail.com)
\date 22.09.2013
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
// ----------------------------------------------------------------------- INCLUDES
#include "utils/src/common/warning_disable.h"
#include <math.h>
#include <QGridLayout>
#include <QAction>
#include <QMenu>
#include "utils/src/common/warning_enable.h"
// ----------------------------------------------------------------------- SYNOPSIS
#include "app/rdo_studio/plugins/game5/src/graph_widget.h"
// --------------------------------------------------------------------------------
namespace
{
const double MAX_FACTOR = 10;
const double MIN_FACTOR = 0.01;
const double SCALE_SPEED = 1/2400.;
const double MANUAL_SCALE_FACTOR = 40 * SCALE_SPEED;
} // end anonymous namespace
GraphWidget::GraphWidget(QWidget* pParent)
: QGraphicsView(pParent)
, m_graphInfo(this)
, m_autoScale(true)
{
QGraphicsScene* pScene = new QGraphicsScene(this);
pScene->setItemIndexMethod(QGraphicsScene::NoIndex);
setScene(pScene);
QGridLayout* graphWidgetLayout = new QGridLayout(this);
graphWidgetLayout->setContentsMargins(0, 0, 0, 0);
QSpacerItem* verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum , QSizePolicy::Expanding);
QSpacerItem* horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
graphWidgetLayout->addWidget(&m_graphInfo , 0, 0, 1, 1);
graphWidgetLayout->addItem (verticalSpacer , 1, 0, 1, 1);
graphWidgetLayout->addItem (horizontalSpacer, 0, 1, 2, 1);
setCacheMode(CacheBackground);
setViewportUpdateMode(BoundingRectViewportUpdate);
setRenderHint(QPainter::Antialiasing);
setTransformationAnchor(AnchorUnderMouse);
setContextMenuPolicy(Qt::CustomContextMenu);
connect(this, &QWidget::customContextMenuRequested, this, &GraphWidget::callContextMenu);
zoomInAct = new QAction("Zoom In", this);
zoomInAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Plus));
zoomInAct->setStatusTip("Приблизить");
connect(zoomInAct, &QAction::triggered, this, &GraphWidget::zoomIn);
zoomOutAct = new QAction("Zoom Out", this);
zoomOutAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Minus));
zoomOutAct->setStatusTip("Отдалить");
connect(zoomOutAct, &QAction::triggered, this, &GraphWidget::zoomOut);
zoomFitAct = new QAction("Zoom Fit", this);
zoomFitAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_9));
zoomFitAct->setStatusTip("Вписать граф в окно");
connect(zoomFitAct, &QAction::triggered, this, &GraphWidget::zoomFit);
normalSizeAct = new QAction("Normal Size", this);
normalSizeAct->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0));
normalSizeAct->setStatusTip("Вернуть масштаб 1:1");
connect(normalSizeAct, &QAction::triggered, this, &GraphWidget::normalSize);
addAction(zoomInAct);
addAction(zoomOutAct);
addAction(zoomFitAct);
addAction(normalSizeAct);
}
GraphWidget::~GraphWidget()
{}
void GraphWidget::updateGraphInfo(const QString& solutionCost, const QString& numberOfOpenNodes, const QString& totalNumberOfNodes)
{
m_graphInfo.update(solutionCost, numberOfOpenNodes, totalNumberOfNodes);
}
void GraphWidget::zoomIn()
{
scaleView(pow(2., MANUAL_SCALE_FACTOR));
}
void GraphWidget::zoomOut()
{
scaleView(pow(2., -MANUAL_SCALE_FACTOR));
}
void GraphWidget::zoomFit()
{
m_autoScale = true;
fitInView(scene()->itemsBoundingRect(), Qt::KeepAspectRatio);
const double factor = transform().mapRect(QRectF(0, 0, 1, 1)).width();
if (factor > MAX_FACTOR)
{
scale(MAX_FACTOR / factor, MAX_FACTOR / factor);
}
if (factor < MIN_FACTOR)
{
scale(MIN_FACTOR / factor, MIN_FACTOR / factor);
}
}
void GraphWidget::normalSize()
{
m_autoScale = false;
setTransform(QTransform());
}
void GraphWidget::wheelEvent(QWheelEvent* wEvent)
{
if (wEvent->modifiers() & Qt::SHIFT)
{
scaleView(pow(2., wEvent->delta() * SCALE_SPEED));
}
else
{
QGraphicsView::wheelEvent(wEvent);
}
}
void GraphWidget::keyPressEvent(QKeyEvent* kEvent)
{
QGraphicsView::keyPressEvent(kEvent);
if (kEvent->key() == Qt::Key_Control)
{
setDragMode(ScrollHandDrag);
setInteractive(false);
m_dragModeCtrl = true;
}
}
void GraphWidget::keyReleaseEvent(QKeyEvent* kEvent)
{
QGraphicsView::keyReleaseEvent(kEvent);
if (kEvent->key() == Qt::Key_Control)
{
if (!m_dragModeClick)
{
setDragMode(NoDrag);
setInteractive(true);
}
m_dragModeCtrl = false;
}
}
void GraphWidget::mousePressEvent(QMouseEvent* mEvent)
{
if (mEvent->button() == Qt::MouseButton::LeftButton && !itemAt(mEvent->pos()))
{
setDragMode(ScrollHandDrag);
m_dragModeClick = true;
}
QGraphicsView::mousePressEvent(mEvent);
}
void GraphWidget::mouseReleaseEvent(QMouseEvent* mEvent)
{
if (mEvent->button() == Qt::MouseButton::LeftButton)
{
if (!m_dragModeCtrl)
{
setDragMode(NoDrag);
}
m_dragModeClick = false;
}
QGraphicsView::mouseReleaseEvent(mEvent);
}
void GraphWidget::scaleView(double scaleFactor)
{
m_autoScale = false;
const double factor = transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width();
if (MIN_FACTOR < factor && factor < MAX_FACTOR)
{
scale(scaleFactor, scaleFactor);
}
}
void GraphWidget::resizeEvent(QResizeEvent* event)
{
if (m_autoScale)
{
zoomFit();
}
QGraphicsView::resizeEvent(event);
}
void GraphWidget::callContextMenu(const QPoint& pos)
{
QMenu* menu = new QMenu;
menu->addAction(zoomInAct);
menu->addAction(zoomOutAct);
menu->addAction(zoomFitAct);
menu->addAction(normalSizeAct);
menu->exec(viewport()->mapToGlobal(pos));
}
<|endoftext|> |
<commit_before>
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif
// Software Guide : BeginCommandLineArgs
// INPUTS: {QB_Suburb.png}, {RandomImage.png}
// OUTPUTS: {MarkovClassification1.png}
// 1.0 30 1.0
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the details of the \doxygen{otb}{MarkovClassificationFilter}.
// This filter is an application of the Markov Random Fields for classification,
// segmentation or restauration.
//
// This example applies the \doxygen{otb}{MarkovClassificationFilter} to
// classify an image into four classes defined by their mean and variance. The
// optimization is done using an Metropolis algorithm with a random sampler. The
// regularization energy is defined by a Potts model and the fidelity by a
// Gaussian model.
//
// Software Guide : EndLatex
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbImage.h"
#include "otbMarkovRandomFieldFilter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginLatex
//
// The first step towards the use of this filter is the inclusion of the proper
// header files.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbMRFEnergy.h"
#include "otbMRFEnergyPotts.h"
#include "otbMRFEnergyGaussianClassification.h"
#include "otbMRFOptimizerMetropolis.h"
#include "otbMRFSamplerRandom.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[] )
{
if( argc < 6 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " inputImage inputInitialization output lambda iterations temperature" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// Then we must decide what pixel type to use for the image. We
// choose to make all computations with double precision.
// The labeled image is of type unsigned char to allow up to 256 different
// classes.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef double InternalPixelType;
typedef unsigned char LabelledPixelType;
typedef otb::Image<InternalPixelType, Dimension> InputImageType;
typedef otb::Image<LabelledPixelType, Dimension> LabelledImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We define a reader for the image to be classified, an initialisation for the
// classification (which could be random) and a writer for the final
// classification.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader< InputImageType > ReaderType;
typedef otb::ImageFileReader< LabelledImageType > ReaderLabelledType;
typedef otb::ImageFileWriter< LabelledImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
ReaderLabelledType::Pointer reader2 = ReaderLabelledType::New();
WriterType::Pointer writer = WriterType::New();
const char * inputFilename = argv[1];
const char * labelledFilename = argv[2];
const char * outputFilename = argv[3];
reader->SetFileName( inputFilename );
reader2->SetFileName( labelledFilename );
writer->SetFileName( outputFilename );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we define the different classes necessary for the Markov classification.
// A \doxygen{otb}{MarkovClassificationFilter} is instanciated, this is the
// main class which connects the others to do the Markov classification.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MarkovRandomFieldFilter
<InputImageType,LabelledImageType> MarkovRandomFieldFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An \doxygen{otb}{MRFSamplerRandomMAP}, which derives from the
// \doxygen{otb}{MRFSampler}, is instanciated. The sampler is in charge of
// proposing a modification for a given site. The
// \doxygen{otb}{MRFSamplerRandomMAP}, randomly picks one possible value
// according to the MAP probability.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFSamplerRandom< InputImageType, LabelledImageType> SamplerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An \doxygen{otb}{MRFOptimizerMetropoli}, which derives from the
// \doxygen{otb}{MRFOptimizer}, is instanciated. The optimizer is in charge
// of accepting or rejecting the value proposed by the sampler. The
// \doxygen{otb}{MRFSamplerRandomMAP}, accept the proposal according to the
// variation of energy it causes and a temperature parameter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFOptimizerMetropolis OptimizerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Two energies, deriving from the \doxygen{otb}{MRFEnergy} class needs to be instanciated. One energy
// is required for the regularization, taking into account the relationship between neighborhing pixels
// in the classified image. Here, this is done with the \doxygen{otb}{MRFEnergyPotts} which implements
// a Potts model.
//
// The second energy is for the fidelity to the original data. Here it is done with an
// \doxygen{otb}{MRFEnergyGaussianClassification} class, which defines a gaussian model for the data.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFEnergyPotts
<LabelledImageType, LabelledImageType> EnergyRegularizationType;
typedef otb::MRFEnergyGaussianClassification
<InputImageType, LabelledImageType> EnergyFidelityType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The different filters composing our pipeline are created by invoking their
// \code{New()} methods, assigning the results to smart pointers.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MarkovRandomFieldFilterType::Pointer markovFilter = MarkovRandomFieldFilterType::New();
EnergyRegularizationType::Pointer energyRegularization = EnergyRegularizationType::New();
EnergyFidelityType::Pointer energyFidelity = EnergyFidelityType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
SamplerType::Pointer sampler = SamplerType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Variables for the \doxygen{otb}{MRFEnergyGaussianClassification} class, meand
// and standard deviation are created.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
unsigned int nClass = 4;
itk::VariableLengthVector<double> mean;
itk::VariableLengthVector<double> stdDev;
mean.SetSize(nClass);
stdDev.SetSize(nClass);
mean[0]=10;mean[1]=80;mean[2]=150;mean[3]=220;
stdDev[0]=10;stdDev[1]=10;stdDev[2]=10;stdDev[3]=10;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// These parameters are passed to the different classs and the sampler, optimizer and
// energies are connected with the Markov filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
energyFidelity->SetNumberOfParameters(2*nClass);
EnergyFidelityType::ParametersType parameters;
parameters.SetSize(energyFidelity->GetNumberOfParameters());
parameters[0]=10.0; //Class 0 mean
parameters[1]=10.0; //Class 0 stdev
parameters[2]=80.0;//Class 1 mean
parameters[3]=10.0; //Class 1 stdev
parameters[4]=150.0; //Class 2 mean
parameters[5]=10.0; //Class 2 stdev
parameters[6]=220.0;//Class 3 mean
parameters[7]=10.0; //Class 3 stde
energyFidelity->SetParameters(parameters);
OptimizerType::ParametersType paramOpt(1);
paramOpt.Fill(atof(argv[6]));
optimizer->SetParameters(paramOpt);
markovFilter->SetValueInsteadRandom(500); // Unable rand() calculation
markovFilter->SetNumberOfClasses(nClass);
markovFilter->SetMaximumNumberOfIterations(atoi(argv[5]));
markovFilter->SetErrorTolerance(-1.0);
markovFilter->SetLambda(atof(argv[4]));
markovFilter->SetNeighborhoodRadius(1);
markovFilter->SetEnergyRegularization(energyRegularization);
markovFilter->SetEnergyFidelity(energyFidelity);
markovFilter->SetOptimizer(optimizer);
markovFilter->SetSampler(sampler);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The pipeline is connected. An \doxygen{itk}{RescaleIntensityImageFilter}
// rescales the classified image before saving it.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
markovFilter->SetTrainingInput(reader2->GetOutput());
markovFilter->SetInput(reader->GetOutput());
typedef itk::RescaleIntensityImageFilter
< LabelledImageType, LabelledImageType > RescaleType;
RescaleType::Pointer rescaleFilter = RescaleType::New();
rescaleFilter->SetOutputMinimum(0);
rescaleFilter->SetOutputMaximum(255);
rescaleFilter->SetInput( markovFilter->GetOutput() );
writer->SetInput( rescaleFilter->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, the pipeline execution is triggered.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Figure \ref{fig:MARKOVCLASS1} shows the result of the SVM classification.
// \begin{figure}
// \center
// \includegraphics[width=0.45\textwidth]{QB_Suburb.eps}
// \includegraphics[width=0.45\textwidth]{MarkovClassification1.eps}
// \itkcaption[Markov Random Field Image Classification]{Result of the MRF
// classification using a Metropolis algorithm with a random sampler
// and a Potts regularization energy and a Gaussian fidelity. Left: Original image. Right: image of classes.}
// \label{fig:MARKOVCLASS1}
// \end{figure}
// Software Guide : EndLatex
return 0;
}
<commit_msg>SVM->MRF<commit_after>
/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt 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.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#ifdef __BORLANDC__
#define ITK_LEAN_AND_MEAN
#endif
// Software Guide : BeginCommandLineArgs
// INPUTS: {QB_Suburb.png}, {RandomImage.png}
// OUTPUTS: {MarkovClassification1.png}
// 1.0 30 1.0
// Software Guide : EndCommandLineArgs
// Software Guide : BeginLatex
//
// This example illustrates the details of the \doxygen{otb}{MarkovClassificationFilter}.
// This filter is an application of the Markov Random Fields for classification,
// segmentation or restauration.
//
// This example applies the \doxygen{otb}{MarkovClassificationFilter} to
// classify an image into four classes defined by their mean and variance. The
// optimization is done using an Metropolis algorithm with a random sampler. The
// regularization energy is defined by a Potts model and the fidelity by a
// Gaussian model.
//
// Software Guide : EndLatex
#include "otbImageFileReader.h"
#include "otbImageFileWriter.h"
#include "otbImage.h"
#include "otbMarkovRandomFieldFilter.h"
#include "itkRescaleIntensityImageFilter.h"
// Software Guide : BeginLatex
//
// The first step towards the use of this filter is the inclusion of the proper
// header files.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
#include "otbMRFEnergy.h"
#include "otbMRFEnergyPotts.h"
#include "otbMRFEnergyGaussianClassification.h"
#include "otbMRFOptimizerMetropolis.h"
#include "otbMRFSamplerRandom.h"
// Software Guide : EndCodeSnippet
int main(int argc, char* argv[] )
{
if( argc < 6 )
{
std::cerr << "Missing Parameters " << std::endl;
std::cerr << "Usage: " << argv[0];
std::cerr << " inputImage inputInitialization output lambda iterations temperature" << std::endl;
return 1;
}
// Software Guide : BeginLatex
//
// Then we must decide what pixel type to use for the image. We
// choose to make all computations with double precision.
// The labeled image is of type unsigned char to allow up to 256 different
// classes.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
const unsigned int Dimension = 2;
typedef double InternalPixelType;
typedef unsigned char LabelledPixelType;
typedef otb::Image<InternalPixelType, Dimension> InputImageType;
typedef otb::Image<LabelledPixelType, Dimension> LabelledImageType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// We define a reader for the image to be classified, an initialisation for the
// classification (which could be random) and a writer for the final
// classification.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::ImageFileReader< InputImageType > ReaderType;
typedef otb::ImageFileReader< LabelledImageType > ReaderLabelledType;
typedef otb::ImageFileWriter< LabelledImageType > WriterType;
ReaderType::Pointer reader = ReaderType::New();
ReaderLabelledType::Pointer reader2 = ReaderLabelledType::New();
WriterType::Pointer writer = WriterType::New();
const char * inputFilename = argv[1];
const char * labelledFilename = argv[2];
const char * outputFilename = argv[3];
reader->SetFileName( inputFilename );
reader2->SetFileName( labelledFilename );
writer->SetFileName( outputFilename );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, we define the different classes necessary for the Markov classification.
// A \doxygen{otb}{MarkovClassificationFilter} is instanciated, this is the
// main class which connects the others to do the Markov classification.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MarkovRandomFieldFilter
<InputImageType,LabelledImageType> MarkovRandomFieldFilterType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An \doxygen{otb}{MRFSamplerRandomMAP}, which derives from the
// \doxygen{otb}{MRFSampler}, is instanciated. The sampler is in charge of
// proposing a modification for a given site. The
// \doxygen{otb}{MRFSamplerRandomMAP}, randomly picks one possible value
// according to the MAP probability.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFSamplerRandom< InputImageType, LabelledImageType> SamplerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// An \doxygen{otb}{MRFOptimizerMetropoli}, which derives from the
// \doxygen{otb}{MRFOptimizer}, is instanciated. The optimizer is in charge
// of accepting or rejecting the value proposed by the sampler. The
// \doxygen{otb}{MRFSamplerRandomMAP}, accept the proposal according to the
// variation of energy it causes and a temperature parameter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFOptimizerMetropolis OptimizerType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Two energies, deriving from the \doxygen{otb}{MRFEnergy} class needs to be instanciated. One energy
// is required for the regularization, taking into account the relationship between neighborhing pixels
// in the classified image. Here, this is done with the \doxygen{otb}{MRFEnergyPotts} which implements
// a Potts model.
//
// The second energy is for the fidelity to the original data. Here it is done with an
// \doxygen{otb}{MRFEnergyGaussianClassification} class, which defines a gaussian model for the data.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
typedef otb::MRFEnergyPotts
<LabelledImageType, LabelledImageType> EnergyRegularizationType;
typedef otb::MRFEnergyGaussianClassification
<InputImageType, LabelledImageType> EnergyFidelityType;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The different filters composing our pipeline are created by invoking their
// \code{New()} methods, assigning the results to smart pointers.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
MarkovRandomFieldFilterType::Pointer markovFilter = MarkovRandomFieldFilterType::New();
EnergyRegularizationType::Pointer energyRegularization = EnergyRegularizationType::New();
EnergyFidelityType::Pointer energyFidelity = EnergyFidelityType::New();
OptimizerType::Pointer optimizer = OptimizerType::New();
SamplerType::Pointer sampler = SamplerType::New();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Variables for the \doxygen{otb}{MRFEnergyGaussianClassification} class, meand
// and standard deviation are created.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
unsigned int nClass = 4;
itk::VariableLengthVector<double> mean;
itk::VariableLengthVector<double> stdDev;
mean.SetSize(nClass);
stdDev.SetSize(nClass);
mean[0]=10;mean[1]=80;mean[2]=150;mean[3]=220;
stdDev[0]=10;stdDev[1]=10;stdDev[2]=10;stdDev[3]=10;
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// These parameters are passed to the different classs and the sampler, optimizer and
// energies are connected with the Markov filter.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
energyFidelity->SetNumberOfParameters(2*nClass);
EnergyFidelityType::ParametersType parameters;
parameters.SetSize(energyFidelity->GetNumberOfParameters());
parameters[0]=10.0; //Class 0 mean
parameters[1]=10.0; //Class 0 stdev
parameters[2]=80.0;//Class 1 mean
parameters[3]=10.0; //Class 1 stdev
parameters[4]=150.0; //Class 2 mean
parameters[5]=10.0; //Class 2 stdev
parameters[6]=220.0;//Class 3 mean
parameters[7]=10.0; //Class 3 stde
energyFidelity->SetParameters(parameters);
OptimizerType::ParametersType paramOpt(1);
paramOpt.Fill(atof(argv[6]));
optimizer->SetParameters(paramOpt);
markovFilter->SetValueInsteadRandom(500); // Unable rand() calculation
markovFilter->SetNumberOfClasses(nClass);
markovFilter->SetMaximumNumberOfIterations(atoi(argv[5]));
markovFilter->SetErrorTolerance(-1.0);
markovFilter->SetLambda(atof(argv[4]));
markovFilter->SetNeighborhoodRadius(1);
markovFilter->SetEnergyRegularization(energyRegularization);
markovFilter->SetEnergyFidelity(energyFidelity);
markovFilter->SetOptimizer(optimizer);
markovFilter->SetSampler(sampler);
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// The pipeline is connected. An \doxygen{itk}{RescaleIntensityImageFilter}
// rescales the classified image before saving it.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
markovFilter->SetTrainingInput(reader2->GetOutput());
markovFilter->SetInput(reader->GetOutput());
typedef itk::RescaleIntensityImageFilter
< LabelledImageType, LabelledImageType > RescaleType;
RescaleType::Pointer rescaleFilter = RescaleType::New();
rescaleFilter->SetOutputMinimum(0);
rescaleFilter->SetOutputMaximum(255);
rescaleFilter->SetInput( markovFilter->GetOutput() );
writer->SetInput( rescaleFilter->GetOutput() );
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
//
// Finally, the pipeline execution is triggered.
//
// Software Guide : EndLatex
// Software Guide : BeginCodeSnippet
writer->Update();
// Software Guide : EndCodeSnippet
// Software Guide : BeginLatex
// Figure \ref{fig:MARKOVCLASS1} shows the result of the MRF classification.
// \begin{figure}
// \center
// \includegraphics[width=0.45\textwidth]{QB_Suburb.eps}
// \includegraphics[width=0.45\textwidth]{MarkovClassification1.eps}
// \itkcaption[Markov Random Field Image Classification]{Result of the MRF
// classification using a Metropolis algorithm with a random sampler
// and a Potts regularization energy and a Gaussian fidelity. Left: Original image. Right: image of classes.}
// \label{fig:MARKOVCLASS1}
// \end{figure}
// Software Guide : EndLatex
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "texture_manager.hpp"
#include "device.hpp"
#include "stb_image.h"
#include "memory_mapped_texture.hpp"
#include "texture_files.hpp"
#include "texture_decoder.hpp"
#ifdef GRANITE_VULKAN_MT
#include "thread_group.hpp"
#include "thread_id.hpp"
#endif
using namespace std;
namespace Vulkan
{
bool Texture::init_texture()
{
if (!path.empty())
return init();
else
return true;
}
Texture::Texture(Device *device_, const std::string &path_, VkFormat format_, const VkComponentMapping &swizzle_)
: VolatileSource(path_), device(device_), format(format_), swizzle(swizzle_)
{
}
Texture::Texture(Device *device_)
: device(device_), format(VK_FORMAT_UNDEFINED)
{
}
void Texture::set_path(const std::string &path_)
{
path = path_;
}
void Texture::update(std::unique_ptr<Granite::File> file)
{
auto *f = file.release();
auto work = [f, this]() {
#if defined(GRANITE_VULKAN_MT) && defined(VULKAN_DEBUG)
LOGI("Loading texture in thread index: %u\n", get_current_thread_index());
#endif
unique_ptr<Granite::File> updated_file{f};
auto size = updated_file->get_size();
void *mapped = updated_file->map();
if (size && mapped)
{
if (Granite::SceneFormats::MemoryMappedTexture::is_header(mapped, size))
update_gtx(move(updated_file), mapped);
else
update_other(mapped, size);
device->get_texture_manager().notify_updated_texture(path, *this);
}
else
{
LOGE("Failed to map texture file ...\n");
update_checkerboard();
}
};
#ifdef GRANITE_VULKAN_MT
auto &workers = *Granite::Global::thread_group();
// Workaround, cannot copy the lambda because of owning a unique_ptr.
auto task = workers.create_task(move(work));
task->flush();
#else
work();
#endif
}
void Texture::update_checkerboard()
{
LOGE("Failed to load texture: %s, falling back to a checkerboard.\n",
path.c_str());
ImageInitialData initial = {};
static const uint32_t checkerboard[] = {
0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u,
0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u,
0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu,
0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu,
};
initial.data = checkerboard;
auto info = ImageCreateInfo::immutable_2d_image(4, 4, VK_FORMAT_R8G8B8A8_UNORM, false);
info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT |
IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT;
auto image = device->create_image(info, &initial);
if (image)
device->set_name(*image, path.c_str());
replace_image(image);
}
void Texture::update_gtx(const Granite::SceneFormats::MemoryMappedTexture &mapped_file)
{
if (mapped_file.empty())
{
update_checkerboard();
return;
}
auto &layout = mapped_file.get_layout();
Vulkan::ImageHandle image;
if (!device->image_format_is_supported(layout.get_format(), VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) &&
format_compression_type(layout.get_format()) != FormatCompressionType::Uncompressed)
{
LOGI("Compressed format #%u is not supported, falling back to compute decode of compressed image.\n",
unsigned(layout.get_format()));
auto cmd = device->request_command_buffer(CommandBuffer::Type::AsyncCompute);
image = Granite::decode_compressed_image(*cmd, layout, swizzle);
Semaphore sem;
device->submit(cmd, nullptr, 1, &sem);
device->add_wait_semaphore(CommandBuffer::Type::Generic, sem, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, true);
}
else
{
ImageCreateInfo info = ImageCreateInfo::immutable_image(layout);
info.swizzle = swizzle;
info.flags = (mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_CUBE_MAP_COMPATIBLE_BIT) ?
VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT :
0;
info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT |
IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT;
mapped_file.remap_swizzle(info.swizzle);
if (info.levels == 1 &&
(mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_GENERATE_MIPMAP_ON_LOAD_BIT) != 0 &&
device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_SRC_BIT) &&
device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_DST_BIT))
{
info.levels = 0;
info.misc |= IMAGE_MISC_GENERATE_MIPS_BIT;
}
if (!device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
{
LOGE("Format (%u) is not supported!\n", unsigned(info.format));
return;
}
auto staging = device->create_image_staging_buffer(layout);
image = device->create_image_from_staging_buffer(info, &staging);
}
if (image)
device->set_name(*image, path.c_str());
replace_image(image);
}
void Texture::update_gtx(unique_ptr<Granite::File> file, void *mapped)
{
Granite::SceneFormats::MemoryMappedTexture mapped_file;
if (!mapped_file.map_read(move(file), mapped))
{
LOGE("Failed to read texture.\n");
return;
}
update_gtx(mapped_file);
}
void Texture::update_other(const void *data, size_t size)
{
auto tex = Granite::load_texture_from_memory(data, size,
(format == VK_FORMAT_R8G8B8A8_SRGB ||
format == VK_FORMAT_UNDEFINED ||
format == VK_FORMAT_B8G8R8A8_SRGB ||
format == VK_FORMAT_A8B8G8R8_SRGB_PACK32) ?
Granite::ColorSpace::sRGB : Granite::ColorSpace::Linear);
update_gtx(tex);
}
void Texture::load()
{
if (!handle.get_nowait())
init();
}
void Texture::unload()
{
deinit();
handle.reset();
}
void Texture::replace_image(ImageHandle handle_)
{
auto old = this->handle.write_object(move(handle_));
if (old)
device->keep_handle_alive(move(old));
if (enable_notification)
device->get_texture_manager().notify_updated_texture(path, *this);
}
Image *Texture::get_image()
{
auto ret = handle.get();
VK_ASSERT(ret);
return ret;
}
void Texture::set_enable_notification(bool enable)
{
enable_notification = enable;
}
TextureManager::TextureManager(Device *device_)
: device(device_)
{
}
Texture *TextureManager::request_texture(const std::string &path, VkFormat format, const VkComponentMapping &mapping)
{
Util::Hasher hasher;
hasher.string(path);
auto deferred_hash = hasher.get();
hasher.u32(format);
hasher.u32(mapping.r);
hasher.u32(mapping.g);
hasher.u32(mapping.b);
hasher.u32(mapping.a);
auto hash = hasher.get();
auto *ret = deferred_textures.find(deferred_hash);
if (ret)
return ret;
ret = textures.find(hash);
if (ret)
return ret;
ret = textures.emplace_yield(hash, device, path, format, mapping);
if (!ret->init_texture())
ret->update_checkerboard();
return ret;
}
void TextureManager::register_texture_update_notification(const std::string &modified_path,
std::function<void(Texture &)> func)
{
Util::Hasher hasher;
hasher.string(modified_path);
auto hash = hasher.get();
auto *ret = deferred_textures.find(hash);
if (ret)
func(*ret);
notifications[modified_path].push_back(move(func));
}
void TextureManager::notify_updated_texture(const std::string &path, Vulkan::Texture &texture)
{
auto itr = notifications.find(path);
if (itr != end(notifications))
for (auto &f : itr->second)
if (f)
f(texture);
}
Texture *TextureManager::register_deferred_texture(const std::string &path)
{
Util::Hasher hasher;
hasher.string(path);
auto hash = hasher.get();
auto *ret = deferred_textures.find(hash);
if (!ret)
{
auto *texture = deferred_textures.allocate(device);
texture->set_path(path);
texture->set_enable_notification(false);
ret = deferred_textures.insert_yield(hash, texture);
}
return ret;
}
}
<commit_msg>Remap the GTX input swizzle properly on load.<commit_after>/* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "texture_manager.hpp"
#include "device.hpp"
#include "stb_image.h"
#include "memory_mapped_texture.hpp"
#include "texture_files.hpp"
#include "texture_decoder.hpp"
#ifdef GRANITE_VULKAN_MT
#include "thread_group.hpp"
#include "thread_id.hpp"
#endif
using namespace std;
namespace Vulkan
{
bool Texture::init_texture()
{
if (!path.empty())
return init();
else
return true;
}
Texture::Texture(Device *device_, const std::string &path_, VkFormat format_, const VkComponentMapping &swizzle_)
: VolatileSource(path_), device(device_), format(format_), swizzle(swizzle_)
{
}
Texture::Texture(Device *device_)
: device(device_), format(VK_FORMAT_UNDEFINED)
{
}
void Texture::set_path(const std::string &path_)
{
path = path_;
}
void Texture::update(std::unique_ptr<Granite::File> file)
{
auto *f = file.release();
auto work = [f, this]() {
#if defined(GRANITE_VULKAN_MT) && defined(VULKAN_DEBUG)
LOGI("Loading texture in thread index: %u\n", get_current_thread_index());
#endif
unique_ptr<Granite::File> updated_file{f};
auto size = updated_file->get_size();
void *mapped = updated_file->map();
if (size && mapped)
{
if (Granite::SceneFormats::MemoryMappedTexture::is_header(mapped, size))
update_gtx(move(updated_file), mapped);
else
update_other(mapped, size);
device->get_texture_manager().notify_updated_texture(path, *this);
}
else
{
LOGE("Failed to map texture file ...\n");
update_checkerboard();
}
};
#ifdef GRANITE_VULKAN_MT
auto &workers = *Granite::Global::thread_group();
// Workaround, cannot copy the lambda because of owning a unique_ptr.
auto task = workers.create_task(move(work));
task->flush();
#else
work();
#endif
}
void Texture::update_checkerboard()
{
LOGE("Failed to load texture: %s, falling back to a checkerboard.\n",
path.c_str());
ImageInitialData initial = {};
static const uint32_t checkerboard[] = {
0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u,
0xffffffffu, 0xffffffffu, 0xff000000u, 0xff000000u,
0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu,
0xff000000u, 0xff000000u, 0xffffffffu, 0xffffffffu,
};
initial.data = checkerboard;
auto info = ImageCreateInfo::immutable_2d_image(4, 4, VK_FORMAT_R8G8B8A8_UNORM, false);
info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT |
IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT;
auto image = device->create_image(info, &initial);
if (image)
device->set_name(*image, path.c_str());
replace_image(image);
}
void Texture::update_gtx(const Granite::SceneFormats::MemoryMappedTexture &mapped_file)
{
if (mapped_file.empty())
{
update_checkerboard();
return;
}
auto &layout = mapped_file.get_layout();
mapped_file.remap_swizzle(swizzle);
Vulkan::ImageHandle image;
if (!device->image_format_is_supported(layout.get_format(), VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) &&
format_compression_type(layout.get_format()) != FormatCompressionType::Uncompressed)
{
LOGI("Compressed format #%u is not supported, falling back to compute decode of compressed image.\n",
unsigned(layout.get_format()));
auto cmd = device->request_command_buffer(CommandBuffer::Type::AsyncCompute);
image = Granite::decode_compressed_image(*cmd, layout, swizzle);
Semaphore sem;
device->submit(cmd, nullptr, 1, &sem);
device->add_wait_semaphore(CommandBuffer::Type::Generic, sem, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, true);
}
else
{
ImageCreateInfo info = ImageCreateInfo::immutable_image(layout);
info.swizzle = swizzle;
info.flags = (mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_CUBE_MAP_COMPATIBLE_BIT) ?
VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT :
0;
info.misc = IMAGE_MISC_CONCURRENT_QUEUE_GRAPHICS_BIT | IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_GRAPHICS_BIT |
IMAGE_MISC_CONCURRENT_QUEUE_ASYNC_COMPUTE_BIT;
mapped_file.remap_swizzle(info.swizzle);
if (info.levels == 1 &&
(mapped_file.get_flags() & Granite::SceneFormats::MEMORY_MAPPED_TEXTURE_GENERATE_MIPMAP_ON_LOAD_BIT) != 0 &&
device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_SRC_BIT) &&
device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_BLIT_DST_BIT))
{
info.levels = 0;
info.misc |= IMAGE_MISC_GENERATE_MIPS_BIT;
}
if (!device->image_format_is_supported(info.format, VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
{
LOGE("Format (%u) is not supported!\n", unsigned(info.format));
return;
}
auto staging = device->create_image_staging_buffer(layout);
image = device->create_image_from_staging_buffer(info, &staging);
}
if (image)
device->set_name(*image, path.c_str());
replace_image(image);
}
void Texture::update_gtx(unique_ptr<Granite::File> file, void *mapped)
{
Granite::SceneFormats::MemoryMappedTexture mapped_file;
if (!mapped_file.map_read(move(file), mapped))
{
LOGE("Failed to read texture.\n");
return;
}
update_gtx(mapped_file);
}
void Texture::update_other(const void *data, size_t size)
{
auto tex = Granite::load_texture_from_memory(data, size,
(format == VK_FORMAT_R8G8B8A8_SRGB ||
format == VK_FORMAT_UNDEFINED ||
format == VK_FORMAT_B8G8R8A8_SRGB ||
format == VK_FORMAT_A8B8G8R8_SRGB_PACK32) ?
Granite::ColorSpace::sRGB : Granite::ColorSpace::Linear);
update_gtx(tex);
}
void Texture::load()
{
if (!handle.get_nowait())
init();
}
void Texture::unload()
{
deinit();
handle.reset();
}
void Texture::replace_image(ImageHandle handle_)
{
auto old = this->handle.write_object(move(handle_));
if (old)
device->keep_handle_alive(move(old));
if (enable_notification)
device->get_texture_manager().notify_updated_texture(path, *this);
}
Image *Texture::get_image()
{
auto ret = handle.get();
VK_ASSERT(ret);
return ret;
}
void Texture::set_enable_notification(bool enable)
{
enable_notification = enable;
}
TextureManager::TextureManager(Device *device_)
: device(device_)
{
}
Texture *TextureManager::request_texture(const std::string &path, VkFormat format, const VkComponentMapping &mapping)
{
Util::Hasher hasher;
hasher.string(path);
auto deferred_hash = hasher.get();
hasher.u32(format);
hasher.u32(mapping.r);
hasher.u32(mapping.g);
hasher.u32(mapping.b);
hasher.u32(mapping.a);
auto hash = hasher.get();
auto *ret = deferred_textures.find(deferred_hash);
if (ret)
return ret;
ret = textures.find(hash);
if (ret)
return ret;
ret = textures.emplace_yield(hash, device, path, format, mapping);
if (!ret->init_texture())
ret->update_checkerboard();
return ret;
}
void TextureManager::register_texture_update_notification(const std::string &modified_path,
std::function<void(Texture &)> func)
{
Util::Hasher hasher;
hasher.string(modified_path);
auto hash = hasher.get();
auto *ret = deferred_textures.find(hash);
if (ret)
func(*ret);
notifications[modified_path].push_back(move(func));
}
void TextureManager::notify_updated_texture(const std::string &path, Vulkan::Texture &texture)
{
auto itr = notifications.find(path);
if (itr != end(notifications))
for (auto &f : itr->second)
if (f)
f(texture);
}
Texture *TextureManager::register_deferred_texture(const std::string &path)
{
Util::Hasher hasher;
hasher.string(path);
auto hash = hasher.get();
auto *ret = deferred_textures.find(hash);
if (!ret)
{
auto *texture = deferred_textures.allocate(device);
texture->set_path(path);
texture->set_enable_notification(false);
ret = deferred_textures.insert_yield(hash, texture);
}
return ret;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: FastMarchingLevelSet.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.
=========================================================================*/
#include <FastMarchingLevelSet.h>
#include <FL/fl_file_chooser.H>
/************************************
*
* Constructor
*
***********************************/
FastMarchingLevelSet
::FastMarchingLevelSet()
{
// This image is only used for providing visual
// feedback to the user. The actual structure
// holding the seeds is in the base class.
m_SeedImage = SeedImageType::New();
m_InputImageViewer.SetLabel("Input Image");
m_ThresholdedImageViewer.SetLabel("Thresholded Image");
m_GradientMagnitudeImageViewer.SetLabel("Gradient Magnitude Image");
m_EdgePotentialImageViewer.SetLabel("Edge Potential Image");
m_InputImageViewer.ClickSelectCallBack( ClickSelectCallback, (void *)this);
// Initialize ITK filter with GUI values
m_ThresholdFilter->SetLowerThreshold(
static_cast<InternalPixelType>( lowerThresholdValueInput->value() ) );
m_ThresholdFilter->SetUpperThreshold(
static_cast<InputPixelType>( upperThresholdValueInput->value() ) );
m_VTKSegmentedImageViewer = VTKImageViewerType::New();
m_VTKSegmentedImageViewer->SetImage( m_ThresholdFilter->GetOutput() );
m_TimeCrossingMapViewer.SetLabel("Time Crossing Map");
// Connect Observers in the GUI
inputImageButton->Observe( m_ImageReader.GetPointer() );
thresholdedImageButton->Observe( m_ThresholdFilter.GetPointer() );
timeCrossingButton->Observe( m_FastMarchingFilter.GetPointer() );
gradientMagnitudeButton->Observe( m_DerivativeFilter.GetPointer() );
edgePotentialButton->Observe( m_ExpNegativeFilter.GetPointer() );
progressSlider->Observe( m_CastImageFilter.GetPointer() );
progressSlider->Observe( m_DerivativeFilter.GetPointer() );
progressSlider->Observe( m_ThresholdFilter.GetPointer() );
progressSlider->Observe( m_ExpNegativeFilter.GetPointer() );
progressSlider->Observe( m_ImageReader.GetPointer() );
progressSlider->Observe( m_FastMarchingFilter.GetPointer() );
typedef itk::SimpleMemberCommand< FastMarchingLevelSet > SimpleCommandType;
SimpleCommandType::Pointer iterationCommand = SimpleCommandType::New();
iterationCommand->SetCallbackFunction( this,
& FastMarchingLevelSet::UpdateGUIAfterIteration );
m_FastMarchingFilter->AddObserver( itk::IterationEvent(), iterationCommand );
m_ThresholdFilter->SetLowerThreshold( lowerThresholdValueInput->value() );
m_ThresholdFilter->SetUpperThreshold( upperThresholdValueInput->value() );
}
/************************************
*
* Destructor
*
***********************************/
FastMarchingLevelSet
::~FastMarchingLevelSet()
{
}
/************************************
*
* Show main console
*
***********************************/
void
FastMarchingLevelSet
::ShowConsole(void)
{
consoleWindow->show();
}
/********************************************
*
* Quit : requires to hide all fltk windows
*
*******************************************/
void
FastMarchingLevelSet
::Quit(void)
{
m_InputImageViewer.Hide();
m_ThresholdedImageViewer.Hide();
m_EdgePotentialImageViewer.Hide();
m_GradientMagnitudeImageViewer.Hide();
m_TimeCrossingMapViewer.Hide();
m_VTKSegmentedImageViewer->Hide();
consoleWindow->hide();
}
/************************************
*
* Load Input Image
*
***********************************/
void
FastMarchingLevelSet
::LoadInputImage( void )
{
const char * filename = fl_file_chooser("Input Image filename","*.*","");
if( !filename )
{
return;
}
this->ShowStatus("Loading input image file...");
try
{
FastMarchingLevelSetBase::LoadInputImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
// Allocate a image of seeds of the same size
m_SeedImage->SetRegions( m_ImageReader->GetOutput()->GetBufferedRegion() );
m_SeedImage->Allocate();
m_SeedImage->FillBuffer( itk::NumericTraits<SeedImageType::PixelType>::Zero );
this->ShowStatus("Input Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Show Status
*
***********************************/
void
FastMarchingLevelSet
::ShowStatus( const char * message )
{
statusTextOutput->value( message );
Fl::check();
}
/************************************
*
* Clear Seeds
*
***********************************/
void
FastMarchingLevelSet
::ClearSeeds( void )
{
this->FastMarchingLevelSetBase::ClearSeeds();
m_SeedImage->FillBuffer( itk::NumericTraits<SeedImageType::PixelType>::Zero );
}
/************************************
*
* Show Input Image
*
***********************************/
void
FastMarchingLevelSet
::ShowInputImage( void )
{
if( !m_InputImageIsLoaded )
{
return;
}
m_CastImageFilter->Update();
m_InputImageViewer.SetImage( m_CastImageFilter->GetOutput() );
m_InputImageViewer.SetOverlay( m_SeedImage );
m_InputImageViewer.Show();
}
/************************************
*
* Show Time Crossing Map Image
*
***********************************/
void
FastMarchingLevelSet
::ShowTimeCrossingMapImage( void )
{
if( !m_InputImageIsLoaded )
{
return;
}
this->RunFastMarching();
m_TimeCrossingMapViewer.SetImage( m_FastMarchingFilter->GetOutput() );
m_TimeCrossingMapViewer.Show();
}
/************************************
*
* Show Gradient Magnitude
*
***********************************/
void
FastMarchingLevelSet
::ShowGradientMagnitudeImage( void )
{
if( !m_InputImageIsLoaded )
{
return;
}
this->ComputeGradientMagnitude();
m_GradientMagnitudeImageViewer.SetImage( m_DerivativeFilter->GetOutput() );
m_GradientMagnitudeImageViewer.Show();
}
/************************************
*
* Show The Edge Potential Map
*
***********************************/
void
FastMarchingLevelSet
::ShowEdgePotentialImage( void )
{
if( !m_InputImageIsLoaded )
{
return;
}
this->ComputeEdgePotential();
m_EdgePotentialImageViewer.SetImage( m_ExpNegativeFilter->GetOutput() );
m_EdgePotentialImageViewer.Show();
}
/************************************
*
* Show Thresholded Image
*
***********************************/
void
FastMarchingLevelSet
::ShowThresholdedImage( void )
{
m_ThresholdFilter->Update();
m_ThresholdedImageViewer.SetImage( m_ThresholdFilter->GetOutput() );
m_ThresholdedImageViewer.SetOverlay( m_SeedImage );
m_ThresholdedImageViewer.Show();
}
/************************************
*
* Show Homogeneous Image
*
***********************************/
void
FastMarchingLevelSet
::ShowThresholdedImageWithVTK( void )
{
m_VTKSegmentedImageViewer->Show();
}
/*****************************************
*
* Callback for Selecting a seed point
*
*****************************************/
void
FastMarchingLevelSet
::ClickSelectCallback(float x, float y, float z, float value, void * args )
{
FastMarchingLevelSet * self =
static_cast<FastMarchingLevelSet *>( args );
self->SelectSeedPoint( x, y, z );
}
/*****************************************
*
* Callback for Selecting a seed point
*
*****************************************/
void
FastMarchingLevelSet
::SelectSeedPoint(float x, float y, float z)
{
typedef SeedImageType::IndexType IndexType;
IndexType seed;
seed[0] = static_cast<IndexType::IndexValueType>( x );
seed[1] = static_cast<IndexType::IndexValueType>( y );
seed[2] = static_cast<IndexType::IndexValueType>( z );
FastMarchingLevelSetBase::AddSeed( seed );
m_SeedImage->SetPixel( seed, 1 );
m_InputImageViewer.Update();
}
/*****************************************
*
* Update GUI after iteration
*
*****************************************/
void
FastMarchingLevelSet
::UpdateGUIAfterIteration()
{
static unsigned int iterationCounter = 0;
iterationValueOutput->value( iterationCounter );
iterationCounter++;
Fl::check();
}
/* Finaly the main() that will instantiate the application */
int main()
{
try
{
FastMarchingLevelSet * console = new FastMarchingLevelSet();
console->ShowConsole();
Fl::run();
delete console;
}
catch( itk::ExceptionObject & e )
{
std::cerr << "ITK exception caught in main" << std::endl;
std::cerr << e << std::endl;
}
catch( std::exception & e )
{
std::cerr << "STD exception caught in main" << std::endl;
std::cerr << e.what() << std::endl;
}
catch( ... )
{
std::cerr << "unknown exception caught in main" << std::endl;
}
return 0;
}
<commit_msg>ENH: Value of sigma synchronized with the GUI at creation time.<commit_after>/*=========================================================================
Program: Insight Segmentation & Registration Toolkit
Module: FastMarchingLevelSet.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 2002 Insight Consortium. All rights reserved.
See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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.
=========================================================================*/
#include <FastMarchingLevelSet.h>
#include <FL/fl_file_chooser.H>
/************************************
*
* Constructor
*
***********************************/
FastMarchingLevelSet
::FastMarchingLevelSet()
{
// This image is only used for providing visual
// feedback to the user. The actual structure
// holding the seeds is in the base class.
m_SeedImage = SeedImageType::New();
m_InputImageViewer.SetLabel("Input Image");
m_ThresholdedImageViewer.SetLabel("Thresholded Image");
m_GradientMagnitudeImageViewer.SetLabel("Gradient Magnitude Image");
m_EdgePotentialImageViewer.SetLabel("Edge Potential Image");
m_InputImageViewer.ClickSelectCallBack( ClickSelectCallback, (void *)this);
// Initialize ITK filter with GUI values
m_ThresholdFilter->SetLowerThreshold(
static_cast<InternalPixelType>( lowerThresholdValueInput->value() ) );
m_ThresholdFilter->SetUpperThreshold(
static_cast<InputPixelType>( upperThresholdValueInput->value() ) );
m_DerivativeFilter->SetSigma( sigmaValueInput->value() );
m_VTKSegmentedImageViewer = VTKImageViewerType::New();
m_VTKSegmentedImageViewer->SetImage( m_ThresholdFilter->GetOutput() );
m_TimeCrossingMapViewer.SetLabel("Time Crossing Map");
// Connect Observers in the GUI
inputImageButton->Observe( m_ImageReader.GetPointer() );
thresholdedImageButton->Observe( m_ThresholdFilter.GetPointer() );
timeCrossingButton->Observe( m_FastMarchingFilter.GetPointer() );
gradientMagnitudeButton->Observe( m_DerivativeFilter.GetPointer() );
edgePotentialButton->Observe( m_ExpNegativeFilter.GetPointer() );
progressSlider->Observe( m_CastImageFilter.GetPointer() );
progressSlider->Observe( m_DerivativeFilter.GetPointer() );
progressSlider->Observe( m_ThresholdFilter.GetPointer() );
progressSlider->Observe( m_ExpNegativeFilter.GetPointer() );
progressSlider->Observe( m_ImageReader.GetPointer() );
progressSlider->Observe( m_FastMarchingFilter.GetPointer() );
typedef itk::SimpleMemberCommand< FastMarchingLevelSet > SimpleCommandType;
SimpleCommandType::Pointer iterationCommand = SimpleCommandType::New();
iterationCommand->SetCallbackFunction( this,
& FastMarchingLevelSet::UpdateGUIAfterIteration );
m_FastMarchingFilter->AddObserver( itk::IterationEvent(), iterationCommand );
m_ThresholdFilter->SetLowerThreshold( lowerThresholdValueInput->value() );
m_ThresholdFilter->SetUpperThreshold( upperThresholdValueInput->value() );
}
/************************************
*
* Destructor
*
***********************************/
FastMarchingLevelSet
::~FastMarchingLevelSet()
{
}
/************************************
*
* Show main console
*
***********************************/
void
FastMarchingLevelSet
::ShowConsole(void)
{
consoleWindow->show();
}
/********************************************
*
* Quit : requires to hide all fltk windows
*
*******************************************/
void
FastMarchingLevelSet
::Quit(void)
{
m_InputImageViewer.Hide();
m_ThresholdedImageViewer.Hide();
m_EdgePotentialImageViewer.Hide();
m_GradientMagnitudeImageViewer.Hide();
m_TimeCrossingMapViewer.Hide();
m_VTKSegmentedImageViewer->Hide();
consoleWindow->hide();
}
/************************************
*
* Load Input Image
*
***********************************/
void
FastMarchingLevelSet
::LoadInputImage( void )
{
const char * filename = fl_file_chooser("Input Image filename","*.*","");
if( !filename )
{
return;
}
this->ShowStatus("Loading input image file...");
try
{
FastMarchingLevelSetBase::LoadInputImage( filename );
}
catch( ... )
{
this->ShowStatus("Problems reading file format");
controlsGroup->deactivate();
return;
}
// Allocate a image of seeds of the same size
m_SeedImage->SetRegions( m_ImageReader->GetOutput()->GetBufferedRegion() );
m_SeedImage->Allocate();
m_SeedImage->FillBuffer( itk::NumericTraits<SeedImageType::PixelType>::Zero );
this->ShowStatus("Input Image Loaded");
controlsGroup->activate();
}
/************************************
*
* Show Status
*
***********************************/
void
FastMarchingLevelSet
::ShowStatus( const char * message )
{
statusTextOutput->value( message );
Fl::check();
}
/************************************
*
* Clear Seeds
*
***********************************/
void
FastMarchingLevelSet
::ClearSeeds( void )
{
this->FastMarchingLevelSetBase::ClearSeeds();
m_SeedImage->FillBuffer( itk::NumericTraits<SeedImageType::PixelType>::Zero );
}
/************************************
*
* Show Input Image
*
***********************************/
void
FastMarchingLevelSet
::ShowInputImage( void )
{
if( !m_InputImageIsLoaded )
{
return;
}
m_CastImageFilter->Update();
m_InputImageViewer.SetImage( m_CastImageFilter->GetOutput() );
m_InputImageViewer.SetOverlay( m_SeedImage );
m_InputImageViewer.Show();
}
/************************************
*
* Show Time Crossing Map Image
*
***********************************/
void
FastMarchingLevelSet
::ShowTimeCrossingMapImage( void )
{
if( !m_InputImageIsLoaded )
{
return;
}
this->RunFastMarching();
m_TimeCrossingMapViewer.SetImage( m_FastMarchingFilter->GetOutput() );
m_TimeCrossingMapViewer.Show();
}
/************************************
*
* Show Gradient Magnitude
*
***********************************/
void
FastMarchingLevelSet
::ShowGradientMagnitudeImage( void )
{
if( !m_InputImageIsLoaded )
{
return;
}
this->ComputeGradientMagnitude();
m_GradientMagnitudeImageViewer.SetImage( m_DerivativeFilter->GetOutput() );
m_GradientMagnitudeImageViewer.Show();
}
/************************************
*
* Show The Edge Potential Map
*
***********************************/
void
FastMarchingLevelSet
::ShowEdgePotentialImage( void )
{
if( !m_InputImageIsLoaded )
{
return;
}
this->ComputeEdgePotential();
m_EdgePotentialImageViewer.SetImage( m_ExpNegativeFilter->GetOutput() );
m_EdgePotentialImageViewer.Show();
}
/************************************
*
* Show Thresholded Image
*
***********************************/
void
FastMarchingLevelSet
::ShowThresholdedImage( void )
{
m_ThresholdFilter->Update();
m_ThresholdedImageViewer.SetImage( m_ThresholdFilter->GetOutput() );
m_ThresholdedImageViewer.SetOverlay( m_SeedImage );
m_ThresholdedImageViewer.Show();
}
/************************************
*
* Show Homogeneous Image
*
***********************************/
void
FastMarchingLevelSet
::ShowThresholdedImageWithVTK( void )
{
m_VTKSegmentedImageViewer->Show();
}
/*****************************************
*
* Callback for Selecting a seed point
*
*****************************************/
void
FastMarchingLevelSet
::ClickSelectCallback(float x, float y, float z, float value, void * args )
{
FastMarchingLevelSet * self =
static_cast<FastMarchingLevelSet *>( args );
self->SelectSeedPoint( x, y, z );
}
/*****************************************
*
* Callback for Selecting a seed point
*
*****************************************/
void
FastMarchingLevelSet
::SelectSeedPoint(float x, float y, float z)
{
typedef SeedImageType::IndexType IndexType;
IndexType seed;
seed[0] = static_cast<IndexType::IndexValueType>( x );
seed[1] = static_cast<IndexType::IndexValueType>( y );
seed[2] = static_cast<IndexType::IndexValueType>( z );
FastMarchingLevelSetBase::AddSeed( seed );
m_SeedImage->SetPixel( seed, 1 );
m_InputImageViewer.Update();
}
/*****************************************
*
* Update GUI after iteration
*
*****************************************/
void
FastMarchingLevelSet
::UpdateGUIAfterIteration()
{
static unsigned int iterationCounter = 0;
iterationValueOutput->value( iterationCounter );
iterationCounter++;
Fl::check();
}
/* Finaly the main() that will instantiate the application */
int main()
{
try
{
FastMarchingLevelSet * console = new FastMarchingLevelSet();
console->ShowConsole();
Fl::run();
delete console;
}
catch( itk::ExceptionObject & e )
{
std::cerr << "ITK exception caught in main" << std::endl;
std::cerr << e << std::endl;
}
catch( std::exception & e )
{
std::cerr << "STD exception caught in main" << std::endl;
std::cerr << e.what() << std::endl;
}
catch( ... )
{
std::cerr << "unknown exception caught in main" << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et sw=4 ts=4 sts=4: */
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>
**
** This file is part of duicontrolpanel.
**
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <stdio.h>
#include <getopt.h>
#include <libgen.h>
#include <DuiControlPanelIf>
#include <MDialog>
#include <MApplication>
#include <MApplicationWindow>
#include <MApplicationPage>
#include <MGConfItem>
#include "main.h"
#include "wallpapergconf.h"
#define DEBUG
#include "../debug.h"
static struct option
long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'V'},
{"start-applet", no_argument, 0, 's'},
{"print-gconf", no_argument, 0, 'P'},
{"set-gconf", no_argument, 0, 'S'},
{"edit", no_argument, 0, 'e'},
{"portrait", required_argument, 0, 'p'},
{"landscape", required_argument, 0, 'l'},
{0, 0, 0, 0}
};
static const char *short_options = "hsp:l:Se";
WallpaperCLI::WallpaperCLI () :
m_ProgramName (0),
m_OptionHelp (false),
m_OptionVerbose (false),
m_PrintGconf (false),
m_SetGconf (false),
m_EditImages (false),
m_OptionStartApplet (false),
m_DcpIf (new DuiControlPanelIf),
m_ExitCode (EXIT_SUCCESS)
{
m_LandscapeGConfItem = new MGConfItem (WALLPAPER_LANDSCAPE_KEY);
m_PortraitGConfItem = new MGConfItem (WALLPAPER_PORTRAIT_KEY);
}
WallpaperCLI::~WallpaperCLI ()
{
delete m_DcpIf;
}
bool
WallpaperCLI::parseCommandLineArguments (
int argc, char *argv[])
{
int c;
//int digit_optind = 0;
m_ProgramName = basename (argv[0]);
while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
c = getopt_long (argc, argv,
short_options, long_options, &option_index);
//SYS_DEBUG ("*** c = %c", c);
//SYS_DEBUG ("*** option_index = %d", option_index);
//SYS_DEBUG ("*** optind = %d", optind);
if (c == -1)
break;
switch (c) {
case 's':
m_OptionStartApplet = true;
break;
case 'S':
m_SetGconf = true;
break;
case 'e':
m_EditImages = true;
break;
case 'h':
m_OptionHelp = true;
break;
case 'V':
m_OptionVerbose = true;
break;
case 'P':
m_PrintGconf = true;
break;
case 'L':
m_SetGconf = true;
break;
case 'p':
m_OptionPortraitFilename = argv[optind - 1];
break;
case 'l':
m_OptionLandscapeFilename = argv[optind - 1];
break;
default:
SYS_WARNING ("Unhandled option: %d", c);
}
}
return true;
}
bool
WallpaperCLI::executeCommandLineArguments ()
{
bool retval = true;
/*
* Executing --help: printing the help message and exit.
*/
if (m_OptionHelp) {
printHelp ();
goto finalize;
}
/*
* Executing --set-gconf: Simply changing the file names in the GConf
* database.
*/
if (m_SetGconf) {
m_LandscapeGConfItem->set (m_OptionLandscapeFilename);
m_PortraitGConfItem->set (m_OptionPortraitFilename);
goto finalize;
}
/*
* Printing the values stored in the GConf database.
*/
if (m_PrintGconf) {
QString landscape = m_LandscapeGConfItem->value().toString();
QString portrait = m_PortraitGConfItem->value().toString();
if (m_OptionVerbose) {
printf ("Landscape : '%s'\n", landscape.toLatin1().constData());
printf ("Portrait : '%s'\n", portrait.toLatin1().constData());
} else {
printf ("'%s'\n", landscape.toLatin1().constData());
printf ("'%s'\n", portrait.toLatin1().constData());
}
goto finalize;
}
/*
* Executing --edit: Opening the images in the wallpaper applet for
* editing.
*/
if (m_EditImages) {
retval = performEditImages ();
goto finalize;
}
/*
* Executing --start-applet: Start up the applet in normal mode.
*/
if (m_OptionStartApplet) {
retval = pageToWallpaperApplet ();
goto finalize;
}
finalize:
return true;
}
bool
WallpaperCLI::performEditImages ()
{
MGConfItem lEditedImage (WALLPAPER_EDITED_LANDSCAPE_KEY);
MGConfItem pEditedImage (WALLPAPER_EDITED_PORTRAIT_KEY);
MGConfItem requestCode (WALLPAPER_APPLET_REQUEST_CODE);
bool retval = true;
SYS_DEBUG ("+++ Resetting GConf...");
requestCode.set (-1);
SYS_DEBUG ("+++ Pushing request into GConf...");
lEditedImage.set (m_OptionLandscapeFilename);
pEditedImage.set (m_OptionPortraitFilename);
requestCode.set (WallpaperRequestEdit);
SYS_DEBUG ("+++ Starting up the controlpanel");
if (!pageToWallpaperApplet()) {
retval = false;
goto finalize;
}
finalize:
return retval;
}
void
WallpaperCLI::printHelp ()
{
fprintf (stderr,
"Usage: %s [OPTION...]\n\n"
"-h, --help Print help message and exit.\n"
"--verbose Verbose output.\n"
"\n"
"-s, --start-applet Start the wallpaper applet.\n"
"--print-gconf Print the settings from the GConf database.\n"
"--set-gconf Save the settings from the GConf database.\n"
"--edit Edit the images in the wallpaper applet.\n"
"\n"
"-p, --portrait <filename> Portrait image filename.\n"
"-l, --landscape <filename> Portrait image filename.\n"
"\n\n", m_ProgramName
);
}
void
WallpaperCLI::printError ()
{
SYS_WARNING ("Error: %s", SYS_STR(m_ErrorString));
}
void
WallpaperCLI::startControlPanel ()
{
SYS_DEBUG ("");
system ("duicontrolpanel.launch -software &");
sleep (1);
}
bool
WallpaperCLI::pageToWallpaperApplet ()
{
SYS_DEBUG ("");
Q_ASSERT (m_DcpIf);
/*
* FIXME: It is not clear why do we need to to start up the controlpanel
* manually here...
*/
startControlPanel ();
if (!m_DcpIf->isValid()) {
SYS_WARNING ("ERROR: Service unavailable");
m_ErrorString = "Service unavailable";
m_ExitCode = EXIT_FAILURE;
return false;
}
return m_DcpIf->appletPage("Wallpaper");
}
int
main (
int argc,
char *argv[])
{
WallpaperCLI cli;
bool success;
success = cli.parseCommandLineArguments (argc, argv);
if (!success) {
cli.printError ();
goto finalize;
}
success = cli.executeCommandLineArguments ();
if (!success) {
cli.printError ();
}
finalize:
return cli.exitCode ();
}
<commit_msg>Help enhanced in wallpapercli<commit_after>/* -*- Mode: C; indent-tabs-mode: s; c-basic-offset: 4; tab-width: 4 -*- */
/* vim:set et sw=4 ts=4 sts=4: */
/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Karoliina T. Salminen <karoliina.t.salminen@nokia.com>
**
** This file is part of duicontrolpanel.
**
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include <stdio.h>
#include <getopt.h>
#include <libgen.h>
#include <DuiControlPanelIf>
#include <MDialog>
#include <MApplication>
#include <MApplicationWindow>
#include <MApplicationPage>
#include <MGConfItem>
#include "main.h"
#include "wallpapergconf.h"
#define DEBUG
#include "../debug.h"
static struct option
long_options[] =
{
{"help", no_argument, 0, 'h'},
{"verbose", no_argument, 0, 'V'},
{"start-applet", no_argument, 0, 's'},
{"print-gconf", no_argument, 0, 'P'},
{"set-gconf", no_argument, 0, 'S'},
{"edit", no_argument, 0, 'e'},
{"portrait", required_argument, 0, 'p'},
{"landscape", required_argument, 0, 'l'},
{0, 0, 0, 0}
};
static const char *short_options = "hsp:l:Se";
WallpaperCLI::WallpaperCLI () :
m_ProgramName (0),
m_OptionHelp (false),
m_OptionVerbose (false),
m_PrintGconf (false),
m_SetGconf (false),
m_EditImages (false),
m_OptionStartApplet (false),
m_DcpIf (new DuiControlPanelIf),
m_ExitCode (EXIT_SUCCESS)
{
m_LandscapeGConfItem = new MGConfItem (WALLPAPER_LANDSCAPE_KEY);
m_PortraitGConfItem = new MGConfItem (WALLPAPER_PORTRAIT_KEY);
}
WallpaperCLI::~WallpaperCLI ()
{
delete m_DcpIf;
}
bool
WallpaperCLI::parseCommandLineArguments (
int argc, char *argv[])
{
int c;
//int digit_optind = 0;
m_ProgramName = basename (argv[0]);
while (1) {
int this_option_optind = optind ? optind : 1;
int option_index = 0;
c = getopt_long (argc, argv,
short_options, long_options, &option_index);
//SYS_DEBUG ("*** c = %c", c);
//SYS_DEBUG ("*** option_index = %d", option_index);
//SYS_DEBUG ("*** optind = %d", optind);
if (c == -1)
break;
switch (c) {
case 's':
m_OptionStartApplet = true;
break;
case 'S':
m_SetGconf = true;
break;
case 'e':
m_EditImages = true;
break;
case 'h':
m_OptionHelp = true;
break;
case 'V':
m_OptionVerbose = true;
break;
case 'P':
m_PrintGconf = true;
break;
case 'L':
m_SetGconf = true;
break;
case 'p':
m_OptionPortraitFilename = argv[optind - 1];
break;
case 'l':
m_OptionLandscapeFilename = argv[optind - 1];
break;
default:
SYS_WARNING ("Unhandled option: %d", c);
}
}
return true;
}
bool
WallpaperCLI::executeCommandLineArguments ()
{
bool retval = true;
/*
* Executing --help: printing the help message and exit.
*/
if (m_OptionHelp) {
printHelp ();
goto finalize;
}
/*
* Executing --set-gconf: Simply changing the file names in the GConf
* database.
*/
if (m_SetGconf) {
m_LandscapeGConfItem->set (m_OptionLandscapeFilename);
m_PortraitGConfItem->set (m_OptionPortraitFilename);
goto finalize;
}
/*
* Printing the values stored in the GConf database.
*/
if (m_PrintGconf) {
QString landscape = m_LandscapeGConfItem->value().toString();
QString portrait = m_PortraitGConfItem->value().toString();
if (m_OptionVerbose) {
printf ("Landscape : '%s'\n", landscape.toLatin1().constData());
printf ("Portrait : '%s'\n", portrait.toLatin1().constData());
} else {
printf ("'%s'\n", landscape.toLatin1().constData());
printf ("'%s'\n", portrait.toLatin1().constData());
}
goto finalize;
}
/*
* Executing --edit: Opening the images in the wallpaper applet for
* editing.
*/
if (m_EditImages) {
retval = performEditImages ();
goto finalize;
}
/*
* Executing --start-applet: Start up the applet in normal mode.
*/
if (m_OptionStartApplet) {
retval = pageToWallpaperApplet ();
goto finalize;
}
printHelp ();
finalize:
return true;
}
bool
WallpaperCLI::performEditImages ()
{
MGConfItem lEditedImage (WALLPAPER_EDITED_LANDSCAPE_KEY);
MGConfItem pEditedImage (WALLPAPER_EDITED_PORTRAIT_KEY);
MGConfItem requestCode (WALLPAPER_APPLET_REQUEST_CODE);
bool retval = true;
SYS_DEBUG ("+++ Resetting GConf...");
requestCode.set (-1);
SYS_DEBUG ("+++ Pushing request into GConf...");
lEditedImage.set (m_OptionLandscapeFilename);
pEditedImage.set (m_OptionPortraitFilename);
requestCode.set (WallpaperRequestEdit);
SYS_DEBUG ("+++ Starting up the controlpanel");
if (!pageToWallpaperApplet()) {
retval = false;
goto finalize;
}
finalize:
return retval;
}
void
WallpaperCLI::printHelp ()
{
fprintf (stderr,
"Usage: %s [OPTION...]\n\n"
"-h, --help Print help message and exit.\n"
"--verbose Verbose output.\n"
"\n"
"-s, --start-applet Start the wallpaper applet.\n"
"--print-gconf Print the settings from the GConf database.\n"
"--set-gconf Save the settings from the GConf database.\n"
"--edit Edit the images in the wallpaper applet.\n"
"\n"
"-p, --portrait <filename> Portrait image filename.\n"
"-l, --landscape <filename> Portrait image filename.\n"
"\n"
"Examples:\n\n"
" Starting to edit\n"
" %s --portrait image1.jpg --landscape image2.jpg --edit\n\n"
" Set wallpaper without editing\n"
" %s --portrait image1.jpg --landscape image2.jpg --set-gconf\n\n"
" Show settings\n"
" %s --verbose --print-gconf\n\n"
"", m_ProgramName, m_ProgramName, m_ProgramName, m_ProgramName
);
}
void
WallpaperCLI::printError ()
{
SYS_WARNING ("Error: %s", SYS_STR(m_ErrorString));
}
void
WallpaperCLI::startControlPanel ()
{
SYS_DEBUG ("");
system ("duicontrolpanel.launch -software &");
sleep (1);
}
bool
WallpaperCLI::pageToWallpaperApplet ()
{
SYS_DEBUG ("");
Q_ASSERT (m_DcpIf);
/*
* FIXME: It is not clear why do we need to to start up the controlpanel
* manually here...
*/
startControlPanel ();
if (!m_DcpIf->isValid()) {
SYS_WARNING ("ERROR: Service unavailable");
m_ErrorString = "Service unavailable";
m_ExitCode = EXIT_FAILURE;
return false;
}
return m_DcpIf->appletPage("Wallpaper");
}
int
main (
int argc,
char *argv[])
{
WallpaperCLI cli;
bool success;
success = cli.parseCommandLineArguments (argc, argv);
if (!success) {
cli.printError ();
goto finalize;
}
success = cli.executeCommandLineArguments ();
if (!success) {
cli.printError ();
}
finalize:
return cli.exitCode ();
}
<|endoftext|> |
<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/command_line.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
#include "base/strings/stringprintf.h"
#include "base/test/trace_event_analyzer.h"
#include "base/win/windows_version.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/feature_switch.h"
#include "chrome/common/extensions/features/base_feature_provider.h"
#include "chrome/common/extensions/features/complex_feature.h"
#include "chrome/common/extensions/features/simple_feature.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/test_switches.h"
#include "chrome/test/base/tracing.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/common/content_switches.h"
#include "extensions/common/features/feature.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/perf/perf_test.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/gl/gl_switches.h"
namespace {
const char kExtensionId[] = "ddchlicdkolnonkihahngkmmmjnjlkkf";
enum TestFlags {
kUseGpu = 1 << 0, // Only execute test if --enable-gpu was given
// on the command line. This is required for
// tests that run on GPU.
kForceGpuComposited = 1 << 1, // Force the test to use the compositor.
kDisableVsync = 1 << 2, // Do not limit framerate to vertical refresh.
// when on GPU, nor to 60hz when not on GPU.
kTestThroughWebRTC = 1 << 3, // Send captured frames through webrtc
kSmallWindow = 1 << 4, // 1 = 800x600, 0 = 2000x1000
kScaleQualityMask = 3 << 5, // two bits select which scaling quality
kScaleQualityDefault = 0 << 5, // to use on aura.
kScaleQualityFast = 1 << 5,
kScaleQualityGood = 2 << 5,
kScaleQualityBest = 3 << 5,
};
class TabCapturePerformanceTest
: public ExtensionApiTest,
public testing::WithParamInterface<int> {
public:
TabCapturePerformanceTest() {}
bool HasFlag(TestFlags flag) const {
return (GetParam() & flag) == flag;
}
bool IsGpuAvailable() const {
return CommandLine::ForCurrentProcess()->HasSwitch("enable-gpu");
}
std::string ScalingMethod() const {
switch (GetParam() & kScaleQualityMask) {
case kScaleQualityFast:
return "fast";
case kScaleQualityGood:
return "good";
case kScaleQualityBest:
return "best";
default:
return "";
}
}
std::string GetSuffixForTestFlags() {
std::string suffix;
if (HasFlag(kForceGpuComposited))
suffix += "_comp";
if (HasFlag(kUseGpu))
suffix += "_gpu";
if (HasFlag(kDisableVsync))
suffix += "_novsync";
if (HasFlag(kTestThroughWebRTC))
suffix += "_webrtc";
if (!ScalingMethod().empty())
suffix += "_scale" + ScalingMethod();
if (HasFlag(kSmallWindow))
suffix += "_small";
return suffix;
}
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
if (!ScalingMethod().empty()) {
command_line->AppendSwitchASCII(switches::kTabCaptureUpscaleQuality,
ScalingMethod());
command_line->AppendSwitchASCII(switches::kTabCaptureDownscaleQuality,
ScalingMethod());
}
// UI tests boot up render views starting from about:blank. This causes
// the renderer to start up thinking it cannot use the GPU. To work
// around that, and allow the frame rate test to use the GPU, we must
// pass kAllowWebUICompositing.
command_line->AppendSwitch(switches::kAllowWebUICompositing);
// Some of the tests may launch http requests through JSON or AJAX
// which causes a security error (cross domain request) when the page
// is loaded from the local file system ( file:// ). The following switch
// fixes that error.
command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
if (HasFlag(kSmallWindow)) {
command_line->AppendSwitchASCII(switches::kWindowSize, "800,600");
} else {
command_line->AppendSwitchASCII(switches::kWindowSize, "2000,1500");
}
command_line->AppendSwitch(switches::kDisableTestCompositor);
if (!HasFlag(kUseGpu)) {
command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);
command_line->AppendSwitch(switches::kDisableExperimentalWebGL);
command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);
} else {
command_line->AppendSwitch(switches::kForceCompositingMode);
}
if (HasFlag(kDisableVsync))
command_line->AppendSwitch(switches::kDisableGpuVsync);
command_line->AppendSwitchASCII(switches::kWhitelistedExtensionID,
kExtensionId);
ExtensionApiTest::SetUpCommandLine(command_line);
}
bool PrintResults(trace_analyzer::TraceAnalyzer *analyzer,
const std::string& test_name,
const std::string& event_name,
const std::string& unit) {
trace_analyzer::TraceEventVector events;
trace_analyzer::Query query =
trace_analyzer::Query::EventNameIs(event_name) &&
(trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_BEGIN) ||
trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_ASYNC_BEGIN) ||
trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_FLOW_BEGIN) ||
trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_INSTANT));
analyzer->FindEvents(query, &events);
if (events.size() < 20) {
LOG(INFO) << "Not enough events of type " << event_name << " found.";
return false;
}
// Ignore some events for startup/setup/caching.
trace_analyzer::TraceEventVector rate_events(events.begin() + 3,
events.end() - 3);
trace_analyzer::RateStats stats;
if (!GetRateStats(rate_events, &stats, NULL)) {
LOG(INFO) << "GetRateStats failed";
return false;
}
double mean_ms = stats.mean_us / 1000.0;
double std_dev_ms = stats.standard_deviation_us / 1000.0;
std::string mean_and_error = base::StringPrintf("%f,%f", mean_ms,
std_dev_ms);
perf_test::PrintResultMeanAndError(test_name,
GetSuffixForTestFlags(),
event_name,
mean_and_error,
unit,
true);
return true;
}
void RunTest(const std::string& test_name) {
if (HasFlag(kUseGpu) && !IsGpuAvailable()) {
LOG(WARNING) <<
"Test skipped: requires gpu. Pass --enable-gpu on the command "
"line if use of GPU is desired.";
return;
}
std::string json_events;
ASSERT_TRUE(tracing::BeginTracing("test_fps,mirroring"));
std::string page = "performance.html";
page += HasFlag(kTestThroughWebRTC) ? "?WebRTC=1" : "?WebRTC=0";
// Ideally we'd like to run a higher capture rate when vsync is disabled,
// but libjingle currently doesn't allow that.
// page += HasFlag(kDisableVsync) ? "&fps=300" : "&fps=30";
page += "&fps=30";
ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental", page))
<< message_;
ASSERT_TRUE(tracing::EndTracing(&json_events));
scoped_ptr<trace_analyzer::TraceAnalyzer> analyzer;
analyzer.reset(trace_analyzer::TraceAnalyzer::Create(json_events));
// Only one of these PrintResults should actually print something.
// The printed result will be the average time between frames in the
// browser window.
bool sw_frames = PrintResults(analyzer.get(),
test_name,
"TestFrameTickSW",
"frame_time");
bool gpu_frames = PrintResults(analyzer.get(),
test_name,
"TestFrameTickGPU",
"frame_time");
EXPECT_TRUE(sw_frames || gpu_frames);
EXPECT_NE(sw_frames, gpu_frames);
EXPECT_EQ(gpu_frames, HasFlag(kUseGpu));
// This prints out the average time between capture events.
// As the capture frame rate is capped at 30fps, this score
// cannot get any better than 33.33 ms.
EXPECT_TRUE(PrintResults(analyzer.get(),
test_name,
"Capture",
"capture_time"));
}
};
} // namespace
IN_PROC_BROWSER_TEST_P(TabCapturePerformanceTest, Performance) {
RunTest("TabCapturePerformance");
}
// Note: First argument is optional and intentionally left blank.
// (it's a prefix for the generated test cases)
INSTANTIATE_TEST_CASE_P(
,
TabCapturePerformanceTest,
testing::Values(
0,
kUseGpu | kForceGpuComposited,
kDisableVsync,
kDisableVsync | kUseGpu | kForceGpuComposited,
kTestThroughWebRTC,
kTestThroughWebRTC | kUseGpu | kForceGpuComposited,
kTestThroughWebRTC | kDisableVsync,
kTestThroughWebRTC | kDisableVsync | kUseGpu | kForceGpuComposited));
#ifdef USE_AURA
// TODO(hubbe):
// These are temporary tests for the purpose of determining what the
// appropriate scaling quality is. Once that has been determined,
// these tests will be removed.
const int kScalingTestBase =
kTestThroughWebRTC | kDisableVsync | kUseGpu | kForceGpuComposited;
INSTANTIATE_TEST_CASE_P(
ScalingTests,
TabCapturePerformanceTest,
testing::Values(
kScalingTestBase | kScaleQualityFast,
kScalingTestBase | kScaleQualityGood,
kScalingTestBase | kScaleQualityBest,
kScalingTestBase | kScaleQualityFast | kSmallWindow,
kScalingTestBase | kScaleQualityGood | kSmallWindow,
kScalingTestBase | kScaleQualityBest | kSmallWindow));
#endif // USE_AURA
<commit_msg>Disable tab capture perf tests on Aura.<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/command_line.h"
#if defined(OS_MACOSX)
#include "base/mac/mac_util.h"
#endif
#include "base/strings/stringprintf.h"
#include "base/test/trace_event_analyzer.h"
#include "base/win/windows_version.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/extensions/tab_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/fullscreen/fullscreen_controller.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/extensions/feature_switch.h"
#include "chrome/common/extensions/features/base_feature_provider.h"
#include "chrome/common/extensions/features/complex_feature.h"
#include "chrome/common/extensions/features/simple_feature.h"
#include "chrome/test/base/test_launcher_utils.h"
#include "chrome/test/base/test_switches.h"
#include "chrome/test/base/tracing.h"
#include "content/public/browser/render_process_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/common/content_switches.h"
#include "extensions/common/features/feature.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/perf/perf_test.h"
#include "ui/compositor/compositor_switches.h"
#include "ui/gl/gl_switches.h"
namespace {
const char kExtensionId[] = "ddchlicdkolnonkihahngkmmmjnjlkkf";
enum TestFlags {
kUseGpu = 1 << 0, // Only execute test if --enable-gpu was given
// on the command line. This is required for
// tests that run on GPU.
kForceGpuComposited = 1 << 1, // Force the test to use the compositor.
kDisableVsync = 1 << 2, // Do not limit framerate to vertical refresh.
// when on GPU, nor to 60hz when not on GPU.
kTestThroughWebRTC = 1 << 3, // Send captured frames through webrtc
kSmallWindow = 1 << 4, // 1 = 800x600, 0 = 2000x1000
kScaleQualityMask = 3 << 5, // two bits select which scaling quality
kScaleQualityDefault = 0 << 5, // to use on aura.
kScaleQualityFast = 1 << 5,
kScaleQualityGood = 2 << 5,
kScaleQualityBest = 3 << 5,
};
class TabCapturePerformanceTest
: public ExtensionApiTest,
public testing::WithParamInterface<int> {
public:
TabCapturePerformanceTest() {}
bool HasFlag(TestFlags flag) const {
return (GetParam() & flag) == flag;
}
bool IsGpuAvailable() const {
return CommandLine::ForCurrentProcess()->HasSwitch("enable-gpu");
}
std::string ScalingMethod() const {
switch (GetParam() & kScaleQualityMask) {
case kScaleQualityFast:
return "fast";
case kScaleQualityGood:
return "good";
case kScaleQualityBest:
return "best";
default:
return "";
}
}
std::string GetSuffixForTestFlags() {
std::string suffix;
if (HasFlag(kForceGpuComposited))
suffix += "_comp";
if (HasFlag(kUseGpu))
suffix += "_gpu";
if (HasFlag(kDisableVsync))
suffix += "_novsync";
if (HasFlag(kTestThroughWebRTC))
suffix += "_webrtc";
if (!ScalingMethod().empty())
suffix += "_scale" + ScalingMethod();
if (HasFlag(kSmallWindow))
suffix += "_small";
return suffix;
}
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
if (!ScalingMethod().empty()) {
command_line->AppendSwitchASCII(switches::kTabCaptureUpscaleQuality,
ScalingMethod());
command_line->AppendSwitchASCII(switches::kTabCaptureDownscaleQuality,
ScalingMethod());
}
// UI tests boot up render views starting from about:blank. This causes
// the renderer to start up thinking it cannot use the GPU. To work
// around that, and allow the frame rate test to use the GPU, we must
// pass kAllowWebUICompositing.
command_line->AppendSwitch(switches::kAllowWebUICompositing);
// Some of the tests may launch http requests through JSON or AJAX
// which causes a security error (cross domain request) when the page
// is loaded from the local file system ( file:// ). The following switch
// fixes that error.
command_line->AppendSwitch(switches::kAllowFileAccessFromFiles);
if (HasFlag(kSmallWindow)) {
command_line->AppendSwitchASCII(switches::kWindowSize, "800,600");
} else {
command_line->AppendSwitchASCII(switches::kWindowSize, "2000,1500");
}
command_line->AppendSwitch(switches::kDisableTestCompositor);
if (!HasFlag(kUseGpu)) {
command_line->AppendSwitch(switches::kDisableAcceleratedCompositing);
command_line->AppendSwitch(switches::kDisableExperimentalWebGL);
command_line->AppendSwitch(switches::kDisableAccelerated2dCanvas);
} else {
command_line->AppendSwitch(switches::kForceCompositingMode);
}
if (HasFlag(kDisableVsync))
command_line->AppendSwitch(switches::kDisableGpuVsync);
command_line->AppendSwitchASCII(switches::kWhitelistedExtensionID,
kExtensionId);
ExtensionApiTest::SetUpCommandLine(command_line);
}
bool PrintResults(trace_analyzer::TraceAnalyzer *analyzer,
const std::string& test_name,
const std::string& event_name,
const std::string& unit) {
trace_analyzer::TraceEventVector events;
trace_analyzer::Query query =
trace_analyzer::Query::EventNameIs(event_name) &&
(trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_BEGIN) ||
trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_ASYNC_BEGIN) ||
trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_FLOW_BEGIN) ||
trace_analyzer::Query::EventPhaseIs(TRACE_EVENT_PHASE_INSTANT));
analyzer->FindEvents(query, &events);
if (events.size() < 20) {
LOG(INFO) << "Not enough events of type " << event_name << " found.";
return false;
}
// Ignore some events for startup/setup/caching.
trace_analyzer::TraceEventVector rate_events(events.begin() + 3,
events.end() - 3);
trace_analyzer::RateStats stats;
if (!GetRateStats(rate_events, &stats, NULL)) {
LOG(INFO) << "GetRateStats failed";
return false;
}
double mean_ms = stats.mean_us / 1000.0;
double std_dev_ms = stats.standard_deviation_us / 1000.0;
std::string mean_and_error = base::StringPrintf("%f,%f", mean_ms,
std_dev_ms);
perf_test::PrintResultMeanAndError(test_name,
GetSuffixForTestFlags(),
event_name,
mean_and_error,
unit,
true);
return true;
}
void RunTest(const std::string& test_name) {
if (HasFlag(kUseGpu) && !IsGpuAvailable()) {
LOG(WARNING) <<
"Test skipped: requires gpu. Pass --enable-gpu on the command "
"line if use of GPU is desired.";
return;
}
std::string json_events;
ASSERT_TRUE(tracing::BeginTracing("test_fps,mirroring"));
std::string page = "performance.html";
page += HasFlag(kTestThroughWebRTC) ? "?WebRTC=1" : "?WebRTC=0";
// Ideally we'd like to run a higher capture rate when vsync is disabled,
// but libjingle currently doesn't allow that.
// page += HasFlag(kDisableVsync) ? "&fps=300" : "&fps=30";
page += "&fps=30";
ASSERT_TRUE(RunExtensionSubtest("tab_capture/experimental", page))
<< message_;
ASSERT_TRUE(tracing::EndTracing(&json_events));
scoped_ptr<trace_analyzer::TraceAnalyzer> analyzer;
analyzer.reset(trace_analyzer::TraceAnalyzer::Create(json_events));
// Only one of these PrintResults should actually print something.
// The printed result will be the average time between frames in the
// browser window.
bool sw_frames = PrintResults(analyzer.get(),
test_name,
"TestFrameTickSW",
"frame_time");
bool gpu_frames = PrintResults(analyzer.get(),
test_name,
"TestFrameTickGPU",
"frame_time");
EXPECT_TRUE(sw_frames || gpu_frames);
EXPECT_NE(sw_frames, gpu_frames);
EXPECT_EQ(gpu_frames, HasFlag(kUseGpu));
// This prints out the average time between capture events.
// As the capture frame rate is capped at 30fps, this score
// cannot get any better than 33.33 ms.
EXPECT_TRUE(PrintResults(analyzer.get(),
test_name,
"Capture",
"capture_time"));
}
};
} // namespace
// This does not work on Aura GPU bots yet
// http://crbug.com/308236
#if defined(USE_AURA)
#define MAYBE_Performance DISABLED_Performance
#else
#define MAYBE_Performance Performance
#endif
IN_PROC_BROWSER_TEST_P(TabCapturePerformanceTest, MAYBE_Performance) {
RunTest("TabCapturePerformance");
}
// Note: First argument is optional and intentionally left blank.
// (it's a prefix for the generated test cases)
INSTANTIATE_TEST_CASE_P(
,
TabCapturePerformanceTest,
testing::Values(
0,
kUseGpu | kForceGpuComposited,
kDisableVsync,
kDisableVsync | kUseGpu | kForceGpuComposited,
kTestThroughWebRTC,
kTestThroughWebRTC | kUseGpu | kForceGpuComposited,
kTestThroughWebRTC | kDisableVsync,
kTestThroughWebRTC | kDisableVsync | kUseGpu | kForceGpuComposited));
#if defined(USE_AURA)
// TODO(hubbe):
// These are temporary tests for the purpose of determining what the
// appropriate scaling quality is. Once that has been determined,
// these tests will be removed.
const int kScalingTestBase =
kTestThroughWebRTC | kDisableVsync | kUseGpu | kForceGpuComposited;
INSTANTIATE_TEST_CASE_P(
ScalingTests,
TabCapturePerformanceTest,
testing::Values(
kScalingTestBase | kScaleQualityFast,
kScalingTestBase | kScaleQualityGood,
kScalingTestBase | kScaleQualityBest,
kScalingTestBase | kScaleQualityFast | kSmallWindow,
kScalingTestBase | kScaleQualityGood | kSmallWindow,
kScalingTestBase | kScaleQualityBest | kSmallWindow));
#endif // USE_AURA
<|endoftext|> |
<commit_before>#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/fusion/adapted.hpp>
#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/RequestBuilder.h"
using namespace std;
using namespace restc_cpp;
// C++ structure that match the Json entries received
// from http://jsonplaceholder.typicode.com/posts/{id}
struct Post {
int userId = 0;
int id = 0;
string title;
string body;
};
// Add C++ reflection to the Post structure.
// This allows our Json (de)serialization to do it's magic.
BOOST_FUSION_ADAPT_STRUCT(
Post,
(int, userId)
(int, id)
(string, title)
(string, body)
)
// The C++ main function - the place where any adventure starts
void first() {
// Create and instantiate a Post from data received from the server.
Post my_post = RestClient::Create()->ProcessWithPromiseT<Post>([&](Context& ctx) {
// This is a co-routine, running in a worker-thread
// Instantiate a Post structure.
Post post;
// Serialize it asynchronously. The asynchronously part does not really matter
// here, but it may if you receive huge data structures.
SerializeFromJson(post,
// Construct a request to the server
RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Add some headers for good taste
.Header("X-Client", "RESTC_CPP")
.Header("X-Client-Purpose", "Testing")
// Send the request
.Execute());
// Return the post instance trough a C++ future<>
return post;
})
// Get the Post instance from the future<>, or any C++ exception thrown
// within the lambda.
.get();
// Print the result for everyone to see.
cout << "Received post# " << my_post.id << ", title: " << my_post.title;
}
void DoSomethingInteresting(Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server and fetch some data.
auto reply = ctx.Get("http://jsonplaceholder.typicode.com/posts/1");
// Asynchronously fetch the entire data-set and return it as a string.
auto json = reply->GetBodyAsString();
// Just dump the data.
cout << "Received data: " << json << endl;
}
void second() {
auto rest_client = RestClient::Create();
// Call DoSomethingInteresting as a co-routine in a worker-thread.
rest_client->Process(DoSomethingInteresting);
// Wait for a little while to allow the worker-thread to finish
this_thread::sleep_for(chrono::seconds(5));
}
void third() {
auto rest_client = RestClient::Create();
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://localhost:3001/restricted/posts/1")
// Authenticate as 'alice' with a very popular password
.BasicAuthentication("alice", "12345")
// Send the request.
.Execute();
// Dump the well protected data
cout << "Got: " << reply->GetBodyAsString();
}).get();
}
void forth() {
Request::Properties properties;
properties.proxy.type = Request::Proxy::Type::HTTP;
properties.proxy.address = "http://127.0.0.1:3003";
auto rest_client = RestClient::Create(properties);
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server trough a HTTP proxy and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://fwd/normal/posts/1")
// Send the request.
.Execute();
// Dump the well protected data
cout << "Got: " << reply->GetBodyAsString();
}).get();
}
int main() {
try {
// cout << "First: " << endl;
// first();
//
// cout << "Second: " << endl;
// second();
//
// cout << "Third: " << endl;
// third();
cout << "Forth: " << endl;
forth();
} catch(const exception& ex) {
cerr << "Something threw up: " << ex.what() << endl;
}
}
<commit_msg>Updated tests.<commit_after>#include <iostream>
#include <boost/lexical_cast.hpp>
#include <boost/fusion/adapted.hpp>
#include "restc-cpp/restc-cpp.h"
#include "restc-cpp/RequestBuilder.h"
using namespace std;
using namespace restc_cpp;
// C++ structure that match the Json entries received
// from http://jsonplaceholder.typicode.com/posts/{id}
struct Post {
int userId = 0;
int id = 0;
string title;
string body;
};
// Add C++ reflection to the Post structure.
// This allows our Json (de)serialization to do it's magic.
BOOST_FUSION_ADAPT_STRUCT(
Post,
(int, userId)
(int, id)
(string, title)
(string, body)
)
// The C++ main function - the place where any adventure starts
void first() {
// Create and instantiate a Post from data received from the server.
Post my_post = RestClient::Create()->ProcessWithPromiseT<Post>([&](Context& ctx) {
// This is a co-routine, running in a worker-thread
// Instantiate a Post structure.
Post post;
// Serialize it asynchronously. The asynchronously part does not really matter
// here, but it may if you receive huge data structures.
SerializeFromJson(post,
// Construct a request to the server
RequestBuilder(ctx)
.Get("http://jsonplaceholder.typicode.com/posts/1")
// Add some headers for good taste
.Header("X-Client", "RESTC_CPP")
.Header("X-Client-Purpose", "Testing")
// Send the request
.Execute());
// Return the post instance trough a C++ future<>
return post;
})
// Get the Post instance from the future<>, or any C++ exception thrown
// within the lambda.
.get();
// Print the result for everyone to see.
cout << "Received post# " << my_post.id << ", title: " << my_post.title;
}
void DoSomethingInteresting(Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server and fetch some data.
auto reply = ctx.Get("http://jsonplaceholder.typicode.com/posts/1");
// Asynchronously fetch the entire data-set and return it as a string.
auto json = reply->GetBodyAsString();
// Just dump the data.
cout << "Received data: " << json << endl;
}
void second() {
auto rest_client = RestClient::Create();
// Call DoSomethingInteresting as a co-routine in a worker-thread.
rest_client->Process(DoSomethingInteresting);
// Wait for a little while to allow the worker-thread to finish
this_thread::sleep_for(chrono::seconds(5));
}
void third() {
auto rest_client = RestClient::Create();
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://localhost:3001/restricted/posts/1")
// Authenticate as 'alice' with a very popular password
.BasicAuthentication("alice", "12345")
// Send the request.
.Execute();
// Dump the well protected data
cout << "Got: " << reply->GetBodyAsString();
}).get();
}
void forth() {
// Add the proxy information to the properties used by the client
Request::Properties properties;
properties.proxy.type = Request::Proxy::Type::HTTP;
properties.proxy.address = "http://127.0.0.1:3003";
// Create the client with our configuration
auto rest_client = RestClient::Create(properties);
rest_client->ProcessWithPromise([&](Context& ctx) {
// Here we are again in a co-routine, running in a worker-thread.
// Asynchronously connect to a server trough a HTTP proxy and fetch some data.
auto reply = RequestBuilder(ctx)
.Get("http://fwd/normal/posts/1")
// Send the request.
.Execute();
// Dump the data
cout << "Got: " << reply->GetBodyAsString();
}).get();
}
int main() {
try {
cout << "First: " << endl;
first();
cout << "Second: " << endl;
second();
cout << "Third: " << endl;
third();
cout << "Forth: " << endl;
forth();
} catch(const exception& ex) {
cerr << "Something threw up: " << ex.what() << endl;
}
}
<|endoftext|> |
<commit_before>/*-
* Copyright (c) 2008 Michael Marner <michael@20papercups.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <assert.h>
#include <math.h>
#include "Face.h"
#include "Plane.h"
namespace wcl
{
Face::Face(const Face& f)
{
assert(!(*(f.v1) == *(f.v2) && *(f.v1) == *(f.v3) && *(f.v2) == *(f.v3)));
//let std::vector do the copying for us
//since we are only storing pointers after all...
this->v1 = f.v1;
this->v2 = f.v2;
this->v3 = f.v3;
}
Face::Face(Vertex* v1,Vertex* v2,Vertex* v3)
{
assert(!(*(v1) == *(v2) && *(v1) == *(v3) && *(v2) == *(v3)));
this->v1 = v1;
this->v2 = v2;
this->v3 = v3;
}
const BoundingBox& Face::getBoundingBox()
{
return boundingBox;
}
double Face::getArea()
{
wcl::Vector p1 = v1->position;
wcl::Vector p2 = v2->position;
wcl::Vector p3 = v3->position;
wcl::Vector xy(p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2]);
wcl::Vector xz(p3[0] - p1[0], p3[1] - p1[1], p3[2] - p1[2]);
double a = fabs((p1 - p2).normal());
double c = fabs((p1 - p3).normal());
double b = xy.angle(xz);
return (a * c * sin(b)) / 2.0;
}
void Face::invert()
{
Vertex* temp = v2;
v2 = v1;
v1 = temp;
}
wcl::Vector Face::getNormal() const
{
wcl::Vector& vec1 = v1->position;
wcl::Vector& vec2 = v2->position;
wcl::Vector& vec3 = v3->position;
return (vec2 - vec1).crossProduct(vec3 - vec1).unit();
}
Plane Face::getPlane() const
{
return Plane(v1->position,v2->position,v3->position);
}
bool Face::operator==(const Face& f) const
{
return (*v1 == *(f.v1) && *v2 == *(f.v2) && *v3 == *(f.v3));
}
bool Face::hasPoint(const wcl::Vector& p) const
{
LinePosition res1, res2, res3;
bool hasUp, hasDown, hasOn;
wcl::Vector normal = this->getNormal();
if (fabs(normal[0]) > TOL)
{
res1 = linePositionInX(p, v1->position, v2->position);
res2 = linePositionInX(p, v2->position, v3->position);
res3 = linePositionInX(p, v3->position, v1->position);
}
else if (fabs(normal[1]) > TOL)
{
res1 = linePositionInY(p, v1->position, v2->position);
res2 = linePositionInY(p, v2->position, v3->position);
res3 = linePositionInY(p, v3->position, v1->position);
}
else
{
res1 = linePositionInY(p, v1->position, v2->position);
res2 = linePositionInY(p, v2->position, v3->position);
res3 = linePositionInY(p, v3->position, v1->position);
}
if (((res1 == UP)||(res2==UP)||(res3==UP)) && ((res1==DOWN)||(res2==DOWN)||(res3==DOWN)))
return true;
else if ((res1==ON)||(res2==ON)||(res3==ON))
return true;
else
return false;
}
bool Face::quickClassify()
{
IntersectStatus s1 = v1->status;
IntersectStatus s2 = v2->status;
IntersectStatus s3 = v3->status;
if (s1 == INSIDE || s1 == OUTSIDE)
{
this->status = s1;
return true;
}
if (s2 == INSIDE || s2 == OUTSIDE)
{
this->status = s2;
return true;
}
if (s3 == INSIDE || s3 == OUTSIDE)
{
this->status = s3;
return true;
}
return false;
}
Face::LinePosition Face::linePositionInX(const wcl::Vector& point, const wcl::Vector& pLine1, const wcl::Vector& pLine2) const
{
double a,b,z;
if ((fabs(pLine1[1] - pLine2[1]) > TOL) &&(((point[1]>=pLine1[1]) && (point[1] <= pLine2[1])) || ((point[1] <= pLine1[1]) && (point[1]>=pLine2[1]))))
{
a = (pLine2[2] - pLine1[2]) / (pLine2[1] - pLine1[1]);
b = pLine1[2] - a*pLine1[1];
z = a*point[1] + b;
if (z> point[2] + TOL)
{
return UP;
}
else if (z < point[2] - TOL)
{
return DOWN;
}
else
{
return ON;
}
}
else
{
return NONE;
}
}
Face::LinePosition Face::linePositionInY(const wcl::Vector& point, const wcl::Vector& pLine1, const wcl::Vector& pLine2) const
{
double a,b,z;
if ((fabs(pLine1[0] - pLine2[0]) > TOL) &&(((point[0]>=pLine1[0]) && (point[0] <= pLine2[0])) || ((point[0] <= pLine1[0]) && (point[0]>=pLine2[0]))))
{
a = (pLine2[2] - pLine1[2]) / (pLine2[0] - pLine1[0]);
b = pLine1[2] - a*pLine1[0];
z = a*point[0] + b;
if (z> point[2] + TOL)
{
return UP;
}
else if (z < point[2] - TOL)
{
return DOWN;
}
else
{
return ON;
}
}
else
{
return NONE;
}
}
Face::LinePosition Face::linePositionInZ(const wcl::Vector& point, const wcl::Vector& pLine1, const wcl::Vector& pLine2) const
{
double a,b,y;
if ((fabs(pLine1[0] - pLine2[0]) > TOL) &&(((point[0]>=pLine1[0]) && (point[0] <= pLine2[0])) || ((point[0] <= pLine1[0]) && (point[0]>=pLine2[0]))))
{
a = (pLine2[1] - pLine1[1]) / (pLine2[0] - pLine1[0]);
b = pLine1[1] - a*pLine1[0];
y = a*point[0] + b;
if (y> point[1] + TOL)
{
return UP;
}
else if (y < point[1] - TOL)
{
return DOWN;
}
else
{
return ON;
}
}
else
{
return NONE;
}
}
}
<commit_msg>Face's bounding box was never initialised.<commit_after>/*-
* Copyright (c) 2008 Michael Marner <michael@20papercups.net>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <assert.h>
#include <math.h>
#include "Face.h"
#include "Plane.h"
namespace wcl
{
Face::Face(const Face& f)
{
assert(!(*(f.v1) == *(f.v2) && *(f.v1) == *(f.v3) && *(f.v2) == *(f.v3)));
//let std::vector do the copying for us
//since we are only storing pointers after all...
this->v1 = f.v1;
this->v2 = f.v2;
this->v3 = f.v3;
boundingBox.addPoint(v1->position);
boundingBox.addPoint(v1->position);
boundingBox.addPoint(v3->position);
}
Face::Face(Vertex* v1,Vertex* v2,Vertex* v3)
{
assert(!(*(v1) == *(v2) && *(v1) == *(v3) && *(v2) == *(v3)));
this->v1 = v1;
this->v2 = v2;
this->v3 = v3;
boundingBox.addPoint(v1->position);
boundingBox.addPoint(v1->position);
boundingBox.addPoint(v3->position);
}
const BoundingBox& Face::getBoundingBox()
{
return boundingBox;
}
double Face::getArea()
{
wcl::Vector p1 = v1->position;
wcl::Vector p2 = v2->position;
wcl::Vector p3 = v3->position;
wcl::Vector xy(p2[0] - p1[0], p2[1] - p1[1], p2[2] - p1[2]);
wcl::Vector xz(p3[0] - p1[0], p3[1] - p1[1], p3[2] - p1[2]);
double a = fabs((p1 - p2).normal());
double c = fabs((p1 - p3).normal());
double b = xy.angle(xz);
return (a * c * sin(b)) / 2.0;
}
void Face::invert()
{
Vertex* temp = v2;
v2 = v1;
v1 = temp;
}
wcl::Vector Face::getNormal() const
{
wcl::Vector& vec1 = v1->position;
wcl::Vector& vec2 = v2->position;
wcl::Vector& vec3 = v3->position;
return (vec2 - vec1).crossProduct(vec3 - vec1).unit();
}
Plane Face::getPlane() const
{
return Plane(v1->position,v2->position,v3->position);
}
bool Face::operator==(const Face& f) const
{
return (*v1 == *(f.v1) && *v2 == *(f.v2) && *v3 == *(f.v3));
}
bool Face::hasPoint(const wcl::Vector& p) const
{
LinePosition res1, res2, res3;
bool hasUp, hasDown, hasOn;
wcl::Vector normal = this->getNormal();
if (fabs(normal[0]) > TOL)
{
res1 = linePositionInX(p, v1->position, v2->position);
res2 = linePositionInX(p, v2->position, v3->position);
res3 = linePositionInX(p, v3->position, v1->position);
}
else if (fabs(normal[1]) > TOL)
{
res1 = linePositionInY(p, v1->position, v2->position);
res2 = linePositionInY(p, v2->position, v3->position);
res3 = linePositionInY(p, v3->position, v1->position);
}
else
{
res1 = linePositionInY(p, v1->position, v2->position);
res2 = linePositionInY(p, v2->position, v3->position);
res3 = linePositionInY(p, v3->position, v1->position);
}
if (((res1 == UP)||(res2==UP)||(res3==UP)) && ((res1==DOWN)||(res2==DOWN)||(res3==DOWN)))
return true;
else if ((res1==ON)||(res2==ON)||(res3==ON))
return true;
else
return false;
}
bool Face::quickClassify()
{
IntersectStatus s1 = v1->status;
IntersectStatus s2 = v2->status;
IntersectStatus s3 = v3->status;
if (s1 == INSIDE || s1 == OUTSIDE)
{
this->status = s1;
return true;
}
if (s2 == INSIDE || s2 == OUTSIDE)
{
this->status = s2;
return true;
}
if (s3 == INSIDE || s3 == OUTSIDE)
{
this->status = s3;
return true;
}
return false;
}
Face::LinePosition Face::linePositionInX(const wcl::Vector& point, const wcl::Vector& pLine1, const wcl::Vector& pLine2) const
{
double a,b,z;
if ((fabs(pLine1[1] - pLine2[1]) > TOL) &&(((point[1]>=pLine1[1]) && (point[1] <= pLine2[1])) || ((point[1] <= pLine1[1]) && (point[1]>=pLine2[1]))))
{
a = (pLine2[2] - pLine1[2]) / (pLine2[1] - pLine1[1]);
b = pLine1[2] - a*pLine1[1];
z = a*point[1] + b;
if (z> point[2] + TOL)
{
return UP;
}
else if (z < point[2] - TOL)
{
return DOWN;
}
else
{
return ON;
}
}
else
{
return NONE;
}
}
Face::LinePosition Face::linePositionInY(const wcl::Vector& point, const wcl::Vector& pLine1, const wcl::Vector& pLine2) const
{
double a,b,z;
if ((fabs(pLine1[0] - pLine2[0]) > TOL) &&(((point[0]>=pLine1[0]) && (point[0] <= pLine2[0])) || ((point[0] <= pLine1[0]) && (point[0]>=pLine2[0]))))
{
a = (pLine2[2] - pLine1[2]) / (pLine2[0] - pLine1[0]);
b = pLine1[2] - a*pLine1[0];
z = a*point[0] + b;
if (z> point[2] + TOL)
{
return UP;
}
else if (z < point[2] - TOL)
{
return DOWN;
}
else
{
return ON;
}
}
else
{
return NONE;
}
}
Face::LinePosition Face::linePositionInZ(const wcl::Vector& point, const wcl::Vector& pLine1, const wcl::Vector& pLine2) const
{
double a,b,y;
if ((fabs(pLine1[0] - pLine2[0]) > TOL) &&(((point[0]>=pLine1[0]) && (point[0] <= pLine2[0])) || ((point[0] <= pLine1[0]) && (point[0]>=pLine2[0]))))
{
a = (pLine2[1] - pLine1[1]) / (pLine2[0] - pLine1[0]);
b = pLine1[1] - a*pLine1[0];
y = a*point[0] + b;
if (y> point[1] + TOL)
{
return UP;
}
else if (y < point[1] - TOL)
{
return DOWN;
}
else
{
return ON;
}
}
else
{
return NONE;
}
}
}
<|endoftext|> |
<commit_before>#include "ghost/config.h"
#include "ghost/svqb.h"
#include "ghost/util.h"
#include "ghost/tsmttsm.h"
#include "ghost/tsmm.h"
#include <complex>
#ifdef GHOST_HAVE_LAPACK
#ifdef GHOST_HAVE_MKL
#include <mkl_lapacke.h>
#else
#include <lapacke.h>
#endif
template<typename T, typename T_b>
static lapack_int call_eig_function(int matrix_order, char jobz, char uplo, lapack_int n, T *a, lapack_int lda, T_b *w)
{
ERROR_LOG("This should not be called!");
return -999;
}
template<>
static lapack_int call_eig_function<double,double>(int matrix_order, char jobz, char uplo, lapack_int n, double *a, lapack_int lda, double *w)
{
return LAPACKE_dsyevd(matrix_order, jobz, uplo, n, a, lda, w);
}
template<>
static lapack_int call_eig_function<float,float>(int matrix_order, char jobz, char uplo, lapack_int n, float *a, lapack_int lda, float *w)
{
return LAPACKE_ssyevd(matrix_order, jobz, uplo, n, a, lda, w);
}
template<>
static lapack_int call_eig_function<std::complex<float>,float>(int matrix_order, char jobz, char uplo, lapack_int n, std::complex<float> *a, lapack_int lda, float *w)
{
return LAPACKE_cheevd(matrix_order, jobz, uplo, n, (lapack_complex_float *)a, lda, w);
}
template<>
static lapack_int call_eig_function<std::complex<double>,double>(int matrix_order, char jobz, char uplo, lapack_int n, std::complex<double> *a, lapack_int lda, double *w)
{
return LAPACKE_zheevd(matrix_order, jobz, uplo, n, (lapack_complex_double *)a, lda, w);
}
template <typename T, typename T_b>
static ghost_error_t ghost_svqb_tmpl (ghost_densemat_t * v_ot , ghost_densemat_t * v)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret = GHOST_SUCCESS;
T one = 1.0;
T zero = 0.0;
ghost_idx_t i,j;
ghost_idx_t n = v->traits.ncols;
ghost_datatype_t DT = v->traits.datatype;
ghost_densemat_t *x;
ghost_idx_t ldx;
T_b *eigs, *D;
ghost_densemat_traits_t xtraits = GHOST_DENSEMAT_TRAITS_INITIALIZER;
GHOST_CALL_GOTO(ghost_malloc((void **)&eigs, n*sizeof(double)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&D, n*sizeof(double)),err,ret);
xtraits.flags |= GHOST_DENSEMAT_NO_HALO;
xtraits.ncols = n;
xtraits.nrows = n;
xtraits.storage = GHOST_DENSEMAT_COLMAJOR;
xtraits.datatype = DT;
GHOST_CALL_GOTO(ghost_densemat_create(&x,NULL,xtraits),err,ret);
GHOST_CALL_GOTO(x->fromScalar(x,&zero),err,ret);
ldx = *x->stride;
T * xval;
GHOST_CALL_GOTO(ghost_densemat_valptr(x,(void **)&xval),err,ret);
GHOST_CALL_GOTO(ghost_tsmttsm( x, v, v,&one,&zero),err,ret);
for (i=0;i<n;i++) {
D[i] = std::real((T)1./std::sqrt(xval[i*ldx+i]));
}
for (i=0;i<n;i++) {
for( j=0;j<n;j++) {
xval[i*ldx+j] *= D[i]*D[j];
}
}
if (call_eig_function<T,T_b>( LAPACK_COL_MAJOR, 'V' , 'U', n, xval, ldx, eigs)) {
ERROR_LOG("LAPACK eigenvalue function failed!");
ret = GHOST_ERR_LAPACK;
goto err;
}
for( i=0;i<n;i++) {
eigs[i] = 1./sqrt(eigs[i]);
for( j=0;j<n;j++) xval[i*ldx+j] *= D[j]*eigs[i];
}
GHOST_CALL_GOTO(ghost_tsmm( v_ot, v, x, &one, &zero),err,ret);
goto out;
err:
out:
x->destroy(x);
free(eigs);
free(D);
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
ghost_error_t ghost_svqb(ghost_densemat_t * v_ot , ghost_densemat_t * v)
{
if (v->traits.datatype & GHOST_DT_COMPLEX) {
if (v->traits.datatype & GHOST_DT_DOUBLE) {
return ghost_svqb_tmpl<std::complex<double>, double>(v_ot, v);
} else {
return ghost_svqb_tmpl<std::complex<float>, float>(v_ot, v);
}
} else {
if (v->traits.datatype & GHOST_DT_DOUBLE) {
return ghost_svqb_tmpl<double, double>(v_ot, v);
} else {
return ghost_svqb_tmpl<float, float>(v_ot, v);
}
}
}
#else
ghost_error_t ghost_svqb(ghost_densemat_t * v_ot , ghost_densemat_t * v)
{
UNUSED(v_ot);
UNUSED(v);
ERROR_LOG("LAPACKE not found!");
return GHOST_ERR_NOT_IMPLEMENTED;
}
#endif
<commit_msg>svqb.cpp: template specializations should not have 'static' in front of them (gcc complained about that)<commit_after>#include "ghost/config.h"
#include "ghost/svqb.h"
#include "ghost/util.h"
#include "ghost/tsmttsm.h"
#include "ghost/tsmm.h"
#include <complex>
#ifdef GHOST_HAVE_LAPACK
#ifdef GHOST_HAVE_MKL
#include <mkl_lapacke.h>
#else
#include <lapacke.h>
#endif
template<typename T, typename T_b>
lapack_int call_eig_function(int matrix_order, char jobz, char uplo, lapack_int n, T *a, lapack_int lda, T_b *w)
{
ERROR_LOG("This should not be called!");
return -999;
}
template<>
lapack_int call_eig_function<double,double>(int matrix_order, char jobz, char uplo, lapack_int n, double *a, lapack_int lda, double *w)
{
return LAPACKE_dsyevd(matrix_order, jobz, uplo, n, a, lda, w);
}
template<>
lapack_int call_eig_function<float,float>(int matrix_order, char jobz, char uplo, lapack_int n, float *a, lapack_int lda, float *w)
{
return LAPACKE_ssyevd(matrix_order, jobz, uplo, n, a, lda, w);
}
template<>
lapack_int call_eig_function<std::complex<float>,float>(int matrix_order, char jobz, char uplo, lapack_int n, std::complex<float> *a, lapack_int lda, float *w)
{
return LAPACKE_cheevd(matrix_order, jobz, uplo, n, (lapack_complex_float *)a, lda, w);
}
template<>
lapack_int call_eig_function<std::complex<double>,double>(int matrix_order, char jobz, char uplo, lapack_int n, std::complex<double> *a, lapack_int lda, double *w)
{
return LAPACKE_zheevd(matrix_order, jobz, uplo, n, (lapack_complex_double *)a, lda, w);
}
template <typename T, typename T_b>
ghost_error_t ghost_svqb_tmpl (ghost_densemat_t * v_ot , ghost_densemat_t * v)
{
GHOST_FUNC_ENTER(GHOST_FUNCTYPE_MATH);
ghost_error_t ret = GHOST_SUCCESS;
T one = 1.0;
T zero = 0.0;
ghost_idx_t i,j;
ghost_idx_t n = v->traits.ncols;
ghost_datatype_t DT = v->traits.datatype;
ghost_densemat_t *x;
ghost_idx_t ldx;
T_b *eigs, *D;
ghost_densemat_traits_t xtraits = GHOST_DENSEMAT_TRAITS_INITIALIZER;
GHOST_CALL_GOTO(ghost_malloc((void **)&eigs, n*sizeof(double)),err,ret);
GHOST_CALL_GOTO(ghost_malloc((void **)&D, n*sizeof(double)),err,ret);
xtraits.flags |= GHOST_DENSEMAT_NO_HALO;
xtraits.ncols = n;
xtraits.nrows = n;
xtraits.storage = GHOST_DENSEMAT_COLMAJOR;
xtraits.datatype = DT;
GHOST_CALL_GOTO(ghost_densemat_create(&x,NULL,xtraits),err,ret);
GHOST_CALL_GOTO(x->fromScalar(x,&zero),err,ret);
ldx = *x->stride;
T * xval;
GHOST_CALL_GOTO(ghost_densemat_valptr(x,(void **)&xval),err,ret);
GHOST_CALL_GOTO(ghost_tsmttsm( x, v, v,&one,&zero),err,ret);
for (i=0;i<n;i++) {
D[i] = std::real((T)1./std::sqrt(xval[i*ldx+i]));
}
for (i=0;i<n;i++) {
for( j=0;j<n;j++) {
xval[i*ldx+j] *= D[i]*D[j];
}
}
if (call_eig_function<T,T_b>( LAPACK_COL_MAJOR, 'V' , 'U', n, xval, ldx, eigs)) {
ERROR_LOG("LAPACK eigenvalue function failed!");
ret = GHOST_ERR_LAPACK;
goto err;
}
for( i=0;i<n;i++) {
eigs[i] = 1./sqrt(eigs[i]);
for( j=0;j<n;j++) xval[i*ldx+j] *= D[j]*eigs[i];
}
GHOST_CALL_GOTO(ghost_tsmm( v_ot, v, x, &one, &zero),err,ret);
goto out;
err:
out:
x->destroy(x);
free(eigs);
free(D);
GHOST_FUNC_EXIT(GHOST_FUNCTYPE_MATH);
return ret;
}
ghost_error_t ghost_svqb(ghost_densemat_t * v_ot , ghost_densemat_t * v)
{
if (v->traits.datatype & GHOST_DT_COMPLEX) {
if (v->traits.datatype & GHOST_DT_DOUBLE) {
return ghost_svqb_tmpl<std::complex<double>, double>(v_ot, v);
} else {
return ghost_svqb_tmpl<std::complex<float>, float>(v_ot, v);
}
} else {
if (v->traits.datatype & GHOST_DT_DOUBLE) {
return ghost_svqb_tmpl<double, double>(v_ot, v);
} else {
return ghost_svqb_tmpl<float, float>(v_ot, v);
}
}
}
#else
ghost_error_t ghost_svqb(ghost_densemat_t * v_ot , ghost_densemat_t * v)
{
UNUSED(v_ot);
UNUSED(v);
ERROR_LOG("LAPACKE not found!");
return GHOST_ERR_NOT_IMPLEMENTED;
}
#endif
<|endoftext|> |
<commit_before>#include <node.h>
#include "pi_2_dht_read.h"
namespace dht {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Number;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
int sensor = args[0]->IntegerValue();
int pin = args[1]->IntegerValue();
float humidity;
float temperature;
pi_2_dht_read(sensor, pin, &humidity, &temperature);
Local<Object> obj = Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate, "humidity"), Number::New(isolate, humidity));
obj->Set(String::NewFromUtf8(isolate, "temperature"), Number::New(isolate, temperature));
args.GetReturnValue().Set(obj);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "read", Method);
}
NODE_MODULE(addon, init)
} // namespace demo
<commit_msg>Exception is thrown when GPIO access is denied or when unable to read data from sensor<commit_after>#include <node.h>
#include "pi_2_dht_read.h"
namespace dht {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
using v8::Number;
using v8::Exception;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
int sensor = args[0]->IntegerValue();
int pin = args[1]->IntegerValue();
float humidity;
float temperature;
int errorCode = pi_2_dht_read(sensor, pin, &humidity, &temperature);
if (errorCode == DHT_ERROR_GPIO) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Error accessing GPIO.")));
return;
}
else if (errorCode != DHT_SUCCESS) {
isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Could not read data from DHT sensor.")));
return;
}
Local<Object> obj = Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate, "humidity"), Number::New(isolate, humidity));
obj->Set(String::NewFromUtf8(isolate, "temperature"), Number::New(isolate, temperature));
args.GetReturnValue().Set(obj);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "read", Method);
}
NODE_MODULE(addon, init)
} // namespace demo
<|endoftext|> |
<commit_before>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#include "hadesmem/pelib/tls_dir.hpp"
#include <sstream>
#include <utility>
#define BOOST_TEST_MODULE tls_dir
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/read.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/config.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
#include "hadesmem/module_list.hpp"
#include "hadesmem/pelib/pe_file.hpp"
// Boost.Test causes the following warning under GCC:
// error: base class 'struct boost::unit_test::ut_detail::nil_t' has a
// non-virtual destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)
// Boost.Test causes the following warning under Clang:
// error: declaration requires a global constructor
// [-Werror,-Wglobal-constructors]
#if defined(HADESMEM_CLANG)
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#endif // #if defined(HADESMEM_CLANG)
BOOST_AUTO_TEST_CASE(tls_dir)
{
// Use threads and TSS to ensure that at least one module has a TLS dir
static __declspec(thread) int tls_dummy = 0;
boost::thread_specific_ptr<int> tss_dummy;
tss_dummy.reset(new int(1234));
hadesmem::Process const process(::GetCurrentProcessId());
hadesmem::PeFile pe_file_1(process, GetModuleHandle(nullptr),
hadesmem::PeFileType::Image);
hadesmem::TlsDir tls_dir_1(process, pe_file_1);
hadesmem::TlsDir tls_dir_2(tls_dir_1);
BOOST_CHECK_EQUAL(tls_dir_1, tls_dir_2);
tls_dir_1 = tls_dir_2;
BOOST_CHECK_EQUAL(tls_dir_1, tls_dir_2);
hadesmem::TlsDir tls_dir_3(std::move(tls_dir_2));
BOOST_CHECK_EQUAL(tls_dir_3, tls_dir_1);
tls_dir_2 = std::move(tls_dir_3);
BOOST_CHECK_EQUAL(tls_dir_1, tls_dir_2);
bool processed_one_tls_dir = false;
hadesmem::ModuleList modules(process);
for (auto const& mod : modules)
{
// TODO: Also test FileType_Data
hadesmem::PeFile const cur_pe_file(process, mod.GetHandle(),
hadesmem::PeFileType::Data);
std::unique_ptr<hadesmem::TlsDir> cur_tls_dir;
try
{
cur_tls_dir.reset(new hadesmem::TlsDir(process, cur_pe_file));
}
catch (std::exception const& /*e*/)
{
continue;
}
processed_one_tls_dir = true;
auto const tls_dir_raw = hadesmem::Read<IMAGE_TLS_DIRECTORY>(process,
cur_tls_dir->GetBase());
cur_tls_dir->SetStartAddressOfRawData(
cur_tls_dir->GetStartAddressOfRawData());
cur_tls_dir->SetEndAddressOfRawData(cur_tls_dir->GetEndAddressOfRawData());
cur_tls_dir->SetAddressOfIndex(cur_tls_dir->GetAddressOfIndex());
cur_tls_dir->SetAddressOfCallBacks(cur_tls_dir->GetAddressOfCallBacks());
cur_tls_dir->SetSizeOfZeroFill(cur_tls_dir->GetSizeOfZeroFill());
cur_tls_dir->SetCharacteristics(cur_tls_dir->GetCharacteristics());
cur_tls_dir->GetCallbacks();
auto const tls_dir_raw_new = hadesmem::Read<IMAGE_TLS_DIRECTORY>(process,
cur_tls_dir->GetBase());
BOOST_CHECK_EQUAL(std::memcmp(&tls_dir_raw, &tls_dir_raw_new,
sizeof(tls_dir_raw)), 0);
std::stringstream test_str_1;
test_str_1.imbue(std::locale::classic());
test_str_1 << cur_tls_dir;
std::stringstream test_str_2;
test_str_2.imbue(std::locale::classic());
test_str_2 << cur_tls_dir->GetBase();
// TODO: Ensure that base address is different across modules (similar to
// other tests).
}
BOOST_CHECK(processed_one_tls_dir);
}
<commit_msg>* Remove MSVC specific code.<commit_after>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#include "hadesmem/pelib/tls_dir.hpp"
#include <sstream>
#include <utility>
#define BOOST_TEST_MODULE tls_dir
#include "hadesmem/detail/warning_disable_prefix.hpp"
#include <boost/thread.hpp>
#include <boost/test/unit_test.hpp>
#include "hadesmem/detail/warning_disable_suffix.hpp"
#include "hadesmem/read.hpp"
#include "hadesmem/error.hpp"
#include "hadesmem/config.hpp"
#include "hadesmem/module.hpp"
#include "hadesmem/process.hpp"
#include "hadesmem/module_list.hpp"
#include "hadesmem/pelib/pe_file.hpp"
// Boost.Test causes the following warning under GCC:
// error: base class 'struct boost::unit_test::ut_detail::nil_t' has a
// non-virtual destructor [-Werror=effc++]
#if defined(HADESMEM_GCC)
#pragma GCC diagnostic ignored "-Weffc++"
#endif // #if defined(HADESMEM_GCC)
// Boost.Test causes the following warning under Clang:
// error: declaration requires a global constructor
// [-Werror,-Wglobal-constructors]
#if defined(HADESMEM_CLANG)
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#endif // #if defined(HADESMEM_CLANG)
BOOST_AUTO_TEST_CASE(tls_dir)
{
// Use threads and TSS to ensure that at least one module has a TLS dir
boost::thread_specific_ptr<int> tss_dummy;
tss_dummy.reset(new int(1234));
hadesmem::Process const process(::GetCurrentProcessId());
hadesmem::PeFile pe_file_1(process, GetModuleHandle(nullptr),
hadesmem::PeFileType::Image);
hadesmem::TlsDir tls_dir_1(process, pe_file_1);
hadesmem::TlsDir tls_dir_2(tls_dir_1);
BOOST_CHECK_EQUAL(tls_dir_1, tls_dir_2);
tls_dir_1 = tls_dir_2;
BOOST_CHECK_EQUAL(tls_dir_1, tls_dir_2);
hadesmem::TlsDir tls_dir_3(std::move(tls_dir_2));
BOOST_CHECK_EQUAL(tls_dir_3, tls_dir_1);
tls_dir_2 = std::move(tls_dir_3);
BOOST_CHECK_EQUAL(tls_dir_1, tls_dir_2);
bool processed_one_tls_dir = false;
hadesmem::ModuleList modules(process);
for (auto const& mod : modules)
{
// TODO: Also test FileType_Data
hadesmem::PeFile const cur_pe_file(process, mod.GetHandle(),
hadesmem::PeFileType::Data);
std::unique_ptr<hadesmem::TlsDir> cur_tls_dir;
try
{
cur_tls_dir.reset(new hadesmem::TlsDir(process, cur_pe_file));
}
catch (std::exception const& /*e*/)
{
continue;
}
processed_one_tls_dir = true;
auto const tls_dir_raw = hadesmem::Read<IMAGE_TLS_DIRECTORY>(process,
cur_tls_dir->GetBase());
cur_tls_dir->SetStartAddressOfRawData(
cur_tls_dir->GetStartAddressOfRawData());
cur_tls_dir->SetEndAddressOfRawData(cur_tls_dir->GetEndAddressOfRawData());
cur_tls_dir->SetAddressOfIndex(cur_tls_dir->GetAddressOfIndex());
cur_tls_dir->SetAddressOfCallBacks(cur_tls_dir->GetAddressOfCallBacks());
cur_tls_dir->SetSizeOfZeroFill(cur_tls_dir->GetSizeOfZeroFill());
cur_tls_dir->SetCharacteristics(cur_tls_dir->GetCharacteristics());
cur_tls_dir->GetCallbacks();
auto const tls_dir_raw_new = hadesmem::Read<IMAGE_TLS_DIRECTORY>(process,
cur_tls_dir->GetBase());
BOOST_CHECK_EQUAL(std::memcmp(&tls_dir_raw, &tls_dir_raw_new,
sizeof(tls_dir_raw)), 0);
std::stringstream test_str_1;
test_str_1.imbue(std::locale::classic());
test_str_1 << cur_tls_dir;
std::stringstream test_str_2;
test_str_2.imbue(std::locale::classic());
test_str_2 << cur_tls_dir->GetBase();
// TODO: Ensure that base address is different across modules (similar to
// other tests).
}
BOOST_CHECK(processed_one_tls_dir);
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* tests/api/io_test.cpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <thrill/api/allgather.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/generate_from_file.hpp>
#include <thrill/api/read_binary.hpp>
#include <thrill/api/read_lines.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/write_binary.hpp>
#include <thrill/api/write_lines.hpp>
#include <thrill/api/write_lines_many.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/system_exception.hpp>
#include <gtest/gtest.h>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <random>
#include <string>
#include <vector>
#include <dirent.h>
#include <glob.h>
#include <sys/stat.h>
using namespace thrill;
using thrill::api::Context;
using thrill::api::DIARef;
/*!
* A class which creates a temporary directory in /tmp/ and returns it via
* get(). When the object is destroyed the temporary directory is wiped
* non-recursively.
*/
class TemporaryDirectory
{
public:
//! Create a temporary directory, returns its name without trailing /.
static std::string make_directory(
const char* sample = "thrill-testsuite-") {
std::string tmp_dir = std::string(sample) + "XXXXXX";
// evil const_cast, but mkdtemp replaces the XXXXXX with something
// unique. it also mkdirs.
mkdtemp(const_cast<char*>(tmp_dir.c_str()));
return tmp_dir;
}
//! wipe temporary directory NON RECURSIVELY!
static void wipe_directory(const std::string& tmp_dir, bool do_rmdir) {
DIR* d = opendir(tmp_dir.c_str());
if (d == nullptr) {
throw common::SystemException(
"Could open temporary directory " + tmp_dir, errno);
}
struct dirent* de, entry;
while (readdir_r(d, &entry, &de) == 0 && de != nullptr) {
// skip ".", "..", and also hidden files (don't create them).
if (de->d_name[0] == '.') continue;
std::string path = tmp_dir + "/" + de->d_name;
int r = unlink(path.c_str());
if (r != 0)
sLOG1 << "Could not unlink temporary file " << path
<< ": " << strerror(errno);
}
closedir(d);
if (!do_rmdir) return;
if (rmdir(tmp_dir.c_str()) != 0) {
sLOG1 << "Could not unlink temporary directory " << tmp_dir
<< ": " << strerror(errno);
}
}
TemporaryDirectory()
: dir_(make_directory())
{ }
~TemporaryDirectory() {
wipe_directory(dir_, true);
}
//! non-copyable: delete copy-constructor
TemporaryDirectory(const TemporaryDirectory&) = delete;
//! non-copyable: delete assignment operator
TemporaryDirectory& operator = (const TemporaryDirectory&) = delete;
//! return the temporary directory name
const std::string & get() const { return dir_; }
//! wipe contents of directory
void wipe() const {
wipe_directory(dir_, false);
}
protected:
std::string dir_;
};
TEST(IO, ReadSingleFile) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = ReadLines(ctx, "test1")
.Map([](const std::string& line) {
return std::stoi(line);
});
std::vector<int> out_vec = integers.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_EQ(element, i++);
}
ASSERT_EQ((size_t)16, out_vec.size());
};
api::RunLocalTests(start_func);
}
TEST(IO, ReadFolder) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
ASSERT_EQ(ReadLines(ctx, "read_folder/*").Size(), 20);
};
api::RunLocalTests(start_func);
}
TEST(IO, ReadPartOfFolderCompressed) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
// folder read_ints contains compressed and non-compressed files with integers
// from 25 to 1 and a file 'donotread', which contains non int-castable
// strings
auto integers = ReadLines(ctx, "read_ints/read*")
.Map([](const std::string& line) {
return std::stoi(line);
});
std::vector<int> out_vec = integers.AllGather();
int i = 25;
for (int element : out_vec) {
ASSERT_EQ(element, i--);
}
ASSERT_EQ((size_t)25, out_vec.size());
};
api::RunLocalTests(start_func);
}
TEST(IO, GenerateFromFileRandomIntegers) {
api::RunSameThread(
[](api::Context& ctx) {
std::default_random_engine generator({ std::random_device()() });
std::uniform_int_distribution<int> distribution(1000, 10000);
size_t generate_size = distribution(generator);
auto input = GenerateFromFile(
ctx,
"test1",
[](const std::string& line) {
return std::stoi(line);
},
generate_size);
size_t writer_size = 0;
input.Map(
[&writer_size](const int& item) {
// file contains ints between 1 and 16
// fails if wrong integer is generated
EXPECT_GE(item, 1);
EXPECT_GE(16, item);
writer_size++;
return std::to_string(item) + "\n";
})
.WriteLinesMany("out1_");
// DIA contains as many elements as we wanted to generate
ASSERT_EQ(generate_size, writer_size);
});
}
TEST(IO, WriteBinaryPatternFormatter) {
using WriteBinaryNode = api::WriteBinaryNode<int, int>;
std::string str1 = WriteBinaryNode::make_path("test-$$$$-########", 42, 10);
ASSERT_EQ("test-0042-00000010", str1);
std::string str2 = WriteBinaryNode::make_path("test", 42, 10);
ASSERT_EQ("test00420000000010", str2);
}
TEST(IO, GenerateIntegerWriteReadBinary) {
TemporaryDirectory tmpdir;
api::RunLocalTests(
[&tmpdir](api::Context& ctx) {
// wipe directory from last test
if (ctx.my_rank() == 0) {
tmpdir.wipe();
}
ctx.Barrier();
// generate a dia of integers and write them to disk
size_t generate_size = 320000;
{
auto dia = Generate(
ctx,
[](const size_t index) { return index + 42; },
generate_size);
dia.WriteBinary(tmpdir.get() + "/IO.IntegerBinary",
16 * 1024);
}
ctx.Barrier();
// read the integers from disk (collectively) and compare
{
auto dia = api::ReadBinary<size_t>(
ctx,
tmpdir.get() + "/IO.IntegerBinary*");
std::vector<size_t> vec = dia.AllGather();
ASSERT_EQ(generate_size, vec.size());
// this is another action
ASSERT_EQ(generate_size, dia.Size());
for (size_t i = 0; i < vec.size(); ++i) {
ASSERT_EQ(42 + i, vec[i]);
}
}
});
}
TEST(IO, GenerateIntegerWriteReadBinaryCompressed) {
TemporaryDirectory tmpdir;
api::RunLocalTests(
[&tmpdir](api::Context& ctx) {
// wipe directory from last test
if (ctx.my_rank() == 0) {
tmpdir.wipe();
}
ctx.Barrier();
// generate a dia of integers and write them to disk
size_t generate_size = 320000;
{
auto dia = Generate(
ctx,
[](const size_t index) { return index + 42; },
generate_size);
dia.WriteBinary(tmpdir.get() + "/IO.IntegerBinary-$$$$-####.gz",
16 * 1024);
}
ctx.Barrier();
// read the integers from disk (collectively) and compare
{
auto dia = api::ReadBinary<size_t>(
ctx,
tmpdir.get() + "/IO.IntegerBinary*");
std::vector<size_t> vec = dia.AllGather();
ASSERT_EQ(generate_size, vec.size());
// this is another action
ASSERT_EQ(generate_size, dia.Size());
for (size_t i = 0; i < vec.size(); ++i) {
ASSERT_EQ(42 + i, vec[i]);
}
}
});
}
// make weird test strings of different lengths
std::string test_string(size_t index) {
return std::string('0' + index % 100, (index * index) % 20);
}
TEST(IO, GenerateStringWriteBinary) {
TemporaryDirectory tmpdir;
// use pairs for easier checking and stranger string sizes.
using Item = std::pair<size_t, std::string>;
api::RunLocalTests(
[&tmpdir](api::Context& ctx) {
// wipe directory from last test
if (ctx.my_rank() == 0) {
tmpdir.wipe();
}
ctx.Barrier();
// generate a dia of string Items and write them to disk
size_t generate_size = 320000;
{
auto dia = Generate(
ctx,
[](const size_t index) {
return Item(index, test_string(index));
},
generate_size);
dia.WriteBinary(tmpdir.get() + "/IO.StringBinary",
16 * 1024);
}
ctx.Barrier();
// read the Items from disk (collectively) and compare
{
auto dia = api::ReadBinary<Item>(
ctx,
tmpdir.get() + "/IO.StringBinary*");
std::vector<Item> vec = dia.AllGather();
ASSERT_EQ(generate_size, vec.size());
// this is another action
ASSERT_EQ(generate_size, dia.Size());
for (size_t i = 0; i < vec.size(); ++i) {
ASSERT_EQ(Item(i, test_string(i)), vec[i]);
}
}
});
}
TEST(IO, WriteAndReadBinaryEqualDIAS) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
if (ctx.my_rank() == 0) {
std::system("rm -r ./binary/*");
}
ctx.Barrier();
auto integers = ReadLines(ctx, "test1")
.Map([](const std::string& line) {
return std::stoi(line);
});
integers.WriteBinary("binary/output_");
std::string path = "testsf.out";
ctx.Barrier();
auto integers2 = api::ReadBinary<int>(
ctx, "./binary/*");
integers2.Map(
[](const int& item) {
return std::to_string(item);
})
.WriteLines(path);
// Race condition as one worker might be finished while others are
// still writing to output file.
ctx.Barrier();
std::ifstream file(path);
size_t begin = file.tellg();
file.seekg(0, std::ios::end);
size_t end = file.tellg();
ASSERT_EQ(end - begin, 39);
file.seekg(0);
for (int i = 1; i <= 16; i++) {
std::string line;
std::getline(file, line);
ASSERT_EQ(std::stoi(line), i);
}
};
api::RunLocalTests(start_func);
}
/******************************************************************************/
<commit_msg>Resize IO-Tests from 320k to 32k<commit_after>/*******************************************************************************
* tests/api/io_test.cpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Alexander Noe <aleexnoe@gmail.com>
* Copyright (C) 2015 Timo Bingmann <tb@panthema.net>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#include <thrill/api/allgather.hpp>
#include <thrill/api/generate.hpp>
#include <thrill/api/generate_from_file.hpp>
#include <thrill/api/read_binary.hpp>
#include <thrill/api/read_lines.hpp>
#include <thrill/api/size.hpp>
#include <thrill/api/write_binary.hpp>
#include <thrill/api/write_lines.hpp>
#include <thrill/api/write_lines_many.hpp>
#include <thrill/common/logger.hpp>
#include <thrill/common/system_exception.hpp>
#include <gtest/gtest.h>
#include <algorithm>
#include <cstdlib>
#include <functional>
#include <random>
#include <string>
#include <vector>
#include <dirent.h>
#include <glob.h>
#include <sys/stat.h>
using namespace thrill;
using thrill::api::Context;
using thrill::api::DIARef;
/*!
* A class which creates a temporary directory in /tmp/ and returns it via
* get(). When the object is destroyed the temporary directory is wiped
* non-recursively.
*/
class TemporaryDirectory
{
public:
//! Create a temporary directory, returns its name without trailing /.
static std::string make_directory(
const char* sample = "thrill-testsuite-") {
std::string tmp_dir = std::string(sample) + "XXXXXX";
// evil const_cast, but mkdtemp replaces the XXXXXX with something
// unique. it also mkdirs.
mkdtemp(const_cast<char*>(tmp_dir.c_str()));
return tmp_dir;
}
//! wipe temporary directory NON RECURSIVELY!
static void wipe_directory(const std::string& tmp_dir, bool do_rmdir) {
DIR* d = opendir(tmp_dir.c_str());
if (d == nullptr) {
throw common::SystemException(
"Could open temporary directory " + tmp_dir, errno);
}
struct dirent* de, entry;
while (readdir_r(d, &entry, &de) == 0 && de != nullptr) {
// skip ".", "..", and also hidden files (don't create them).
if (de->d_name[0] == '.') continue;
std::string path = tmp_dir + "/" + de->d_name;
int r = unlink(path.c_str());
if (r != 0)
sLOG1 << "Could not unlink temporary file " << path
<< ": " << strerror(errno);
}
closedir(d);
if (!do_rmdir) return;
if (rmdir(tmp_dir.c_str()) != 0) {
sLOG1 << "Could not unlink temporary directory " << tmp_dir
<< ": " << strerror(errno);
}
}
TemporaryDirectory()
: dir_(make_directory())
{ }
~TemporaryDirectory() {
wipe_directory(dir_, true);
}
//! non-copyable: delete copy-constructor
TemporaryDirectory(const TemporaryDirectory&) = delete;
//! non-copyable: delete assignment operator
TemporaryDirectory& operator = (const TemporaryDirectory&) = delete;
//! return the temporary directory name
const std::string & get() const { return dir_; }
//! wipe contents of directory
void wipe() const {
wipe_directory(dir_, false);
}
protected:
std::string dir_;
};
TEST(IO, ReadSingleFile) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
auto integers = ReadLines(ctx, "test1")
.Map([](const std::string& line) {
return std::stoi(line);
});
std::vector<int> out_vec = integers.AllGather();
int i = 1;
for (int element : out_vec) {
ASSERT_EQ(element, i++);
}
ASSERT_EQ((size_t)16, out_vec.size());
};
api::RunLocalTests(start_func);
}
TEST(IO, ReadFolder) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
ASSERT_EQ(ReadLines(ctx, "read_folder/*").Size(), 20);
};
api::RunLocalTests(start_func);
}
TEST(IO, ReadPartOfFolderCompressed) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
// folder read_ints contains compressed and non-compressed files with integers
// from 25 to 1 and a file 'donotread', which contains non int-castable
// strings
auto integers = ReadLines(ctx, "read_ints/read*")
.Map([](const std::string& line) {
return std::stoi(line);
});
std::vector<int> out_vec = integers.AllGather();
int i = 25;
for (int element : out_vec) {
ASSERT_EQ(element, i--);
}
ASSERT_EQ((size_t)25, out_vec.size());
};
api::RunLocalTests(start_func);
}
TEST(IO, GenerateFromFileRandomIntegers) {
api::RunSameThread(
[](api::Context& ctx) {
std::default_random_engine generator({ std::random_device()() });
std::uniform_int_distribution<int> distribution(1000, 10000);
size_t generate_size = distribution(generator);
auto input = GenerateFromFile(
ctx,
"test1",
[](const std::string& line) {
return std::stoi(line);
},
generate_size);
size_t writer_size = 0;
input.Map(
[&writer_size](const int& item) {
// file contains ints between 1 and 16
// fails if wrong integer is generated
EXPECT_GE(item, 1);
EXPECT_GE(16, item);
writer_size++;
return std::to_string(item) + "\n";
})
.WriteLinesMany("out1_");
// DIA contains as many elements as we wanted to generate
ASSERT_EQ(generate_size, writer_size);
});
}
TEST(IO, WriteBinaryPatternFormatter) {
using WriteBinaryNode = api::WriteBinaryNode<int, int>;
std::string str1 = WriteBinaryNode::make_path("test-$$$$-########", 42, 10);
ASSERT_EQ("test-0042-00000010", str1);
std::string str2 = WriteBinaryNode::make_path("test", 42, 10);
ASSERT_EQ("test00420000000010", str2);
}
TEST(IO, GenerateIntegerWriteReadBinary) {
TemporaryDirectory tmpdir;
api::RunLocalTests(
[&tmpdir](api::Context& ctx) {
// wipe directory from last test
if (ctx.my_rank() == 0) {
tmpdir.wipe();
}
ctx.Barrier();
// generate a dia of integers and write them to disk
size_t generate_size = 32000;
{
auto dia = Generate(
ctx,
[](const size_t index) { return index + 42; },
generate_size);
dia.WriteBinary(tmpdir.get() + "/IO.IntegerBinary",
16 * 1024);
}
ctx.Barrier();
// read the integers from disk (collectively) and compare
{
auto dia = api::ReadBinary<size_t>(
ctx,
tmpdir.get() + "/IO.IntegerBinary*");
std::vector<size_t> vec = dia.AllGather();
ASSERT_EQ(generate_size, vec.size());
// this is another action
ASSERT_EQ(generate_size, dia.Size());
for (size_t i = 0; i < vec.size(); ++i) {
ASSERT_EQ(42 + i, vec[i]);
}
}
});
}
TEST(IO, GenerateIntegerWriteReadBinaryCompressed) {
TemporaryDirectory tmpdir;
api::RunLocalTests(
[&tmpdir](api::Context& ctx) {
// wipe directory from last test
if (ctx.my_rank() == 0) {
tmpdir.wipe();
}
ctx.Barrier();
// generate a dia of integers and write them to disk
size_t generate_size = 32000;
{
auto dia = Generate(
ctx,
[](const size_t index) { return index + 42; },
generate_size);
dia.WriteBinary(tmpdir.get() + "/IO.IntegerBinary-$$$$-####.gz",
16 * 1024);
}
ctx.Barrier();
// read the integers from disk (collectively) and compare
{
auto dia = api::ReadBinary<size_t>(
ctx,
tmpdir.get() + "/IO.IntegerBinary*");
std::vector<size_t> vec = dia.AllGather();
ASSERT_EQ(generate_size, vec.size());
// this is another action
ASSERT_EQ(generate_size, dia.Size());
for (size_t i = 0; i < vec.size(); ++i) {
ASSERT_EQ(42 + i, vec[i]);
}
}
});
}
// make weird test strings of different lengths
std::string test_string(size_t index) {
return std::string('0' + index % 100, (index * index) % 20);
}
TEST(IO, GenerateStringWriteBinary) {
TemporaryDirectory tmpdir;
// use pairs for easier checking and stranger string sizes.
using Item = std::pair<size_t, std::string>;
api::RunLocalTests(
[&tmpdir](api::Context& ctx) {
// wipe directory from last test
if (ctx.my_rank() == 0) {
tmpdir.wipe();
}
ctx.Barrier();
// generate a dia of string Items and write them to disk
size_t generate_size = 32000;
{
auto dia = Generate(
ctx,
[](const size_t index) {
return Item(index, test_string(index));
},
generate_size);
dia.WriteBinary(tmpdir.get() + "/IO.StringBinary",
16 * 1024);
}
ctx.Barrier();
// read the Items from disk (collectively) and compare
{
auto dia = api::ReadBinary<Item>(
ctx,
tmpdir.get() + "/IO.StringBinary*");
std::vector<Item> vec = dia.AllGather();
ASSERT_EQ(generate_size, vec.size());
// this is another action
ASSERT_EQ(generate_size, dia.Size());
for (size_t i = 0; i < vec.size(); ++i) {
ASSERT_EQ(Item(i, test_string(i)), vec[i]);
}
}
});
}
TEST(IO, WriteAndReadBinaryEqualDIAS) {
std::function<void(Context&)> start_func =
[](Context& ctx) {
if (ctx.my_rank() == 0) {
std::system("rm -r ./binary/*");
}
ctx.Barrier();
auto integers = ReadLines(ctx, "test1")
.Map([](const std::string& line) {
return std::stoi(line);
});
integers.WriteBinary("binary/output_");
std::string path = "testsf.out";
ctx.Barrier();
auto integers2 = api::ReadBinary<int>(
ctx, "./binary/*");
integers2.Map(
[](const int& item) {
return std::to_string(item);
})
.WriteLines(path);
// Race condition as one worker might be finished while others are
// still writing to output file.
ctx.Barrier();
std::ifstream file(path);
size_t begin = file.tellg();
file.seekg(0, std::ios::end);
size_t end = file.tellg();
ASSERT_EQ(end - begin, 39);
file.seekg(0);
for (int i = 1; i <= 16; i++) {
std::string line;
std::getline(file, line);
ASSERT_EQ(std::stoi(line), i);
}
};
api::RunLocalTests(start_func);
}
/******************************************************************************/
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "phonebookcell.h"
#include <MLabel>
#include <MLayout>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MImageWidget>
#include <MProgressIndicator>
PhoneBookCell::PhoneBookCell()
: MListItem(),
layout(NULL),
titleLabel(NULL),
subtitleLabel(NULL),
imageWidget(NULL)
{
}
PhoneBookCell::~PhoneBookCell()
{
}
void PhoneBookCell::initLayout()
{
setLayout(createLayout());
}
MLayout *PhoneBookCell::createLayout()
{
layout = new MLayout(this);
landscapePolicy = new MGridLayoutPolicy(layout);
landscapePolicy->setContentsMargins(0, 0, 0, 0);
landscapePolicy->setSpacing(0);
// title
titleLabel = new MLabel(this);
titleLabel->setTextElide(true);
titleLabel->setObjectName("CommonTitle");
// subtitle
subtitleLabel = new MLabel(this);
subtitleLabel->setTextElide(true);
subtitleLabel->setObjectName("CommonSubTitle");
// icon
imageWidget = new MImageWidget(this);
imageWidget->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
imageWidget->setObjectName("CommonMainIcon");
imageWidget->setVisible(false);
// spinner
spinner = new MProgressIndicator(this, MProgressIndicator::spinnerType);
spinner->setSizePolicy(QSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed));
spinner->setUnknownDuration(true);
spinner->setObjectName("CommonMainIcon");
// add to layout
landscapePolicy->addItem(spinner, 0, 0, 4, 1);
landscapePolicy->addItem(titleLabel, 1, 1, Qt::AlignTop);
landscapePolicy->addItem(subtitleLabel, 2, 1);
landscapePolicy->addItem(new QGraphicsWidget(), 3, 1);
portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal);
portraitPolicy->setContentsMargins(0, 0, 0, 0);
portraitPolicy->setSpacing(0);
portraitPolicy->addItem(spinner);
portraitPolicy->addItem(titleLabel);
layout->setPortraitPolicy(portraitPolicy);
layout->setLandscapePolicy(landscapePolicy);
return layout;
}
QString PhoneBookCell::title() const
{
return titleLabel->text();
}
void PhoneBookCell::setTitle(const QString &title)
{
titleLabel->setText(title);
}
QString PhoneBookCell::subtitle() const
{
return subtitleLabel->text();
}
void PhoneBookCell::setSubtitle(const QString &subtitle)
{
subtitleLabel->setText(subtitle);
}
QImage PhoneBookCell::image() const
{
return imageWidget->pixmap()->toImage();
}
void PhoneBookCell::setImage(const QImage &image)
{
imageWidget->setImage(image);
imageWidget->setVisible(true);
if (layout->policy() == landscapePolicy) {
if (landscapePolicy->itemAt(0, 0) == spinner && !image.isNull()) {
landscapePolicy->removeItem(spinner);
landscapePolicy->addItem(imageWidget, 0, 0, 4, 1);
} else if (landscapePolicy->itemAt(0, 0) == imageWidget && image.isNull()) {
landscapePolicy->removeItem(imageWidget);
landscapePolicy->addItem(spinner, 0, 0, 4, 1);
}
} else if (layout->policy() == portraitPolicy) {
if (portraitPolicy->itemAt(0) == imageWidget && image.isNull()) {
portraitPolicy->removeAt(0);
portraitPolicy->insertItem(0, spinner, Qt::AlignLeft);
} else if (portraitPolicy->itemAt(0) == spinner && !image.isNull()) {
portraitPolicy->removeAt(0);
portraitPolicy->insertItem(0, imageWidget, Qt::AlignLeft);
}
}
}
<commit_msg>Changes: Layout fixes and optimizaton of phonebookcell in WidgetsGallery.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libmeegotouch.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "phonebookcell.h"
#include <MLabel>
#include <MLayout>
#include <MGridLayoutPolicy>
#include <MLinearLayoutPolicy>
#include <MImageWidget>
#include <MProgressIndicator>
PhoneBookCell::PhoneBookCell()
: MListItem(),
layout(NULL),
titleLabel(NULL),
subtitleLabel(NULL),
imageWidget(NULL)
{
}
PhoneBookCell::~PhoneBookCell()
{
}
void PhoneBookCell::initLayout()
{
setLayout(createLayout());
}
MLayout *PhoneBookCell::createLayout()
{
setObjectName("BasicListItemIconWithTitleAndSubtitle");
layout = new MLayout(this);
layout->setContentsMargins(0, 0, 0, 0);
layout->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
landscapePolicy = new MGridLayoutPolicy(layout);
landscapePolicy->setContentsMargins(0, 0, 0, 0);
landscapePolicy->setSpacing(0);
// title
titleLabel = new MLabel(this);
titleLabel->setTextElide(true);
titleLabel->setObjectName("CommonTitleWithLeftMargin");
// subtitle
subtitleLabel = new MLabel(this);
subtitleLabel->setTextElide(true);
subtitleLabel->setObjectName("CommonSubTitleWithLeftMargin");
// icon
imageWidget = new MImageWidget(this);
imageWidget->setObjectName("CommonMainIcon");
imageWidget->setVisible(false);
// spinner
spinner = new MProgressIndicator(this, MProgressIndicator::spinnerType);
spinner->setUnknownDuration(true);
spinner->setObjectName("CommonMainIcon");
// add to layout
landscapePolicy->addItem(spinner, 0, 0, 2, 1, Qt::AlignLeft | Qt::AlignVCenter);
landscapePolicy->addItem(titleLabel, 0, 1, Qt::AlignLeft | Qt::AlignTop);
landscapePolicy->addItem(subtitleLabel, 1, 1, Qt::AlignLeft | Qt::AlignBottom);
portraitPolicy = new MLinearLayoutPolicy(layout, Qt::Horizontal);
portraitPolicy->setContentsMargins(0, 0, 0, 0);
portraitPolicy->setSpacing(0);
portraitPolicy->addItem(spinner, Qt::AlignLeft | Qt::AlignVCenter);
portraitPolicy->addItem(titleLabel, Qt::AlignLeft | Qt::AlignVCenter);
layout->setPortraitPolicy(portraitPolicy);
layout->setLandscapePolicy(landscapePolicy);
return layout;
}
QString PhoneBookCell::title() const
{
return titleLabel->text();
}
void PhoneBookCell::setTitle(const QString &title)
{
titleLabel->setText(title);
}
QString PhoneBookCell::subtitle() const
{
return subtitleLabel->text();
}
void PhoneBookCell::setSubtitle(const QString &subtitle)
{
subtitleLabel->setText(subtitle);
}
QImage PhoneBookCell::image() const
{
return imageWidget->pixmap()->toImage();
}
void PhoneBookCell::setImage(const QImage &image)
{
if (image.isNull() || imageWidget->image().isEmpty()) {
if (layout->policy() == landscapePolicy) {
if (landscapePolicy->itemAt(0, 0) == spinner && !image.isNull()) {
landscapePolicy->removeItem(spinner);
landscapePolicy->addItem(imageWidget, 0, 0, 2, 1, Qt::AlignLeft | Qt::AlignVCenter);
} else if (landscapePolicy->itemAt(0, 0) == imageWidget && image.isNull()) {
landscapePolicy->removeItem(imageWidget);
landscapePolicy->addItem(spinner, 0, 0, 2, 1, Qt::AlignLeft | Qt::AlignVCenter);
}
} else if (layout->policy() == portraitPolicy) {
if (portraitPolicy->itemAt(0) == imageWidget && image.isNull()) {
portraitPolicy->removeAt(0);
portraitPolicy->insertItem(0, spinner, Qt::AlignLeft | Qt::AlignVCenter);
} else if (portraitPolicy->itemAt(0) == spinner && !image.isNull()) {
portraitPolicy->removeAt(0);
portraitPolicy->insertItem(0, imageWidget, Qt::AlignLeft | Qt::AlignVCenter);
}
}
}
if (!image.isNull()) {
imageWidget->setImage(image);
imageWidget->setVisible(true);
}
}
<|endoftext|> |
<commit_before>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include "Core.h"
#include "TcpServer.h"
#include "Tcp.h"
#include "VariableTracing.h"
#include "Log.h"
#include "Context.h"
#include "Capture.h"
#include "OrbitAsio.h"
#include "Callstack.h"
#include "SamplingProfiler.h"
#include "TimerManager.h"
#include "OrbitUnreal.h"
#include "OrbitProcess.h"
#include "ConnectionManager.h"
#include <thread>
TcpServer* GTcpServer;
//-----------------------------------------------------------------------------
TcpServer::TcpServer() : m_TcpServer(nullptr)
{
PRINT_FUNC;
m_LastNumMessages = 0;
m_LastNumBytes = 0;
m_NumReceivedMessages = 0;
m_NumMessagesPerSecond = 0;
m_BytesPerSecond = 0;
m_MaxTimersAtOnce = 0;
m_NumTimersAtOnce = 0;
m_NumTargetQueuedEntries = 0;
m_NumTargetFlushedEntries = 0;
m_NumTargetFlushedTcpPackets = 0;
m_NumMessagesFromPreviousSession = 0;
}
//-----------------------------------------------------------------------------
TcpServer::~TcpServer()
{
delete m_TcpServer;
}
//-----------------------------------------------------------------------------
void TcpServer::Start( unsigned short a_Port )
{
TcpEntity::Start();
PRINT_FUNC;
m_TcpService = new TcpService();
m_TcpServer = new tcp_server( *m_TcpService->m_IoService, a_Port );
PRINT_VAR(a_Port);
std::thread t([&](){ this->ServerThread(); });
t.detach();
m_StatTimer.Start();
m_IsValid = true;
}
//-----------------------------------------------------------------------------
void TcpServer::ResetStats()
{
m_NumReceivedMessages = 0;
if(m_TcpServer)
m_TcpServer->ResetStats();
}
//-----------------------------------------------------------------------------
std::vector<std::string> TcpServer::GetStats()
{
std::vector<std::string> stats;
stats.push_back( VAR_TO_ANSI( m_NumReceivedMessages ) );
stats.push_back( VAR_TO_ANSI( m_NumMessagesPerSecond ) );
std::string bytesRcv = "Capture::GNumBytesReceiced = " + ws2s( GetPrettySize( m_TcpServer->GetNumBytesReceived() ) ) + "\n";
stats.push_back( bytesRcv );
std::string bitRate = "Capture::Bitrate = "
+ ws2s( GetPrettySize( (ULONG64)m_BytesPerSecond ) )
+ "/s"
+ " ( " + GetPrettyBitRate( (ULONG64)m_BytesPerSecond ) + " )\n";
stats.push_back( bitRate );
return stats;
}
//-----------------------------------------------------------------------------
TcpSocket* TcpServer::GetSocket()
{
return m_TcpServer->GetSocket();
}
//-----------------------------------------------------------------------------
void TcpServer::Receive( const Message & a_Message )
{
PRINT_FUNC;
const Message::Header & MessageHeader = a_Message.GetHeader();
++m_NumReceivedMessages;
// Disregard messages from previous session
// TODO: Take care of the IsRemote case
if( !ConnectionManager::Get().IsRemote() && a_Message.m_SessionID != Message::GSessionID )
{
++m_NumMessagesFromPreviousSession;
return;
}
PRINT_VAR(a_Message.GetType());
switch (a_Message.GetType())
{
case Msg_String:
{
const char* msg = a_Message.GetData();
std::cout << msg << std::endl;
PRINT_VAR(msg);
break;
}
case Msg_Timer:
{
uint32_t numTimers = (uint32_t)a_Message.m_Size/sizeof(Timer);
Timer* timers = (Timer*)a_Message.GetData();
for (uint32_t i = 0; i < numTimers; ++i)
{
GTimerManager->Add(timers[i]);
}
if( numTimers > m_MaxTimersAtOnce )
{
m_MaxTimersAtOnce = numTimers;
}
m_NumTimersAtOnce = numTimers;
break;
}
case Msg_NumQueuedEntries:
m_NumTargetQueuedEntries = *((uint32_t*)a_Message.GetData());
break;
case Msg_NumFlushedEntries:
m_NumTargetFlushedEntries = *((uint32_t*)a_Message.GetData());
break;
case Msg_NumFlushedItems:
m_NumTargetFlushedTcpPackets = *( (uint32_t*)a_Message.GetData() );
break;
case Msg_NumInstalledHooks:
Capture::GNumInstalledHooks = *((uint32_t*)a_Message.GetData());
break;
case Msg_Callstack:
{
CallStackPOD* callstackPOD = (CallStackPOD*)a_Message.GetData();
CallStack callstack(*callstackPOD);
Capture::AddCallstack( callstack );
break;
}
case Msg_OrbitZoneName:
{
OrbitZoneName* zoneName = (OrbitZoneName*)a_Message.GetData();
Capture::RegisterZoneName( zoneName->m_Address, zoneName->m_Data );
break;
}
case Msg_OrbitUnrealObject:
{
const UnrealObjectHeader & header = MessageHeader.m_UnrealObjectHeader;
std::wstring & objectName = GOrbitUnreal.GetObjectNames()[header.m_Ptr];
if( header.m_WideStr )
{
objectName = (wchar_t*)a_Message.GetData();
}
else
{
objectName = s2ws( (char*)a_Message.GetData() );
}
break;
}
case Msg_ThreadInfo:
{
std::wstring threadName((wchar_t*)a_Message.GetData());
Capture::GTargetProcess->SetThreadName(a_Message.m_ThreadId, threadName);
PRINT_VAR(threadName);
break;
}
default:
{
Callback(a_Message);
break;
}
}
}
//-----------------------------------------------------------------------------
void TcpServer::SendToUiAsync( const std::wstring & a_Message )
{
if( m_UiCallback )
{
m_UiLockFreeQueue.enqueue( a_Message );
}
}
//-----------------------------------------------------------------------------
void TcpServer::SendToUiNow( const std::wstring & a_Message )
{
if( m_UiCallback )
{
m_UiCallback( a_Message );
}
}
//-----------------------------------------------------------------------------
void TcpServer::MainThreadTick()
{
std::wstring msg;
while( m_UiLockFreeQueue.try_dequeue( msg ) )
{
m_UiCallback( msg );
}
static double period = 500.0;
double elapsedTime = m_StatTimer.QueryMillis();
if( elapsedTime > period )
{
m_NumMessagesPerSecond = ((double)(m_NumReceivedMessages - m_LastNumMessages))/(elapsedTime*0.001);
m_LastNumMessages = m_NumReceivedMessages;
uint64_t numBytesReceived = m_TcpServer ? m_TcpServer->GetNumBytesReceived() : 0;
m_BytesPerSecond = (double( numBytesReceived - m_LastNumBytes))/(elapsedTime*0.001);
m_LastNumBytes = numBytesReceived;
m_StatTimer.Reset();
}
if( !Capture::IsRemote() && Capture::GInjected && Capture::IsCapturing() )
{
TcpSocket* socket = GetSocket();
if( socket == nullptr || !socket->m_Socket || !socket->m_Socket->is_open() )
{
Capture::StopCapture();
}
}
}
//-----------------------------------------------------------------------------
bool TcpServer::IsLocalConnection()
{
TcpSocket* socket = GetSocket();
if( socket != nullptr && socket->m_Socket )
{
std::string endPoint = socket->m_Socket->remote_endpoint().address().to_string();
if( endPoint == "127.0.0.1" || ToLower( endPoint ) == "localhost" )
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
void TcpServer::Disconnect()
{
PRINT_FUNC;
m_TcpServer->Disconnect();
}
//-----------------------------------------------------------------------------
bool TcpServer::HasConnection()
{
return m_TcpServer->HasConnection();
}
//-----------------------------------------------------------------------------
void TcpServer::ServerThread()
{
PRINT_FUNC;
SetCurrentThreadName(L"TcpServer");
m_TcpService->m_IoService->run();
}
<commit_msg>Removed log in TcpServer.<commit_after>//-----------------------------------
// Copyright Pierric Gimmig 2013-2017
//-----------------------------------
#include "Core.h"
#include "TcpServer.h"
#include "Tcp.h"
#include "VariableTracing.h"
#include "Log.h"
#include "Context.h"
#include "Capture.h"
#include "OrbitAsio.h"
#include "Callstack.h"
#include "SamplingProfiler.h"
#include "TimerManager.h"
#include "OrbitUnreal.h"
#include "OrbitProcess.h"
#include "ConnectionManager.h"
#include <thread>
TcpServer* GTcpServer;
//-----------------------------------------------------------------------------
TcpServer::TcpServer() : m_TcpServer(nullptr)
{
PRINT_FUNC;
m_LastNumMessages = 0;
m_LastNumBytes = 0;
m_NumReceivedMessages = 0;
m_NumMessagesPerSecond = 0;
m_BytesPerSecond = 0;
m_MaxTimersAtOnce = 0;
m_NumTimersAtOnce = 0;
m_NumTargetQueuedEntries = 0;
m_NumTargetFlushedEntries = 0;
m_NumTargetFlushedTcpPackets = 0;
m_NumMessagesFromPreviousSession = 0;
}
//-----------------------------------------------------------------------------
TcpServer::~TcpServer()
{
delete m_TcpServer;
}
//-----------------------------------------------------------------------------
void TcpServer::Start( unsigned short a_Port )
{
TcpEntity::Start();
PRINT_FUNC;
m_TcpService = new TcpService();
m_TcpServer = new tcp_server( *m_TcpService->m_IoService, a_Port );
PRINT_VAR(a_Port);
std::thread t([&](){ this->ServerThread(); });
t.detach();
m_StatTimer.Start();
m_IsValid = true;
}
//-----------------------------------------------------------------------------
void TcpServer::ResetStats()
{
m_NumReceivedMessages = 0;
if(m_TcpServer)
m_TcpServer->ResetStats();
}
//-----------------------------------------------------------------------------
std::vector<std::string> TcpServer::GetStats()
{
std::vector<std::string> stats;
stats.push_back( VAR_TO_ANSI( m_NumReceivedMessages ) );
stats.push_back( VAR_TO_ANSI( m_NumMessagesPerSecond ) );
std::string bytesRcv = "Capture::GNumBytesReceiced = " + ws2s( GetPrettySize( m_TcpServer->GetNumBytesReceived() ) ) + "\n";
stats.push_back( bytesRcv );
std::string bitRate = "Capture::Bitrate = "
+ ws2s( GetPrettySize( (ULONG64)m_BytesPerSecond ) )
+ "/s"
+ " ( " + GetPrettyBitRate( (ULONG64)m_BytesPerSecond ) + " )\n";
stats.push_back( bitRate );
return stats;
}
//-----------------------------------------------------------------------------
TcpSocket* TcpServer::GetSocket()
{
return m_TcpServer->GetSocket();
}
//-----------------------------------------------------------------------------
void TcpServer::Receive( const Message & a_Message )
{
PRINT_FUNC;
const Message::Header & MessageHeader = a_Message.GetHeader();
++m_NumReceivedMessages;
// Disregard messages from previous session
// TODO: Take care of the IsRemote case
if( !ConnectionManager::Get().IsRemote() && a_Message.m_SessionID != Message::GSessionID )
{
++m_NumMessagesFromPreviousSession;
return;
}
switch (a_Message.GetType())
{
case Msg_String:
{
const char* msg = a_Message.GetData();
std::cout << msg << std::endl;
PRINT_VAR(msg);
break;
}
case Msg_Timer:
{
uint32_t numTimers = (uint32_t)a_Message.m_Size/sizeof(Timer);
Timer* timers = (Timer*)a_Message.GetData();
for (uint32_t i = 0; i < numTimers; ++i)
{
GTimerManager->Add(timers[i]);
}
if( numTimers > m_MaxTimersAtOnce )
{
m_MaxTimersAtOnce = numTimers;
}
m_NumTimersAtOnce = numTimers;
break;
}
case Msg_NumQueuedEntries:
m_NumTargetQueuedEntries = *((uint32_t*)a_Message.GetData());
break;
case Msg_NumFlushedEntries:
m_NumTargetFlushedEntries = *((uint32_t*)a_Message.GetData());
break;
case Msg_NumFlushedItems:
m_NumTargetFlushedTcpPackets = *( (uint32_t*)a_Message.GetData() );
break;
case Msg_NumInstalledHooks:
Capture::GNumInstalledHooks = *((uint32_t*)a_Message.GetData());
break;
case Msg_Callstack:
{
CallStackPOD* callstackPOD = (CallStackPOD*)a_Message.GetData();
CallStack callstack(*callstackPOD);
Capture::AddCallstack( callstack );
break;
}
case Msg_OrbitZoneName:
{
OrbitZoneName* zoneName = (OrbitZoneName*)a_Message.GetData();
Capture::RegisterZoneName( zoneName->m_Address, zoneName->m_Data );
break;
}
case Msg_OrbitUnrealObject:
{
const UnrealObjectHeader & header = MessageHeader.m_UnrealObjectHeader;
std::wstring & objectName = GOrbitUnreal.GetObjectNames()[header.m_Ptr];
if( header.m_WideStr )
{
objectName = (wchar_t*)a_Message.GetData();
}
else
{
objectName = s2ws( (char*)a_Message.GetData() );
}
break;
}
case Msg_ThreadInfo:
{
std::wstring threadName((wchar_t*)a_Message.GetData());
Capture::GTargetProcess->SetThreadName(a_Message.m_ThreadId, threadName);
PRINT_VAR(threadName);
break;
}
default:
{
Callback(a_Message);
break;
}
}
}
//-----------------------------------------------------------------------------
void TcpServer::SendToUiAsync( const std::wstring & a_Message )
{
if( m_UiCallback )
{
m_UiLockFreeQueue.enqueue( a_Message );
}
}
//-----------------------------------------------------------------------------
void TcpServer::SendToUiNow( const std::wstring & a_Message )
{
if( m_UiCallback )
{
m_UiCallback( a_Message );
}
}
//-----------------------------------------------------------------------------
void TcpServer::MainThreadTick()
{
std::wstring msg;
while( m_UiLockFreeQueue.try_dequeue( msg ) )
{
m_UiCallback( msg );
}
static double period = 500.0;
double elapsedTime = m_StatTimer.QueryMillis();
if( elapsedTime > period )
{
m_NumMessagesPerSecond = ((double)(m_NumReceivedMessages - m_LastNumMessages))/(elapsedTime*0.001);
m_LastNumMessages = m_NumReceivedMessages;
uint64_t numBytesReceived = m_TcpServer ? m_TcpServer->GetNumBytesReceived() : 0;
m_BytesPerSecond = (double( numBytesReceived - m_LastNumBytes))/(elapsedTime*0.001);
m_LastNumBytes = numBytesReceived;
m_StatTimer.Reset();
}
if( !Capture::IsRemote() && Capture::GInjected && Capture::IsCapturing() )
{
TcpSocket* socket = GetSocket();
if( socket == nullptr || !socket->m_Socket || !socket->m_Socket->is_open() )
{
Capture::StopCapture();
}
}
}
//-----------------------------------------------------------------------------
bool TcpServer::IsLocalConnection()
{
TcpSocket* socket = GetSocket();
if( socket != nullptr && socket->m_Socket )
{
std::string endPoint = socket->m_Socket->remote_endpoint().address().to_string();
if( endPoint == "127.0.0.1" || ToLower( endPoint ) == "localhost" )
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
void TcpServer::Disconnect()
{
PRINT_FUNC;
m_TcpServer->Disconnect();
}
//-----------------------------------------------------------------------------
bool TcpServer::HasConnection()
{
return m_TcpServer->HasConnection();
}
//-----------------------------------------------------------------------------
void TcpServer::ServerThread()
{
PRINT_FUNC;
SetCurrentThreadName(L"TcpServer");
m_TcpService->m_IoService->run();
}
<|endoftext|> |
<commit_before>#include "roomsreader.h"
RRNode::RRNode(TiXmlElement *root)
{
this->root = root;
gotoRoot();
}
RRNode::~RRNode()
{
}
RRNode *RRNode::gotoElement(string name)
{
cursor = findElement(root, name);
}
RRNode *RRNode::gotoRoot()
{
cursor = root;
return this;
}
RRNode *RRNode::gotoChild(string name)
{
cursor = cursor->FirstChildElement(name.c_str());
return this;
}
RRNode *RRNode::gotoParent()
{
cursor = cursor->Parent()->ToElement();
return this;
}
RRNode *RRNode::gotoNext()
{
cursor = cursor->NextSiblingElement(cursor->Value());
return this;
}
bool RRNode::isNull()
{
return cursor;
}
int RRNode::attrInt(string name)
{
int tmp = 0;
cursor->QueryIntAttribute(name.c_str(), &tmp);
return tmp;
}
float RRNode::attrFloat(string name)
{
float tmp = 0.0;
cursor->QueryFloatAttribute(name.c_str(), &tmp);
return tmp;
}
string RRNode::attrStr(string name)
{
return cursor->Attribute(name.c_str());
}
Event *RRNode::fetchEvent()
{
if (isNull()) return 0;
Event *event = new Event(attrStr("id"));
for (gotoChild("item_req"); !isNull(); gotoNext())
event->addItemReq(attrStr("id"), attrStr("value"));
gotoParent();
for (gotoChild("var_req"); !isNull(); gotoNext())
event->addVarReq(attrStr("id"), attrInt("value"));
gotoParent();
for (gotoChild("action"); !isNull(); gotoNext())
{
Action *act = event->addAction(attrStr("id"));
for (gotoChild("param"); isNull(); gotoNext())
act->pushParam(attrStr("value"));
gotoParent();
}
gotoParent();
return event;
}
Room *RRNode::fetchRoom()
{
if (isNull()) return 0;
Room *room = new Room(attrStr("id"));
room->bg(attrStr("bg"));
for (gotoChild("area"); !isNull(); gotoNext())
{
Area *area = room->addArea(attrStr("id"));
area->size(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height"));
area->setEvent(attrStr("event"));
}
gotoParent();
return room;
}
Item *RRNode::fetchItem()
{
if (isNull()) return 0;
Item *item = new Item(attrStr("id"));
item->size(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height"));
item->setEvent(attrStr("event"));
item->setImage(attrStr("image"));
item->move(attrStr("room"));
return item;
}
Dialog *RRNode::fetchDialog()
{
if (isNull()) return 0;
Dialog *d = new Dialog(attrStr("id"), attrStr("start"));
for (gotoChild("step"); !isNull(); gotoNext())
{
DialogStep *step = d->addStep(attrStr("id"), attrStr("text"));
step->event = fetchEvent();
for (gotoChild("link"); !isNull(); gotoNext())
d->addLink(step->id, attrStr("id"), attrStr("text"));
gotoParent();
}
gotoParent();
return d;
}
TiXmlElement *RRNode::findElement(TiXmlElement *elem, string name)
{
if (elem == 0)
return 0;
if (string(elem->Value()) == name)
return elem;
TiXmlElement *result = findElement(elem->NextSiblingElement(), name);
if (result != 0)
return result;
result = findElement(elem->FirstChildElement(), name);
if (result != 0)
return result;
return 0;
}
RoomsReader::RoomsReader()
{
crawler = 0;
parse_map["world"] = &RoomsReader::parseWorld;
parse_map["room"] = &RoomsReader::parseRoom;
parse_map["area"] = &RoomsReader::parseArea;
parse_map["action"] = &RoomsReader::parseAction;
parse_map["event"] = &RoomsReader::parseEvent;
parse_map["dialog"] = &RoomsReader::parseDialog;
parse_map["step"] = &RoomsReader::parseDialogStep;
parse_map["var"] = &RoomsReader::parseVar;
parse_map["item"] = &RoomsReader::parseItem;
parse_map["param"] = &RoomsReader::parseParam;
parse_map["item_req"] = &RoomsReader::parseItemReq;
parse_map["var_req"] = &RoomsReader::parseVarReq;
parse_map["img"] = &RoomsReader::parseImages;
}
RoomsReader::~RoomsReader()
{
if(crawler)
delete crawler;
}
bool RoomsReader::loadFromFile(const string filename)
{
std::ifstream xml(filename.c_str(), std::ios::binary);
xml.seekg (0, std::ios::end);
long length = xml.tellg();
char *buffer = new char [length];
xml.seekg (0, std::ios::beg);
xml.read(buffer, length);
bool res = loadFromStr(buffer);
xml.close();
delete [] buffer;
return res;
}
bool RoomsReader::loadFromStr(const string content)
{
doc.Parse(content.c_str());
if (!parse()) return false;
crawler = new RRNode(doc.RootElement());
return true;
}
bool RoomsReader::parse()
{
return parseElement(doc.RootElement());
}
RRNode *RoomsReader::getCrawler()
{
return crawler;
}
bool RoomsReader::checkUniqueId(std::set<string> &ids, const string id)
{
if (ids.count(id) != 0)
return false;
ids.insert(id);
return true;
}
bool RoomsReader::checkParent(TiXmlElement *elem, string name)
{
return (elem->Parent() != 0 &&
string(elem->Parent()->Value()) == name);
}
bool RoomsReader::parseElement(TiXmlElement *elem)
{
if (elem == 0)
return true;
bool value = true;
if (parse_map.find(elem->Value()) != parse_map.end())
{
ParseMethod method = parse_map.find(elem->Value())->second;
value = (this->*method)(elem);
}
return (value && parseElement(elem->FirstChildElement()) && parseElement(elem->NextSiblingElement()));
}
bool RoomsReader::parseArea(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "x", ATTR_FLOAT) &&
parseAttr(elem, "y", ATTR_FLOAT) &&
parseAttr(elem, "width", ATTR_FLOAT) &&
parseAttr(elem, "height", ATTR_FLOAT)))
return false;
if (!(checkUniqueId(unique_ids_areas, elem->Attribute("id")) &&
checkParent(elem, "room")))
return false;
return true;
}
bool RoomsReader::parseItem(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "room", ATTR_STR) &&
parseAttr(elem, "image", ATTR_STR) &&
parseAttr(elem, "x", ATTR_FLOAT) &&
parseAttr(elem, "y", ATTR_FLOAT) &&
parseAttr(elem, "width", ATTR_FLOAT) &&
parseAttr(elem, "height", ATTR_FLOAT)))
return false;
if (!(checkUniqueId(unique_ids_items, elem->Attribute("id")) &&
checkParent(elem, "items")))
return false;
if (checkUniqueId(unique_ids_images, elem->Attribute("image")))
return false;
return true;
}
bool RoomsReader::parseRoom(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "bg", ATTR_STR)))
return false;
if (!(checkUniqueId(unique_ids_rooms, elem->Attribute("id")) &&
checkUniqueId(unique_ids_images, elem->Attribute("bg")) &&
checkParent(elem, "rooms")))
return false;
return true;
}
bool RoomsReader::parseAction(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
checkParent(elem, "event")))
return false;
else
return true;
}
bool RoomsReader::parseWorld(TiXmlElement *elem)
{
if (!(parseAttr(elem, "version", ATTR_STR) &&
parseAttr(elem, "name", ATTR_STR) &&
parseAttr(elem, "start", ATTR_STR) &&
parseAttr(elem, "width", ATTR_INT) &&
parseAttr(elem, "height", ATTR_INT)))
return false;
return true;
}
bool RoomsReader::parseEvent(TiXmlElement *elem)
{
if (!parseAttr(elem, "id", ATTR_STR))
return false;
if (!(checkUniqueId(unique_ids_events, elem->Attribute("id")) &&
checkParent(elem, "events")))
return false;
return true;
}
bool RoomsReader::parseVar(TiXmlElement *elem)
{
if (!(parseAttr(elem, "value", ATTR_STR) &&
checkParent(elem, "action")))
return false;
return true;
}
bool RoomsReader::parseImages(TiXmlElement *elem)
{
if (!(parseAttr(elem, "file", ATTR_STR) &&
checkParent(elem, "images")))
return false;
if (!checkUniqueId(unique_ids_images, elem->Attribute("file")))
return false;
return true;
}
bool RoomsReader::parseItemReq(TiXmlElement *elem)
{
if (!parseAttr(elem, "id", ATTR_STR))
return false;
if (!(!checkUniqueId(unique_ids_items, elem->Attribute("id")) &&
(checkParent(elem, "event") || checkParent(elem, "step"))))
return false;
return true;
}
bool RoomsReader::parseVarReq(TiXmlElement *elem)
{
if (!parseAttr(elem, "id", ATTR_STR))
return false;
if (!(!checkUniqueId(unique_ids_vars, elem->Attribute("id")) &&
(checkParent(elem, "event") || checkParent(elem, "step"))))
return false;
return true;
}
bool RoomsReader::parseParam(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "value", ATTR_INT)))
return false;
if (!(checkUniqueId(unique_ids_vars, elem->Attribute("id")) &&
checkParent(elem, "vars")))
return false;
return true;
}
bool RoomsReader::parseDialog(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "start", ATTR_STR)))
return false;
if (!(checkUniqueId(unique_ids_dialogs, elem->Attribute("id")) &&
checkParent(elem, "dialogs")))
return false;
return true;
}
bool RoomsReader::parseDialogStep(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "text", ATTR_STR) &&
checkParent(elem, "dialog")))
return false;
return true;
}
bool RoomsReader::parseAttr(TiXmlElement *elem, string name, AttributeType type)
{
switch (type)
{
case ATTR_FLOAT:
{
float tmp;
return (elem->QueryFloatAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);
break;
}
case ATTR_INT:
{
int tmp;
return (elem->QueryIntAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);
break;
}
case ATTR_STR:
{
return (elem->Attribute(name.c_str()));
break;
}
default:
{
return false;
break;
}
}
}
<commit_msg>Some bug fixes about xml parsing.<commit_after>#include "roomsreader.h"
RRNode::RRNode(TiXmlElement *root)
{
this->root = root;
gotoRoot();
}
RRNode::~RRNode()
{
}
RRNode *RRNode::gotoElement(string name)
{
cursor = findElement(root, name);
}
RRNode *RRNode::gotoRoot()
{
cursor = root;
return this;
}
RRNode *RRNode::gotoChild(string name)
{
cursor = cursor->FirstChildElement(name.c_str());
return this;
}
RRNode *RRNode::gotoParent()
{
cursor = cursor->Parent()->ToElement();
return this;
}
RRNode *RRNode::gotoNext()
{
cursor = cursor->NextSiblingElement(cursor->Value());
return this;
}
bool RRNode::isNull()
{
return cursor;
}
int RRNode::attrInt(string name)
{
int tmp = 0;
cursor->QueryIntAttribute(name.c_str(), &tmp);
return tmp;
}
float RRNode::attrFloat(string name)
{
float tmp = 0.0;
cursor->QueryFloatAttribute(name.c_str(), &tmp);
return tmp;
}
string RRNode::attrStr(string name)
{
return cursor->Attribute(name.c_str());
}
Event *RRNode::fetchEvent()
{
if (isNull()) return 0;
Event *event = new Event(attrStr("id"));
for (gotoChild("item_req"); !isNull(); gotoNext())
event->addItemReq(attrStr("id"), attrStr("value"));
gotoParent();
for (gotoChild("var_req"); !isNull(); gotoNext())
event->addVarReq(attrStr("id"), attrInt("value"));
gotoParent();
for (gotoChild("action"); !isNull(); gotoNext())
{
Action *act = event->addAction(attrStr("id"));
for (gotoChild("param"); isNull(); gotoNext())
act->pushParam(attrStr("value"));
gotoParent();
}
gotoParent();
return event;
}
Room *RRNode::fetchRoom()
{
if (isNull()) return 0;
Room *room = new Room(attrStr("id"));
room->bg(attrStr("bg"));
for (gotoChild("area"); !isNull(); gotoNext())
{
Area *area = room->addArea(attrStr("id"));
area->size(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height"));
area->setEvent(attrStr("event"));
}
gotoParent();
return room;
}
Item *RRNode::fetchItem()
{
if (isNull()) return 0;
Item *item = new Item(attrStr("id"));
item->size(attrFloat("x"), attrFloat("y"), attrFloat("width"), attrFloat("height"));
item->setEvent(attrStr("event"));
item->setImage(attrStr("image"));
item->move(attrStr("room"));
return item;
}
Dialog *RRNode::fetchDialog()
{
if (isNull()) return 0;
Dialog *d = new Dialog(attrStr("id"), attrStr("start"));
for (gotoChild("step"); !isNull(); gotoNext())
{
DialogStep *step = d->addStep(attrStr("id"), attrStr("text"));
step->event = fetchEvent();
for (gotoChild("link"); !isNull(); gotoNext())
d->addLink(step->id, attrStr("id"), attrStr("text"));
gotoParent();
}
gotoParent();
return d;
}
TiXmlElement *RRNode::findElement(TiXmlElement *elem, string name)
{
if (elem == 0)
return 0;
if (string(elem->Value()) == name)
return elem;
TiXmlElement *result = findElement(elem->NextSiblingElement(), name);
if (result != 0)
return result;
result = findElement(elem->FirstChildElement(), name);
if (result != 0)
return result;
return 0;
}
RoomsReader::RoomsReader()
{
crawler = 0;
parse_map["world"] = &RoomsReader::parseWorld;
parse_map["room"] = &RoomsReader::parseRoom;
parse_map["area"] = &RoomsReader::parseArea;
parse_map["action"] = &RoomsReader::parseAction;
parse_map["event"] = &RoomsReader::parseEvent;
parse_map["dialog"] = &RoomsReader::parseDialog;
parse_map["step"] = &RoomsReader::parseDialogStep;
parse_map["var"] = &RoomsReader::parseVar;
parse_map["item"] = &RoomsReader::parseItem;
parse_map["param"] = &RoomsReader::parseParam;
parse_map["item_req"] = &RoomsReader::parseItemReq;
parse_map["var_req"] = &RoomsReader::parseVarReq;
parse_map["img"] = &RoomsReader::parseImages;
}
RoomsReader::~RoomsReader()
{
if(crawler)
delete crawler;
}
bool RoomsReader::loadFromFile(const string filename)
{
std::ifstream xml(filename.c_str(), std::ios::binary);
xml.seekg (0, std::ios::end);
long length = xml.tellg();
char *buffer = new char [length];
xml.seekg (0, std::ios::beg);
xml.read(buffer, length);
bool res = loadFromStr(buffer);
xml.close();
delete [] buffer;
return res;
}
bool RoomsReader::loadFromStr(const string content)
{
doc.Parse(content.c_str());
if (!parse()) return false;
crawler = new RRNode(doc.RootElement());
return true;
}
bool RoomsReader::parse()
{
return parseElement(doc.RootElement());
}
RRNode *RoomsReader::getCrawler()
{
return crawler;
}
bool RoomsReader::checkUniqueId(std::set<string> &ids, const string id)
{
if (ids.count(id) != 0)
return false;
ids.insert(id);
return true;
}
bool RoomsReader::checkParent(TiXmlElement *elem, string name)
{
return (elem->Parent() != 0 &&
string(elem->Parent()->Value()) == name);
}
bool RoomsReader::parseElement(TiXmlElement *elem)
{
if (elem == 0)
return true;
bool value = true;
if (parse_map.find(elem->Value()) != parse_map.end())
{
ParseMethod method = parse_map.find(elem->Value())->second;
value = (this->*method)(elem);
}
return (value && parseElement(elem->FirstChildElement()) && parseElement(elem->NextSiblingElement()));
}
bool RoomsReader::parseArea(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "x", ATTR_FLOAT) &&
parseAttr(elem, "y", ATTR_FLOAT) &&
parseAttr(elem, "width", ATTR_FLOAT) &&
parseAttr(elem, "height", ATTR_FLOAT)))
return false;
if (!(checkUniqueId(unique_ids_areas, elem->Attribute("id")) &&
checkParent(elem, "room")))
return false;
return true;
}
bool RoomsReader::parseItem(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "room", ATTR_STR) &&
parseAttr(elem, "image", ATTR_STR) &&
parseAttr(elem, "x", ATTR_FLOAT) &&
parseAttr(elem, "y", ATTR_FLOAT) &&
parseAttr(elem, "width", ATTR_FLOAT) &&
parseAttr(elem, "height", ATTR_FLOAT)))
return false;
if (!(checkUniqueId(unique_ids_items, elem->Attribute("id")) &&
checkParent(elem, "items") &&
!checkUniqueId(unique_ids_images, elem->Attribute("image"))))
return false;
return true;
}
bool RoomsReader::parseRoom(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "bg", ATTR_STR)))
return false;
if (!(checkUniqueId(unique_ids_rooms, elem->Attribute("id")) &&
checkParent(elem, "rooms")))
return false;
return true;
}
bool RoomsReader::parseAction(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
checkParent(elem, "event")))
return false;
return true;
}
bool RoomsReader::parseWorld(TiXmlElement *elem)
{
if (!(parseAttr(elem, "version", ATTR_STR) &&
parseAttr(elem, "name", ATTR_STR) &&
parseAttr(elem, "start", ATTR_STR) &&
parseAttr(elem, "width", ATTR_INT) &&
parseAttr(elem, "height", ATTR_INT)))
return false;
return true;
}
bool RoomsReader::parseEvent(TiXmlElement *elem)
{
if (!parseAttr(elem, "id", ATTR_STR))
return false;
if (!(checkUniqueId(unique_ids_events, elem->Attribute("id")) &&
checkParent(elem, "events")))
return false;
return true;
}
bool RoomsReader::parseVar(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "value", ATTR_STR) &&
checkParent(elem, "vars")))
return false;
return true;
}
bool RoomsReader::parseImages(TiXmlElement *elem)
{
if (!(parseAttr(elem, "file", ATTR_STR) &&
checkParent(elem, "images")))
return false;
if (!checkUniqueId(unique_ids_images, elem->Attribute("file")))
return false;
return true;
}
bool RoomsReader::parseItemReq(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "value", ATTR_STR)))
return false;
if (!(!checkUniqueId(unique_ids_items, elem->Attribute("id")) &&
(checkParent(elem, "event") || checkParent(elem, "step"))))
return false;
return true;
}
bool RoomsReader::parseVarReq(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "value", ATTR_INT)))
return false;
if (!(checkParent(elem, "event") || checkParent(elem, "step")))
return false;
return true;
}
bool RoomsReader::parseParam(TiXmlElement *elem)
{
if (!parseAttr(elem, "value", ATTR_STR))
return false;
return true;
}
bool RoomsReader::parseDialog(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "start", ATTR_STR)))
return false;
if (!(checkUniqueId(unique_ids_dialogs, elem->Attribute("id")) &&
checkParent(elem, "dialogs")))
return false;
return true;
}
bool RoomsReader::parseDialogStep(TiXmlElement *elem)
{
if (!(parseAttr(elem, "id", ATTR_STR) &&
parseAttr(elem, "text", ATTR_STR) &&
checkParent(elem, "dialog")))
return false;
return true;
}
bool RoomsReader::parseAttr(TiXmlElement *elem, string name, AttributeType type)
{
switch (type)
{
case ATTR_FLOAT:
{
float tmp;
return (elem->QueryFloatAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);
break;
}
case ATTR_INT:
{
int tmp;
return (elem->QueryIntAttribute(name.c_str(), &tmp) == TIXML_SUCCESS);
break;
}
case ATTR_STR:
{
return (elem->Attribute(name.c_str()));
break;
}
default:
{
return false;
break;
}
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
created: Fri, 4th July 2014
author: Henri I Hyyryläinen
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
namespace CEGUI
{
// Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders
//! A string containing an HLSL vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_HLSL(""
"float4x4 modelViewProjMatrix;\n"
"\n"
"struct VertOut\n"
"{\n"
" float4 pos : SV_Position;\n"
" float4 colour : COLOR;\n"
"};\n"
"\n"
"VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\n"
"{\n"
" VertOut output;\n"
"\n"
" output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\n"
" output.colour = inColour;\n"
"\n"
" return output;\n"
"}\n"
);
//! A string containing an HLSL fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_HLSL(""
"uniform float alphaPercentage;\n"
"\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
"};\n"
"\n"
"float4 main(VS_OUT input) : COLOR\n"
"{\n"
" float4 colour = input.colour;\n"
" colour.a *= alphaPercentage;\n"
" return colour;\n"
"}\n"
"\n"
);
/*!
A string containing an HLSL vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_HLSL(""
"float4x4 modelViewProjMatrix;\n"
"\n"
"struct VertOut\n"
"{\n"
" float4 pos : SV_Position;\n"
" float4 colour : COLOR;\n"
" float2 texcoord0 : TEXCOORD;\n"
"};\n"
"\n"
"// Vertex shader\n"
"VertOut main(float4 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\n"
"{\n"
" VertOut output;\n"
"\n"
" output.pos = mul(modelViewProjMatrix, inPos);\n"
" output.texcoord0 = inTexCoord0;\n"
" output.colour = inColour;\n"
"\n"
" return output;\n"
"}\n"
);
/*!
A string containing an HLSL fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_HLSL(""
"uniform float alphaPercentage;\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
" float2 uv : TEXCOORD0;\n"
"};\n"
"\n"
"float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, "
" uniform sampler2D texture0 : TEXUNIT0) : COLOR\n"
"{\n"
" colour = tex2D(texture0, uv) * colour;\n"
" colour.a *= alphaPercentage;\n"
" return colour;\n"
"}\n"
"\n"
);
//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderTextured_GLSL_Compat(""
"uniform mat4 modelViewProjMatrix;\n"
"void main(void)"
"{"
" gl_TexCoord[0] = gl_MultiTexCoord0;"
" gl_FrontColor = gl_Color;"
" gl_Position = modelViewProjMatrix * gl_Vertex;"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderTextured_GLSL_Compat(""
"uniform sampler2D texture0;"
"uniform float alphaPercentage;\n"
"void main(void)"
"{"
" gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderColoured_GLSL_Compat(""
"uniform mat4 modelViewProjMatrix;\n"
"void main(void)"
"{"
" gl_FrontColor = gl_Color;"
" gl_Position = modelViewProjMatrix * gl_Vertex;"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderColoured_GLSL_Compat(""
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{"
" gl_FragColor = gl_Color;"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
//! A string containing an OpenGL3 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSL(""
"#version 150 core\n"
"uniform mat4 modelViewProjMatrix;\n"
"in vec4 vertex;\n"
"in vec4 colour;\n"
"out vec4 exColour;"
"void main(void)\n"
"{\n"
" exColour = colour;\n"
" gl_Position = modelViewProjMatrix * vertex;\n"
"}"
);
//! A string containing an OpenGL3 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSL(""
"#version 150 core\n"
"in vec4 exColour;\n"
"out vec4 fragColour;\n"
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{\n"
" fragColour = exColour;\n"
" fragColour.a *= alphaPercentage;\n"
"}"
);
/*!
A string containing an OpenGL3 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSL(""
"#version 150 core\n"
"uniform mat4 modelViewProjMatrix;\n"
"in vec4 vertex;\n"
"in vec4 colour;\n"
"in vec2 uv0;\n"
"out vec2 exTexCoord;\n"
"out vec4 exColour;\n"
"void main()\n"
"{\n"
" exTexCoord = uv0;\n"
" exColour = colour;\n"
" gl_Position = modelViewProjMatrix * vertex;\n"
"}"
);
/*!
A string containing an OpenGL3 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSL(""
"#version 150 core\n"
"uniform sampler2D texture0;\n"
"uniform float alphaPercentage;\n"
"in vec2 exTexCoord;\n"
"in vec4 exColour;\n"
"out vec4 fragColour;\n"
"void main(void)\n"
"{\n"
" fragColour = texture(texture0, exTexCoord) * exColour;\n"
" fragColour.a *= alphaPercentage;\n"
"}"
);
//! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSLES1(""
"#version 100\n"
"precision mediump int;\n"
"precision mediump float;\n"
"uniform mat4 modelViewProjMatrix;\n"
"attribute vec4 vertex;\n"
"attribute vec4 colour;\n"
"varying vec4 exColour;\n"
"void main(void)\n"
"{\n"
" exColour = colour;\n"
" gl_Position = modelViewProjMatrix * vertex;\n"
"}"
);
//! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSLES1(""
"#version 100\n"
"precision mediump int;\n"
"precision mediump float;\n"
"varying vec4 exColour;\n"
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = exColour;\n"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
/*!
A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSLES1(""
"#version 100\n"
"precision mediump int;\n"
"precision mediump float;\n"
"uniform mat4 modelViewProjMatrix;\n"
"attribute vec4 vertex;\n"
"attribute vec4 colour;\n"
"attribute vec2 uv0;\n"
"varying vec2 exTexCoord;\n"
"varying vec4 exColour;\n"
"void main()\n"
"{\n"
" exTexCoord = uv0;\n"
" exColour = colour;"
" gl_Position = modelViewProjMatrix * vertex;\n"
"}"
);
/*!
A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSLES1(""
"#version 100\n"
"precision mediump int;\n"
"precision mediump float;\n"
"uniform sampler2D texture0;\n"
"uniform float alphaPercentage;\n"
"varying vec2 exTexCoord;\n"
"varying vec4 exColour;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\n"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
}
<commit_msg>precision for sampler<commit_after>/***********************************************************************
created: Fri, 4th July 2014
author: Henri I Hyyryläinen
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
namespace CEGUI
{
// Shaders for Ogre renderer adapted from OpenGL and Direct3D11 shaders
//! A string containing an HLSL vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_HLSL(""
"float4x4 modelViewProjMatrix;\n"
"\n"
"struct VertOut\n"
"{\n"
" float4 pos : SV_Position;\n"
" float4 colour : COLOR;\n"
"};\n"
"\n"
"VertOut main(float3 inPos : POSITION, float4 inColour : COLOR)\n"
"{\n"
" VertOut output;\n"
"\n"
" output.pos = mul(modelViewProjMatrix, float4(inPos, 1.0));\n"
" output.colour = inColour;\n"
"\n"
" return output;\n"
"}\n"
);
//! A string containing an HLSL fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_HLSL(""
"uniform float alphaPercentage;\n"
"\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
"};\n"
"\n"
"float4 main(VS_OUT input) : COLOR\n"
"{\n"
" float4 colour = input.colour;\n"
" colour.a *= alphaPercentage;\n"
" return colour;\n"
"}\n"
"\n"
);
/*!
A string containing an HLSL vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_HLSL(""
"float4x4 modelViewProjMatrix;\n"
"\n"
"struct VertOut\n"
"{\n"
" float4 pos : SV_Position;\n"
" float4 colour : COLOR;\n"
" float2 texcoord0 : TEXCOORD;\n"
"};\n"
"\n"
"// Vertex shader\n"
"VertOut main(float4 inPos : POSITION, float4 inColour : COLOR, float2 inTexCoord0 : TEXCOORD)\n"
"{\n"
" VertOut output;\n"
"\n"
" output.pos = mul(modelViewProjMatrix, inPos);\n"
" output.texcoord0 = inTexCoord0;\n"
" output.colour = inColour;\n"
"\n"
" return output;\n"
"}\n"
);
/*!
A string containing an HLSL fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_HLSL(""
"uniform float alphaPercentage;\n"
"struct VS_OUT\n"
"{\n"
" float4 position : POSITION;\n"
" float4 colour : COLOR;\n"
" float2 uv : TEXCOORD0;\n"
"};\n"
"\n"
"float4 main(float4 colour : COLOR, float2 uv : TEXCOORD0, "
" uniform sampler2D texture0 : TEXUNIT0) : COLOR\n"
"{\n"
" colour = tex2D(texture0, uv) * colour;\n"
" colour.a *= alphaPercentage;\n"
" return colour;\n"
"}\n"
"\n"
);
//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderTextured_GLSL_Compat(""
"uniform mat4 modelViewProjMatrix;\n"
"void main(void)"
"{"
" gl_TexCoord[0] = gl_MultiTexCoord0;"
" gl_FrontColor = gl_Color;"
" gl_Position = modelViewProjMatrix * gl_Vertex;"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderTextured_GLSL_Compat(""
"uniform sampler2D texture0;"
"uniform float alphaPercentage;\n"
"void main(void)"
"{"
" gl_FragColor = texture2D(texture0, gl_TexCoord[0].st) * gl_Color;"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String VertexShaderColoured_GLSL_Compat(""
"uniform mat4 modelViewProjMatrix;\n"
"void main(void)"
"{"
" gl_FrontColor = gl_Color;"
" gl_Position = modelViewProjMatrix * gl_Vertex;"
"}"
);
//! Shader for older OpenGL versions < 3
static Ogre::String PixelShaderColoured_GLSL_Compat(""
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{"
" gl_FragColor = gl_Color;"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
//! A string containing an OpenGL3 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSL(""
"#version 150 core\n"
"uniform mat4 modelViewProjMatrix;\n"
"in vec4 vertex;\n"
"in vec4 colour;\n"
"out vec4 exColour;"
"void main(void)\n"
"{\n"
" exColour = colour;\n"
" gl_Position = modelViewProjMatrix * vertex;\n"
"}"
);
//! A string containing an OpenGL3 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSL(""
"#version 150 core\n"
"in vec4 exColour;\n"
"out vec4 fragColour;\n"
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{\n"
" fragColour = exColour;\n"
" fragColour.a *= alphaPercentage;\n"
"}"
);
/*!
A string containing an OpenGL3 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSL(""
"#version 150 core\n"
"uniform mat4 modelViewProjMatrix;\n"
"in vec4 vertex;\n"
"in vec4 colour;\n"
"in vec2 uv0;\n"
"out vec2 exTexCoord;\n"
"out vec4 exColour;\n"
"void main()\n"
"{\n"
" exTexCoord = uv0;\n"
" exColour = colour;\n"
" gl_Position = modelViewProjMatrix * vertex;\n"
"}"
);
/*!
A string containing an OpenGL3 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSL(""
"#version 150 core\n"
"uniform sampler2D texture0;\n"
"uniform float alphaPercentage;\n"
"in vec2 exTexCoord;\n"
"in vec4 exColour;\n"
"out vec4 fragColour;\n"
"void main(void)\n"
"{\n"
" fragColour = texture(texture0, exTexCoord) * exColour;\n"
" fragColour.a *= alphaPercentage;\n"
"}"
);
//! A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for solid colouring of a polygon
static Ogre::String VertexShaderColoured_GLSLES1(""
"#version 100\n"
"precision mediump int;\n"
"precision mediump float;\n"
"uniform mat4 modelViewProjMatrix;\n"
"attribute vec4 vertex;\n"
"attribute vec4 colour;\n"
"varying vec4 exColour;\n"
"void main(void)\n"
"{\n"
" exColour = colour;\n"
" gl_Position = modelViewProjMatrix * vertex;\n"
"}"
);
//! A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for solid colouring of a polygon
static Ogre::String PixelShaderColoured_GLSLES1(""
"#version 100\n"
"precision mediump int;\n"
"precision mediump float;\n"
"varying vec4 exColour;\n"
"uniform float alphaPercentage;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = exColour;\n"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
/*!
A string containing an OpenGL ES 2.0 / GLES 1.0 vertex shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String VertexShaderTextured_GLSLES1(""
"#version 100\n"
"precision mediump int;\n"
"precision mediump float;\n"
"uniform mat4 modelViewProjMatrix;\n"
"attribute vec4 vertex;\n"
"attribute vec4 colour;\n"
"attribute vec2 uv0;\n"
"varying vec2 exTexCoord;\n"
"varying vec4 exColour;\n"
"void main()\n"
"{\n"
" exTexCoord = uv0;\n"
" exColour = colour;"
" gl_Position = modelViewProjMatrix * vertex;\n"
"}"
);
/*!
A string containing an OpenGL ES 2.0 / GLES 1.0 fragment shader for polygons that should be coloured
based on a texture. The fetched texture colour will be multiplied by a colour
supplied to the shader, resulting in the final colour.
*/
static Ogre::String PixelShaderTextured_GLSLES1(""
"#version 100\n"
"precision mediump int;\n"
"precision mediump float;\n"
"precision lowp sampler2D;\n"
"uniform sampler2D texture0;\n"
"uniform float alphaPercentage;\n"
"varying vec2 exTexCoord;\n"
"varying vec4 exColour;\n"
"void main(void)\n"
"{\n"
" gl_FragColor = texture2D(texture0, exTexCoord) * exColour;\n"
" gl_FragColor.a *= alphaPercentage;\n"
"}"
);
}
<|endoftext|> |
<commit_before>#include "main.hpp"
#include <anarch/x64/multiboot-region-list>
#include <anarch/x64/init>
#include <anarch/api/global-map>
#include <anarch/api/panic>
#include <anarch/stream>
#include <ansa/macros>
#include <ansa/cstring>
extern "C" {
void AluxMainX64(void * mbootPtr) {
anarch::x64::InitializeSingletons();
anarch::StreamModule::GetGlobal().Load();
anarch::cout << "AluxMainX64(" << (uint64_t)mbootPtr << ")"
<< anarch::endl;
__asm__ __volatile__("cli\nhlt"); // TODO: delete this
// this stack is going to be preserved throughout the runtime of the OS, so
// it is acceptable to store the boot info here
anarch::x64::MultibootRegionList regions(mbootPtr);
// TODO: here, calculate the length of the kernel by loading the program
anarch::x64::BootInfo bootInfo(regions, 0x300000);
anarch::x64::SetBootInfo(&bootInfo);
// load the global map
anarch::GlobalMap::GetGlobal().Load();
anarch::cout << "finished loading GlobalMap" << anarch::endl;
}
}
<commit_msg>GlobalMap configuration succeessful!<commit_after>#include "main.hpp"
#include <anarch/x64/multiboot-region-list>
#include <anarch/x64/init>
#include <anarch/api/global-map>
#include <anarch/api/panic>
#include <anarch/stream>
#include <ansa/macros>
#include <ansa/cstring>
extern "C" {
void AluxMainX64(void * mbootPtr) {
anarch::x64::InitializeSingletons();
anarch::StreamModule::GetGlobal().Load();
anarch::cout << "AluxMainX64(" << (uint64_t)mbootPtr << ")"
<< anarch::endl;
// this stack is going to be preserved throughout the runtime of the OS, so
// it is acceptable to store the boot info here
anarch::x64::MultibootRegionList regions(mbootPtr);
// TODO: here, calculate the length of the kernel by loading the program
anarch::x64::BootInfo bootInfo(regions, 0x300000);
anarch::x64::SetBootInfo(&bootInfo);
// load the global map
anarch::GlobalMap::GetGlobal().Load();
anarch::cout << "finished loading GlobalMap" << anarch::endl;
}
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include "test_common.h"
#include <boost/test/unit_test.hpp>
#include <engine.h>
#include <timeutil.h>
#include <utils/fs.h>
#include <utils/logger.h>
class BenchCallback : public dariadb::storage::ReaderClb {
public:
BenchCallback() { count = 0; }
void call(const dariadb::Meas &) { count++; }
size_t count;
};
BOOST_AUTO_TEST_CASE(Engine_common_test) {
const std::string storage_path = "testStorage";
const size_t chunk_per_storage = 10000;
const size_t chunk_size = 256;
const size_t cap_B = 5;
const dariadb::Time from = 0;
const dariadb::Time to = from + 1021;
const dariadb::Time step = 10;
{
if (dariadb::utils::fs::path_exists(storage_path)) {
dariadb::utils::fs::rm(storage_path);
}
dariadb::storage::MeasStorage_ptr ms{new dariadb::storage::Engine(
dariadb::storage::PageManager::Params(storage_path, chunk_per_storage,
chunk_size),
dariadb::storage::Capacitor::Params(cap_B, storage_path),
dariadb::storage::Engine::Limits(10))};
dariadb_test::storage_test_check(ms.get(), from, to, step);
}
{
dariadb::storage::MeasStorage_ptr ms{new dariadb::storage::Engine(
dariadb::storage::PageManager::Params(storage_path, chunk_per_storage,
chunk_size),
dariadb::storage::Capacitor::Params(cap_B, storage_path),
dariadb::storage::Engine::Limits(0))};
dariadb::Meas::MeasList mlist;
ms->currentValue(dariadb::IdArray{}, 0)->readAll(&mlist);
BOOST_CHECK(mlist.size() == size_t(1));
BOOST_CHECK(mlist.front().flag != dariadb::Flags::_NO_DATA);
}
if (dariadb::utils::fs::path_exists(storage_path)) {
dariadb::utils::fs::rm(storage_path);
}
}
<commit_msg>test for subscribe.<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE Main
#include "test_common.h"
#include <boost/test/unit_test.hpp>
#include <engine.h>
#include <timeutil.h>
#include <utils/fs.h>
#include <utils/logger.h>
class BenchCallback : public dariadb::storage::ReaderClb {
public:
BenchCallback() { count = 0; }
void call(const dariadb::Meas &) { count++; }
size_t count;
};
BOOST_AUTO_TEST_CASE(Engine_common_test) {
const std::string storage_path = "testStorage";
const size_t chunk_per_storage = 10000;
const size_t chunk_size = 256;
const size_t cap_B = 5;
const dariadb::Time from = 0;
const dariadb::Time to = from + 1021;
const dariadb::Time step = 10;
{
if (dariadb::utils::fs::path_exists(storage_path)) {
dariadb::utils::fs::rm(storage_path);
}
dariadb::storage::MeasStorage_ptr ms{new dariadb::storage::Engine(
dariadb::storage::PageManager::Params(storage_path, chunk_per_storage,
chunk_size),
dariadb::storage::Capacitor::Params(cap_B, storage_path),
dariadb::storage::Engine::Limits(10))};
dariadb_test::storage_test_check(ms.get(), from, to, step);
}
{
dariadb::storage::MeasStorage_ptr ms{new dariadb::storage::Engine(
dariadb::storage::PageManager::Params(storage_path, chunk_per_storage,
chunk_size),
dariadb::storage::Capacitor::Params(cap_B, storage_path),
dariadb::storage::Engine::Limits(0))};
dariadb::Meas::MeasList mlist;
ms->currentValue(dariadb::IdArray{}, 0)->readAll(&mlist);
BOOST_CHECK(mlist.size() == size_t(1));
BOOST_CHECK(mlist.front().flag != dariadb::Flags::_NO_DATA);
}
if (dariadb::utils::fs::path_exists(storage_path)) {
dariadb::utils::fs::rm(storage_path);
}
}
class Moc_SubscribeClbk : public dariadb::storage::ReaderClb {
public:
std::list<dariadb::Meas> values;
void call(const dariadb::Meas &m) override { values.push_back(m); }
~Moc_SubscribeClbk() {}
};
BOOST_AUTO_TEST_CASE(Subscribe) {
const size_t id_count = 5;
std::shared_ptr<Moc_SubscribeClbk> c1(new Moc_SubscribeClbk);
std::shared_ptr<Moc_SubscribeClbk> c2(new Moc_SubscribeClbk);
std::shared_ptr<Moc_SubscribeClbk> c3(new Moc_SubscribeClbk);
std::shared_ptr<Moc_SubscribeClbk> c4(new Moc_SubscribeClbk);
const std::string storage_path = "testStorage";
const size_t chunk_per_storage = 10000;
const size_t chunk_size = 256;
const size_t cap_B = 5;
const dariadb::Time from = 0;
const dariadb::Time to = from + 1021;
const dariadb::Time step = 10;
{
if (dariadb::utils::fs::path_exists(storage_path)) {
dariadb::utils::fs::rm(storage_path);
}
dariadb::storage::MeasStorage_ptr ms{new dariadb::storage::Engine(
dariadb::storage::PageManager::Params(storage_path, chunk_per_storage,
chunk_size),
dariadb::storage::Capacitor::Params(cap_B, storage_path),
dariadb::storage::Engine::Limits(10))};
dariadb::IdArray ids{};
ms->subscribe(ids, 0, c1); // all
ids.push_back(2);
ms->subscribe(ids, 0, c2); // 2
ids.push_back(1);
ms->subscribe(ids, 0, c3); // 1 2
ids.clear();
ms->subscribe(ids, 1, c4); // with flag=1
auto m = dariadb::Meas::empty();
const size_t total_count = 100;
const dariadb::Time time_step = 1;
for (size_t i = 0; i < total_count; i += time_step) {
m.id = i % id_count;
m.flag = dariadb::Flag(i);
m.time = i;
m.value = 0;
ms->append(m);
}
BOOST_CHECK_EQUAL(c1->values.size(), total_count);
BOOST_CHECK_EQUAL(c2->values.size(), size_t(total_count / id_count));
BOOST_CHECK_EQUAL(c2->values.front().id, dariadb::Id(2));
BOOST_CHECK_EQUAL(c3->values.size(), size_t(total_count / id_count) * 2);
BOOST_CHECK_EQUAL(c3->values.front().id, dariadb::Id(1));
BOOST_CHECK_EQUAL(c4->values.size(), size_t(1));
BOOST_CHECK_EQUAL(c4->values.front().flag, dariadb::Flag(1));
}
if (dariadb::utils::fs::path_exists(storage_path)) {
dariadb::utils::fs::rm(storage_path);
}
}<|endoftext|> |
<commit_before>/*
Append QA TPC metadata decribing tree structure, and annotating branche variables
Instead of the manual entering all metadatas, arrays of regular expressions defining classes of variables
-- kineVariablesClass
-- qaVariableClass
-- statClassClass
-- categoryClass
varName.class=<statClass>+<kineVariableClass>+<qaVariableClass>+<categoryClass>+<Class:>
Examples:
dcar_negC_1_Err.class: TPC Err FitGX DCAr CSide Neg
dcar_negC_1_Err.Title: #sigma x_{G} DCAr C side Q<0
meanMIPvsSector..class: TPC Mean dEdx Sector Class:TVectorT<double>
meanMIPvsSector.Title: mean dEdx Sector
Work in progress: include other types of metadata
-- automatic html metadata
-- markers and colors for predefined variable (charge, side?)
-- automatic parser of aliases ?
Usage and debugging of metadata setting:
1.) Metadata can be setup invoking macro:
AliExternalInfo info;
TTree * tree = info.GetTree("QA.TPC","LHC15o","cpass1_pass1","QA.TPC;QA.TRD;QA.TOF;QA.ITS;QA.EVS;Logbook.detector");
.x $ALICE_ROOT/../src/STAT/Macros/qatpcAddMetadata.C+(tree,4)
2.) Macro can be executed automatically if proper configuation file leaded AliExternalInfo.cfg - see line:
QA.TPC.metadataMacro $ALICE_ROOT/STAT/Macros/qatpcAddMetadata.C+
3.) Printing all metadata:
a.)
AliTreePlayer::selectMetadata(tree, "[class==\"\"]",0)->Print();
3.) Example query particular info:
AliTreePlayer::selectMetadata(tree, "[class==\"DCAR&&!ERR&&!CHI2\"]",0)->Print();
AliTreePlayer::selectMetadata(tree, "[class==\"DCAR&&ERR\"]",0)->Print();
AliTreePlayer::selectMetadata(tree, "[class==\"DCAZ\"]",0)->Print();
AliTreePlayer::selectMetadata(tree,"[class==DCAr&&!Pos&&!Neg",0).Print();
// alternative
((TObjArray*)(tree->GetUserInfo()->FindObject("metaTable"))).Print("",TPRegexp("dca.*class"))
*/
#include "TTree.h"
#include "TPRegexp.h"
#include "TList.h"
#include "AliTreePlayer.h"
#include "TStatToolkit.h"
void qatpcAddMetadata(TTree*tree, Int_t verbose){
//
// Set metadata infomation
//
if (tree==NULL) {
::Error("qatpcAddMetadata","Start processing. Emtpy tree");
return;
}
::Info("qatpcAddMetadata","Start processing Tree %s",tree->GetName());
TObjArray * branches=tree->GetListOfBranches();
// Clasigication of variables
// regular expression to defined automaticaly some variables following naming conventions - used to define classes/Axis/legends
// default description
// regular expression used can be tested on site https://regex101.com/
// hovewer root (perl) regular expression looks to be in some cases different - in some case double escape had to be used
// e.g to math c. expression c\\. has to be used
// variables
const TString kineVariableClass[11]={"X", "Y","Z", "Phi", "Theta", "Pt", "QOverPt", "FitPhi","FitGX", "FitGY", "Constrain"};
const TString kineVariableAxisTitle[11]={"x(cm)", "y(cm)","z(cm)", "#phi", "#Theta", "p_{T}(Gev/c)", "q/p_{T}(c/GeV)", "#phi","x_{G}", "y_{G}", " "};
const TString kineVariableLegend[11]={"x", "y","z", "#phi", "#Theta", "p_{T}", "q/p_{T}", "#phi","x_{G}", "y_{G}", " "};
const TString kineVariableTitle[11]={"x", "y","z", "#phi", "#Theta", "p_{T}", "q/p_{T}", "#phi","x_{G}", "y_{G}", " "};
TPRegexp regKineVariables[11];
regKineVariables[0]=TPRegexp("^x|x$"); // X - varaible begining on X
regKineVariables[1]=TPRegexp("(^y|^infoy|y$)"); // Y -
regKineVariables[2]=TPRegexp("(^z|^infoz|z$)"); // Z
regKineVariables[3]=TPRegexp("(phi|infophi)"); // phi
regKineVariables[4]=TPRegexp("(theta|lambda|infolambda)"); // theta
regKineVariables[5]=TPRegexp("(^pt|^infopt|meanpt|deltapt)"); // pt
regKineVariables[6]=TPRegexp("qoverpt"); // qoverPt
regKineVariables[7]=TPRegexp("(_0^|_-_)"); // fit Phi
regKineVariables[8]=TPRegexp("(_1^|_1_)"); // fit GlobalX
regKineVariables[9]=TPRegexp("(_2^|_2_)"); // fit GlobalY
//
// QA variables
const TString qaVariableClass[11]={"Ncl", "Eff","dEdx", "DCAr", "DCAz","Occ","Attach","Electron"};
const TString qaVariableAxisTitle[11]={"Ncl(#)", "Eff(unit)","dEdx(MIP/50)", "DCAr(cm)", "DCAz(cm)", "Occupancy","Attach","Electron"};
const TString qaVariableLegend[11]={"Ncl", "Eff","dEdx", "DCAr", "DCAz","Occ.","Attach","e-"};
const TString qaVariableTitle[11]={"Ncl", "Eff","dEdx", "DCAr", "DCAz", "Occupancy","Attach","e-"};
TPRegexp regQAVariable[11];
regQAVariable[0]=TPRegexp("ncl"); // Ncl
regQAVariable[1]=TPRegexp("tpcitsmatch"); // TPC->ITS eff
regQAVariable[2]=TPRegexp("mip"); // dEdx
regQAVariable[3]=TPRegexp("dcar"); // dcar
regQAVariable[4]=TPRegexp("dcaz"); // dcaz
regQAVariable[5]=TPRegexp("occ"); // occupancy
regQAVariable[6]=TPRegexp("attach"); // attachement
regQAVariable[7]=TPRegexp("(electron|ele$)"); // Electron char.
//
// statistic
//
const TString statClass[10]={"Constrain", "Mean","Delta","Median", "RMS","Pull", "Err","Chi2", "StatInfo[]","FitInfo[]"};
const TString statAxisTitle[10]={"Constrain", "mean","#Delta","med.", "rms","pull", "#sigma"," #chi2","stat[]","fit[]"};
const TString statTitle[10]={"Constrain", "mean","#Delta","med.", "rms","pull", "#sigma"," #chi2","stat[]","fit[]" };
TPRegexp regStat[10];
regStat[0]=TPRegexp("constrain"); // constrain
regStat[1]=TPRegexp("^mean"); // mean
regStat[2]=TPRegexp("^delta"); // delta
regStat[3]=TPRegexp("^median"); // median variable
regStat[4]=TPRegexp("(^rms|resolution)");// rms resolution
regStat[5]=TPRegexp("pull"); // pull
regStat[6]=TPRegexp("err"); // error
regStat[7]=TPRegexp("chi2"); // chi2
regStat[8]=TPRegexp("^info"); // stat info array
regStat[9]=TPRegexp("^fit"); // fit info array
//
//
const TString categoryClass[10]={"ASide","CSide","Pos", "Neg", "ROC", "IROC", "OROC", "Sector", "HighPt"};
const TString categoryLegend[10]={"A side","C side","Q>0", "Q<0","ROC", "IROC", "OROC", "Sector", "high p_{T}"};
const TString categoryTitle[10]={"A side","C side","Q>0", "Q<0","ROC", "IROC", "OROC", "Sector", "high p_{T}"};
// TString categoryAxisTitle[10] - empty
TPRegexp regCategory[10];
regCategory[0]=TPRegexp("(a$|a.?side|a\\.$|dcarap|a_(0|1|2))"); // is A side - options( a at the beigininng, a ... side, a. at the end)
regCategory[1]=TPRegexp("(c$|c.?side|c\\.$|dcarcp|c_(0|1|2))"); // is C side
regCategory[2]=TPRegexp("(_pos|pos$)"); // QA for positive charge particle
regCategory[3]=TPRegexp("(_neg|neg$)"); // positive charge particle
regCategory[4]=TPRegexp("^roc"); // ROC
regCategory[5]=TPRegexp("iroc"); // IROC
regCategory[6]=TPRegexp("oroc"); // OROC
regCategory[7]=TPRegexp("sector"); // sector
regCategory[8]=TPRegexp("highpt"); // hightPt QA
for (Int_t ibr=0; ibr<branches->GetEntriesFast(); ibr++){
TBranch * branch = (TBranch*)branches->At(ibr);
TString brClass="";
TString brAxisTitle="";
TString brTitle="";
TString brLegend="";
//
TString brNameCase(branches->At(ibr)->GetName());
brNameCase.ToLower();
//
// define met
brClass="TPC";
brAxisTitle="";
// stat
for (Int_t ivar=0; ivar<9; ivar++) if (brNameCase.Contains( regStat[ivar])) {
brClass+=" "+statClass[ivar];
brTitle+=statTitle[ivar];
}
// kine variables
for (Int_t ivar=0; ivar<10; ivar++) if (brNameCase.Contains( regKineVariables[ivar])) {
brClass+=" "+kineVariableClass[ivar];
brAxisTitle+=" "+kineVariableAxisTitle[ivar];
brTitle+=" "+kineVariableTitle[ivar];
brLegend+=" "+kineVariableLegend[ivar];
}
// QA variables
for (Int_t ivar=0; ivar<10; ivar++) if (brNameCase.Contains( regQAVariable[ivar])) {
brClass+=" "+qaVariableClass[ivar];
brAxisTitle+=" "+qaVariableAxisTitle[ivar];
brTitle+=" "+qaVariableTitle[ivar];
brLegend+=" "+qaVariableLegend[ivar];
}
// category
for (Int_t ivar=0; ivar<9; ivar++) if (brNameCase.Contains(regCategory[ivar])) {
brClass+=" "+categoryClass[ivar];
brLegend+=" "+categoryLegend[ivar];
brTitle+=" "+categoryTitle[ivar];
}
if (branch!=NULL && branch->GetClassName()!=NULL && strlen(branch->GetClassName())>0){
brClass+=" Class:";
brClass+=branch->GetClassName();
}
//
TStatToolkit::AddMetadata(tree,TString::Format("%s.Description",branches->At(ibr)->GetName()).Data(),
TString::Format("TPC standard QA variables. Class %s", brClass.Data()).Data());
TStatToolkit::AddMetadata(tree,TString::Format("%s.class",branches->At(ibr)->GetName()).Data(),brClass.Data());
TStatToolkit::AddMetadata(tree,TString::Format("%s.AxisTitle",branches->At(ibr)->GetName()).Data(),brAxisTitle.Data());
TStatToolkit::AddMetadata(tree,TString::Format("%s.Title",branches->At(ibr)->GetName()).Data(),brTitle.Data());
TStatToolkit::AddMetadata(tree,TString::Format("%s.Legend",branches->At(ibr)->GetName()).Data(),brLegend.Data());
if (verbose&4) printf("Class %s: \t%s\n", branches->At(ibr)->GetName(),brClass.Data());
if (verbose&8) printf("Axis title %s: \t%s\n", branches->At(ibr)->GetName(),brAxisTitle.Data());
if (verbose&16) printf("Title %s: \t%s\n", branches->At(ibr)->GetName(),brTitle.Data());
if (verbose&32) printf("Legend %s: \t%s\n", branches->At(ibr)->GetName(),brLegend.Data());
}
// Fill Based and custom metadata
//
// Index
TStatToolkit::AddMetadata(tree,"run.class","Base Index");
TStatToolkit::AddMetadata(tree,"run.Title","run");
TStatToolkit::AddMetadata(tree,"run.AxisTitle","run");
//
TList * mlist = (TList*)(tree->GetUserInfo()->FindObject("metaTable"));
mlist->Sort();
if ((verbose&1)>0){
mlist->Print();
}
if ((verbose&2)>0){
AliTreePlayer::selectMetadata(tree, "[class==\"\"]",0)->Print();
}
::Info("qatpcAddMetadata","End");
}
<commit_msg>ATO-290, ATO-46, ATO-360 Append QA TPC metadata decribing tree structure, and annotating branche variables (branch, alias)<commit_after>/*
Append QA TPC metadata decribing tree structure, and annotating branche variables.
Partialy inspired by CSS (https://de.wikipedia.org/wiki/Cascading_Style_Sheets) but not full functionality implemented
Instead of the manual entering all metadatas, arrays of regular expressions defining classes of variables
-- kineVariablesClass
-- qaVariableClass
-- statClassClass
-- categoryClass
varName.class=<statClass>+<kineVariableClass>+<qaVariableClass>+<categoryClass>+<Class:>
Examples:
dcar_negC_1_Err.class: TPC Err FitGX DCAr CSide Neg
dcar_negC_1_Err.Title: #sigma x_{G} DCAr C side Q<0
meanMIPvsSector..class: TPC Mean dEdx Sector Class:TVectorT<double>
meanMIPvsSector.Title: mean dEdx Sector
Work in progress: include other types of metadata
-- automatic html metadata
-- markers and colors for predefined variable (charge, side?)
-- automatic parser of aliases ?
Usage and debugging of metadata setting:
1.) Metadata can be setup invoking macro:
AliExternalInfo info;
TTree * tree = info.GetTree("QA.TPC","LHC15o","cpass1_pass1","QA.TPC;QA.TRD;QA.TOF;QA.ITS;QA.EVS;Logbook.detector");
.x $ALICE_ROOT/../src/STAT/Macros/qatpcAddMetadata.C+(tree,4)
2.) Macro can be executed automatically if proper configuation file leaded AliExternalInfo.cfg - see line:
QA.TPC.metadataMacro $ALICE_ROOT/STAT/Macros/qatpcAddMetadata.C+
3.) Printing all metadata:
a.)
AliTreePlayer::selectMetadata(tree, "[class==\"\"]",0)->Print();
3.) Example query particular info:
AliTreePlayer::selectMetadata(tree, "[class==\"DCAR&&!ERR&&!CHI2\"]",0)->Print();
AliTreePlayer::selectMetadata(tree, "[class==\"DCAR&&ERR\"]",0)->Print();
AliTreePlayer::selectMetadata(tree, "[class==\"DCAZ\"]",0)->Print();
AliTreePlayer::selectMetadata(tree,"[class==DCAr&&!Pos&&!Neg",0).Print();
// alternative
((TObjArray*)(tree->GetUserInfo()->FindObject("metaTable"))).Print("",TPRegexp("dca.*class"))
*/
#include "TTree.h"
#include "TPRegexp.h"
#include "TList.h"
#include "AliTreePlayer.h"
#include "TStatToolkit.h"
void qatpcAddMetadata(TTree*tree, Int_t verbose){
//
// Set metadata infomation
//
if (tree==NULL) {
::Error("qatpcAddMetadata","Start processing. Emtpy tree");
return;
}
::Info("qatpcAddMetadata","Start processing Tree %s",tree->GetName());
TObjArray * branches=tree->GetListOfBranches();
// Clasigication of variables
// regular expression to defined automaticaly some variables following naming conventions - used to define classes/Axis/legends
// default description
// regular expression used can be tested on site https://regex101.com/
// hovewer root (perl) regular expression looks to be in some cases different - in some case double escape had to be used
// e.g to math c. expression c\\. has to be used
// variables
const TString kineVariableClass[11]={"X", "Y","Z", "Phi", "Theta", "Pt", "QOverPt", "FitPhi","FitGX", "FitGY", "Constrain"};
const TString kineVariableAxisTitle[11]={"x(cm)", "y(cm)","z(cm)", "#phi", "#Theta", "p_{T}(Gev/c)", "q/p_{T}(c/GeV)", "#phi","x_{G}", "y_{G}", " "};
const TString kineVariableLegend[11]={"x", "y","z", "#phi", "#Theta", "p_{T}", "q/p_{T}", "#phi","x_{G}", "y_{G}", " "};
const TString kineVariableTitle[11]={"x", "y","z", "#phi", "#Theta", "p_{T}", "q/p_{T}", "#phi","x_{G}", "y_{G}", " "};
TPRegexp regKineVariables[11];
regKineVariables[0]=TPRegexp("^x|x$"); // X - varaible begining on X
regKineVariables[1]=TPRegexp("(^y|^infoy|y$)"); // Y -
regKineVariables[2]=TPRegexp("(^z|^infoz|z$)"); // Z
regKineVariables[3]=TPRegexp("(phi|infophi)"); // phi
regKineVariables[4]=TPRegexp("(theta|lambda|infolambda)"); // theta
regKineVariables[5]=TPRegexp("(^pt|^infopt|meanpt|deltapt)"); // pt
regKineVariables[6]=TPRegexp("qoverpt"); // qoverPt
regKineVariables[7]=TPRegexp("(_0^|_-_)"); // fit Phi
regKineVariables[8]=TPRegexp("(_1^|_1_)"); // fit GlobalX
regKineVariables[9]=TPRegexp("(_2^|_2_)"); // fit GlobalY
//
// QA variables
const TString qaVariableClass[11]={"Ncl", "Eff","dEdx", "DCAr", "DCAz","Occ","Attach","Electron"};
const TString qaVariableAxisTitle[11]={"Ncl(#)", "Eff(unit)","dEdx(MIP/50)", "DCAr(cm)", "DCAz(cm)", "Occupancy","Attach","Electron"};
const TString qaVariableLegend[11]={"Ncl", "Eff","dEdx", "DCAr", "DCAz","Occ.","Attach","e-"};
const TString qaVariableTitle[11]={"Ncl", "Eff","dEdx", "DCAr", "DCAz", "Occupancy","Attach","e-"};
TPRegexp regQAVariable[11];
regQAVariable[0]=TPRegexp("ncl"); // Ncl
regQAVariable[1]=TPRegexp("tpcitsmatch"); // TPC->ITS eff
regQAVariable[2]=TPRegexp("mip"); // dEdx
regQAVariable[3]=TPRegexp("dcar"); // dcar
regQAVariable[4]=TPRegexp("dcaz"); // dcaz
regQAVariable[5]=TPRegexp("occ"); // occupancy
regQAVariable[6]=TPRegexp("attach"); // attachement
regQAVariable[7]=TPRegexp("(electron|ele$)"); // Electron char.
//
// statistic
//
const TString statClass[10]={"Constrain", "Mean","Delta","Median", "RMS","Pull", "Err","Chi2", "StatInfo[]","FitInfo[]"};
const TString statAxisTitle[10]={"Constrain", "mean","#Delta","med.", "rms","pull", "#sigma"," #chi2","stat[]","fit[]"};
const TString statTitle[10]={"Constrain", "mean","#Delta","med.", "rms","pull", "#sigma"," #chi2","stat[]","fit[]" };
TPRegexp regStat[10];
regStat[0]=TPRegexp("constrain"); // constrain
regStat[1]=TPRegexp("^mean"); // mean
regStat[2]=TPRegexp("^delta"); // delta
regStat[3]=TPRegexp("^median"); // median variable
regStat[4]=TPRegexp("(^rms|resolution)");// rms resolution
regStat[5]=TPRegexp("pull"); // pull
regStat[6]=TPRegexp("err"); // error
regStat[7]=TPRegexp("chi2"); // chi2
regStat[8]=TPRegexp("^info"); // stat info array
regStat[9]=TPRegexp("^fit"); // fit info array
//
//
const TString categoryClass[10]={"ASide","CSide","Pos", "Neg", "ROC", "IROC", "OROC", "Sector", "HighPt"};
const TString categoryLegend[10]={"A side","C side","Q>0", "Q<0","ROC", "IROC", "OROC", "Sector", "high p_{T}"};
const TString categoryTitle[10]={"A side","C side","Q>0", "Q<0","ROC", "IROC", "OROC", "Sector", "high p_{T}"};
// TString categoryAxisTitle[10] - empty
TPRegexp regCategory[10];
regCategory[0]=TPRegexp("(a$|a.?side|a\\.$|dcarap|a_(0|1|2))"); // is A side - options( a at the beigininng, a ... side, a. at the end)
regCategory[1]=TPRegexp("(c$|c.?side|c\\.$|dcarcp|c_(0|1|2))"); // is C side
regCategory[2]=TPRegexp("(_pos|pos$)"); // QA for positive charge particle
regCategory[3]=TPRegexp("(_neg|neg$)"); // positive charge particle
regCategory[4]=TPRegexp("^roc"); // ROC
regCategory[5]=TPRegexp("iroc"); // IROC
regCategory[6]=TPRegexp("oroc"); // OROC
regCategory[7]=TPRegexp("sector"); // sector
regCategory[8]=TPRegexp("highpt"); // hightPt QA
for (Int_t ibr=0; ibr<branches->GetEntriesFast(); ibr++){
TBranch * branch = (TBranch*)branches->At(ibr);
TString brClass="";
TString brAxisTitle="";
TString brTitle="";
TString brLegend="";
//
TString brNameCase(branches->At(ibr)->GetName());
brNameCase.ToLower();
//
// define met
brClass="TPC";
brAxisTitle="";
// stat
for (Int_t ivar=0; ivar<9; ivar++) if (brNameCase.Contains( regStat[ivar])) {
brClass+=" "+statClass[ivar];
brTitle+=statTitle[ivar];
}
// kine variables
for (Int_t ivar=0; ivar<10; ivar++) if (brNameCase.Contains( regKineVariables[ivar])) {
brClass+=" "+kineVariableClass[ivar];
brAxisTitle+=" "+kineVariableAxisTitle[ivar];
brTitle+=" "+kineVariableTitle[ivar];
brLegend+=" "+kineVariableLegend[ivar];
}
// QA variables
for (Int_t ivar=0; ivar<10; ivar++) if (brNameCase.Contains( regQAVariable[ivar])) {
brClass+=" "+qaVariableClass[ivar];
brAxisTitle+=" "+qaVariableAxisTitle[ivar];
brTitle+=" "+qaVariableTitle[ivar];
brLegend+=" "+qaVariableLegend[ivar];
}
// category
for (Int_t ivar=0; ivar<9; ivar++) if (brNameCase.Contains(regCategory[ivar])) {
brClass+=" "+categoryClass[ivar];
brLegend+=" "+categoryLegend[ivar];
brTitle+=" "+categoryTitle[ivar];
}
if (branch!=NULL && branch->GetClassName()!=NULL && strlen(branch->GetClassName())>0){
brClass+=" Class:";
brClass+=branch->GetClassName();
}
//
TStatToolkit::AddMetadata(tree,TString::Format("%s.Description",branches->At(ibr)->GetName()).Data(),
TString::Format("TPC standard QA variables. Class %s", brClass.Data()).Data());
TStatToolkit::AddMetadata(tree,TString::Format("%s.class",branches->At(ibr)->GetName()).Data(),brClass.Data());
TStatToolkit::AddMetadata(tree,TString::Format("%s.AxisTitle",branches->At(ibr)->GetName()).Data(),brAxisTitle.Data());
TStatToolkit::AddMetadata(tree,TString::Format("%s.Title",branches->At(ibr)->GetName()).Data(),brTitle.Data());
TStatToolkit::AddMetadata(tree,TString::Format("%s.Legend",branches->At(ibr)->GetName()).Data(),brLegend.Data());
if (verbose&4) printf("Class %s: \t%s\n", branches->At(ibr)->GetName(),brClass.Data());
if (verbose&8) printf("Axis title %s: \t%s\n", branches->At(ibr)->GetName(),brAxisTitle.Data());
if (verbose&16) printf("Title %s: \t%s\n", branches->At(ibr)->GetName(),brTitle.Data());
if (verbose&32) printf("Legend %s: \t%s\n", branches->At(ibr)->GetName(),brLegend.Data());
}
// Fill Based and custom metadata
//
// Index
TStatToolkit::AddMetadata(tree,"run.class","Base Index");
TStatToolkit::AddMetadata(tree,"run.Title","run");
TStatToolkit::AddMetadata(tree,"run.AxisTitle","run");
//
TList * mlist = (TList*)(tree->GetUserInfo()->FindObject("metaTable"));
mlist->Sort();
if ((verbose&1)>0){
mlist->Print();
}
if ((verbose&2)>0){
AliTreePlayer::selectMetadata(tree, "[class==\"\"]",0)->Print();
}
::Info("qatpcAddMetadata","End");
}
<|endoftext|> |
<commit_before> /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: AliTriggerRunScalers.cxx 22322 2007-11-22 11:43:14Z cvetan $ */
///////////////////////////////////////////////////////////////////////////////
//
// Class to define the ALICE Trigger Scalers Record per Run.
//
//
//////////////////////////////////////////////////////////////////////////////
#include <Riostream.h>
#include <TObject.h>
#include <TClass.h>
#include <TArrayC.h>
#include <TSystem.h>
#include <TObjString.h>
#include <TObjArray.h>
#include <TSystem.h>
#include <TFile.h>
#include "AliLog.h"
#include "AliTimeStamp.h"
#include "AliTriggerScalers.h"
#include "AliTriggerScalersRecord.h"
#include "AliTriggerRunScalers.h"
ClassImp( AliTriggerRunScalers )
//_____________________________________________________________________________
AliTriggerRunScalers::AliTriggerRunScalers():
TObject(),
fVersion(0),
fRunNumber(0),
fnClasses(0),
fClassIndex(),
fScalersRecord()
{
// Default constructor
}
//_____________________________________________________________________________
void AliTriggerRunScalers::AddTriggerScalers( AliTriggerScalersRecord* scaler )
{
//
fScalersRecord.AddLast( scaler );
fScalersRecord.Sort();
}
//_____________________________________________________________________________
AliTriggerRunScalers* AliTriggerRunScalers::ReadScalers( TString & filename )
{
if( gSystem->AccessPathName( filename.Data() ) ) {
AliErrorClass( Form( "file (%s) not found", filename.Data() ) );
return NULL;
}
ifstream *file = new ifstream ( filename.Data() );
if (!*file) {
AliErrorClass(Form("Error opening file (%s) !\n",filename.Data()));
file->close();
delete file;
return NULL;
}
AliTriggerRunScalers* rScaler = new AliTriggerRunScalers();
TString strLine;
Bool_t verflag = kFALSE;
Bool_t classflag = kFALSE;
UChar_t nclass = 0;
while (strLine.ReadLine(*file)) {
if (strLine.BeginsWith("#")) continue;
TObjArray *tokens = strLine.Tokenize(" \t");
Int_t ntokens = tokens->GetEntriesFast();
// 1st line, version, it is one number,
if (!verflag) {
if (ntokens != 1) {
AliErrorClass( Form( "Error reading version number from (%s), line :%s\n",
filename.Data() , strLine.Data() ) );
return NULL;
}
// cout << "Version "<< ((TObjString*)tokens->At(0))->String().Atoi() << endl;
rScaler->SetVersion( ((TObjString*)tokens->At(0))->String().Atoi() );
verflag = kTRUE;
delete tokens;
continue;
}
// 2nd line, run number , number of classes, list of classes used in this partition
if (!classflag) {
if ( !((TObjString*)tokens->At(1))->String().IsDigit() ) {
AliErrorClass( Form( "Error reading Run number from (%s)\n", filename.Data() ));
}
// cout << "Run Number " << ((TObjString*)tokens->At(0))->String().Atoi() << endl;
rScaler->SetRunNumber( ((TObjString*)tokens->At(0))->String().Atoi() );
nclass = (UChar_t)((TObjString*)tokens->At(1))->String().Atoi();
// cout << "Number of classes " << nclass << endl;
rScaler->SetNumClasses( nclass );
if ( nclass != ntokens - 2 ) {
AliErrorClass( Form( "Error reading number of classes from (%s)\n", filename.Data() ));
}
for (UChar_t i=0; i<nclass; ++i) {
rScaler->SetClass( i, (Char_t)((TObjString*)tokens->At(2+i))->String().Atoi() );
}
classflag = kTRUE;
delete tokens;
continue;
}
// Records
// Each record consists of 1+(number of classes in partition) lines
// 1st line of record = time stamp (4 words)
// 1st word = ORBIT(24 bits)
// 2nd word = Period Counter (28 bit)
// 3rd word = seconds (32 bits) from epoch
// 4th word = microsecs (32 bits)
// other lines = 6 words of counters (L0 before,L0 after, ....)
if (ntokens != 4) {
AliErrorClass( Form( "Error reading timestamp from (%s): line (%s)",
filename.Data(), strLine.Data() ));
return NULL;
}
UInt_t orbit = ((TObjString*)tokens->At(0))->String().Atoi();
UInt_t period = ((TObjString*)tokens->At(1))->String().Atoi();
UInt_t seconds = ((TObjString*)tokens->At(2))->String().Atoi();
UInt_t microSecs = ((TObjString*)tokens->At(3))->String().Atoi();
AliTriggerScalersRecord * rec = new AliTriggerScalersRecord();
rec->SetTimeStamp( orbit, period, seconds, microSecs );
TString strLine1;
for (Int_t i=0; i<nclass; ++i) {
strLine1.ReadLine(*file);
if (strLine1.BeginsWith("#")) continue;
TObjArray *tokens1 = strLine1.Tokenize(" \t");
Int_t ntokens1 = tokens1->GetEntriesFast();
if( ntokens1 != 6 ) {
AliErrorClass( Form( "Error reading scalers from (%s): line (%s)\n",
filename.Data(), strLine1.Data() ));
}
UInt_t LOCB = ((TObjString*)tokens1->At(0))->String().Atoi();
UInt_t LOCA = ((TObjString*)tokens1->At(1))->String().Atoi();
UInt_t L1CB = ((TObjString*)tokens1->At(2))->String().Atoi();
UInt_t L1CA = ((TObjString*)tokens1->At(3))->String().Atoi();
UInt_t L2CB = ((TObjString*)tokens1->At(4))->String().Atoi();
UInt_t L2CA = ((TObjString*)tokens1->At(5))->String().Atoi();
rScaler->GetClass(i);
rec->AddTriggerScalers( rScaler->GetClass(i),
LOCB, LOCA, L1CB,
L1CA, L2CB, L2CA );
delete tokens1;
}
rScaler->AddTriggerScalers( rec );
delete tokens;
}
file->close();
delete file;
return rScaler;
}
//_____________________________________________________________________________
Int_t AliTriggerRunScalers::FindNearestScalersRecord( AliTimeStamp * stamp )
{
// Find Trigger scaler record with the closest timestamp <= "stamp"
// using a binary search.
// return the index in the array of records, if the timestamp
// is out of range return -1
Int_t base, position=-1, last, result = 0;
AliTimeStamp *op2 = NULL;
fScalersRecord.Sort();
base = 0;
last = fScalersRecord.GetEntriesFast();
while (last >= base) {
position = (base+last) / 2;
cout << "pos " << position<< " base " << base << "last " << last << endl;
AliTriggerScalersRecord* rec = (AliTriggerScalersRecord*)fScalersRecord.At(position);
if( rec ) op2 = rec->GetTimeStamp();
if( op2 && (result = stamp->Compare(op2)) == 0 )
return position; // exact match
cout << "result " << result << " op2 " << op2 << " rec "<< rec << endl;
if (!op2 || result < 0)
last = position-1;
else
base = position+1;
op2 = NULL;
}
if( (position == 0 && result < 0) || position >= fScalersRecord.GetEntriesFast() )
return -1; // out of range
else
return (result < 0 ) ? position-1 : position; // nearst < stamp
}
//_____________________________________________________________________________
void AliTriggerRunScalers::Print( const Option_t* ) const
{
// Print
cout << "Trigger Scalers Record per Run: " << endl;
cout << " File version :" << fVersion << endl;
cout << " Run Number :" << fRunNumber << endl;
cout << " Number of Classes :" << (Int_t)fnClasses << endl;
cout << " Classes ID:";
for( Int_t i=0; i<fnClasses; ++i )
cout << " " << (Int_t)fClassIndex[i];
cout << endl;
for( Int_t i=0; i<fScalersRecord.GetEntriesFast(); ++i )
((AliTriggerScalersRecord*)fScalersRecord.At(i))->Print();
}
<commit_msg>Do not crash, but rather skip the remaining scaler records in case of corrupted data file.<commit_after> /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id: AliTriggerRunScalers.cxx 22322 2007-11-22 11:43:14Z cvetan $ */
///////////////////////////////////////////////////////////////////////////////
//
// Class to define the ALICE Trigger Scalers Record per Run.
//
//
//////////////////////////////////////////////////////////////////////////////
#include <Riostream.h>
#include <TObject.h>
#include <TClass.h>
#include <TArrayC.h>
#include <TSystem.h>
#include <TObjString.h>
#include <TObjArray.h>
#include <TSystem.h>
#include <TFile.h>
#include "AliLog.h"
#include "AliTimeStamp.h"
#include "AliTriggerScalers.h"
#include "AliTriggerScalersRecord.h"
#include "AliTriggerRunScalers.h"
ClassImp( AliTriggerRunScalers )
//_____________________________________________________________________________
AliTriggerRunScalers::AliTriggerRunScalers():
TObject(),
fVersion(0),
fRunNumber(0),
fnClasses(0),
fClassIndex(),
fScalersRecord()
{
// Default constructor
}
//_____________________________________________________________________________
void AliTriggerRunScalers::AddTriggerScalers( AliTriggerScalersRecord* scaler )
{
//
fScalersRecord.AddLast( scaler );
fScalersRecord.Sort();
}
//_____________________________________________________________________________
AliTriggerRunScalers* AliTriggerRunScalers::ReadScalers( TString & filename )
{
if( gSystem->AccessPathName( filename.Data() ) ) {
AliErrorClass( Form( "file (%s) not found", filename.Data() ) );
return NULL;
}
ifstream *file = new ifstream ( filename.Data() );
if (!*file) {
AliErrorClass(Form("Error opening file (%s) !\n",filename.Data()));
file->close();
delete file;
return NULL;
}
AliTriggerRunScalers* rScaler = new AliTriggerRunScalers();
TString strLine;
Bool_t verflag = kFALSE;
Bool_t classflag = kFALSE;
UChar_t nclass = 0;
while (strLine.ReadLine(*file)) {
if (strLine.BeginsWith("#")) continue;
TObjArray *tokens = strLine.Tokenize(" \t");
Int_t ntokens = tokens->GetEntriesFast();
// 1st line, version, it is one number,
if (!verflag) {
if (ntokens != 1) {
AliErrorClass( Form( "Error reading version number from (%s), line :%s\n",
filename.Data() , strLine.Data() ) );
return NULL;
}
// cout << "Version "<< ((TObjString*)tokens->At(0))->String().Atoi() << endl;
rScaler->SetVersion( ((TObjString*)tokens->At(0))->String().Atoi() );
verflag = kTRUE;
delete tokens;
continue;
}
// 2nd line, run number , number of classes, list of classes used in this partition
if (!classflag) {
if ( !((TObjString*)tokens->At(1))->String().IsDigit() ) {
AliErrorClass( Form( "Error reading Run number from (%s)\n", filename.Data() ));
}
// cout << "Run Number " << ((TObjString*)tokens->At(0))->String().Atoi() << endl;
rScaler->SetRunNumber( ((TObjString*)tokens->At(0))->String().Atoi() );
nclass = (UChar_t)((TObjString*)tokens->At(1))->String().Atoi();
// cout << "Number of classes " << nclass << endl;
rScaler->SetNumClasses( nclass );
if ( nclass != ntokens - 2 ) {
AliErrorClass( Form( "Error reading number of classes from (%s)\n", filename.Data() ));
}
for (UChar_t i=0; i<nclass; ++i) {
rScaler->SetClass( i, (Char_t)((TObjString*)tokens->At(2+i))->String().Atoi() );
}
classflag = kTRUE;
delete tokens;
continue;
}
// Records
// Each record consists of 1+(number of classes in partition) lines
// 1st line of record = time stamp (4 words)
// 1st word = ORBIT(24 bits)
// 2nd word = Period Counter (28 bit)
// 3rd word = seconds (32 bits) from epoch
// 4th word = microsecs (32 bits)
// other lines = 6 words of counters (L0 before,L0 after, ....)
if (ntokens != 4) {
AliErrorClass( Form( "Error reading timestamp from (%s): line (%s)",
filename.Data(), strLine.Data() ));
return NULL;
}
UInt_t orbit = ((TObjString*)tokens->At(0))->String().Atoi();
UInt_t period = ((TObjString*)tokens->At(1))->String().Atoi();
UInt_t seconds = ((TObjString*)tokens->At(2))->String().Atoi();
UInt_t microSecs = ((TObjString*)tokens->At(3))->String().Atoi();
AliTriggerScalersRecord * rec = new AliTriggerScalersRecord();
rec->SetTimeStamp( orbit, period, seconds, microSecs );
TString strLine1;
for (Int_t i=0; i<nclass; ++i) {
strLine1.ReadLine(*file);
if (strLine1.BeginsWith("#")) continue;
TObjArray *tokens1 = strLine1.Tokenize(" \t");
Int_t ntokens1 = tokens1->GetEntriesFast();
if( ntokens1 != 6 ) {
AliErrorClass( Form( "Error reading scalers from (%s): line (%s)",
filename.Data(), strLine1.Data() ));
delete rec;
return rScaler;
}
UInt_t LOCB = ((TObjString*)tokens1->At(0))->String().Atoi();
UInt_t LOCA = ((TObjString*)tokens1->At(1))->String().Atoi();
UInt_t L1CB = ((TObjString*)tokens1->At(2))->String().Atoi();
UInt_t L1CA = ((TObjString*)tokens1->At(3))->String().Atoi();
UInt_t L2CB = ((TObjString*)tokens1->At(4))->String().Atoi();
UInt_t L2CA = ((TObjString*)tokens1->At(5))->String().Atoi();
rScaler->GetClass(i);
rec->AddTriggerScalers( rScaler->GetClass(i),
LOCB, LOCA, L1CB,
L1CA, L2CB, L2CA );
delete tokens1;
}
rScaler->AddTriggerScalers( rec );
delete tokens;
}
file->close();
delete file;
return rScaler;
}
//_____________________________________________________________________________
Int_t AliTriggerRunScalers::FindNearestScalersRecord( AliTimeStamp * stamp )
{
// Find Trigger scaler record with the closest timestamp <= "stamp"
// using a binary search.
// return the index in the array of records, if the timestamp
// is out of range return -1
Int_t base, position=-1, last, result = 0;
AliTimeStamp *op2 = NULL;
fScalersRecord.Sort();
base = 0;
last = fScalersRecord.GetEntriesFast();
while (last >= base) {
position = (base+last) / 2;
cout << "pos " << position<< " base " << base << "last " << last << endl;
AliTriggerScalersRecord* rec = (AliTriggerScalersRecord*)fScalersRecord.At(position);
if( rec ) op2 = rec->GetTimeStamp();
if( op2 && (result = stamp->Compare(op2)) == 0 )
return position; // exact match
cout << "result " << result << " op2 " << op2 << " rec "<< rec << endl;
if (!op2 || result < 0)
last = position-1;
else
base = position+1;
op2 = NULL;
}
if( (position == 0 && result < 0) || position >= fScalersRecord.GetEntriesFast() )
return -1; // out of range
else
return (result < 0 ) ? position-1 : position; // nearst < stamp
}
//_____________________________________________________________________________
void AliTriggerRunScalers::Print( const Option_t* ) const
{
// Print
cout << "Trigger Scalers Record per Run: " << endl;
cout << " File version :" << fVersion << endl;
cout << " Run Number :" << fRunNumber << endl;
cout << " Number of Classes :" << (Int_t)fnClasses << endl;
cout << " Classes ID:";
for( Int_t i=0; i<fnClasses; ++i )
cout << " " << (Int_t)fClassIndex[i];
cout << endl;
for( Int_t i=0; i<fScalersRecord.GetEntriesFast(); ++i )
((AliTriggerScalersRecord*)fScalersRecord.At(i))->Print();
}
<|endoftext|> |
<commit_before>// Copyright 2021 The IREE Authors
//
// Licensed 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 <utility>
#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
#include "iree/compiler/Dialect/Stream/IR/StreamDialect.h"
#include "iree/compiler/Dialect/Stream/IR/StreamOps.h"
#include "iree/compiler/Dialect/Stream/IR/StreamTraits.h"
#include "iree/compiler/Dialect/Stream/Transforms/PassDetail.h"
#include "iree/compiler/Dialect/Stream/Transforms/Passes.h"
#include "iree/compiler/Dialect/Util/IR/UtilDialect.h"
#include "iree/compiler/Dialect/Util/IR/UtilOps.h"
#include "llvm/ADT/TypeSwitch.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/Pass/Pass.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Stream {
//===----------------------------------------------------------------------===//
// Base pass utility
//===----------------------------------------------------------------------===//
class Verifier {
public:
enum class Legality {
LEGAL,
RECURSIVELY_LEGAL,
ILLEGAL,
};
using OpVerifierFn = std::function<Optional<Legality>(Operation *op)>;
using TypeVerifierFn = std::function<Legality(Type type)>;
void addIllegalDialect(StringRef dialectName) {
dialectLegality.insert({dialectName, Legality::ILLEGAL});
}
template <typename DialectT>
void addIllegalDialect() {
addIllegalDialect(DialectT::getDialectNamespace());
}
template <typename OpT>
void addLegalOp() {
opLegality.insert({OpT::getOperationName(), Legality::LEGAL});
}
template <typename OpT>
void addRecursivelyLegalOp() {
opLegality.insert({OpT::getOperationName(), Legality::RECURSIVELY_LEGAL});
}
template <typename OpT>
void addIllegalOp() {
opLegality.insert({OpT::getOperationName(), Legality::ILLEGAL});
}
void addOpVerifier(std::function<Optional<Legality>(Operation *)> fn) {
opVerifiers.push_back(fn);
}
template <typename OpT>
void addOpVerifier(std::function<Optional<Legality>(OpT)> fn) {
auto wrapperFn = [=](Operation *baseOp) -> Optional<Legality> {
if (auto op = dyn_cast<OpT>(baseOp)) {
return fn(op);
}
return llvm::None;
};
opVerifiers.push_back(wrapperFn);
}
template <typename TypeT>
void addIllegalType() {
typeLegality.insert({TypeID::get<TypeT>(), Legality::ILLEGAL});
}
template <typename TypeT>
void addTypeVerifier(std::function<Legality(TypeT)> fn) {
auto wrapperFn = [=](Type baseType) { return fn(baseType.cast<TypeT>()); };
if (typeVerifiers.insert({TypeID::get<TypeT>(), wrapperFn}).second ==
false) {
assert(false && "already registered for this type");
}
}
LogicalResult run(Operation *rootOp) {
bool foundAnyIllegal = false;
rootOp->walk<WalkOrder::PreOrder>([&](Operation *op) {
auto walkResult = WalkResult::advance();
// Check for op legality - can skip the expensive work if known-illegal.
auto legality = getOpLegality(op);
switch (legality) {
case Legality::LEGAL:
// Op itself is legal but may not have valid operands/results.
break;
case Legality::RECURSIVELY_LEGAL:
// If the entire op w/ nested ops is legal then skip.
return WalkResult::skip();
default:
case Legality::ILLEGAL:
// Early-exit on illegal ops without recursing.
emitIllegalOpError(op);
foundAnyIllegal = true;
return WalkResult::skip();
}
// Check types for operands/results.
for (auto operandType : llvm::enumerate(op->getOperandTypes())) {
if (isTypeLegal(operandType.value())) continue;
emitIllegalTypeError(op, "operand", operandType.index(),
operandType.value());
foundAnyIllegal = true;
}
for (auto resultType : llvm::enumerate(op->getResultTypes())) {
if (isTypeLegal(resultType.value())) continue;
emitIllegalTypeError(op, "result", resultType.index(),
resultType.value());
foundAnyIllegal = true;
}
return walkResult;
});
return success(!foundAnyIllegal);
}
private:
Legality getOpLegality(Operation *op) {
auto opName = op->getName();
// Check specific ops first (we may override dialect settings).
{
auto legalityIt = opLegality.find(opName.getStringRef());
if (legalityIt != opLegality.end()) {
return legalityIt->second;
}
}
// Check all op verifiers (usually used for interface checks).
for (auto &opVerifier : opVerifiers) {
auto legalOr = opVerifier(op);
if (legalOr.hasValue()) {
return legalOr.getValue();
}
}
// If no op carveout is applied then check to see if the dialect is
// allowed at all.
{
auto legalityIt = dialectLegality.find(opName.getDialectNamespace());
if (legalityIt != dialectLegality.end()) {
return legalityIt->second;
}
}
// Assume legal by default.
return Legality::LEGAL;
}
bool isTypeLegal(Type type) {
// TODO(benvanik): subelements interface checks using recursive legality.
// Defer to verifiers first.
auto it = typeVerifiers.find(type.getTypeID());
if (it != typeVerifiers.end()) {
return it->second(type) != Legality::ILLEGAL;
}
// Check legality of the base type.
{
auto legalityIt = typeLegality.find(type.getTypeID());
if (legalityIt != typeLegality.end()) {
return legalityIt->second != Legality::ILLEGAL;
}
}
// Assume legal by default.
return true;
}
void emitIllegalOpError(Operation *op) {
op->emitOpError()
<< "illegal for this phase of lowering in the stream dialect; "
"expected to have been converted or removed";
}
void emitIllegalTypeError(Operation *op, StringRef location, unsigned idx,
Type type) {
op->emitOpError()
<< location << " " << idx << " type " << type
<< " illegal for this phase of lowering in the stream dialect";
}
DenseMap<StringRef, Legality> dialectLegality;
DenseMap<StringRef, Legality> opLegality;
SmallVector<OpVerifierFn> opVerifiers;
DenseMap<TypeID, Legality> typeLegality;
DenseMap<TypeID, TypeVerifierFn> typeVerifiers;
};
static void setupDefaultOpLegality(Verifier &verifier) {
verifier.addRecursivelyLegalOp<IREE::HAL::ExecutableOp>();
}
static void markStreamTensorOpsIllegal(Verifier &verifier) {
verifier.addOpVerifier([](Operation *op) -> Optional<Verifier::Legality> {
if (op->hasTrait<OpTrait::IREE::Stream::TensorPhaseOp>()) {
return Verifier::Legality::ILLEGAL;
}
return llvm::None;
});
}
static void markStreamAsyncOpsIllegal(Verifier &verifier) {
verifier.addOpVerifier([](Operation *op) -> Optional<Verifier::Legality> {
if (op->hasTrait<OpTrait::IREE::Stream::AsyncPhaseOp>()) {
return Verifier::Legality::ILLEGAL;
}
return llvm::None;
});
}
static void markStreamCmdOpsIllegal(Verifier &verifier) {
verifier.addOpVerifier([](Operation *op) -> Optional<Verifier::Legality> {
if (op->hasTrait<OpTrait::IREE::Stream::CmdPhaseOp>()) {
return Verifier::Legality::ILLEGAL;
}
return llvm::None;
});
}
//===----------------------------------------------------------------------===//
// -iree-stream-verify-input
//===----------------------------------------------------------------------===//
namespace {
class VerifyInputPass : public VerifyInputBase<VerifyInputPass> {
public:
VerifyInputPass() = default;
void runOnOperation() override {
Verifier verifier;
setupDefaultOpLegality(verifier);
// TODO(#7432): add indirect global expansion support to streams.
verifier.addIllegalOp<IREE::Util::GlobalAddressOp>();
verifier.addIllegalOp<IREE::Util::GlobalLoadIndirectOp>();
verifier.addIllegalOp<IREE::Util::GlobalStoreIndirectOp>();
if (failed(verifier.run(getOperation()))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<mlir::ModuleOp>> createVerifyInputPass() {
return std::make_unique<VerifyInputPass>();
}
//===----------------------------------------------------------------------===//
// -iree-stream-verify-lowering-to-tensors
//===----------------------------------------------------------------------===//
static void markTensorInputsIllegal(Verifier &verifier) {
// Tensorish dialects should all be either converted or outlined into
// executables. Everything should be in resources now.
verifier.addIllegalDialect("tensor");
verifier.addIllegalDialect("linalg");
// We don't allow the flow dialect except for inside of executables for which
// we don't yet have a full mapping to in the stream dialect.
// TODO(#7277): remove this carveout once we switch over to streams fully.
verifier.addIllegalDialect("flow");
verifier.addRecursivelyLegalOp<IREE::Stream::ExecutableOp>();
}
namespace {
class VerifyLoweringToTensorsPass
: public VerifyLoweringToTensorsBase<VerifyLoweringToTensorsPass> {
public:
VerifyLoweringToTensorsPass() = default;
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<IREE::Stream::StreamDialect>();
registry.insert<IREE::Util::UtilDialect>();
}
void runOnOperation() override {
// We cannot have stream.cmd.* ops mixed with stream.tensor/async.* ops
// as they use different memory models.
Verifier verifier;
setupDefaultOpLegality(verifier);
markTensorInputsIllegal(verifier);
markStreamCmdOpsIllegal(verifier);
if (failed(verifier.run(getOperation()))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<mlir::ModuleOp>>
createVerifyLoweringToTensorsPass() {
return std::make_unique<VerifyLoweringToTensorsPass>();
}
//===----------------------------------------------------------------------===//
// -iree-stream-verify-lowering-to-tensors
//===----------------------------------------------------------------------===//
namespace {
class VerifyLoweringToAsyncPass
: public VerifyLoweringToAsyncBase<VerifyLoweringToAsyncPass> {
public:
VerifyLoweringToAsyncPass() = default;
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<IREE::Stream::StreamDialect>();
registry.insert<IREE::Util::UtilDialect>();
}
void runOnOperation() override {
// We cannot have stream.cmd.* ops mixed with stream.tensor/async.* ops
// as they use different memory models.
Verifier verifier;
setupDefaultOpLegality(verifier);
markTensorInputsIllegal(verifier);
markStreamTensorOpsIllegal(verifier);
markStreamCmdOpsIllegal(verifier);
// All resources should have had their usage assigned.
verifier.addTypeVerifier<IREE::Stream::ResourceType>([](auto type) {
if (type.getLifetime() == IREE::Stream::Lifetime::Unknown) {
return Verifier::Legality::ILLEGAL;
}
return Verifier::Legality::LEGAL;
});
// All streamable ops should be inside of execution regions.
verifier.addOpVerifier<IREE::Stream::StreamableOpInterface>(
[](auto op) -> Optional<Verifier::Legality> {
// Allow metadata ops outside of execution regions.
if (op.isMetadata()) return Verifier::Legality::LEGAL;
// TODO(benvanik): execution region interface to make this generic.
if (!op->template getParentOfType<IREE::Stream::AsyncExecuteOp>()) {
op->emitOpError()
<< ": streamable op expected to be in an execution region";
return Verifier::Legality::ILLEGAL;
}
return llvm::None;
});
if (failed(verifier.run(getOperation()))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<mlir::ModuleOp>>
createVerifyLoweringToAsyncPass() {
return std::make_unique<VerifyLoweringToAsyncPass>();
}
//===----------------------------------------------------------------------===//
// -iree-stream-verify-lowering-to-cmd
//===----------------------------------------------------------------------===//
namespace {
class VerifyLoweringToCmdPass
: public VerifyLoweringToCmdBase<VerifyLoweringToCmdPass> {
public:
VerifyLoweringToCmdPass() = default;
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<IREE::Stream::StreamDialect>();
registry.insert<IREE::Util::UtilDialect>();
}
void runOnOperation() override {
Verifier verifier;
setupDefaultOpLegality(verifier);
markTensorInputsIllegal(verifier);
markStreamTensorOpsIllegal(verifier);
markStreamAsyncOpsIllegal(verifier);
// All resources should have had their usage assigned.
verifier.addTypeVerifier<IREE::Stream::ResourceType>([](auto type) {
if (type.getLifetime() == IREE::Stream::Lifetime::Unknown) {
return Verifier::Legality::ILLEGAL;
}
return Verifier::Legality::LEGAL;
});
if (failed(verifier.run(getOperation()))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<mlir::ModuleOp>> createVerifyLoweringToCmdPass() {
return std::make_unique<VerifyLoweringToCmdPass>();
}
} // namespace Stream
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<commit_msg>flow dialect ops are allowed inside of stream.executables. Eventually we can have standardized ops that are not flow specific but there's no pressing need.<commit_after>// Copyright 2021 The IREE Authors
//
// Licensed 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 <utility>
#include "iree/compiler/Dialect/HAL/IR/HALOps.h"
#include "iree/compiler/Dialect/Stream/IR/StreamDialect.h"
#include "iree/compiler/Dialect/Stream/IR/StreamOps.h"
#include "iree/compiler/Dialect/Stream/IR/StreamTraits.h"
#include "iree/compiler/Dialect/Stream/Transforms/PassDetail.h"
#include "iree/compiler/Dialect/Stream/Transforms/Passes.h"
#include "iree/compiler/Dialect/Util/IR/UtilDialect.h"
#include "iree/compiler/Dialect/Util/IR/UtilOps.h"
#include "llvm/ADT/TypeSwitch.h"
#include "mlir/IR/Attributes.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/Diagnostics.h"
#include "mlir/Pass/Pass.h"
namespace mlir {
namespace iree_compiler {
namespace IREE {
namespace Stream {
//===----------------------------------------------------------------------===//
// Base pass utility
//===----------------------------------------------------------------------===//
class Verifier {
public:
enum class Legality {
LEGAL,
RECURSIVELY_LEGAL,
ILLEGAL,
};
using OpVerifierFn = std::function<Optional<Legality>(Operation *op)>;
using TypeVerifierFn = std::function<Legality(Type type)>;
void addIllegalDialect(StringRef dialectName) {
dialectLegality.insert({dialectName, Legality::ILLEGAL});
}
template <typename DialectT>
void addIllegalDialect() {
addIllegalDialect(DialectT::getDialectNamespace());
}
template <typename OpT>
void addLegalOp() {
opLegality.insert({OpT::getOperationName(), Legality::LEGAL});
}
template <typename OpT>
void addRecursivelyLegalOp() {
opLegality.insert({OpT::getOperationName(), Legality::RECURSIVELY_LEGAL});
}
template <typename OpT>
void addIllegalOp() {
opLegality.insert({OpT::getOperationName(), Legality::ILLEGAL});
}
void addOpVerifier(std::function<Optional<Legality>(Operation *)> fn) {
opVerifiers.push_back(fn);
}
template <typename OpT>
void addOpVerifier(std::function<Optional<Legality>(OpT)> fn) {
auto wrapperFn = [=](Operation *baseOp) -> Optional<Legality> {
if (auto op = dyn_cast<OpT>(baseOp)) {
return fn(op);
}
return llvm::None;
};
opVerifiers.push_back(wrapperFn);
}
template <typename TypeT>
void addIllegalType() {
typeLegality.insert({TypeID::get<TypeT>(), Legality::ILLEGAL});
}
template <typename TypeT>
void addTypeVerifier(std::function<Legality(TypeT)> fn) {
auto wrapperFn = [=](Type baseType) { return fn(baseType.cast<TypeT>()); };
if (typeVerifiers.insert({TypeID::get<TypeT>(), wrapperFn}).second ==
false) {
assert(false && "already registered for this type");
}
}
LogicalResult run(Operation *rootOp) {
bool foundAnyIllegal = false;
rootOp->walk<WalkOrder::PreOrder>([&](Operation *op) {
auto walkResult = WalkResult::advance();
// Check for op legality - can skip the expensive work if known-illegal.
auto legality = getOpLegality(op);
switch (legality) {
case Legality::LEGAL:
// Op itself is legal but may not have valid operands/results.
break;
case Legality::RECURSIVELY_LEGAL:
// If the entire op w/ nested ops is legal then skip.
return WalkResult::skip();
default:
case Legality::ILLEGAL:
// Early-exit on illegal ops without recursing.
emitIllegalOpError(op);
foundAnyIllegal = true;
return WalkResult::skip();
}
// Check types for operands/results.
for (auto operandType : llvm::enumerate(op->getOperandTypes())) {
if (isTypeLegal(operandType.value())) continue;
emitIllegalTypeError(op, "operand", operandType.index(),
operandType.value());
foundAnyIllegal = true;
}
for (auto resultType : llvm::enumerate(op->getResultTypes())) {
if (isTypeLegal(resultType.value())) continue;
emitIllegalTypeError(op, "result", resultType.index(),
resultType.value());
foundAnyIllegal = true;
}
return walkResult;
});
return success(!foundAnyIllegal);
}
private:
Legality getOpLegality(Operation *op) {
auto opName = op->getName();
// Check specific ops first (we may override dialect settings).
{
auto legalityIt = opLegality.find(opName.getStringRef());
if (legalityIt != opLegality.end()) {
return legalityIt->second;
}
}
// Check all op verifiers (usually used for interface checks).
for (auto &opVerifier : opVerifiers) {
auto legalOr = opVerifier(op);
if (legalOr.hasValue()) {
return legalOr.getValue();
}
}
// If no op carveout is applied then check to see if the dialect is
// allowed at all.
{
auto legalityIt = dialectLegality.find(opName.getDialectNamespace());
if (legalityIt != dialectLegality.end()) {
return legalityIt->second;
}
}
// Assume legal by default.
return Legality::LEGAL;
}
bool isTypeLegal(Type type) {
// TODO(benvanik): subelements interface checks using recursive legality.
// Defer to verifiers first.
auto it = typeVerifiers.find(type.getTypeID());
if (it != typeVerifiers.end()) {
return it->second(type) != Legality::ILLEGAL;
}
// Check legality of the base type.
{
auto legalityIt = typeLegality.find(type.getTypeID());
if (legalityIt != typeLegality.end()) {
return legalityIt->second != Legality::ILLEGAL;
}
}
// Assume legal by default.
return true;
}
void emitIllegalOpError(Operation *op) {
op->emitOpError()
<< "illegal for this phase of lowering in the stream dialect; "
"expected to have been converted or removed";
}
void emitIllegalTypeError(Operation *op, StringRef location, unsigned idx,
Type type) {
op->emitOpError()
<< location << " " << idx << " type " << type
<< " illegal for this phase of lowering in the stream dialect";
}
DenseMap<StringRef, Legality> dialectLegality;
DenseMap<StringRef, Legality> opLegality;
SmallVector<OpVerifierFn> opVerifiers;
DenseMap<TypeID, Legality> typeLegality;
DenseMap<TypeID, TypeVerifierFn> typeVerifiers;
};
static void setupDefaultOpLegality(Verifier &verifier) {
verifier.addRecursivelyLegalOp<IREE::HAL::ExecutableOp>();
}
static void markStreamTensorOpsIllegal(Verifier &verifier) {
verifier.addOpVerifier([](Operation *op) -> Optional<Verifier::Legality> {
if (op->hasTrait<OpTrait::IREE::Stream::TensorPhaseOp>()) {
return Verifier::Legality::ILLEGAL;
}
return llvm::None;
});
}
static void markStreamAsyncOpsIllegal(Verifier &verifier) {
verifier.addOpVerifier([](Operation *op) -> Optional<Verifier::Legality> {
if (op->hasTrait<OpTrait::IREE::Stream::AsyncPhaseOp>()) {
return Verifier::Legality::ILLEGAL;
}
return llvm::None;
});
}
static void markStreamCmdOpsIllegal(Verifier &verifier) {
verifier.addOpVerifier([](Operation *op) -> Optional<Verifier::Legality> {
if (op->hasTrait<OpTrait::IREE::Stream::CmdPhaseOp>()) {
return Verifier::Legality::ILLEGAL;
}
return llvm::None;
});
}
//===----------------------------------------------------------------------===//
// -iree-stream-verify-input
//===----------------------------------------------------------------------===//
namespace {
class VerifyInputPass : public VerifyInputBase<VerifyInputPass> {
public:
VerifyInputPass() = default;
void runOnOperation() override {
Verifier verifier;
setupDefaultOpLegality(verifier);
// TODO(#7432): add indirect global expansion support to streams.
verifier.addIllegalOp<IREE::Util::GlobalAddressOp>();
verifier.addIllegalOp<IREE::Util::GlobalLoadIndirectOp>();
verifier.addIllegalOp<IREE::Util::GlobalStoreIndirectOp>();
if (failed(verifier.run(getOperation()))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<mlir::ModuleOp>> createVerifyInputPass() {
return std::make_unique<VerifyInputPass>();
}
//===----------------------------------------------------------------------===//
// -iree-stream-verify-lowering-to-tensors
//===----------------------------------------------------------------------===//
static void markTensorInputsIllegal(Verifier &verifier) {
// Tensorish dialects should all be either converted or outlined into
// executables. Everything should be in resources now.
verifier.addIllegalDialect("tensor");
verifier.addIllegalDialect("linalg");
// We don't allow the flow dialect except for inside of executables where
// we don't yet have a full mapping to in the stream dialect (and may never).
// Ideally we'd not be using the flow ops inside at all at this point but
// that'd require some upstream ops (or something in codegen) for the tensor
// load and store behaviors as well as the workgroup info.
verifier.addIllegalDialect("flow");
verifier.addRecursivelyLegalOp<IREE::Stream::ExecutableOp>();
}
namespace {
class VerifyLoweringToTensorsPass
: public VerifyLoweringToTensorsBase<VerifyLoweringToTensorsPass> {
public:
VerifyLoweringToTensorsPass() = default;
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<IREE::Stream::StreamDialect>();
registry.insert<IREE::Util::UtilDialect>();
}
void runOnOperation() override {
// We cannot have stream.cmd.* ops mixed with stream.tensor/async.* ops
// as they use different memory models.
Verifier verifier;
setupDefaultOpLegality(verifier);
markTensorInputsIllegal(verifier);
markStreamCmdOpsIllegal(verifier);
if (failed(verifier.run(getOperation()))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<mlir::ModuleOp>>
createVerifyLoweringToTensorsPass() {
return std::make_unique<VerifyLoweringToTensorsPass>();
}
//===----------------------------------------------------------------------===//
// -iree-stream-verify-lowering-to-tensors
//===----------------------------------------------------------------------===//
namespace {
class VerifyLoweringToAsyncPass
: public VerifyLoweringToAsyncBase<VerifyLoweringToAsyncPass> {
public:
VerifyLoweringToAsyncPass() = default;
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<IREE::Stream::StreamDialect>();
registry.insert<IREE::Util::UtilDialect>();
}
void runOnOperation() override {
// We cannot have stream.cmd.* ops mixed with stream.tensor/async.* ops
// as they use different memory models.
Verifier verifier;
setupDefaultOpLegality(verifier);
markTensorInputsIllegal(verifier);
markStreamTensorOpsIllegal(verifier);
markStreamCmdOpsIllegal(verifier);
// All resources should have had their usage assigned.
verifier.addTypeVerifier<IREE::Stream::ResourceType>([](auto type) {
if (type.getLifetime() == IREE::Stream::Lifetime::Unknown) {
return Verifier::Legality::ILLEGAL;
}
return Verifier::Legality::LEGAL;
});
// All streamable ops should be inside of execution regions.
verifier.addOpVerifier<IREE::Stream::StreamableOpInterface>(
[](auto op) -> Optional<Verifier::Legality> {
// Allow metadata ops outside of execution regions.
if (op.isMetadata()) return Verifier::Legality::LEGAL;
// TODO(benvanik): execution region interface to make this generic.
if (!op->template getParentOfType<IREE::Stream::AsyncExecuteOp>()) {
op->emitOpError()
<< ": streamable op expected to be in an execution region";
return Verifier::Legality::ILLEGAL;
}
return llvm::None;
});
if (failed(verifier.run(getOperation()))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<mlir::ModuleOp>>
createVerifyLoweringToAsyncPass() {
return std::make_unique<VerifyLoweringToAsyncPass>();
}
//===----------------------------------------------------------------------===//
// -iree-stream-verify-lowering-to-cmd
//===----------------------------------------------------------------------===//
namespace {
class VerifyLoweringToCmdPass
: public VerifyLoweringToCmdBase<VerifyLoweringToCmdPass> {
public:
VerifyLoweringToCmdPass() = default;
void getDependentDialects(DialectRegistry ®istry) const override {
registry.insert<IREE::Stream::StreamDialect>();
registry.insert<IREE::Util::UtilDialect>();
}
void runOnOperation() override {
Verifier verifier;
setupDefaultOpLegality(verifier);
markTensorInputsIllegal(verifier);
markStreamTensorOpsIllegal(verifier);
markStreamAsyncOpsIllegal(verifier);
// All resources should have had their usage assigned.
verifier.addTypeVerifier<IREE::Stream::ResourceType>([](auto type) {
if (type.getLifetime() == IREE::Stream::Lifetime::Unknown) {
return Verifier::Legality::ILLEGAL;
}
return Verifier::Legality::LEGAL;
});
if (failed(verifier.run(getOperation()))) {
return signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OperationPass<mlir::ModuleOp>> createVerifyLoweringToCmdPass() {
return std::make_unique<VerifyLoweringToCmdPass>();
}
} // namespace Stream
} // namespace IREE
} // namespace iree_compiler
} // namespace mlir
<|endoftext|> |
<commit_before>// ScreenCaptureBlockerForRDP.cpp : アプリケーションのエントリ ポイントを定義します。
//
#include "stdafx.h"
#include <shellapi.h>
#include "ScreenCaptureBlockerForRDP.h"
#include "HookDLL/HookDLL.h"
#define MAX_LOADSTRING 100
// グローバル定数:
WCHAR const SZWINDOWCLASS[] = L"SCREENCAPTUREBLOCKERFORRDP"; // メイン ウィンドウ クラス名
UINT const WMAPP_NOTIFYCALLBACK = WM_APP + 1;
// グローバル変数:
HINSTANCE hInst; // 現在のインターフェイス
WCHAR szTitle[MAX_LOADSTRING]; // タイトル バーのテキスト
// このコード モジュールに含まれる関数の宣言を転送します:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
void ShowContextMenu(HWND hwnd, POINT pt);
BOOL AddNotificationIcon(HWND hwnd);
BOOL DeleteNotificationIcon();
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: ここにコードを挿入してください。
// グローバル文字列を初期化しています。
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// アプリケーションの初期化を実行します:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
MSG msg;
// メイン メッセージ ループ:
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
//
// 関数: MyRegisterClass()
//
// 目的: ウィンドウ クラスを登録します。
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_DENYTAKINGSCREENCAPTUREFORRDP));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = 0;
wcex.lpszClassName = SZWINDOWCLASS;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_DENYTAKINGSCREENCAPTUREFORRDP));
return RegisterClassExW(&wcex);
}
//
// 関数: InitInstance(HINSTANCE, int)
//
// 目的: インスタンス ハンドルを保存して、メイン ウィンドウを作成します。
//
// コメント:
//
// この関数で、グローバル変数でインスタンス ハンドルを保存し、
// メイン プログラム ウィンドウを作成および表示します。
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // グローバル変数にインスタンス処理を格納します。
HWND hWnd = CreateWindowW(SZWINDOWCLASS, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
InstallHook(hWnd);
return TRUE;
}
//
// 関数: AddNotificationIcon()
//
// 目的: 通知領域にインジケーターアイコンを表示します。
//
BOOL AddNotificationIcon(HWND hwnd)
{
NOTIFYICONDATA nid = { sizeof(nid) };
nid.hWnd = hwnd;
nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE | NIF_SHOWTIP | NIF_GUID;
nid.uCallbackMessage = WMAPP_NOTIFYCALLBACK;
nid.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_DENYTAKINGSCREENCAPTUREFORRDP));
LoadString(hInst, IDS_TOOLTIP, nid.szTip, ARRAYSIZE(nid.szTip));
Shell_NotifyIcon(NIM_ADD, &nid);
nid.uVersion = NOTIFYICON_VERSION_4;
return Shell_NotifyIcon(NIM_SETVERSION, &nid);
}
//
// 関数: DeleteNotificationIcon()
//
// 目的: 通知領域からインジケーターアイコンを削除します。
//
BOOL DeleteNotificationIcon()
{
NOTIFYICONDATA nid = { sizeof(nid) };
nid.uFlags = NIF_GUID;
return Shell_NotifyIcon(NIM_DELETE, &nid);
}
//
// 関数: ShowContextMenu()
//
// 目的: インジケーターアイコン上で右クリックした時に表示されるメニューの処理を行います。
//
void ShowContextMenu(HWND hwnd, POINT pt)
{
HMENU hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDC_CONTEXTMENU));
if (hMenu)
{
HMENU hSubMenu = GetSubMenu(hMenu, 0);
if (hSubMenu)
{
SetForegroundWindow(hwnd);
UINT uFlags = TPM_RIGHTBUTTON;
if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0)
{
uFlags |= TPM_RIGHTALIGN;
}
else
{
uFlags |= TPM_LEFTALIGN;
}
TrackPopupMenuEx(hSubMenu, uFlags, pt.x, pt.y, hwnd, NULL);
}
DestroyMenu(hMenu);
}
}
//
// 関数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 目的: メイン ウィンドウのメッセージを処理します。
//
// WM_COMMAND - アプリケーション メニューの処理
// WM_PAINT - メイン ウィンドウの描画
// WM_DESTROY - 中止メッセージを表示して戻る
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
if (!AddNotificationIcon(hWnd))
{
MessageBox(hWnd, L"Error adding icon", L"Error", MB_OK);
return -1;
}
break;
case WM_COMMAND:
{
int const wmId = LOWORD(wParam);
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WMAPP_NOTIFYCALLBACK:
switch (LOWORD(lParam))
{
case WM_CONTEXTMENU:
{
POINT const pt = { LOWORD(wParam), HIWORD(wParam) };
ShowContextMenu(hWnd, pt);
}
break;
default:
;
}
break;
case WM_DESTROY:
UninstallHook();
DeleteNotificationIcon();
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// バージョン情報ボックスのメッセージ ハンドラーです。
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
<commit_msg>プログラムを終了しても通知アイコンが消えないバグの修正<commit_after>// ScreenCaptureBlockerForRDP.cpp : アプリケーションのエントリ ポイントを定義します。
//
#include "stdafx.h"
#include <shellapi.h>
#include "ScreenCaptureBlockerForRDP.h"
#include "HookDLL/HookDLL.h"
#define MAX_LOADSTRING 100
// グローバル定数:
WCHAR const SZWINDOWCLASS[] = L"SCREENCAPTUREBLOCKERFORRDP"; // メイン ウィンドウ クラス名
UINT const WMAPP_NOTIFYCALLBACK = WM_APP + 1;
// グローバル変数:
HINSTANCE hInst; // 現在のインターフェイス
WCHAR szTitle[MAX_LOADSTRING]; // タイトル バーのテキスト
// このコード モジュールに含まれる関数の宣言を転送します:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM);
void ShowContextMenu(HWND hwnd, POINT pt);
BOOL AddNotificationIcon(HWND hwnd);
BOOL DeleteNotificationIcon(HWND hwnd);
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: ここにコードを挿入してください。
// グローバル文字列を初期化しています。
LoadStringW(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// アプリケーションの初期化を実行します:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
MSG msg;
// メイン メッセージ ループ:
while (GetMessage(&msg, nullptr, 0, 0))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
return (int) msg.wParam;
}
//
// 関数: MyRegisterClass()
//
// 目的: ウィンドウ クラスを登録します。
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEXW wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_DENYTAKINGSCREENCAPTUREFORRDP));
wcex.hCursor = LoadCursor(nullptr, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = 0;
wcex.lpszClassName = SZWINDOWCLASS;
wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_DENYTAKINGSCREENCAPTUREFORRDP));
return RegisterClassExW(&wcex);
}
//
// 関数: InitInstance(HINSTANCE, int)
//
// 目的: インスタンス ハンドルを保存して、メイン ウィンドウを作成します。
//
// コメント:
//
// この関数で、グローバル変数でインスタンス ハンドルを保存し、
// メイン プログラム ウィンドウを作成および表示します。
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
hInst = hInstance; // グローバル変数にインスタンス処理を格納します。
HWND hWnd = CreateWindowW(SZWINDOWCLASS, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, nullptr, nullptr, hInstance, nullptr);
if (!hWnd)
{
return FALSE;
}
InstallHook(hWnd);
return TRUE;
}
//
// 関数: AddNotificationIcon()
//
// 目的: 通知領域にインジケーターアイコンを表示します。
//
BOOL AddNotificationIcon(HWND hwnd)
{
NOTIFYICONDATA nid = { sizeof(nid) };
nid.hWnd = hwnd;
nid.uFlags = NIF_ICON | NIF_TIP | NIF_MESSAGE | NIF_SHOWTIP | NIF_GUID;
nid.uCallbackMessage = WMAPP_NOTIFYCALLBACK;
nid.hIcon = LoadIcon(hInst, MAKEINTRESOURCE(IDI_DENYTAKINGSCREENCAPTUREFORRDP));
LoadString(hInst, IDS_TOOLTIP, nid.szTip, ARRAYSIZE(nid.szTip));
Shell_NotifyIcon(NIM_ADD, &nid);
nid.uVersion = NOTIFYICON_VERSION_4;
return Shell_NotifyIcon(NIM_SETVERSION, &nid);
}
//
// 関数: DeleteNotificationIcon()
//
// 目的: 通知領域からインジケーターアイコンを削除します。
//
BOOL DeleteNotificationIcon(HWND hwnd)
{
NOTIFYICONDATA nid = { sizeof(nid) };
nid.hWnd = hwnd;
nid.uFlags = NIF_ICON;
return Shell_NotifyIcon(NIM_DELETE, &nid);
}
//
// 関数: ShowContextMenu()
//
// 目的: インジケーターアイコン上で右クリックした時に表示されるメニューの処理を行います。
//
void ShowContextMenu(HWND hwnd, POINT pt)
{
HMENU hMenu = LoadMenu(hInst, MAKEINTRESOURCE(IDC_CONTEXTMENU));
if (hMenu)
{
HMENU hSubMenu = GetSubMenu(hMenu, 0);
if (hSubMenu)
{
SetForegroundWindow(hwnd);
UINT uFlags = TPM_RIGHTBUTTON;
if (GetSystemMetrics(SM_MENUDROPALIGNMENT) != 0)
{
uFlags |= TPM_RIGHTALIGN;
}
else
{
uFlags |= TPM_LEFTALIGN;
}
TrackPopupMenuEx(hSubMenu, uFlags, pt.x, pt.y, hwnd, NULL);
}
DestroyMenu(hMenu);
}
}
//
// 関数: WndProc(HWND, UINT, WPARAM, LPARAM)
//
// 目的: メイン ウィンドウのメッセージを処理します。
//
// WM_COMMAND - アプリケーション メニューの処理
// WM_PAINT - メイン ウィンドウの描画
// WM_DESTROY - 中止メッセージを表示して戻る
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
if (!AddNotificationIcon(hWnd))
{
MessageBox(hWnd, L"Error adding icon", L"Error", MB_OK);
return -1;
}
break;
case WM_COMMAND:
{
int const wmId = LOWORD(wParam);
switch (wmId)
{
case IDM_ABOUT:
DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About);
break;
case IDM_EXIT:
DestroyWindow(hWnd);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
break;
case WMAPP_NOTIFYCALLBACK:
switch (LOWORD(lParam))
{
case WM_CONTEXTMENU:
{
POINT const pt = { LOWORD(wParam), HIWORD(wParam) };
ShowContextMenu(hWnd, pt);
}
break;
default:
;
}
break;
case WM_DESTROY:
UninstallHook();
DeleteNotificationIcon(hWnd);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// バージョン情報ボックスのメッセージ ハンドラーです。
INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
UNREFERENCED_PARAMETER(lParam);
switch (message)
{
case WM_INITDIALOG:
return (INT_PTR)TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return (INT_PTR)TRUE;
}
break;
}
return (INT_PTR)FALSE;
}
<|endoftext|> |
<commit_before>/*
* VocabMatch.cpp
*
* Created on: Oct 11, 2013
* Author: andresf
*/
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <sys/stat.h>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <opencv2/core/core.hpp>
#include <VocabTree.h>
#include <FileUtils.hpp>
double mytime;
//int BasifyFilename(const char *filename, char *base);
void BasifyFilename(const std::string& filename, std::string& base);
void PrintHTMLHeader(FILE *f, int num_nns);
void PrintHTMLRow(FILE *f, const std::string &query, cv::Mat& scores,
cv::Mat& perm, int num_nns, const std::vector<std::string> &db_images);
void PrintHTMLFooter(FILE *f);
int main(int argc, char **argv) {
if (argc < 6 || argc > 8) {
printf("\nUsage:\n"
"\t%s <in.tree> <in.db.list> <in.query.list>"
" <num_nbrs> <matches.out> [results.html] [candidates.txt]\n\n",
argv[0]);
return EXIT_FAILURE;
}
char *tree_in = argv[1];
char *db_list_in = argv[2];
char *query_list_in = argv[3];
uint num_nbrs = atoi(argv[4]);
char *matches_out = argv[5];
const char *output_html = "results.html";
const char *candidates_out = "candidates.txt";
if (argc >= 7)
output_html = argv[6];
if (argc >= 8)
candidates_out = argv[7];
// Verifying input parameters
boost::regex expression("^(.+)(\\.)(yaml|xml)(\\.)(gz)$");
if (boost::regex_match(std::string(tree_in), expression) == false) {
fprintf(stderr,
"Input tree file must have the extension .yaml.gz or .xml.gz\n");
return EXIT_FAILURE;
}
// Step 1/4: load tree
cvflann::VocabTree tree;
printf("-- Reading tree from [%s]\n", tree_in);
mytime = cv::getTickCount();
tree.load(std::string(tree_in));
mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
* 1000;
printf(" Tree loaded in [%lf] ms, got [%lu] words \n", mytime,
tree.size());
// Step 2/4: read the database keyfiles
printf("-- Loading DB keyfiles names and landmark id's\n");
std::vector<std::string> db_filenames;
std::vector<int> db_landmarks;
std::ifstream keysList(db_list_in, std::fstream::in);
if (keysList.is_open() == false) {
fprintf(stderr, "Error opening file [%s] for reading\n", db_list_in);
return EXIT_FAILURE;
}
// Loading file names in list into a vector
std::string line;
while (getline(keysList, line)) {
// Verifying line format
if (boost::regex_match(line, boost::regex("^(.+)\\s(.+)$")) == false) {
fprintf(stderr,
"Error while parsing DB list file [%s], line [%s] should be: <key.file> <landmark.id>\n",
db_list_in, line.c_str());
return EXIT_FAILURE;
}
// Extracting filename and landmark from line
char filename[256];
int landmark;
sscanf(line.c_str(), "%s %d", filename, &landmark);
// Checking that file exists, if not print error and exit
struct stat buffer;
if (stat(filename, &buffer) != 0) {
fprintf(stderr, "Keypoints file [%s] doesn't exist\n", filename);
return EXIT_FAILURE;
}
// Checking that filename refers to a compressed yaml or xml file
if (boost::regex_match(std::string(filename), expression) == false) {
fprintf(stderr,
"Keypoints file [%s] must have the extension .yaml.gz or .xml.gz\n",
filename);
return EXIT_FAILURE;
}
db_filenames.push_back(std::string(filename));
db_landmarks.push_back(landmark);
}
// Close file
keysList.close();
// Step 3/4: read the query keyfiles
printf("-- Loading query keyfiles names\n");
std::vector<std::string> query_filenames;
keysList.open(query_list_in, std::fstream::in);
if (keysList.is_open() == false) {
fprintf(stderr, "Error opening file [%s] for reading\n", db_list_in);
return EXIT_FAILURE;
}
// Loading file names in list into a vector
while (getline(keysList, line)) {
// Checking that file exists, if not print error and exit
struct stat buffer;
if (stat(line.c_str(), &buffer) != 0) {
fprintf(stderr, "Keypoints file [%s] doesn't exist\n",
line.c_str());
return EXIT_FAILURE;
}
// Checking that line refers to a compressed yaml or xml file
if (boost::regex_match(line, expression) == false) {
fprintf(stderr,
"Keypoints file [%s] must have the extension .yaml.gz or .xml.gz\n",
line.c_str());
return EXIT_FAILURE;
}
query_filenames.push_back(line);
}
// Close file
keysList.close();
// Step 4/4: score each query keyfile
int normType = cv::NORM_L1;
printf("-- Scoring [%lu] query images against [%lu] DB images using [%s]\n",
query_filenames.size(), db_filenames.size(),
normType == cv::NORM_L1 ? "L1-norm" :
normType == cv::NORM_L2 ? "L2-norm" : "UNKNOWN-norm");
std::vector<cv::KeyPoint> imgKeypoints;
cv::Mat imgDescriptors;
cv::Mat scores;
int max_ld = *std::max_element(db_landmarks.begin(), db_landmarks.end());
FILE *f_match = fopen(matches_out, "w");
if (f_match == NULL) {
fprintf(stderr, "Error opening file [%s] for writing\n",
candidates_out);
return EXIT_FAILURE;
}
FILE *f_candidates = fopen(candidates_out, "w");
if (f_candidates == NULL) {
fprintf(stderr, "Error opening file [%s] for writing\n",
candidates_out);
return EXIT_FAILURE;
}
FILE *f_html = fopen(output_html, "w");
PrintHTMLHeader(f_html, num_nbrs);
if (f_html == NULL) {
fprintf(stderr, "Error opening file [%s] for writing\n",
candidates_out);
return EXIT_FAILURE;
}
for (size_t i = 0; i < query_filenames.size(); i++) {
// Initialize keypoints and descriptors
imgKeypoints.clear();
imgDescriptors = cv::Mat();
// Load query keypoints and descriptors
FileUtils::loadFeatures(query_filenames[i], imgKeypoints,
imgDescriptors);
// Score query bow vector against DB images bow vectors
mytime = cv::getTickCount();
try {
tree.scoreQuery(imgDescriptors, scores, db_filenames.size(),
cv::NORM_L1);
} catch (const std::runtime_error& error) {
fprintf(stderr, "%s\n", error.what());
return EXIT_FAILURE;
}
mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
* 1000;
// Print to standard output the matching scores between
// the query bow vector and the DB images bow vectors
for (size_t j = 0; (int) j < scores.cols; j++) {
printf(
" Match score between [%lu] query image and [%lu] DB image: %f\n",
i, j, scores.at<float>(0, j));
}
// Obtain indices of ordered scores
cv::Mat perm;
// Note: recall that the index of the images in the inverted file corresponds
// to the zero-based line number in the file used to build the DB.
// Hence scores matrix and db_landmarks and db_filenames vectors.
// are equally ordered.
// Also the images in list_db and list_db_ld must be equally ordered,
// that implies same number of elements.
//
// list_db list_db_ld
// img1 ---> img1 ld1
// img2 ---> img2 ld1
// img3 ---> img3 ld1
// img4 ---> img4 ld2
// img5 ---> img5 ld2
// img6 ---> img6 ld2
cv::sortIdx(scores, perm, cv::SORT_EVERY_ROW + cv::SORT_DESCENDING);
int top = MIN (num_nbrs, db_filenames.size());
// Initialize votes vector
// Note: size is maximum landmark id plus one because landmark index its zero-based
std::vector<int> votes(max_ld + 1, 0);
// Accumulating landmark votes for the top scored images
// Note: recall that images might refer to the same landmark
for (size_t i = 0; (int) i < top; i++) {
votes[db_landmarks[perm.at<int>(0, i)]]++;
}
// Finding max voted landmark and the number of votes it got
int max_votes = 0;
int max_landmark = -1;
for (int j = 0; j < max_ld + 1; j++) {
if (votes[j] > max_votes) {
max_votes = votes[j];
max_landmark = j;
}
}
// Print to a file the ranked list of candidates ordered by score
fprintf(f_candidates, "%s", query_filenames[i].c_str());
for (int j = 0; j < top; j++) {
std::string d_base = db_filenames[perm.at<int>(0, j)];
fprintf(f_candidates, " %s", d_base.c_str());
}
fprintf(f_candidates, "\n");
fflush(f_candidates);
// Print to a file the max voted landmark information
fprintf(f_match, "%lu %d %d\n", i, max_landmark, max_votes);
fflush(f_match);
fflush(stdout);
// Print to a file the ranked list of candidates ordered by score in HTML format
PrintHTMLRow(f_html, query_filenames[i], scores, perm, top,
db_filenames);
}
fclose(f_candidates);
fclose(f_match);
PrintHTMLFooter(f_html);
fclose(f_html);
return EXIT_SUCCESS;
}
void PrintHTMLHeader(FILE *f, int num_nns) {
fprintf(f, "<html>\n"
"<header>\n"
"<title>Vocabulary tree results</title>\n"
"</header>\n"
"<body>\n"
"<h1>Vocabulary tree results</h1>\n"
"<hr>\n\n");
fprintf(f, "<table border=2 align=center>\n<tr>\n<th>Query image</th>\n");
for (int i = 0; i < num_nns; i++) {
fprintf(f, "<th>Match %d</th>\n", i + 1);
}
fprintf(f, "</tr>\n");
}
void PrintHTMLRow(FILE *f, const std::string &query, cv::Mat& scores,
cv::Mat& perm, int num_nns, const std::vector<std::string> &db_images) {
std::string q_thumb;
BasifyFilename(query, q_thumb);
fprintf(f,
"<tr align=center>\n<td><img src=\"%s\" style=\"max-height:200px\"><br><p>%s</p></td>\n",
q_thumb.c_str(), q_thumb.c_str());
for (int i = 0; i < num_nns; i++) {
std::string d_thumb;
BasifyFilename(db_images[perm.at<int>(0, i)], d_thumb);
fprintf(f,
"<td><img src=\"%s\" style=\"max-height:200px\"><br><p>%s</p></td>\n",
d_thumb.c_str(), d_thumb.c_str());
}
fprintf(f, "</tr>\n<tr align=right>\n");
fprintf(f, "<td></td>\n");
for (int i = 0; i < num_nns; i++)
fprintf(f, "<td>%0.5f</td>\n", scores.at<float>(0, perm.at<int>(0, i)));
fprintf(f, "</tr>\n");
}
void PrintHTMLFooter(FILE *f) {
fprintf(f, "</tr>\n"
"</table>\n"
"<hr>\n"
"</body>\n"
"</html>\n");
}
//int BasifyFilename(const char *filename, char *base)
void BasifyFilename(const std::string& key_fname, std::string& img_fname) {
// Extract key file name from query key file path
std::vector<std::string> tokens;
boost::split(tokens, key_fname, boost::is_any_of("//"));
CV_Assert(tokens.size() > 0);
// Get query key file name and query images path
std::string query_fname = tokens.back();
tokens.pop_back();
img_fname = boost::algorithm::join(tokens, "/");
tokens.clear();
boost::split(tokens, query_fname, boost::is_any_of("\\."));
CV_Assert(tokens.size() == 4);
img_fname += std::string("/") + tokens[0] + std::string(".thumb.jpg");
}
<commit_msg>VocabMatch/VocabMatch.cpp * Rolledback changes in BasifyFileName function so that the solution is simpler and doesn't imply any change in code but on the lists sent as parameters.<commit_after>/*
* VocabMatch.cpp
*
* Created on: Oct 11, 2013
* Author: andresf
*/
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <vector>
#include <sys/stat.h>
#include <boost/regex.hpp>
#include <opencv2/core/core.hpp>
#include <VocabTree.h>
#include <FileUtils.hpp>
double mytime;
int BasifyFilename(const char *filename, char *base);
void PrintHTMLHeader(FILE *f, int num_nns);
void PrintHTMLRow(FILE *f, const std::string &query, cv::Mat& scores,
cv::Mat& perm, int num_nns, const std::vector<std::string> &db_images);
void PrintHTMLFooter(FILE *f);
int main(int argc, char **argv) {
if (argc < 6 || argc > 8) {
printf("\nUsage:\n"
"\t%s <in.tree> <in.db.list> <in.query.list>"
" <num_nbrs> <matches.out> [results.html] [candidates.txt]\n\n",
argv[0]);
return EXIT_FAILURE;
}
char *tree_in = argv[1];
char *db_list_in = argv[2];
char *query_list_in = argv[3];
uint num_nbrs = atoi(argv[4]);
char *matches_out = argv[5];
const char *output_html = "results.html";
const char *candidates_out = "candidates.txt";
if (argc >= 7)
output_html = argv[6];
if (argc >= 8)
candidates_out = argv[7];
// Verifying input parameters
boost::regex expression("^(.+)(\\.)(yaml|xml)(\\.)(gz)$");
if (boost::regex_match(std::string(tree_in), expression) == false) {
fprintf(stderr,
"Input tree file must have the extension .yaml.gz or .xml.gz\n");
return EXIT_FAILURE;
}
// Step 1/4: load tree
cvflann::VocabTree tree;
printf("-- Reading tree from [%s]\n", tree_in);
mytime = cv::getTickCount();
tree.load(std::string(tree_in));
mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
* 1000;
printf(" Tree loaded in [%lf] ms, got [%lu] words \n", mytime,
tree.size());
// Step 2/4: read the database keyfiles
printf("-- Loading DB keyfiles names and landmark id's\n");
std::vector<std::string> db_filenames;
std::vector<int> db_landmarks;
std::ifstream keysList(db_list_in, std::fstream::in);
if (keysList.is_open() == false) {
fprintf(stderr, "Error opening file [%s] for reading\n", db_list_in);
return EXIT_FAILURE;
}
// Loading file names in list into a vector
std::string line;
while (getline(keysList, line)) {
// Verifying line format
if (boost::regex_match(line, boost::regex("^(.+)\\s(.+)$")) == false) {
fprintf(stderr,
"Error while parsing DB list file [%s], line [%s] should be: <key.file> <landmark.id>\n",
db_list_in, line.c_str());
return EXIT_FAILURE;
}
// Extracting filename and landmark from line
char filename[256];
int landmark;
sscanf(line.c_str(), "%s %d", filename, &landmark);
// Checking that file exists, if not print error and exit
struct stat buffer;
if (stat(filename, &buffer) != 0) {
fprintf(stderr, "Keypoints file [%s] doesn't exist\n", filename);
return EXIT_FAILURE;
}
// Checking that filename refers to a compressed yaml or xml file
if (boost::regex_match(std::string(filename), expression) == false) {
fprintf(stderr,
"Keypoints file [%s] must have the extension .yaml.gz or .xml.gz\n",
filename);
return EXIT_FAILURE;
}
db_filenames.push_back(std::string(filename));
db_landmarks.push_back(landmark);
}
// Close file
keysList.close();
// Step 3/4: read the query keyfiles
printf("-- Loading query keyfiles names\n");
std::vector<std::string> query_filenames;
keysList.open(query_list_in, std::fstream::in);
if (keysList.is_open() == false) {
fprintf(stderr, "Error opening file [%s] for reading\n", db_list_in);
return EXIT_FAILURE;
}
// Loading file names in list into a vector
while (getline(keysList, line)) {
// Checking that file exists, if not print error and exit
struct stat buffer;
if (stat(line.c_str(), &buffer) != 0) {
fprintf(stderr, "Keypoints file [%s] doesn't exist\n",
line.c_str());
return EXIT_FAILURE;
}
// Checking that line refers to a compressed yaml or xml file
if (boost::regex_match(line, expression) == false) {
fprintf(stderr,
"Keypoints file [%s] must have the extension .yaml.gz or .xml.gz\n",
line.c_str());
return EXIT_FAILURE;
}
query_filenames.push_back(line);
}
// Close file
keysList.close();
// Step 4/4: score each query keyfile
int normType = cv::NORM_L1;
printf("-- Scoring [%lu] query images against [%lu] DB images using [%s]\n",
query_filenames.size(), db_filenames.size(),
normType == cv::NORM_L1 ? "L1-norm" :
normType == cv::NORM_L2 ? "L2-norm" : "UNKNOWN-norm");
std::vector<cv::KeyPoint> imgKeypoints;
cv::Mat imgDescriptors;
cv::Mat scores;
int max_ld = *std::max_element(db_landmarks.begin(), db_landmarks.end());
FILE *f_match = fopen(matches_out, "w");
if (f_match == NULL) {
fprintf(stderr, "Error opening file [%s] for writing\n",
candidates_out);
return EXIT_FAILURE;
}
FILE *f_candidates = fopen(candidates_out, "w");
if (f_candidates == NULL) {
fprintf(stderr, "Error opening file [%s] for writing\n",
candidates_out);
return EXIT_FAILURE;
}
FILE *f_html = fopen(output_html, "w");
PrintHTMLHeader(f_html, num_nbrs);
if (f_html == NULL) {
fprintf(stderr, "Error opening file [%s] for writing\n",
candidates_out);
return EXIT_FAILURE;
}
for (size_t i = 0; i < query_filenames.size(); i++) {
// Initialize keypoints and descriptors
imgKeypoints.clear();
imgDescriptors = cv::Mat();
// Load query keypoints and descriptors
FileUtils::loadFeatures(query_filenames[i], imgKeypoints,
imgDescriptors);
// Score query bow vector against DB images bow vectors
mytime = cv::getTickCount();
try {
tree.scoreQuery(imgDescriptors, scores, db_filenames.size(),
cv::NORM_L1);
} catch (const std::runtime_error& error) {
fprintf(stderr, "%s\n", error.what());
return EXIT_FAILURE;
}
mytime = ((double) cv::getTickCount() - mytime) / cv::getTickFrequency()
* 1000;
// Print to standard output the matching scores between
// the query bow vector and the DB images bow vectors
for (size_t j = 0; (int) j < scores.cols; j++) {
printf(
" Match score between [%lu] query image and [%lu] DB image: %f\n",
i, j, scores.at<float>(0, j));
}
// Obtain indices of ordered scores
cv::Mat perm;
// Note: recall that the index of the images in the inverted file corresponds
// to the zero-based line number in the file used to build the DB.
// Hence scores matrix and db_landmarks and db_filenames vectors.
// are equally ordered.
// Also the images in list_db and list_db_ld must be equally ordered,
// that implies same number of elements.
//
// list_db list_db_ld
// img1 ---> img1 ld1
// img2 ---> img2 ld1
// img3 ---> img3 ld1
// img4 ---> img4 ld2
// img5 ---> img5 ld2
// img6 ---> img6 ld2
cv::sortIdx(scores, perm, cv::SORT_EVERY_ROW + cv::SORT_DESCENDING);
int top = MIN (num_nbrs, db_filenames.size());
// Initialize votes vector
// Note: size is maximum landmark id plus one because landmark index its zero-based
std::vector<int> votes(max_ld + 1, 0);
// Accumulating landmark votes for the top scored images
// Note: recall that images might refer to the same landmark
for (size_t i = 0; (int) i < top; i++) {
votes[db_landmarks[perm.at<int>(0, i)]]++;
}
// Finding max voted landmark and the number of votes it got
int max_votes = 0;
int max_landmark = -1;
for (int j = 0; j < max_ld + 1; j++) {
if (votes[j] > max_votes) {
max_votes = votes[j];
max_landmark = j;
}
}
// Print to a file the ranked list of candidates ordered by score
fprintf(f_candidates, "%s", query_filenames[i].c_str());
for (int j = 0; j < top; j++) {
std::string d_base = db_filenames[perm.at<int>(0, j)];
fprintf(f_candidates, " %s", d_base.c_str());
}
fprintf(f_candidates, "\n");
fflush(f_candidates);
// Print to a file the max voted landmark information
fprintf(f_match, "%lu %d %d\n", i, max_landmark, max_votes);
fflush(f_match);
fflush(stdout);
// Print to a file the ranked list of candidates ordered by score in HTML format
PrintHTMLRow(f_html, query_filenames[i], scores, perm, top,
db_filenames);
}
fclose(f_candidates);
fclose(f_match);
PrintHTMLFooter(f_html);
fclose(f_html);
return EXIT_SUCCESS;
}
void PrintHTMLHeader(FILE *f, int num_nns) {
fprintf(f, "<html>\n"
"<header>\n"
"<title>Vocabulary tree results</title>\n"
"</header>\n"
"<body>\n"
"<h1>Vocabulary tree results</h1>\n"
"<hr>\n\n");
fprintf(f, "<table border=2 align=center>\n<tr>\n<th>Query image</th>\n");
for (int i = 0; i < num_nns; i++) {
fprintf(f, "<th>Match %d</th>\n", i + 1);
}
fprintf(f, "</tr>\n");
}
void PrintHTMLRow(FILE *f, const std::string &query, cv::Mat& scores,
cv::Mat& perm, int num_nns, const std::vector<std::string> &db_images) {
char q_base[512], q_thumb[512];
BasifyFilename(query.c_str(), q_base);
sprintf(q_thumb, "%s.thumb.jpg", q_base);
fprintf(f,
"<tr align=center>\n<td><img src=\"%s\" style=\"max-height:200px\"><br><p>%s</p></td>\n",
q_thumb, q_thumb);
for (int i = 0; i < num_nns; i++) {
char d_base[512], d_thumb[512];
BasifyFilename(db_images[perm.at<int>(0, i)].c_str(), d_base);
sprintf(d_thumb, "%s.thumb.jpg", d_base);
fprintf(f,
"<td><img src=\"%s\" style=\"max-height:200px\"><br><p>%s</p></td>\n",
d_thumb, d_thumb);
}
fprintf(f, "</tr>\n<tr align=right>\n");
fprintf(f, "<td></td>\n");
for (int i = 0; i < num_nns; i++)
fprintf(f, "<td>%0.5f</td>\n", scores.at<float>(0, i));
fprintf(f, "</tr>\n");
}
void PrintHTMLFooter(FILE *f) {
fprintf(f, "</tr>\n"
"</table>\n"
"<hr>\n"
"</body>\n"
"</html>\n");
}
int BasifyFilename(const char *filename, char *base) {
strcpy(base, filename);
base[strlen(base) - 8] = 0;
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>'firstPartyForCookies' walks the ancestor tree.<commit_after><|endoftext|> |
<commit_before>#include <cstddef>
#include "gtest/gtest.h"
#include "resize.h"
namespace cs375 {
TEST(NextTableSize, Zero) {
EXPECT_EQ(2u, next_table_size(0u));
}
TEST(NextTableSize, One) {
EXPECT_EQ(2u, next_table_size(1u));
}
TEST(NextTableSize, Two) {
EXPECT_EQ(5u, next_table_size(2u));
}
TEST(NextTableSize, Three) {
EXPECT_EQ(7u, next_table_size(3u));
}
TEST(NextTableSize, Five) {
EXPECT_EQ(11u, next_table_size(5u));
}
TEST(NextTableSize, Seven) {
EXPECT_EQ(17u, next_table_size(7u));
}
TEST(NextTableSize, Eleven) {
EXPECT_EQ(23u, next_table_size(11u));
}
TEST(NextTableSize, Thirteen) {
EXPECT_EQ(29u, next_table_size(13u));
}
TEST(NextTableSize, Seventeen) {
EXPECT_EQ(37u, next_table_size(17u));
}
TEST(NextTableSize, Nineteen) {
EXPECT_EQ(41u, next_table_size(19u));
}
TEST(NextTableSize, TwentyThree) {
EXPECT_EQ(47u, next_table_size(23u));
}
TEST(NextTableSize, SizeMax) {
EXPECT_EQ(SIZE_MAX, next_table_size(SIZE_MAX));
}
}
<commit_msg>Use parameterized tests<commit_after>#include <cstddef>
#include <utility>
#include "gtest/gtest.h"
#include "resize.h"
namespace cs375 {
namespace {
using test_case = std::pair<std::size_t, std::size_t>;
}
struct NextTableSizeTest : ::testing::TestWithParam<test_case> {
};
TEST_P(NextTableSizeTest, ReturnsNextPrimeAfterDoubling) {
auto &&c = GetParam();
EXPECT_EQ(c.second, next_table_size(c.first));
}
INSTANTIATE_TEST_CASE_P(, NextTableSizeTest,
::testing::Values(
test_case{0, 2},
test_case{1, 2},
test_case{2, 5},
test_case{3, 7},
test_case{5, 11},
test_case{7, 17},
test_case{11, 23},
test_case{13, 29},
test_case{17, 37},
test_case{19, 41},
test_case{23, 47}
));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: VLineProperties.hxx,v $
*
* $Revision: 1.1 $
*
* last change: $Author: iha $ $Date: 2003-11-13 09:50:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2003 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CHART2_VLINEPROPERTIES_HXX
#define _CHART2_VLINEPROPERTIES_HXX
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
struct VLineProperties
{
com::sun::star::uno::Any Color; //type sal_Int32 UNO_NAME_LINECOLOR
com::sun::star::uno::Any LineStyle; //type drawing::LineStyle for property UNO_NAME_LINESTYLE
com::sun::star::uno::Any Transparence;//type sal_Int16 for property UNO_NAME_LINETRANSPARENCE
com::sun::star::uno::Any Width;//type sal_Int32 for property UNO_NAME_LINEWIDTH
com::sun::star::uno::Any Dash;//type drawing::LineDash for property UNO_NAME_LINEDASH
VLineProperties();
void initFromPropertySet( const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet >& xProp
, bool bUseSeriesPropertyNames=false );
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.1.110); FILE MERGED 2005/09/05 18:43:49 rt 1.1.110.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: VLineProperties.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2005-09-08 01:45:48 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _CHART2_VLINEPROPERTIES_HXX
#define _CHART2_VLINEPROPERTIES_HXX
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
//.............................................................................
namespace chart
{
//.............................................................................
//-----------------------------------------------------------------------------
/**
*/
struct VLineProperties
{
com::sun::star::uno::Any Color; //type sal_Int32 UNO_NAME_LINECOLOR
com::sun::star::uno::Any LineStyle; //type drawing::LineStyle for property UNO_NAME_LINESTYLE
com::sun::star::uno::Any Transparence;//type sal_Int16 for property UNO_NAME_LINETRANSPARENCE
com::sun::star::uno::Any Width;//type sal_Int32 for property UNO_NAME_LINEWIDTH
com::sun::star::uno::Any Dash;//type drawing::LineDash for property UNO_NAME_LINEDASH
VLineProperties();
void initFromPropertySet( const ::com::sun::star::uno::Reference<
::com::sun::star::beans::XPropertySet >& xProp
, bool bUseSeriesPropertyNames=false );
};
//.............................................................................
} //namespace chart
//.............................................................................
#endif
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.