hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
20b9d8e3091fee27330b126e52011b5b9a2901d2
16,248
cpp
C++
packages/monte_carlo/estimator/native/src/MonteCarlo_EstimatorHDF5FileHandler.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/estimator/native/src/MonteCarlo_EstimatorHDF5FileHandler.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
packages/monte_carlo/estimator/native/src/MonteCarlo_EstimatorHDF5FileHandler.cpp
lkersting/SCR-2123
06ae3d92998664a520dc6a271809a5aeffe18f72
[ "BSD-3-Clause" ]
null
null
null
//---------------------------------------------------------------------------// //! //! \file MonteCarlo_EstimatorHDF5FileHandler.hpp //! \author Alex Robinson //! \brief Estimator hdf5 file handler class definition //! //---------------------------------------------------------------------------// // Std Lib Includes #include <sstream> // FRENSIE Includes #include "MonteCarlo_EstimatorHDF5FileHandler.hpp" #include "Utility_ExceptionCatchMacros.hpp" #include "Utility_ContractException.hpp" namespace MonteCarlo{ // Initialize static member data const std::string EstimatorHDF5FileHandler::estimator_group_loc_name( "/Estimators/" ); // Constructor (file ownership) /*! \details The EstimatorHDF5FileOps enum will determine how the HDF5 file * is opened. If the read only option is used, calling any of the set * methods will result in an exception. */ EstimatorHDF5FileHandler::EstimatorHDF5FileHandler( const std::string& hdf5_file_name, const EstimatorHDF5FileOps file_op ) : d_hdf5_file( new Utility::HDF5FileHandler ), d_hdf5_file_ownership( true ) { // Make sure the name is valid testPrecondition( hdf5_file_name.size() > 0 ); Utility::HDF5FileHandler::throwExceptions(); try{ switch( file_op ) { case OVERWRITE_ESTIMATOR_HDF5_FILE: d_hdf5_file->openHDF5FileAndOverwrite( hdf5_file_name ); break; case APPEND_ESTIMATOR_HDF5_FILE: d_hdf5_file->openHDF5FileAndAppend( hdf5_file_name ); break; case READ_ONLY_ESTIMATOR_HDF5_FILE: d_hdf5_file->openHDF5FileAndReadOnly( hdf5_file_name ); break; } } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Ownership Constructor Error" ); } // Constructor (file sharing) EstimatorHDF5FileHandler::EstimatorHDF5FileHandler( const Teuchos::RCP<Utility::HDF5FileHandler>& hdf5_file ) : d_hdf5_file( hdf5_file ), d_hdf5_file_ownership( false ) { // Make sure the file is valid testPrecondition( !hdf5_file.is_null() ); testPrecondition( hdf5_file->hasOpenFile() ); } // Destructor EstimatorHDF5FileHandler::~EstimatorHDF5FileHandler() { if( d_hdf5_file_ownership ) d_hdf5_file->closeHDF5File(); } // Set the simulation time void EstimatorHDF5FileHandler::setSimulationTime( const double simulation_time ) { // Make sure the simulation time is valid testPrecondition( simulation_time > 0.0 ); try{ d_hdf5_file->writeValueToGroupAttribute( simulation_time, estimator_group_loc_name, "simulation_time" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Simulation Time Error" ); } // Get the simulation time void EstimatorHDF5FileHandler::getSimulationTime( double& simulation_time ) const { try{ d_hdf5_file->readValueFromGroupAttribute( simulation_time, estimator_group_loc_name, "simulation_time" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Simulation Time Error" ); } // Set the last history simulated void EstimatorHDF5FileHandler::setLastHistorySimulated( const unsigned long long last_history_simulated ) { try{ d_hdf5_file->writeValueToGroupAttribute( last_history_simulated, estimator_group_loc_name, "last_history_simulated" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Last History Simulated Error" ); } // Get the last history simulated void EstimatorHDF5FileHandler::getLastHistorySimulated( unsigned long long& last_history_simulated ) const { try{ d_hdf5_file->readValueFromGroupAttribute( last_history_simulated, estimator_group_loc_name, "last_history_simulated" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Last History Simulated Error" ); } // Set the number of histories simulated void EstimatorHDF5FileHandler::setNumberOfHistoriesSimulated( const unsigned long long number_histories_simulated ) { // Make sure the number of histories simulated is valid testPrecondition( number_histories_simulated > 0ull ); try{ d_hdf5_file->writeValueToGroupAttribute( number_histories_simulated, estimator_group_loc_name, "number_of_histories_simulated" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Number of Histories Simulated Error" ); } // Get the number of histories simulated void EstimatorHDF5FileHandler::getNumberOfHistoriesSimulated( unsigned long long& number_histories_simulated ) const { try{ d_hdf5_file->readValueFromGroupAttribute( number_histories_simulated, estimator_group_loc_name, "number_of_histories_simulated"); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Number of Histories Simulated Error" ); } // Check if an estimator exists bool EstimatorHDF5FileHandler::doesEstimatorExist( const unsigned estimator_id ) const { return d_hdf5_file->doesGroupExist( this->getEstimatorGroupLocation( estimator_id ) ); } // Set the estimator as a surface estimator void EstimatorHDF5FileHandler::setSurfaceEstimator( const unsigned estimator_id ) { try{ d_hdf5_file->writeValueToGroupAttribute( SURFACE_ENTITY, this->getEstimatorGroupLocation( estimator_id ), "entity_type" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Surface Estimator Error" ); } // Check if the estimator is a surface estimator bool EstimatorHDF5FileHandler::isSurfaceEstimator( const unsigned estimator_id ) const { EntityType type; try{ d_hdf5_file->readValueFromGroupAttribute( type, this->getEstimatorGroupLocation( estimator_id ), "entity_type" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Is Surface Estimator Error" ); return (type == SURFACE_ENTITY); } // Set the estimator as a cell estimator void EstimatorHDF5FileHandler::setCellEstimator( const unsigned estimator_id ) { try{ d_hdf5_file->writeValueToGroupAttribute( CELL_ENTITY, this->getEstimatorGroupLocation( estimator_id ), "entity_type" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Cell Estimator Error" ); } // Check if the estimator is a cell estimator bool EstimatorHDF5FileHandler::isCellEstimator( const unsigned estimator_id ) const { EntityType type; try{ d_hdf5_file->readValueFromGroupAttribute( type, this->getEstimatorGroupLocation( estimator_id ), "entity_type" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Is Cell Estimator Error" ); return (type == CELL_ENTITY); } // Set the estimator multiplier void EstimatorHDF5FileHandler::setEstimatorMultiplier( const unsigned estimator_id, const double multiplier ) { try{ d_hdf5_file->writeValueToGroupAttribute( multiplier, this->getEstimatorGroupLocation( estimator_id ), "multiplier" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Estimator Multiplier Error" ); } // Get the estimator multiplier void EstimatorHDF5FileHandler::getEstimatorMultiplier( const unsigned estimator_id, double& multiplier ) const { try{ d_hdf5_file->readValueFromGroupAttribute( multiplier, this->getEstimatorGroupLocation( estimator_id ), "multiplier" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Estimator Multiplier Error" ); } // Set the estimator response function ordering void EstimatorHDF5FileHandler::setEstimatorResponseFunctionOrdering( const unsigned estimator_id, const Teuchos::Array<unsigned>& response_function_ordering ) { try{ d_hdf5_file->writeArrayToGroupAttribute( response_function_ordering, this->getEstimatorGroupLocation( estimator_id ), "response_function_ordering" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Estimator Response Function Ordering Error" ); } // Get the estimator response function ordering void EstimatorHDF5FileHandler::getEstimatorResponseFunctionOrdering( const unsigned estimator_id, Teuchos::Array<unsigned>& response_function_ordering ) const { try{ d_hdf5_file->readArrayFromGroupAttribute( response_function_ordering, this->getEstimatorGroupLocation( estimator_id ), "response_function_ordering" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Estimator Response Function Ordering Error" ); } // Set the estimator dimension ordering void EstimatorHDF5FileHandler::setEstimatorDimensionOrdering( const unsigned estimator_id, const Teuchos::Array<PhaseSpaceDimension>& dimension_ordering ) { try{ d_hdf5_file->writeArrayToGroupAttribute( dimension_ordering, this->getEstimatorGroupLocation( estimator_id ), "dimension_ordering" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Estimator Dimension Ordering Error" ); } // Get the estimator dimension ordering void EstimatorHDF5FileHandler::getEstimatorDimensionOrdering( const unsigned estimator_id, Teuchos::Array<PhaseSpaceDimension>& dimension_ordering ) const { dimension_ordering.clear(); // If an exception is thrown, there are no estimator dimensions try{ if( d_hdf5_file->doesGroupAttributeExist( this->getEstimatorGroupLocation( estimator_id ), "dimension_ordering" ) ) { d_hdf5_file->readArrayFromGroupAttribute( dimension_ordering, this->getEstimatorGroupLocation( estimator_id ), "dimension_ordering" ); } } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Estimator Dimension Ordering Error" ); } // Set the total normalization constant void EstimatorHDF5FileHandler::setEstimatorTotalNormConstant( const unsigned estimator_id, const double total_norm_constant ) { try{ d_hdf5_file->writeValueToGroupAttribute( total_norm_constant, this->getEstimatorGroupLocation( estimator_id ), "total_norm_constant" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Total Norm Constant Error" ); } // Get the total normalization constant void EstimatorHDF5FileHandler::getEstimatorTotalNormConstant( const unsigned estimator_id, double& total_norm_constant ) const { try{ d_hdf5_file->readValueFromGroupAttribute( total_norm_constant, this->getEstimatorGroupLocation( estimator_id ), "total_norm_constant" ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Total Norm Constant Error" ); } // Set the raw estimator bin data over all entities (1st, 2nd moments) void EstimatorHDF5FileHandler::setRawEstimatorTotalBinData( const unsigned estimator_id, const Teuchos::Array<Utility::Pair<double,double> >& raw_bin_data ) { // Make sure the bin data is valid testPrecondition( raw_bin_data.size() > 0 ); std::string data_set_location = this->getEstimatorGroupLocation( estimator_id ); data_set_location += "raw_total_bin_data"; try{ d_hdf5_file->writeArrayToDataSet( raw_bin_data, data_set_location ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Raw Estimator Total Bin Data Error" ); } // Get the raw estimator bin data over all entities (1st, 2nd moments) void EstimatorHDF5FileHandler::getRawEstimatorTotalBinData( const unsigned estimator_id, Teuchos::Array<Utility::Pair<double,double> >& raw_bin_data ) const { std::string data_set_location = this->getEstimatorGroupLocation( estimator_id ); data_set_location += "raw_total_bin_data"; try{ d_hdf5_file->readArrayFromDataSet( raw_bin_data, data_set_location ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Raw Estimator Total Bin Data Error" ); } // Set the processed estimator bin data over all entities (mean, rel. err.) void EstimatorHDF5FileHandler::setProcessedEstimatorTotalBinData( const unsigned estimator_id, const Teuchos::Array<Utility::Pair<double,double> >& processed_bin_data ) { // Make sure the total bin data is valid testPrecondition( processed_bin_data.size() > 0 ); std::string data_set_location = this->getEstimatorGroupLocation( estimator_id ); data_set_location += "processed_total_bin_data"; try{ d_hdf5_file->writeArrayToDataSet( processed_bin_data, data_set_location ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Processed Estimator Total Bin Data Error" ); } // Get the processed estimator bin data over all entities (mean, rel. err.) void EstimatorHDF5FileHandler::getProcessedEstimatorTotalBinData( const unsigned estimator_id, Teuchos::Array<Utility::Pair<double,double> >& processed_bin_data ) const { std::string data_set_location = this->getEstimatorGroupLocation( estimator_id ); data_set_location += "processed_total_bin_data"; try{ d_hdf5_file->readArrayFromDataSet( processed_bin_data, data_set_location ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Processed Estimator Total Bin Data Error" ); } // Set the raw estimator total data over all entities void EstimatorHDF5FileHandler::setRawEstimatorTotalData( const unsigned estimator_id, const Teuchos::Array<Utility::Quad<double,double,double,double> >& raw_total_data ) { // Make sure the total bin data is valid testPrecondition( raw_total_data.size() > 0 ); std::string data_set_location = this->getEstimatorGroupLocation( estimator_id ); data_set_location += "raw_total_data"; try{ d_hdf5_file->writeArrayToDataSet( raw_total_data, data_set_location ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Raw Estimator Total Data Error" ); } // Get the raw estimator total data over all entities void EstimatorHDF5FileHandler::getRawEstimatorTotalData( const unsigned estimator_id, Teuchos::Array<Utility::Quad<double,double,double,double> >& raw_total_data ) const { std::string data_set_location = this->getEstimatorGroupLocation( estimator_id ); data_set_location += "raw_total_data"; try{ d_hdf5_file->readArrayFromDataSet( raw_total_data, data_set_location ); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Raw Estimator Total Data Error" ); } // Set the processed estimator total data over all entities void EstimatorHDF5FileHandler::setProcessedEstimatorTotalData( const unsigned estimator_id, const Teuchos::Array<Utility::Quad<double,double,double,double> >& processed_total_data ) { // Make sure the total bin data is valid testPrecondition( processed_total_data.size() > 0 ); std::string data_set_location = this->getEstimatorGroupLocation( estimator_id ); data_set_location += "processed_total_data"; try{ d_hdf5_file->writeArrayToDataSet( processed_total_data, data_set_location); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Set Processed Estimator Total Data Error" ); } // Get the processed estimator total data over all entities void EstimatorHDF5FileHandler::getProcessedEstimatorTotalData( const unsigned estimator_id, Teuchos::Array<Utility::Quad<double,double,double,double> >& processed_total_data ) const { std::string data_set_location = this->getEstimatorGroupLocation( estimator_id ); data_set_location += "processed_total_data"; try{ d_hdf5_file->readArrayFromDataSet(processed_total_data, data_set_location); } EXCEPTION_CATCH_RETHROW( std::runtime_error, "Get Processed Estimator Total Data Error" ); } // Get the estimator location std::string EstimatorHDF5FileHandler::getEstimatorGroupLocation( const unsigned estimator_id ) const { std::ostringstream oss; oss << EstimatorHDF5FileHandler::estimator_group_loc_name; oss << estimator_id << "/"; return oss.str(); } } // end MonteCarlo namespace //---------------------------------------------------------------------------// // end MonteCarlo_EstimatorHDF5FileHandler.cpp //---------------------------------------------------------------------------//
30.948571
79
0.71615
lkersting
20c0826702128042dc8dba2e627adbe1a1ed9f9c
21,115
cc
C++
zetasql/compliance/functions_testlib_string_1.cc
borjavb/zetasql
4fae9217f4e3ab0053926d4aa5799439849bc3f6
[ "Apache-2.0" ]
null
null
null
zetasql/compliance/functions_testlib_string_1.cc
borjavb/zetasql
4fae9217f4e3ab0053926d4aa5799439849bc3f6
[ "Apache-2.0" ]
null
null
null
zetasql/compliance/functions_testlib_string_1.cc
borjavb/zetasql
4fae9217f4e3ab0053926d4aa5799439849bc3f6
[ "Apache-2.0" ]
1
2020-12-31T12:24:15.000Z
2020-12-31T12:24:15.000Z
// // Copyright 2019 Google LLC // // 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 <string> #include <utility> #include <vector> #include "zetasql/compliance/functions_testlib_common.h" #include "zetasql/public/functions/normalize_mode.pb.h" #include "zetasql/public/type.h" #include "zetasql/public/value.h" #include "zetasql/testing/test_function.h" #include "zetasql/testing/test_value.h" #include "zetasql/testing/using_test_value.cc" // NOLINT #include <cstdint> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "zetasql/base/status.h" namespace zetasql { namespace { constexpr absl::StatusCode INVALID_ARGUMENT = absl::StatusCode::kInvalidArgument; constexpr absl::StatusCode OUT_OF_RANGE = absl::StatusCode::kOutOfRange; } // namespace std::vector<FunctionTestCall> GetFunctionTestsOctetLength() { std::vector<FunctionTestCall> results = { // OCTET_LENGTH(string) -> int64_t {"octet_length", {NullString()}, NullInt64()}, {"octet_length", {""}, 0ll}, {"octet_length", {"e"}, 1ll}, {"octet_length", {"abcde"}, 5ll}, {"octet_length", {"абвгд"}, 10ll}, {"octet_length", {"\0\0"}, 2ll}, // OCTET_LENGTH(bytes) -> int64_t {"octet_length", {NullBytes()}, NullInt64()}, {"octet_length", {Bytes("")}, 0ll}, {"octet_length", {Bytes("e")}, 1ll}, {"octet_length", {Bytes("abcde")}, 5ll}, {"octet_length", {Bytes("абвгд")}, 10ll}, {"octet_length", {Bytes("\0\0")}, 2ll}, }; return results; } std::vector<FunctionTestCall> GetFunctionTestsAscii() { std::vector<FunctionTestCall> results = { // ASCII(string) -> int64_t {"ascii", {NullString()}, NullInt64()}, {"ascii", {""}, 0ll}, {"ascii", {" A"}, 32ll}, {"ascii", {"a"}, 97ll}, {"ascii", {"abcd"}, 97ll}, {"ascii", {"nЖЩФ"}, 110ll}, {"ascii", {"\x41"}, 65ll}, {"ascii", {"\?"}, 63ll}, {"ascii", {"\t"}, 9ll}, {"ascii", {"\uFFFF"}, NullInt64(), OUT_OF_RANGE}, {"ascii", {"ЖЩФ"}, NullInt64(), OUT_OF_RANGE}, // ASCII(bytes) -> int64_t {"ascii", {NullBytes()}, NullInt64()}, {"ascii", {Bytes("")}, 0ll}, {"ascii", {Bytes(" A")}, 32ll}, {"ascii", {Bytes("a")}, 97ll}, {"ascii", {Bytes("abcd")}, 97ll}, {"ascii", {Bytes("nbca\0\1cde")}, 110ll}, {"ascii", {Bytes("\x41")}, 65ll}, {"ascii", {Bytes("\?")}, 63ll}, {"ascii", {Bytes("\t")}, 9ll}, {"ascii", {Bytes("\uFFFF")}, 239ll}, {"ascii", {Bytes("ЖЩФ")}, 208ll}, }; return results; } std::vector<FunctionTestCall> GetFunctionTestsUnicode() { std::vector<FunctionTestCall> results = { // unicode(string) -> int64_t {"unicode", {NullString()}, NullInt64()}, {"unicode", {""}, 0ll}, {"unicode", {" A"}, 32ll}, {"unicode", {"a"}, 97ll}, {"unicode", {"abcd"}, 97ll}, {"unicode", {"nЖЩФ"}, 110ll}, {"unicode", {"\x41"}, 65ll}, {"unicode", {"?"}, 63ll}, {"unicode", {"\t"}, 9ll}, {"unicode", {"\uE000"}, 0xE000ll}, {"unicode", {"\uFFFF"}, 0xFFFFll}, {"unicode", {"\U0010FFFE"}, 0x10FFFEll}, {"unicode", {"\U0010FFFF"}, 0x10FFFFll}, {"unicode", {"жщф"}, 1078ll}, }; { // construct a string std::string valid_codepoint_string; valid_codepoint_string.push_back(0x11); valid_codepoint_string.push_back('\xFF'); valid_codepoint_string.push_back('\xFF'); results.push_back({"unicode", {String(valid_codepoint_string)}, 17ll}); } // Error cases. // The C++ compiler rejects Unicode literals in strings that aren't valid // codepoints, so we have to construct them "manually". { std::string invalid_codepoint_string; // The first character is an invalid codepoint. invalid_codepoint_string.push_back(0xD8); // invalid_codepoint_string.push_back('\xFF'); results.push_back( {"unicode", {String(invalid_codepoint_string)}, NullInt64(), absl::OutOfRangeError("First char of input is not a structurally " "valid UTF-8 character: '\\xd8'")}); } { std::string invalid_codepoint_string; // The first character is an invalid codepoint. invalid_codepoint_string.push_back(0xDF); invalid_codepoint_string.push_back('\xFF'); results.push_back( {"unicode", {String(invalid_codepoint_string)}, NullInt64(), absl::OutOfRangeError("First char of input is not a structurally " "valid UTF-8 character: '\\xdf'")}); } { std::string invalid_codepoint_string; // Invalid three-byte codepoint (above the valid range). invalid_codepoint_string.push_back(0xFF); invalid_codepoint_string.push_back('\xFF'); invalid_codepoint_string.push_back('\xFF'); invalid_codepoint_string.push_back('\xFF'); results.push_back( {"unicode", {String(invalid_codepoint_string)}, NullInt64(), absl::OutOfRangeError("First char of input is not a structurally " "valid UTF-8 character: '\\xff'")}); } return results; } std::vector<FunctionTestCall> GetFunctionTestsChr() { std::vector<FunctionTestCall> results = { {"chr", {NullInt64()}, NullString()}, {"chr", {32ll}, String(" ")}, {"chr", {97ll}, String("a")}, {"chr", {66ll}, String("B")}, {"chr", {0ll}, String("\0")}, {"chr", {1ll}, String("\1")}, {"chr", {1078ll}, String("ж")}, {"chr", {1076ll}, String("д")}, {"chr", {0xD7FEll}, String("\uD7FE")}, {"chr", {0xE000ll}, String("\uE000")}, {"chr", {0x10FFFFll}, String("\U0010FFFF")}, {"chr", {-1ll}, NullString(), absl::OutOfRangeError("Invalid codepoint -1")}, {"chr", {-100ll}, NullString(), absl::OutOfRangeError("Invalid codepoint -100")}, {"chr", {0xD800ll}, NullString(), absl::OutOfRangeError("Invalid codepoint 55296")}, {"chr", {0x11FFFFll}, NullString(), absl::OutOfRangeError("Invalid codepoint 1179647")}, {"chr", {0x1000000000000ll}, NullString(), absl::OutOfRangeError("Invalid codepoint 281474976710656")}, }; return results; } std::vector<FunctionTestCall> GetFunctionTestsSoundex() { std::vector<FunctionTestCall> results = { // soundex(string) -> string {"soundex", {NullString()}, NullString()}, {"soundex", {""}, ""}, // Invalid characters are skipped. {"soundex", {" "}, ""}, {"soundex", {" \t \n 78912!(@#& "}, ""}, {"soundex", {"A"}, "A000"}, {"soundex", {"Aa"}, "A000"}, {"soundex", {"AaAaa a123aA"}, "A000"}, // Test that all alpha character maps to the correct value. {"soundex", {"AEIOUYHWaeiouyhw"}, "A000"}, {"soundex", {"ABFPVbfpv"}, "A100"}, {"soundex", {"ACGJKQSXZcgjkqsxz"}, "A200"}, {"soundex", {"ADTdt"}, "A300"}, {"soundex", {"ALl"}, "A400"}, {"soundex", {"AMNmn"}, "A500"}, {"soundex", {"ARr"}, "A600"}, // H, W are considered vowels and are skipped. {"soundex", {"AAWIOUYHWB"}, "A100"}, {"soundex", {"KhcABl"}, "K140"}, // Second c is skipped because it has the same code as K. {"soundex", {"KcABl"}, "K140"}, // c is skipped because the precedent non-skipped code is the same (s). {"soundex", {"Ashcraft"}, "A261"}, {"soundex", {"Robert"}, "R163"}, {"soundex", {"Rupert"}, "R163"}, {"soundex", {"I LOVE YOU"}, "I410"}, {"soundex", {"I LOVE YOU TOO"}, "I413"}, {"soundex", {"ACDL"}, "A234"}, {"soundex", {"3 ACDL"}, "A234"}, {"soundex", {"ACDL56+56/-13"}, "A234"}, {"soundex", {"AC#$!D193 L"}, "A234"}, // Multi-byte UTF8 characters are skipped. The second l is skipped because // the previous valid character is already l. {"soundex", {"Aгдaгдlдl"}, "A400"}}; // Test every character to make sure all non-alpha character is invalid. for (int c = 0; c < 256; ++c) { std::string single_char = std::string(1, static_cast<char>(c)); results.push_back( {"soundex", {single_char}, absl::ascii_isalpha(c) ? absl::StrCat(single_char, "000") : ""}); } return results; } std::vector<FunctionTestCall> GetFunctionTestsTranslate() { constexpr size_t kMaxOutputSize = (1 << 20); // 1MB const std::string small_size_text(kMaxOutputSize / 2 + 1, 'a'); const std::string exact_size_text(kMaxOutputSize, 'a'); const std::string large_size_text(kMaxOutputSize + 1, 'a'); std::vector<FunctionTestCall> results = { // translate(string, string, string) -> string {"translate", {NullString(), NullString(), NullString()}, NullString()}, {"translate", {NullString(), NullString(), ""}, NullString()}, {"translate", {NullString(), "", NullString()}, NullString()}, {"translate", {NullString(), "", ""}, NullString()}, {"translate", {"", NullString(), NullString()}, NullString()}, {"translate", {"", NullString(), ""}, NullString()}, {"translate", {"", "", NullString()}, NullString()}, {"translate", {"", "", ""}, ""}, {"translate", {"abcde", "", ""}, "abcde"}, // Repeated characters in source characters are not allowed (even if they // map to the same target character). {"translate", {"abcde", "aba", "xyz"}, NullString(), OUT_OF_RANGE}, {"translate", {"abcde", "aba", "xyx"}, NullString(), OUT_OF_RANGE}, // Source characters without a corresponding target character are removed // from the input. {"translate", {"abcde", "ad", "x"}, "xbce"}, {"translate", {"abcdebadbad", "ad", "x"}, "xbcebxbx"}, // Extra characters in target characters are ignored. {"translate", {"abcde", "ab", "xyz123xy"}, "xycde"}, // Characters are only modified once. {"translate", {"ababbce", "ab", "ba"}, "babaace"}, {"translate", {"abcde", "abd", "xyz"}, "xycze"}, {"translate", {"abcdebde", "abd", "xyz"}, "xyczeyze"}, {"translate", {"abcde", "abd", "xдz"}, "xдcze"}, {"translate", {"abcdebde", "abde", "xдz"}, "xдczдz"}, {"translate", {"abcдd\nebde", "ab\ndeд", "12ф4\t456"}, "12c44ф\t24\t"}, // Testing output size errors. {"translate", {small_size_text, "a", "a"}, small_size_text}, // Input size is under limit, but TRANSLATE will make it over limit. // ¢ is a 2-byte character. {"translate", {small_size_text, "a", "¢"}, NullString(), absl::OutOfRangeError( "Output of TRANSLATE exceeds max allowed output size of 1MB")}, {"translate", {exact_size_text, "a", "a"}, exact_size_text}, {"translate", {large_size_text, "", ""}, NullString(), absl::OutOfRangeError( "Output of TRANSLATE exceeds max allowed output size of 1MB")}, // Testing duplicate character {"translate", {"unused", "aa", "bc"}, NullString(), absl::OutOfRangeError( "Duplicate character \"a\" in TRANSLATE source characters")}, // Error even if the duplicate character doesn't have a corresponding // target character. {"translate", {"unused", "aa", "bc"}, NullString(), absl::OutOfRangeError( "Duplicate character \"a\" in TRANSLATE source characters")}, // Make sure characters are correctly escaped. {"translate", {"unused", "ab\nd\n", "vwxyz"}, NullString(), absl::OutOfRangeError( "Duplicate character \"\\n\" in TRANSLATE source characters")}, {"translate", {"unused", "ab'd'", "vwxyz"}, NullString(), absl::OutOfRangeError( "Duplicate character \"'\" in TRANSLATE source characters")}, {"translate", {"unused", "ab\"d\"", "vwxyz"}, NullString(), absl::OutOfRangeError( "Duplicate character '\"' in TRANSLATE source characters")}, // translate(bytes, bytes, bytes) -> bytes {"translate", {NullBytes(), NullBytes(), NullBytes()}, NullBytes()}, {"translate", {NullBytes(), NullBytes(), Bytes("")}, NullBytes()}, {"translate", {NullBytes(), Bytes(""), NullBytes()}, NullBytes()}, {"translate", {NullBytes(), Bytes(""), Bytes("")}, NullBytes()}, {"translate", {Bytes(""), NullBytes(), NullBytes()}, NullBytes()}, {"translate", {Bytes(""), NullBytes(), Bytes("")}, NullBytes()}, {"translate", {Bytes(""), Bytes(""), NullBytes()}, NullBytes()}, {"translate", {Bytes(""), Bytes(""), Bytes("")}, Bytes("")}, {"translate", {Bytes("abcde"), Bytes(""), Bytes("")}, Bytes("abcde")}, // Repeated characters in source characters are not allowed (even if they // map to the same target character). {"translate", {Bytes("abcde"), Bytes("aba"), Bytes("xyz")}, NullBytes(), OUT_OF_RANGE}, {"translate", {Bytes("abcde"), Bytes("aba"), Bytes("xyx")}, NullBytes(), OUT_OF_RANGE}, // Source characters without a corresponding target character are removed // from the input. {"translate", {Bytes("abcde"), Bytes("ad"), Bytes("x")}, Bytes("xbce")}, {"translate", {Bytes("abcdebadbad"), Bytes("ad"), Bytes("x")}, Bytes("xbcebxbx")}, // Extra characters in target characters are ignored. {"translate", {Bytes("abcde"), Bytes("ab"), Bytes("xyz123xy")}, Bytes("xycde")}, // Characters are only modified once. {"translate", {Bytes("ababbce"), Bytes("ab"), Bytes("ba")}, Bytes("babaace")}, {"translate", {Bytes("abcde"), Bytes("abd"), Bytes("xyz")}, Bytes("xycze")}, {"translate", {Bytes("abcdebde"), Bytes("abd"), Bytes("xyz")}, Bytes("xyczeyze")}, // д's UTF8 encoding is 0xD0 0xB4. {"translate", {Bytes("abmdgb"), Bytes("abd"), Bytes("xд")}, Bytes("x\xD0m\xB4g\xD0")}, {"translate", {Bytes("\x15\x01\xFFz"), Bytes("abc\x15\xFFxyz"), Bytes("\xAAxyz\xFA")}, Bytes("z\x01\xFA")}, // Testing output size errors. {"translate", {Bytes(small_size_text), Bytes("a"), Bytes("a")}, Bytes(small_size_text)}, {"translate", {Bytes(exact_size_text), Bytes("a"), Bytes("a")}, Bytes(exact_size_text)}, {"translate", {Bytes(large_size_text), Bytes(""), Bytes("")}, NullBytes(), absl::OutOfRangeError( "Output of TRANSLATE exceeds max allowed output size of 1MB")}, // Testing duplicate byte {"translate", {Bytes("unused"), Bytes("abcda"), Bytes("vwxyz")}, NullBytes(), absl::OutOfRangeError("Duplicate byte 0x61 in TRANSLATE source bytes")}, {"translate", {Bytes("unused"), Bytes("\x01\x01"), Bytes("yz")}, NullBytes(), absl::OutOfRangeError("Duplicate byte 0x01 in TRANSLATE source bytes")}, }; return results; } std::vector<FunctionTestCall> GetFunctionTestsInitCap() { return { // initcap(string) -> string {"initcap", {NullString()}, NullString()}, {"initcap", {""}, ""}, {"initcap", {" "}, " "}, {"initcap", {" a 1"}, " A 1"}, {"initcap", {" a \tb"}, " A \tB"}, {"initcap", {" a\tb\nc d"}, " A\tB\nC D"}, {"initcap", {"aB-C ?DEF []h? j"}, "Ab-C ?Def []H? J"}, {"initcap", {"ταινιών"}, "Ταινιών"}, {"initcap", {"abcABC ж--щ фФ"}, "Abcabc Ж--Щ Фф"}, {"initcap", {"\x61\xa7\x65\x71"}, NullString(), OUT_OF_RANGE}, // initcap(string, string) -> string {"initcap", {NullString(), NullString()}, NullString()}, {"initcap", {NullString(), ""}, NullString()}, {"initcap", {"", NullString()}, NullString()}, {"initcap", {"a \tb\n\tc d\ne", " \t"}, "A \tB\n\tC D\ne"}, {"initcap", {"aBc -d", " -"}, "Abc -D"}, {"initcap", {"a b", "ab"}, "a b"}, {"initcap", {"cbac", "aabb"}, "CbaC"}, {"initcap", {"Aa BC\nd", "ab\n"}, "Aa bc\nD"}, {"initcap", {"aAbBc", "abAB"}, "aAbBC"}, {"initcap", {"HERE-iS-a string", "a -"}, "Here-Is-a String"}, {"initcap", {"τΑΑ τιν ιτιών", "τ"}, "τΑα τΙν ιτΙών"}, {"initcap", {" 123 4a 5A b", " 1 234"}, " 123 4A 5a B"}, {"initcap", {"ABCD", ""}, "Abcd"}, {"initcap", {"\x61\xa7\x65\x71", " "}, NullString(), OUT_OF_RANGE}, {"initcap", {"", "\x61\xa7\x65\x71"}, NullString(), OUT_OF_RANGE}, }; } // Defines the test cases for string normalization functions. // The second argument represents the expected results under each // normalize mode following exact same order as {NFC, NFKC, NFD, NFKD}. static std::vector<NormalizeTestCase> GetNormalizeTestCases() { return { // normalize(string [, mode]) -> string {NullString(), {NullString(), NullString(), NullString(), NullString()}}, {"", {"", "", "", ""}}, {"abcABC", {"abcABC", "abcABC", "abcABC", "abcABC"}}, {"abcABCжщфЖЩФ", {"abcABCжщфЖЩФ", "abcABCжщфЖЩФ", "abcABCжщфЖЩФ", "abcABCжщфЖЩФ"}}, {"Ḋ", {"Ḋ", "Ḋ", "D\u0307", "D\u0307"}}, {"D\u0307", {"Ḋ", "Ḋ", "D\u0307", "D\u0307"}}, {"Google™", {"Google™", "GoogleTM", "Google™", "GoogleTM"}}, {"龟", {"龟", "\u9F9F", "龟", "\u9F9F"}}, {"10¹²³", {"10¹²³", "10123", "10¹²³", "10123"}}, {"ẛ̣", {"ẛ̣", "ṩ", "\u017f\u0323\u0307", "s\u0323\u0307"}}, {"Google™Ḋ龟10¹²³", {"Google™Ḋ龟10¹²³", "GoogleTMḊ\u9F9F10123", "Google™D\u0307龟10¹²³", "GoogleTMD\u0307\u9F9F10123"}}, // normalize_and_casefold(string [, mode]) -> string {NullString(), {NullString(), NullString(), NullString(), NullString()}, true /* is_casefold */}, {"", {"", "", "", ""}, true}, {"abcABC", {"abcabc", "abcabc", "abcabc", "abcabc"}, true}, {"abcabcжщфЖЩФ", {"abcabcжщфжщф", "abcabcжщфжщф", "abcabcжщфжщф", "abcabcжщфжщф"}, true}, {"Ḋ", {"ḋ", "ḋ", "d\u0307", "d\u0307"}, true}, {"D\u0307", {"ḋ", "ḋ", "d\u0307", "d\u0307"}, true}, {"Google™", {"google™", "googletm", "google™", "googletm"}, true}, {"龟", {"龟", "\u9F9F", "龟", "\u9F9F"}, true}, {"10¹²³", {"10¹²³", "10123", "10¹²³", "10123"}, true}, {"ẛ̣", {"ṩ", "ṩ", "s\u0323\u0307", "s\u0323\u0307"}, true}, {"Google™Ḋ龟10¹²³", {"google™ḋ龟10¹²³", "googletmḋ\u9F9F10123", "google™d\u0307龟10¹²³", "googletmd\u0307\u9F9F10123"}, true}, }; } std::vector<FunctionTestCall> GetFunctionTestsNormalize() { const zetasql::EnumType* enum_type = nullptr; ZETASQL_CHECK_OK(type_factory()->MakeEnumType( zetasql::functions::NormalizeMode_descriptor(), &enum_type)); // For each NormalizeTestCase, constructs 5 FunctionTestCalls for each // normalize mode (default/NFC, NFC, NFKC, NFD, NFKD), respectively. std::vector<FunctionTestCall> ret; for (const NormalizeTestCase& test_case : GetNormalizeTestCases()) { ZETASQL_CHECK_EQ(functions::NormalizeMode_ARRAYSIZE, test_case.expected_nfs.size()); const std::string function_name = test_case.is_casefold ? "normalize_and_casefold" : "normalize"; ret.push_back( {function_name, {test_case.input}, test_case.expected_nfs[0]}); for (int mode = 0; mode < functions::NormalizeMode_ARRAYSIZE; ++mode) { ret.push_back({function_name, {test_case.input, Value::Enum(enum_type, mode)}, test_case.expected_nfs[mode]}); } if (test_case.is_casefold) continue; // Adds more tests cases for NORMALIZE to verify the invariants between // normal forms. // 1. NFC(NFD(s)) = NFC(s) ret.push_back({"normalize", {test_case.expected_nfs[functions::NormalizeMode::NFD], Value::Enum(enum_type, functions::NormalizeMode::NFC)}, test_case.expected_nfs[functions::NormalizeMode::NFC]}); // 2. NFD(NFC(s)) = NDF(s) ret.push_back({"normalize", {test_case.expected_nfs[functions::NormalizeMode::NFC], Value::Enum(enum_type, functions::NormalizeMode::NFD)}, test_case.expected_nfs[functions::NormalizeMode::NFD]}); for (int mode = 0; mode < functions::NormalizeMode_ARRAYSIZE; ++mode) { // 3. NFKC(s) = NFKC(NFC(s)) = NFKC(NFD(s)) = NFKC(NFKC(s) = NFKC(NFKD(s)) ret.push_back({"normalize", {test_case.expected_nfs[mode], Value::Enum(enum_type, functions::NormalizeMode::NFKC)}, test_case.expected_nfs[functions::NormalizeMode::NFKC]}); // 4. NFKD(s) = NFKD(NFC(s)) = NFKD(NFD(s)) = NFKD(NFKC(s) = NFKD(NFKD(s)) ret.push_back({"normalize", {test_case.expected_nfs[mode], Value::Enum(enum_type, functions::NormalizeMode::NFKD)}, test_case.expected_nfs[functions::NormalizeMode::NFKD]}); } } return ret; } } // namespace zetasql
41.079767
88
0.580156
borjavb
20c0a365d7a3e6a4daf5658a6ec61d76faca7cec
3,141
cpp
C++
Chapter08/Chapter08-2/mainwindow.cpp
DominionSoftware/Hands-On-Mobile-and-Embedded-Development-with-Qt-5
0c85f62d52d570ca1983c2720bb099f2abadb0d1
[ "MIT" ]
28
2019-05-13T02:02:47.000Z
2022-03-27T22:53:50.000Z
Chapter08/Chapter08-2/mainwindow.cpp
DominionSoftware/Hands-On-Mobile-and-Embedded-Development-with-Qt-5
0c85f62d52d570ca1983c2720bb099f2abadb0d1
[ "MIT" ]
null
null
null
Chapter08/Chapter08-2/mainwindow.cpp
DominionSoftware/Hands-On-Mobile-and-Embedded-Development-with-Qt-5
0c85f62d52d570ca1983c2720bb099f2abadb0d1
[ "MIT" ]
19
2019-01-26T10:00:44.000Z
2021-12-26T04:18:37.000Z
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QGeoPositionInfoSource> #include <QDebug> MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QGeoPositionInfoSource *geoSource = QGeoPositionInfoSource::createDefaultSource(this); if (geoSource) { ui->textEdit->insertPlainText(methodsToString(geoSource->supportedPositioningMethods()) + "\n"); geoSource->setUpdateInterval(3000); connect(geoSource, &QGeoPositionInfoSource::positionUpdated, this, &MainWindow::positionUpdated); geoSource->startUpdates(); } } MainWindow::~MainWindow() { delete ui; } void MainWindow::positionUpdated(const QGeoPositionInfo &positionInfo) { QGeoCoordinate coords = positionInfo.coordinate(); QString msg; ui->textEdit->insertPlainText(positionInfo.timestamp().toString() + "\n"); for (int i = 0; i < 6; i++) { if (positionInfo.hasAttribute(static_cast<QGeoPositionInfo::Attribute>(i))) ui->textEdit->insertPlainText(" " + attributeToString(static_cast<QGeoPositionInfo::Attribute>(i)) + " "+ QString::number(positionInfo.attribute(static_cast<QGeoPositionInfo::Attribute>(i))) + "\n"); } ui->textEdit->insertPlainText(QString(" Latitude %1\n").arg(coords.latitude())); ui->textEdit->insertPlainText(QString(" Longitude %1\n").arg(coords.longitude())); if (coords.type() == QGeoCoordinate::Coordinate3D) ui->textEdit->insertPlainText(QString(" Altitude %1\n").arg(coords.altitude())); ui->textEdit->ensureCursorVisible(); } QString MainWindow::attributeToString(QGeoPositionInfo::Attribute attribute) { switch (attribute) { case QGeoPositionInfo::Direction: return QStringLiteral("Direction"); break; case QGeoPositionInfo::GroundSpeed: return QStringLiteral("GroundSpeed"); break; case QGeoPositionInfo::VerticalSpeed: return QStringLiteral("VerticalSpeed"); break; case QGeoPositionInfo::MagneticVariation: return QStringLiteral("MagneticVariation"); break; case QGeoPositionInfo::HorizontalAccuracy: return QStringLiteral("HorizontalAccuracy"); break; case QGeoPositionInfo::VerticalAccuracy: return QStringLiteral("VerticalAccuracy"); break; }; return QString(); } QString MainWindow::methodsToString(QGeoPositionInfoSource::PositioningMethods method) { switch (method) { case QGeoPositionInfoSource::NoPositioningMethods: return QStringLiteral("No Positioning Methods"); break; case QGeoPositionInfoSource::SatellitePositioningMethods: return QStringLiteral("Satellite Positioning Methods"); break; case QGeoPositionInfoSource::NonSatellitePositioningMethods: return QStringLiteral("Non Satellite Positioning Methods"); break; case QGeoPositionInfoSource::AllPositioningMethods: return QStringLiteral("All Positioning Methods"); break; }; return QString(); }
34.141304
135
0.688634
DominionSoftware
20c4b5bedfb46a3992c876887feb15d693884daf
38,267
cpp
C++
src/RemindersDialog.cpp
a1exkos/OutCALL
d84e929d81edf9cad89ff33f4ad3053687bfe4d2
[ "BSD-3-Clause" ]
2
2021-11-24T18:47:31.000Z
2021-12-10T14:50:06.000Z
src/RemindersDialog.cpp
a1exkos/outcall2-master
d84e929d81edf9cad89ff33f4ad3053687bfe4d2
[ "BSD-3-Clause" ]
null
null
null
src/RemindersDialog.cpp
a1exkos/outcall2-master
d84e929d81edf9cad89ff33f4ad3053687bfe4d2
[ "BSD-3-Clause" ]
1
2021-12-09T18:34:01.000Z
2021-12-09T18:34:01.000Z
/* * Класс служит для просмотра и взаимодейстия с напоминаниями. */ #include "RemindersDialog.h" #include "ui_RemindersDialog.h" #include "PopupReminder.h" #include "PopupNotification.h" #include "Global.h" #include "QSqlQueryModelReminders.h" #include "QCustomWidget.h" #include <QDebug> #include <QThread> #include <QMessageBox> #include <QSqlQuery> #include <QLabel> #include <QRegularExpression> #include <QDesktopWidget> #define TIME_TO_UPDATE 5000 // msec RemindersDialog::RemindersDialog(QWidget* parent) : QDialog(parent), ui(new Ui::RemindersDialog) { ui->setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); setWindowFlags(windowFlags() & Qt::WindowMinimizeButtonHint); m_geometry = saveGeometry(); QRegularExpression regExp("^[0-9]*$"); QValidator* validator = new QRegularExpressionValidator(regExp, this); ui->lineEdit_page->setValidator(validator); ui->tableView->verticalHeader()->setSectionsClickable(false); ui->tableView->horizontalHeader()->setSectionsClickable(false); connect(&m_timer, &QTimer::timeout, this, &RemindersDialog::onTimer); connect(ui->tabWidget, &QTabWidget::currentChanged, this, &RemindersDialog::onTabChanged); connect(ui->addReminderButton, &QAbstractButton::clicked, this, &RemindersDialog::onAddReminder); connect(ui->tableView, &QAbstractItemView::doubleClicked, this, &RemindersDialog::onEditReminder); ui->comboBox_list->setVisible(false); m_resizeCells = true; m_go = "default"; m_page = "1"; QSqlQuery query(m_db); query.prepare("SELECT COUNT(*) FROM reminders WHERE phone_to = ? AND active = true"); query.addBindValue(g_personalNumberName); query.exec(); m_oldActiveReminders = 0; if (query.next()) m_oldActiveReminders = query.value(0).toInt(); query.prepare("SELECT COUNT(*) FROM reminders WHERE phone_from <> ? AND phone_to = ? AND active = true AND viewed = false ORDER BY id DESC"); query.addBindValue(g_personalNumberName); query.addBindValue(g_personalNumberName); query.exec(); m_oldReceivedReminders = 0; if (query.next()) m_oldReceivedReminders = query.value(0).toInt(); QList<QString> ids; QList<QDateTime> dateTimes; QList<QString> notes; query.prepare("SELECT id, datetime, content FROM reminders WHERE phone_to = '" + g_personalNumberName + "' AND datetime > '" + QDateTime::currentDateTime().toString("yy-MM-dd hh:mm:ss") + "' AND active IS TRUE"); query.exec(); while (query.next()) { ids.append(query.value(0).value<QString>()); dateTimes.append(query.value(1).value<QDateTime>()); notes.append(query.value(2).value<QString>()); } m_remindersThread = new QThread; m_remindersThreadManager = new RemindersThreadManager(ids, dateTimes, notes); m_remindersThreadManager->moveToThread(m_remindersThread); query.prepare("SELECT id, datetime, content FROM reminders WHERE phone_to = '" + g_personalNumberName + "' AND datetime < '" + QDateTime::currentDateTime().toString("yy-MM-dd hh:mm:ss") + "' AND active IS TRUE"); query.exec(); while (query.next()) { onPastNotify(query.value(0).toString(), query.value(1).value<QDateTime>(), query.value(2).toString()); } connect(m_remindersThread, &QThread::started, m_remindersThreadManager, &RemindersThreadManager::process); connect(m_remindersThreadManager, &RemindersThreadManager::notify, this, &RemindersDialog::onNotify); connect(m_remindersThreadManager, &RemindersThreadManager::finished, m_remindersThread, &QThread::quit); connect(m_remindersThreadManager, &RemindersThreadManager::finished, m_remindersThreadManager, &QObject::deleteLater); connect(m_remindersThread, &QThread::finished, m_remindersThread, &QObject::deleteLater); m_remindersThread->start(); m_timer.setInterval(TIME_TO_UPDATE); loadReminders(); ui->tableView->scrollToTop(); } RemindersDialog::~RemindersDialog() { m_remindersThread->requestInterruption(); delete ui; } /** * Получает запрос на показ / скрытие * всплывающих окон напоминаний. */ void RemindersDialog::showReminders(bool show) { if (show) { m_showReminder = true; loadReminders(); m_timer.start(); } else { m_showReminder = false; m_timer.stop(); } } /** * Выполняет обработку появления окна. */ void RemindersDialog::showEvent(QShowEvent* event) { QDialog::showEvent(event); QSqlQuery query(m_db); query.prepare("UPDATE reminders SET viewed = true WHERE phone_from <> ? AND phone_to = ? AND active = true AND viewed = false"); query.addBindValue(g_personalNumberName); query.addBindValue(g_personalNumberName); query.exec(); emit reminders(false); m_resizeCells = false; m_go = "default"; loadReminders(); } /** * Выполняет обработку закрытия окна. */ void RemindersDialog::closeEvent(QCloseEvent*) { hide(); QDialog::clearFocus(); clearSelections(); m_verticalScrollBar = 0; m_horizontalScrollBar = 0; ui->tabWidget->setCurrentWidget(ui->tabWidget->findChild<QWidget*>(QString("relevant"))); m_go = "default"; m_page = "1"; ui->tableView->scrollToTop(); restoreGeometry(m_geometry); QDesktopWidget desktopWidget; QRect screen = desktopWidget.screenGeometry(this); move(screen.center() - rect().center()); } /** * Выполняет снятие выделения с записей. */ void RemindersDialog::clearSelections() { m_selections.clear(); ui->tableView->clearSelection(); } /** * Выполняет по таймеру обновление списка напоминаний. */ void RemindersDialog::onTimer() { QSqlQuery query(m_db); query.prepare("SELECT COUNT(*) FROM reminders WHERE phone_from <> ? AND phone_to = ? AND active = true AND viewed = false ORDER BY id DESC"); query.addBindValue(g_personalNumberName); query.addBindValue(g_personalNumberName); query.exec(); qint32 newReceivedReminders = 0; if (query.next()) newReceivedReminders = query.value(0).toInt(); if (newReceivedReminders > m_oldReceivedReminders) { query.prepare("SELECT id, phone_from, content FROM reminders WHERE phone_from <> ? AND phone_to = ? AND active = true AND viewed = false ORDER BY id DESC LIMIT 0,?"); query.addBindValue(g_personalNumberName); query.addBindValue(g_personalNumberName); query.addBindValue(newReceivedReminders - m_oldReceivedReminders); query.exec(); if (m_showReminder) { emit reminders(true); while (query.next()) PopupNotification::showReminderNotification(this, query.value(0).toString(), query.value(1).toString(), query.value(2).toString()); } } else { query.prepare("SELECT COUNT(*) FROM reminders WHERE phone_to = ? AND active = true"); query.addBindValue(g_personalNumberName); query.exec(); qint32 newActiveReminders = 0; if (query.next()) newActiveReminders = query.value(0).toInt(); if (newActiveReminders > m_oldActiveReminders) m_resizeCells = true; else m_resizeCells = false; m_oldActiveReminders = newActiveReminders; } m_oldReceivedReminders = newReceivedReminders; m_go = "default"; loadReminders(); sendValues(); } /** * Выполняет удаление объектов класса. */ void RemindersDialog::deleteObjects() { if (!m_queryModel.isNull()) { m_selections = ui->tableView->selectionModel()->selectedRows(); for (qint32 i = 0; i < m_widgets.size(); ++i) m_widgets[i]->deleteLater(); m_widgets.clear(); m_queryModel->deleteLater(); } } /** * Выполняет отправку данных актуальных напоминаний в класс RemindersThreadManager. */ void RemindersDialog::sendValues() { QList<QString> ids; QList<QDateTime> dateTimes; QList<QString> notes; QSqlQuery query(m_db); query.prepare("SELECT id, datetime, content FROM reminders WHERE phone_to = '" + g_personalNumberName + "' AND datetime > '" + QDateTime::currentDateTime().toString("yy-MM-dd hh:mm:ss") + "' AND active IS TRUE"); query.exec(); while (query.next()) { ids.append(query.value(0).value<QString>()); dateTimes.append(query.value(1).value<QDateTime>()); notes.append(query.value(2).value<QString>()); } m_remindersThreadManager->setValues(ids, dateTimes, notes); } /** * Получает запрос на обновление состояния окна. */ void RemindersDialog::receiveData(bool update) { if (update) { emit reminders(false); m_selections.clear(); QSqlQuery query(m_db); query.prepare("SELECT COUNT(*) FROM reminders WHERE phone_to = ? AND active = true"); query.addBindValue(g_personalNumberName); query.exec(); qint32 newActiveReminders = 0; if (query.next()) newActiveReminders = query.value(0).toInt(); m_oldActiveReminders = newActiveReminders; m_go = "default"; onUpdate(); } } /** * Выполняет обновление количества напоминаний. */ void RemindersDialog::updateCount() { QSqlQuery query(m_db); QString queryString; if (ui->tabWidget->currentWidget()->objectName() == "relevant") queryString = "SELECT COUNT(*) FROM reminders WHERE phone_to = '" + g_personalNumberName + "' AND active = true"; if (ui->tabWidget->currentWidget()->objectName() == "irrelevant") queryString = "SELECT COUNT(*) FROM reminders WHERE phone_to = '" + g_personalNumberName + "' AND active = false"; if (ui->tabWidget->currentWidget()->objectName() == "delegated") queryString = "SELECT COUNT(*) FROM (SELECT COUNT(*) FROM reminders WHERE phone_from = '" + g_personalNumberName + "' AND phone_to <> '" + g_personalNumberName + "' GROUP BY CASE WHEN group_id IS NOT NULL THEN group_id ELSE id END) reminders"; query.exec(queryString); query.first(); qint32 count = query.value(0).toInt(); QString pages = ui->label_pages->text(); if (count <= ui->comboBox_list->currentText().toInt()) pages = "1"; else { qint32 remainder = count % ui->comboBox_list->currentText().toInt(); if (remainder) remainder = 1; else remainder = 0; pages = QString::number(count / ui->comboBox_list->currentText().toInt() + remainder); } if (m_go == "previous" && m_page != "1") m_page = QString::number(m_page.toInt() - 1); else if (m_go == "previousStart" && m_page != "1") m_page = "1"; else if (m_go == "next" && m_page.toInt() < pages.toInt()) m_page = QString::number(m_page.toInt() + 1); else if (m_go == "next" && m_page.toInt() >= pages.toInt()) m_page = pages; else if (m_go == "nextEnd" && m_page.toInt() < pages.toInt()) m_page = pages; else if (m_go == "enter" && ui->lineEdit_page->text().toInt() > 0 && ui->lineEdit_page->text().toInt() <= pages.toInt()) m_page = ui->lineEdit_page->text(); else if (m_go == "enter" && ui->lineEdit_page->text().toInt() > pages.toInt()) {} else if (m_go == "default" && m_page.toInt() >= pages.toInt()) m_page = pages; else if (m_go == "default" && m_page == "1") m_page = "1"; ui->lineEdit_page->setText(m_page); ui->label_pages->setText(tr("из ") + pages); } /** * Выполняет вывод и обновление списка напоминаний. */ void RemindersDialog::loadReminders() { deleteObjects(); updateCount(); m_queryModel = new QSqlQueryModelReminders(this); QString queryString = "SELECT id, phone_from, phone_to, datetime, content, active, viewed, completed, group_id FROM reminders WHERE "; if (ui->tabWidget->currentWidget()->objectName() == "relevant") queryString.append("phone_to = '" + g_personalNumberName + "' AND active = true "); else if (ui->tabWidget->currentWidget()->objectName() == "irrelevant") queryString.append("phone_to = '" + g_personalNumberName + "' AND active = false "); else if (ui->tabWidget->currentWidget()->objectName() == "delegated") queryString = "SELECT id, phone_from, IF(group_id IS NULL, phone_to, NULL), datetime, content, active, viewed, completed, group_id FROM reminders WHERE " "phone_from = '" + g_personalNumberName + "' AND phone_to <> '" + g_personalNumberName + "' GROUP BY CASE WHEN group_id IS NOT NULL THEN group_id ELSE id END"; queryString.append(" ORDER BY datetime DESC LIMIT "); if (ui->lineEdit_page->text() == "1") queryString.append("0, " + QString::number(ui->lineEdit_page->text().toInt() * ui->comboBox_list->currentText().toInt()) + " "); else queryString.append("" + QString::number(ui->lineEdit_page->text().toInt() * ui->comboBox_list->currentText().toInt() - ui->comboBox_list->currentText().toInt()) + " , " + QString::number(ui->comboBox_list->currentText().toInt())); m_queryModel->setQuery(queryString); m_queryModel->insertColumn(1); m_queryModel->setHeaderData(1, Qt::Horizontal, tr("Активно")); m_queryModel->setHeaderData(2, Qt::Horizontal, tr("От")); m_queryModel->setHeaderData(3, Qt::Horizontal, tr("Кому")); m_queryModel->setHeaderData(4, Qt::Horizontal, tr("Дата и время")); m_queryModel->insertColumn(9); m_queryModel->setHeaderData(9, Qt::Horizontal, tr("Содержание")); m_queryModel->insertColumn(10); m_queryModel->setHeaderData(10, Qt::Horizontal, tr("Просмотрено")); m_queryModel->insertColumn(11); m_queryModel->setHeaderData(11, Qt::Horizontal, tr("Выполнено")); ui->tableView->setModel(m_queryModel); m_queryModel->setParentTable(ui->tableView); ui->tableView->setColumnHidden(0, true); if (ui->tabWidget->currentWidget()->objectName() == "delegated") ui->tableView->setColumnHidden(2, true); else { ui->tableView->setColumnHidden(3, true); ui->tableView->setColumnHidden(10, true); } ui->tableView->setColumnHidden(5, true); ui->tableView->setColumnHidden(6, true); ui->tableView->setColumnHidden(7, true); ui->tableView->setColumnHidden(8, true); ui->tableView->setColumnHidden(12, true); ui->tableView->horizontalHeader()->setDefaultSectionSize(maximumWidth()); for (qint32 row_index = 0; row_index < ui->tableView->model()->rowCount(); ++row_index) { if (ui->tabWidget->currentWidget()->objectName() == "delegated") { if (ui->tableView->model()->index(row_index, 3).data(Qt::EditRole).toString().isEmpty()) ui->tableView->setIndexWidget(m_queryModel->index(row_index, 3), addPushButtonGroup(row_index)); ui->tableView->setIndexWidget(m_queryModel->index(row_index, 1), addCheckBoxActive(row_index)); ui->tableView->setIndexWidget(m_queryModel->index(row_index, 10), addCheckBoxViewed(row_index)); ui->tableView->setIndexWidget(m_queryModel->index(row_index, 11), addCheckBoxCompleted(row_index)); } else { if (m_queryModel->data(m_queryModel->index(row_index, 2), Qt::EditRole).toString() != m_queryModel->data(m_queryModel->index(row_index, 3), Qt::EditRole).toString()) { ui->tableView->setIndexWidget(m_queryModel->index(row_index, 1), addWidgetActive()); ui->tableView->setIndexWidget(m_queryModel->index(row_index, 11), addCheckBoxCompleted(row_index)); } else { ui->tableView->setIndexWidget(m_queryModel->index(row_index, 1), addCheckBoxActive(row_index)); ui->tableView->setIndexWidget(m_queryModel->index(row_index, 11), addWidgetCompleted()); } } QRegularExpressionMatchIterator hrefIterator = m_hrefRegExp.globalMatch(m_queryModel->data(m_queryModel->index(row_index, 5), Qt::EditRole).toString()); if (hrefIterator.hasNext()) ui->tableView->setIndexWidget(m_queryModel->index(row_index, 9), addWidgetContent(row_index, true)); else ui->tableView->setIndexWidget(m_queryModel->index(row_index, 9), addWidgetContent(row_index, false)); } if (m_resizeCells) { ui->tableView->resizeRowsToContents(); ui->tableView->resizeColumnsToContents(); } if (ui->tableView->model()->columnCount() != 0) ui->tableView->horizontalHeader()->setSectionResizeMode(9, QHeaderView::Stretch); if (!m_selections.isEmpty()) for (qint32 i = 0; i < m_selections.length(); ++i) { QModelIndex index = m_selections.at(i); ui->tableView->selectionModel()->select(index, QItemSelectionModel::Select | QItemSelectionModel::Rows); } if (m_verticalScrollBar != 0) { ui->tableView->verticalScrollBar()->setValue(m_verticalScrollBar); ui->tableView->horizontalScrollBar()->setValue(m_horizontalScrollBar); m_verticalScrollBar = 0; m_horizontalScrollBar = 0; } m_resizeCells = true; emit reminders(false); } /** * Выполняет установку виджета для поля "Содержание". */ QWidget* RemindersDialog::addWidgetContent(qint32 row_index, bool url) { QWidget* widget = new QWidget(this); QHBoxLayout* layout = new QHBoxLayout(widget); QLabel* contentLabel = new QLabel(widget); layout->addWidget(contentLabel); QString note = m_queryModel->data(m_queryModel->index(row_index, 5), Qt::EditRole).toString(); if (url) { QRegularExpressionMatchIterator hrefIterator = m_hrefRegExp.globalMatch(note); QStringList hrefs, hrefsNoCharacters, hrefsReplaceCharacters; note.replace("<", "&lt;").replace(">", "&gt;"); while (hrefIterator.hasNext()) { QRegularExpressionMatch match = hrefIterator.next(); QString href = match.captured(1); hrefs << href; href.remove(QRegularExpression("[\\,\\.\\;\\:\\'\\\"\\-\\!\\?\\^\\`\\~\\*\\№\\%\\&\\$\\#\\<\\>\\(\\)\\[\\]\\{\\}]+$")); hrefsNoCharacters << href; } QStringList firstCharList, lastCharList; for (qint32 i = 0; i < hrefs.length(); ++i) { QString hrefReplaceCharacters = QString(hrefs.at(i)).replace("<", "&lt;").replace(">", "&gt;"); hrefsReplaceCharacters << hrefReplaceCharacters; hrefReplaceCharacters = hrefReplaceCharacters.remove(hrefsNoCharacters.at(i)); if (hrefReplaceCharacters.isEmpty()) lastCharList << " "; else lastCharList << hrefReplaceCharacters; } note.replace(QRegularExpression("\\n"), QString(" <br> ")); qint32 index = 0; for (qint32 i = 0; i < hrefsReplaceCharacters.length(); ++i) { if (i == 0) index = note.indexOf(hrefsReplaceCharacters.at(i)); else index = note.indexOf(hrefsReplaceCharacters.at(i), index + hrefsReplaceCharacters.at(i - 1).size()); if (index > 0) firstCharList << note.at(index - 1); else firstCharList << ""; } for (qint32 i = 0; i < hrefs.length(); ++i) { qint32 size; if (firstCharList.at(i) == "") size = hrefsReplaceCharacters.at(i).size(); else size = hrefsReplaceCharacters.at(i).size() + 1; note.replace(note.indexOf(QRegularExpression("( |^|\\^|\\.|\\,|\\(|\\)|\\[|\\]|\\{|\\}|\\;|\\'|\\\"|[a-zA-Z0-9а-яА-Я]|\\`|\\~|\\%|\\$|\\#|\\№|\\@|\\&|\\/|\\\\|\\!|\\*)" + QRegularExpression::escape(hrefsReplaceCharacters.at(i)) + "( |$)")), size, QString(firstCharList.at(i) + "<a href='" + hrefsNoCharacters.at(i) + "'>" + hrefsNoCharacters.at(i) + "</a>" + lastCharList.at(i))); } } contentLabel->setText(note); contentLabel->setOpenExternalLinks(true); contentLabel->setWordWrap(true); m_widgets.append(widget); return widget; } /** * Реализация кнопки просмотра абонентов, которым отправлено напоминание */ QWidget* RemindersDialog::addPushButtonGroup(qint32 row_index) { QWidget* widget = new QWidget(this); QHBoxLayout* layout = new QHBoxLayout(widget); QPushButton* pushButton = new QPushButton(tr("Группа"), widget); layout->addWidget(pushButton, 0, Qt::AlignCenter); connect(pushButton, &QPushButton::clicked, this, [=]() { QCustomWidget* customWidget = new QCustomWidget(this); QHBoxLayout* gridLayout = new QHBoxLayout(customWidget); QListWidget* listWidget = new QListWidget(customWidget); qint32 size = 60; customWidget->setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); customWidget->setFixedSize(250, size); gridLayout->addWidget(listWidget, 0, Qt::AlignCenter); QString group_id = m_queryModel->data(m_queryModel->index(row_index, 12), Qt::EditRole).toString(); QSqlQuery query(m_db); query.prepare("SELECT phone_to FROM reminders WHERE group_id = ?"); query.addBindValue(group_id); query.exec(); while (query.next()) { listWidget->addItem(query.value(0).toString()); if (listWidget->count() > 2 && customWidget->height() < 170) customWidget->setFixedHeight(size += 17); } for (qint32 i = 0; i < listWidget->count(); ++i) listWidget->item(i)->setFlags(listWidget->item(i)->flags() & ~Qt::ItemIsSelectable); customWidget->setWindowTitle(tr("Группа") + " (" + QString::number(listWidget->count()) + ")"); customWidget->show(); customWidget->setAttribute(Qt::WA_DeleteOnClose); m_verticalScrollBar = ui->tableView->verticalScrollBar()->value(); m_horizontalScrollBar = ui->tableView->horizontalScrollBar()->value(); m_go = "default"; onUpdate(); }); m_widgets.append(widget); return widget; } /** * Выполняет установку виджета для поля "Активно" в полученных напоминаниях. */ QWidget* RemindersDialog::addWidgetActive() { QWidget* widget = new QWidget(this); QHBoxLayout* layout = new QHBoxLayout(widget); QLabel* imageLabel = new QLabel(widget); layout->addWidget(imageLabel, 0, Qt::AlignCenter); imageLabel->setPixmap(QPixmap(":/images/incomingNotification.png").scaled(15, 15, Qt::IgnoreAspectRatio)); m_widgets.append(widget); return widget; } /** * Выполняет установку виджета для поля "Активно" в личных напоминаниях. */ QWidget* RemindersDialog::addCheckBoxActive(qint32 row_index) { QWidget* widget = new QWidget(this); QHBoxLayout* layout = new QHBoxLayout(widget); QCheckBox* checkBox = new QCheckBox(widget); layout->addWidget(checkBox, 0, Qt::AlignCenter); QString group_id = m_queryModel->data(m_queryModel->index(row_index, 12), Qt::EditRole).toString(); if (ui->tabWidget->currentWidget()->objectName() == "delegated") { if (group_id == "0") { if (m_queryModel->data(m_queryModel->index(row_index, 6), Qt::EditRole) == true) checkBox->setChecked(true); else checkBox->setChecked(false); } else { QSqlQuery query(m_db); query.prepare("SELECT active FROM reminders WHERE group_id = ?"); query.addBindValue(group_id); query.exec(); checkBox->setChecked(false); while (query.next()) if (query.value(0).toBool() == true) checkBox->setChecked(true); } } else { if (m_queryModel->data(m_queryModel->index(row_index, 6), Qt::EditRole) == true) checkBox->setChecked(true); else checkBox->setChecked(false); } QString column = "active"; QString id = m_queryModel->data(m_queryModel->index(row_index, 0), Qt::EditRole).toString(); QDateTime dateTime = m_queryModel->data(m_queryModel->index(row_index, 4), Qt::EditRole).toDateTime(); connect(checkBox, &QAbstractButton::pressed, this, &RemindersDialog::checkBoxStateChanged); checkBox->setProperty("id", QVariant::fromValue(id)); checkBox->setProperty("column", QVariant::fromValue(column)); checkBox->setProperty("checkBox", QVariant::fromValue(checkBox)); checkBox->setProperty("group_id", QVariant::fromValue(group_id)); checkBox->setProperty("dateTime", QVariant::fromValue(dateTime)); m_widgets.append(widget); return widget; } /** * Выполняет установку виджета для поля "Просмотрено". */ QWidget* RemindersDialog::addCheckBoxViewed(qint32 row_index) { QWidget* widget = new QWidget(this); QHBoxLayout* layout = new QHBoxLayout(widget); QCheckBox* checkBox = new QCheckBox(widget); layout->addWidget(checkBox, 0, Qt::AlignCenter); QString group_id = m_queryModel->data(m_queryModel->index(row_index, 12), Qt::EditRole).toString(); if (group_id == "0") { if (m_queryModel->data(m_queryModel->index(row_index, 7), Qt::EditRole) == true) checkBox->setChecked(true); else checkBox->setChecked(false); } else { QSqlQuery query(m_db); query.prepare("SELECT viewed, phone_to FROM reminders WHERE group_id = ?"); query.addBindValue(group_id); query.exec(); checkBox->setChecked(true); while (query.next()) if (query.value(0).toBool() == false && query.value(1).toString() != g_personalNumberName) checkBox->setChecked(false); } QString column = "viewed"; QString id = m_queryModel->data(m_queryModel->index(row_index, 0), Qt::EditRole).toString(); QDateTime dateTime = m_queryModel->data(m_queryModel->index(row_index, 4), Qt::EditRole).toDateTime(); connect(checkBox, &QAbstractButton::pressed, this, &RemindersDialog::checkBoxStateChanged); checkBox->setProperty("id", QVariant::fromValue(id)); checkBox->setProperty("column", QVariant::fromValue(column)); checkBox->setProperty("checkBox", QVariant::fromValue(checkBox)); checkBox->setProperty("dateTime", QVariant::fromValue(dateTime)); m_widgets.append(widget); return widget; } /** * Выполняет установку виджета для поля "Выполнено" в личных напоминаниях. */ QWidget* RemindersDialog::addWidgetCompleted() { QWidget* widget = new QWidget(this); m_widgets.append(widget); return widget; } /** * Выполняет установку виджета для поля "Выполнено" в полученных напоминаниях. */ QWidget* RemindersDialog::addCheckBoxCompleted(qint32 row_index) { QWidget* widget = new QWidget(this); QHBoxLayout* layout = new QHBoxLayout(widget); QCheckBox* checkBox = new QCheckBox(widget); layout->addWidget(checkBox, 0, Qt::AlignCenter); QString group_id = m_queryModel->data(m_queryModel->index(row_index, 12), Qt::EditRole).toString(); if (ui->tabWidget->currentWidget()->objectName() == "delegated") { if (group_id == "0") { if (m_queryModel->data(m_queryModel->index(row_index, 8), Qt::EditRole) == true) checkBox->setChecked(true); else checkBox->setChecked(false); } else { QSqlQuery query(m_db); query.prepare("SELECT completed, phone_to FROM reminders WHERE group_id = ?"); query.addBindValue(group_id); query.exec(); checkBox->setChecked(true); while (query.next()) if (query.value(0).toBool() == false && query.value(1).toString() != g_personalNumberName) checkBox->setChecked(false); } } else { if (m_queryModel->data(m_queryModel->index(row_index, 8), Qt::EditRole) == true) checkBox->setChecked(true); else checkBox->setChecked(false); } QString column = "completed"; QString id = m_queryModel->data(m_queryModel->index(row_index, 0), Qt::EditRole).toString(); QDateTime dateTime = m_queryModel->data(m_queryModel->index(row_index, 4), Qt::EditRole).toDateTime(); connect(checkBox, &QAbstractButton::pressed, this, &RemindersDialog::checkBoxStateChanged); checkBox->setProperty("id", QVariant::fromValue(id)); checkBox->setProperty("column", QVariant::fromValue(column)); checkBox->setProperty("checkBox", QVariant::fromValue(checkBox)); checkBox->setProperty("dateTime", QVariant::fromValue(dateTime)); m_widgets.append(widget); return widget; } /** * Выполняет обработку смены состояния чекбокса. */ void RemindersDialog::checkBoxStateChanged() { QString id = sender()->property("id").value<QString>(); QString column = sender()->property("column").value<QString>(); QDateTime dateTime = sender()->property("dateTime").value<QDateTime>(); QCheckBox* checkBox = sender()->property("checkBox").value<QCheckBox*>(); QString group_id = "0"; if (column == "active") group_id = sender()->property("group_id").value<QString>(); if (!checkBox->isChecked() && dateTime < QDateTime::currentDateTime() && (ui->tabWidget->currentWidget()->objectName() == "irrelevant" || ui->tabWidget->currentWidget()->objectName() == "delegated") && column == "active") { checkBox->setChecked(false); m_resizeCells = false; MsgBoxError(tr("Указано прошедшее время!")); } else { QSqlQuery query(m_db); if (ui->tabWidget->currentWidget()->objectName() == "relevant") { if (checkBox->isChecked() && column == "active") { checkBox->setChecked(false); query.prepare("UPDATE reminders SET active = false WHERE id = ?"); query.addBindValue(id); query.exec(); m_resizeCells = true; emit reminders(false); } else if (!checkBox->isChecked() && column == "completed") { checkBox->setChecked(true); query.prepare("UPDATE reminders SET active = false, viewed = true, completed = true WHERE id = ?"); query.addBindValue(id); query.exec(); m_resizeCells = true; emit reminders(false); } } else if (ui->tabWidget->currentWidget()->objectName() == "irrelevant") { if (!checkBox->isChecked() && column == "active") { checkBox->setChecked(true); query.prepare("UPDATE reminders SET active = true WHERE id = ?"); query.addBindValue(id); query.exec(); m_resizeCells = true; emit reminders(false); } else if (checkBox->isChecked() && column == "completed") { checkBox->setChecked(true); m_resizeCells = false; } } else if (ui->tabWidget->currentWidget()->objectName() == "delegated") { if (checkBox->isChecked() && column == "active") { checkBox->setChecked(false); if (group_id == "0") { query.prepare("UPDATE reminders SET active = false WHERE id = ?"); query.addBindValue(id); query.exec(); } else { query.prepare("UPDATE reminders SET active = false WHERE group_id = ?"); query.addBindValue(group_id); query.exec(); } m_resizeCells = false; emit reminders(false); } else if (!checkBox->isChecked() && column == "active") { checkBox->setChecked(true); if (group_id == "0") { query.prepare("UPDATE reminders SET active = true, viewed = false, completed = false WHERE id = ?"); query.addBindValue(id); query.exec(); } else { query.prepare("UPDATE reminders SET active = true, viewed = false, completed = false WHERE group_id = ?"); query.addBindValue(group_id); query.exec(); } m_resizeCells = false; emit reminders(false); } else if (checkBox->isChecked() && column == "completed") { checkBox->setChecked(true); m_resizeCells = false; } else if (!checkBox->isChecked() && column == "completed") { checkBox->setChecked(false); m_resizeCells = false; } else if (checkBox->isChecked() && column == "viewed") { checkBox->setChecked(true); m_resizeCells = false; } else if (!checkBox->isChecked() && column == "viewed") { checkBox->setChecked(false); m_resizeCells = false; } } } m_verticalScrollBar = ui->tableView->verticalScrollBar()->value(); m_horizontalScrollBar = ui->tableView->horizontalScrollBar()->value(); m_go = "default"; onUpdate(); } /** * Выполняет обработку смены вкладки. */ void RemindersDialog::onTabChanged() { ui->tableView->setModel(NULL); m_go = "default"; m_page = "1"; onUpdate(); } /** * Выполняет операции для последующего обновления списка напоминаний. */ void RemindersDialog::onUpdate() { clearSelections(); loadReminders(); if (ui->tabWidget->currentWidget()->objectName() == "relevant") { QSqlQuery query(m_db); query.prepare("UPDATE reminders SET viewed = true WHERE phone_from <> ? AND phone_to = ? AND active = true"); query.addBindValue(g_personalNumberName); query.addBindValue(g_personalNumberName); query.exec(); emit reminders(false); } } /** * Выполняет открытие окна добавления напоминания. */ void RemindersDialog::onAddReminder() { m_addReminderDialog = new AddReminderDialog; connect(m_addReminderDialog, &AddReminderDialog::sendData, this, &RemindersDialog::receiveData); m_addReminderDialog->show(); m_addReminderDialog->setAttribute(Qt::WA_DeleteOnClose); } /** * Выполняет открытие окна редактирования напоминания. */ void RemindersDialog::onEditReminder(const QModelIndex& index) { if (ui->tabWidget->currentWidget()->objectName() == "irrelevant" && m_queryModel->data(m_queryModel->index(index.row(), 2), Qt::EditRole).toString() != m_queryModel->data(m_queryModel->index(index.row(), 3), Qt::EditRole).toString()) return; QString id = m_queryModel->data(m_queryModel->index(index.row(), 0), Qt::EditRole).toString(); QDateTime dateTime = m_queryModel->data(m_queryModel->index(index.row(), 4), Qt::EditRole).toDateTime(); QString note = m_queryModel->data(m_queryModel->index(index.row(), 5), Qt::EditRole).toString(); QString group_id = m_queryModel->data(m_queryModel->index(index.row(), 12), Qt::EditRole).toString(); if (ui->tabWidget->currentWidget()->objectName() == "relevant" && m_queryModel->data(m_queryModel->index(index.row(), 2), Qt::EditRole).toString() != m_queryModel->data(m_queryModel->index(index.row(), 3), Qt::EditRole).toString()) { QSqlQuery query(m_db); query.prepare("UPDATE reminders SET viewed = true WHERE id = ? AND active = true"); query.addBindValue(id); query.exec(); emit reminders(false); } m_editReminderDialog = new EditReminderDialog; m_editReminderDialog->setValues(id, group_id, dateTime, note); connect(m_editReminderDialog, &EditReminderDialog::sendData, this, &RemindersDialog::receiveData); m_editReminderDialog->show(); m_editReminderDialog->setAttribute(Qt::WA_DeleteOnClose); } /** * Получает данные напоминания для их последующей передачи классу PopupReminder. */ void RemindersDialog::onNotify(const QString& id, const QDateTime& dateTime, const QString& note) { if (m_showReminder) PopupReminder::showReminder(this, id, dateTime, note); } void RemindersDialog::onPastNotify(const QString& id, const QDateTime& dateTime, const QString& note) { PopupReminder::showReminder(this, id, dateTime, note); } /** * Выполняет операции для последующего перехода на предыдущую страницу. */ void RemindersDialog::on_previousButton_clicked() { ui->tableView->scrollToTop(); m_go = "previous"; onUpdate(); } /** * Выполняет операции для последующего перехода на следующую страницу. */ void RemindersDialog::on_nextButton_clicked() { ui->tableView->scrollToTop(); m_go = "next"; onUpdate(); } /** * Выполняет операции для последующего перехода на первую страницу. */ void RemindersDialog::on_previousStartButton_clicked() { ui->tableView->scrollToTop(); m_go = "previousStart"; onUpdate(); } /** * Выполняет операции для последующего перехода на последнюю страницу. */ void RemindersDialog::on_nextEndButton_clicked() { ui->tableView->scrollToTop(); m_go = "nextEnd"; onUpdate(); } /** * Выполняет операции для последующего перехода на заданную страницу. */ void RemindersDialog::on_lineEdit_page_returnPressed() { ui->tableView->scrollToTop(); m_go = "enter"; onUpdate(); } /** * Выполняет обработку нажатий клавиш. * Особая обработка для клавиши Esc. */ void RemindersDialog::keyPressEvent(QKeyEvent* event) { if (event->key() == Qt::Key_Escape) QDialog::close(); else QDialog::keyPressEvent(event); }
31.809643
252
0.626127
a1exkos
20c77792525804dc9861b5d160a3ba2f2e933aad
14,495
cpp
C++
plugin/bullet/src/minko/component/bullet/Collider.cpp
aerys/minko
edc3806a4e01570c5cb21f3402223ca695d08d22
[ "BSD-3-Clause" ]
478
2015-01-04T16:59:53.000Z
2022-03-07T20:28:07.000Z
plugin/bullet/src/minko/component/bullet/Collider.cpp
aerys/minko
edc3806a4e01570c5cb21f3402223ca695d08d22
[ "BSD-3-Clause" ]
83
2015-01-15T21:45:06.000Z
2021-11-08T11:01:48.000Z
plugin/bullet/src/minko/component/bullet/Collider.cpp
aerys/minko
edc3806a4e01570c5cb21f3402223ca695d08d22
[ "BSD-3-Clause" ]
175
2015-01-04T03:30:39.000Z
2020-01-27T17:08:14.000Z
/* Copyright (c) 2014 Aerys 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 "minko/component/bullet/Collider.hpp" #include "minko/scene/Node.hpp" #include "minko/scene/NodeSet.hpp" #include "minko/component/Transform.hpp" #include "minko/component/Surface.hpp" #include "minko/component/SceneManager.hpp" #include "minko/component/Renderer.hpp" #include "minko/component/bullet/AbstractPhysicsShape.hpp" #include "minko/component/bullet/ColliderData.hpp" #include "minko/component/bullet/PhysicsWorld.hpp" #include "minko/component/bullet/PhysicsWorld.hpp" #include "minko/file/AssetLibrary.hpp" #include "minko/math/tools.hpp" #include "minko/log/Logger.hpp" using namespace minko; using namespace minko::scene; using namespace minko::component; bullet::Collider::Collider(ColliderData::Ptr data): AbstractComponent(LayoutMask::COLLISIONS_DYNAMIC_DEFAULT), _colliderData(data), _canSleep(false), _triggerCollisions(false), _linearFactor(math::vec3(1.f, 1.f, 1.f)), _linearDamping(0.f), _linearSleepingThreshold(0.8f), _angularFactor(math::vec3(1.f, 1.f, 1.f)), _angularDamping(0.f), _angularSleepingThreshold(1.f), _physicsWorld(nullptr), _correction(math::mat4()), _physicsTransform(math::mat4()), _graphicsTransform(nullptr), _propertiesChanged(Signal<Ptr>::create()), _collisionStarted(Signal<Ptr, Ptr>::create()), _collisionEnded(Signal<Ptr, Ptr>::create()), _physicsTransformChanged(Signal<Ptr, math::mat4>::create()), _graphicsTransformChanged(Signal<Ptr, Transform::Ptr>::create()), _targetAddedSlot(nullptr), _targetRemovedSlot(nullptr), _addedSlot(nullptr), _removedSlot(nullptr) { if (data == nullptr) throw std::invalid_argument("data"); } AbstractComponent::Ptr bullet::Collider::clone(const CloneOption& option) { Collider::Ptr origin = std::static_pointer_cast<Collider>(shared_from_this()); return Collider::create(origin->_colliderData); } void bullet::Collider::targetAdded(Node::Ptr target) { _addedSlot = target->added().connect(std::bind( &bullet::Collider::addedHandler, std::static_pointer_cast<Collider>(shared_from_this()), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3 ) ); _removedSlot = target->removed().connect(std::bind( &bullet::Collider::removedHandler, std::static_pointer_cast<Collider>(shared_from_this()), std::placeholders::_1, std::placeholders::_2, std::placeholders::_3 ) ); _componentAddedSlot = target->componentAdded().connect( [this](Node::Ptr node, Node::Ptr target, AbstractComponent::Ptr component) { auto physicsWorld = std::dynamic_pointer_cast<bullet::PhysicsWorld>(component); if (physicsWorld) initializeFromNode(this->target()); } ); addedHandler(target, target, target->parent()); } void bullet::Collider::targetRemoved(Node::Ptr target) { if (_physicsWorld != nullptr) _physicsWorld->removeCollider(std::static_pointer_cast<Collider>(shared_from_this())); _frameBeginSlot = nullptr; _physicsWorld = nullptr; _graphicsTransform = nullptr; _addedSlot = nullptr; _removedSlot = nullptr; } void bullet::Collider::addedHandler(Node::Ptr target, Node::Ptr child, Node::Ptr ancestor) { if (target->root()->hasComponent<SceneManager>()) { auto sceneManager = target->root()->component<SceneManager>(); _frameBeginSlot = sceneManager->frameBegin()->connect([=](std::shared_ptr<SceneManager>, float, float) { if (!_physicsWorld) initializeFromNode(target); if (_physicsWorld) _frameBeginSlot = nullptr; assert(_graphicsTransform); }); } } void bullet::Collider::removedHandler(Node::Ptr target, Node::Ptr child, Node::Ptr ancestor) { if (target->root()->hasComponent<SceneManager>()) return; if (_physicsWorld != nullptr) _physicsWorld->removeCollider(std::static_pointer_cast<Collider>(shared_from_this())); _frameBeginSlot = nullptr; _physicsWorld = nullptr; _graphicsTransform = nullptr; } void bullet::Collider::initializeFromNode(Node::Ptr node) { if (_graphicsTransform != nullptr && _physicsWorld != nullptr) return; // This matrix is automatically updated by physicsWorldTransformChangedHandler _physicsTransform = math::mat4(); // Get existing transform component or create one if necessary if (!node->hasComponent<Transform>()) node->addComponent(Transform::create()); _graphicsTransform = node->component<Transform>(); if (!_graphicsTransform) { LOG_ERROR("The node has no Transform."); throw std::logic_error("The node has no Transform."); } // The target has just been added to another node, we need to update the modelToWorldMatrix auto modelToWorldMatrix = _graphicsTransform->modelToWorldMatrix(true); // Identify physics world auto withPhysicsWorld = NodeSet::create(node) ->ancestors(true) ->where([](Node::Ptr n){ return n->hasComponent<bullet::PhysicsWorld>(); }); if (withPhysicsWorld->nodes().size() > 1) { LOG_ERROR("Scene cannot contain more than one PhysicsWorld component."); throw std::logic_error("Scene cannot contain more than one PhysicsWorld component."); } _physicsWorld = withPhysicsWorld->nodes().empty() ? nullptr : withPhysicsWorld->nodes().front()->component<bullet::PhysicsWorld>(); if (_physicsWorld) _physicsWorld->addCollider(std::static_pointer_cast<Collider>(shared_from_this())); synchronizePhysicsWithGraphics(); } void bullet::Collider::synchronizePhysicsWithGraphics(bool forceTransformUpdate) { if (_graphicsTransform == nullptr) { initializeFromNode(target()); return; } auto graphicsTransform = _graphicsTransform->modelToWorldMatrix(forceTransformUpdate); static auto graphicsNoScale = math::mat4(); static auto graphicsNoScaleInverse = math::mat4(); static auto centerOfMassOffset = math::mat4(); static auto physicsTransform = math::mat4(); // Remove the scale from the graphics transform, but record it to restitute it during rendering graphicsNoScale = math::removeScalingShear(graphicsTransform, _correction); graphicsNoScaleInverse = math::inverse(graphicsNoScale); centerOfMassOffset = graphicsNoScale * (_colliderData->shape()->deltaTransformInverse() * graphicsNoScaleInverse); physicsTransform = _colliderData->shape()->deltaTransform() * graphicsNoScale; setPhysicsTransform(physicsTransform, &_graphicsTransform->matrix()); if (_physicsWorld) { _physicsWorld->updateRigidBodyState( std::static_pointer_cast<Collider>(shared_from_this()), graphicsNoScale, centerOfMassOffset ); } } bullet::Collider::Ptr bullet::Collider::setPhysicsTransform(const math::mat4& physicsTransform, const math::mat4* graphicsModelToParent, bool forceTransformUpdate) { assert(_graphicsTransform); // Update the physics world transform _physicsTransform = physicsTransform; if (graphicsModelToParent) { _graphicsTransform->matrix(*graphicsModelToParent); } else { // Recompute graphics transform from the physics transform // Update the graphics local transform static auto worldToParent = math::mat4(); worldToParent = _graphicsTransform->matrix() * math::inverse(_graphicsTransform->modelToWorldMatrix(forceTransformUpdate)); _graphicsTransform->matrix(worldToParent * (_physicsTransform * (_colliderData->shape()->deltaTransformInverse() * _correction))); } // Fire update signals _physicsTransformChanged->execute(std::static_pointer_cast<Collider>(shared_from_this()), _physicsTransform); _graphicsTransformChanged->execute(std::static_pointer_cast<Collider>(shared_from_this()), _graphicsTransform); return std::static_pointer_cast<Collider>(shared_from_this()); } math::mat4 bullet::Collider::getPhysicsTransform() const { return _physicsTransform; } math::vec3 bullet::Collider::linearVelocity() const { return _physicsWorld ? _physicsWorld->getColliderLinearVelocity( std::static_pointer_cast<const Collider>(shared_from_this()) ) : math::vec3(); } bullet::Collider::Ptr bullet::Collider::linearVelocity(const math::vec3& value) { if (_physicsWorld) _physicsWorld->setColliderLinearVelocity( std::static_pointer_cast<Collider>(shared_from_this()), value ); return std::static_pointer_cast<Collider>(shared_from_this()); } math::vec3 bullet::Collider::angularVelocity(const math::vec3& output) const { return _physicsWorld ? _physicsWorld->getColliderAngularVelocity( std::static_pointer_cast<const Collider>(shared_from_this()) ) : math::vec3(); } bullet::Collider::Ptr bullet::Collider::angularVelocity(const math::vec3& value) { if (_physicsWorld) _physicsWorld->setColliderAngularVelocity( std::static_pointer_cast<Collider>(shared_from_this()), value ); return std::static_pointer_cast<Collider>(shared_from_this()); } math::vec3 bullet::Collider::gravity() const { return _physicsWorld ? _physicsWorld->getColliderGravity( std::static_pointer_cast<const Collider>(shared_from_this()) ) : math::vec3(); } bullet::Collider::Ptr bullet::Collider::gravity(const math::vec3& value) { if (_physicsWorld) _physicsWorld->setColliderGravity( std::static_pointer_cast<Collider>(shared_from_this()), value ); return std::static_pointer_cast<Collider>(shared_from_this()); } bool bullet::Collider::raycast(const math::vec3& direction, float maxDist, float* distance) { if (_physicsWorld) { math::vec3 hit; auto pos = math::vec3(_graphicsTransform->modelToWorldMatrix()[3]); if (_physicsWorld->raycast(pos, direction, maxDist, hit)) { distance[0] = math::distance(pos, hit); return true; } } return false; } bullet::Collider::Ptr bullet::Collider::applyImpulse(const math::vec3& impulse, const math::vec3& relPosition) { _physicsWorld->applyImpulse( std::static_pointer_cast<Collider>(shared_from_this()), impulse, false, relPosition ); return std::static_pointer_cast<Collider>(shared_from_this()); } bullet::Collider::Ptr bullet::Collider::applyRelativeImpulse(const math::vec3& impulse, const math::vec3& relPosition) { _physicsWorld->applyImpulse( std::static_pointer_cast<Collider>(shared_from_this()), impulse, true, math::vec3() ); return std::static_pointer_cast<Collider>(shared_from_this()); } bullet::Collider::Ptr bullet::Collider::linearFactor(const math::vec3& values) { const bool changed = fabsf(values.x - _linearFactor.x) > 1e-3f || fabsf(values.y - _linearFactor.y) > 1e-3f || fabsf(values.z - _linearFactor.z) > 1e-3f; _linearFactor = values; if (changed) _propertiesChanged->execute(std::static_pointer_cast<Collider>(shared_from_this())); return std::static_pointer_cast<Collider>(shared_from_this()); } bullet::Collider::Ptr bullet::Collider::angularFactor(const math::vec3& values) { const bool changed = fabsf(values.x - _angularFactor.x) > 1e-3f || fabsf(values.y - _angularFactor.y) > 1e-3f || fabsf(values.z - _angularFactor.z) > 1e-3f; _angularFactor = values; if (changed) _propertiesChanged->execute(std::static_pointer_cast<Collider>(shared_from_this())); return std::static_pointer_cast<Collider>(shared_from_this()); } bullet::Collider::Ptr bullet::Collider::damping(float linearDamping, float angularDamping) { const bool changed = fabsf(_linearDamping - linearDamping) > 1e-3f || fabsf(_angularDamping - angularDamping) > 1e-3f; _linearDamping = linearDamping; _angularDamping = angularDamping; if (changed) _propertiesChanged->execute(std::static_pointer_cast<Collider>(shared_from_this())); return std::static_pointer_cast<Collider>(shared_from_this()); } bullet::Collider::Ptr bullet::Collider::sleepingThresholds(float linearSleepingThreshold, float angularSleepingThreshold) { const bool changed = fabsf(_linearSleepingThreshold - linearSleepingThreshold) > 1e-3f || fabsf(_angularSleepingThreshold - angularSleepingThreshold) > 1e-3f; _linearSleepingThreshold = linearSleepingThreshold; _angularSleepingThreshold = angularSleepingThreshold; if (changed) _propertiesChanged->execute(std::static_pointer_cast<Collider>(shared_from_this())); return std::static_pointer_cast<Collider>(shared_from_this()); } bullet::Collider::Ptr bullet::Collider::canSleep(bool value) { const bool changed = _canSleep != value; _canSleep = value; if (changed) _propertiesChanged->execute(std::static_pointer_cast<Collider>(shared_from_this())); return std::static_pointer_cast<Collider>(shared_from_this()); }
31.10515
138
0.69831
aerys
20cf32562eeecc13a8d1119c0a73783689932f30
897
hpp
C++
Sort/Bubblesort.hpp
A200K/Sort
fdeff6fd237dd1fe0e9259606ff2f7e23d7a075d
[ "MIT" ]
null
null
null
Sort/Bubblesort.hpp
A200K/Sort
fdeff6fd237dd1fe0e9259606ff2f7e23d7a075d
[ "MIT" ]
null
null
null
Sort/Bubblesort.hpp
A200K/Sort
fdeff6fd237dd1fe0e9259606ff2f7e23d7a075d
[ "MIT" ]
1
2021-08-09T03:46:17.000Z
2021-08-09T03:46:17.000Z
#ifndef BUBBLESORT_H #define BUBBLESORT_H #include "Sort.hpp" /* Bubblesort Best-Case Perf: O( n² ) ( n for optimized version ) Average Perf: O( n² ) Worst-Case Perf: O( n² ) Worst-Case Space: O( n ) */ template<typename T> class Bubblesort : public SortBase<T> { public: Bubblesort( ) {} virtual wchar_t *GetName( ) { return L"Bubblesort"; } private: virtual void DoSortAscending( T *pArray, int pLeft, int pRight ) { for ( int i = ( pRight - pLeft + 1 ); i > 1; i-- ) { for ( int j = 0; j < ( i - 1 ); j++ ) { if ( pArray[j] > pArray[j + 1] ) this->Swap( pArray, j, j + 1 ); } } } virtual void DoSortDescending( T *pArray, int pLeft, int pRight ) { for ( int i = ( pRight - pLeft + 1 ); i > 1; i-- ) { for ( int j = 0; j < ( i - 1 ); j++ ) { if ( pArray[j] < pArray[j + 1] ) this->Swap( pArray, j, j + 1 ); } } } }; #endif
16.309091
66
0.54738
A200K
20d55a131d8af3ca6fb8f8d68a3cbeb1cdd44703
1,770
cpp
C++
compiler/circle2circle/src/Model.cpp
toomuchsalt/ONE-1
92898a1e9e738b9fc70933e64d1000df73c6b31b
[ "Apache-2.0" ]
1
2020-05-22T13:53:40.000Z
2020-05-22T13:53:40.000Z
compiler/circle2circle/src/Model.cpp
toomuchsalt/ONE-1
92898a1e9e738b9fc70933e64d1000df73c6b31b
[ "Apache-2.0" ]
null
null
null
compiler/circle2circle/src/Model.cpp
toomuchsalt/ONE-1
92898a1e9e738b9fc70933e64d1000df73c6b31b
[ "Apache-2.0" ]
1
2021-07-22T11:02:43.000Z
2021-07-22T11:02:43.000Z
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "Model.h" #include <fstream> #include <vector> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> namespace { class FileModel final : public luci::Model { public: explicit FileModel(const std::string &filename) : _filename(filename) {} public: FileModel(const FileModel &) = delete; FileModel(FileModel &&) = delete; public: const ::circle::Model *model(void) override { std::ifstream file(_filename, std::ios::binary | std::ios::in); if (!file.good()) return nullptr; file.unsetf(std::ios::skipws); std::streampos fileSize; file.seekg(0, std::ios::end); fileSize = file.tellg(); file.seekg(0, std::ios::beg); // reserve capacity _data.reserve(fileSize); // read the data file.read(_data.data(), fileSize); if (file.fail()) return nullptr; return ::circle::GetModel(_data.data()); } private: const std::string _filename; std::vector<char> _data; }; } // namespace namespace luci { std::unique_ptr<Model> load_model(const std::string &path) { return std::unique_ptr<Model>{new FileModel(path)}; } } // namespace luci
22.405063
75
0.684181
toomuchsalt
20d7019578cace5a3b218b09ebd07d87a37fdf79
4,706
hpp
C++
ql/instruments/compositeinstrument.hpp
markxio/Quantuccia
ebe71a1b9c2a9ee7fc4ea918a9602f100316869d
[ "BSD-3-Clause" ]
29
2017-03-20T14:17:39.000Z
2021-12-22T08:00:52.000Z
ql/instruments/compositeinstrument.hpp
markxio/Quantuccia
ebe71a1b9c2a9ee7fc4ea918a9602f100316869d
[ "BSD-3-Clause" ]
10
2017-04-02T14:34:07.000Z
2021-01-13T05:31:12.000Z
ql/instruments/compositeinstrument.hpp
markxio/Quantuccia
ebe71a1b9c2a9ee7fc4ea918a9602f100316869d
[ "BSD-3-Clause" ]
22
2017-03-19T05:56:19.000Z
2022-03-16T13:30:20.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006 StatPro Italia srl This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ /*! \file compositeinstrument.hpp \brief Composite instrument class */ #ifndef quantlib_composite_instrument_hpp #define quantlib_composite_instrument_hpp #include <ql/instrument.hpp> #include <list> #include <utility> namespace QuantLib { //! %Composite instrument /*! This instrument is an aggregate of other instruments. Its NPV is the sum of the NPVs of its components, each possibly multiplied by a given factor. <b>Example: </b> \link Replication.cpp static replication of a down-and-out barrier option \endlink \warning Methods that drive the calculation directly (such as recalculate(), freeze() and others) might not work correctly. \ingroup instruments */ class CompositeInstrument : public Instrument { typedef std::pair<boost::shared_ptr<Instrument>, Real> component; typedef std::list<component>::iterator iterator; typedef std::list<component>::const_iterator const_iterator; public: //! adds an instrument to the composite void add(const boost::shared_ptr<Instrument>& instrument, Real multiplier = 1.0); //! shorts an instrument from the composite void subtract(const boost::shared_ptr<Instrument>& instrument, Real multiplier = 1.0); //! \name Instrument interface //@{ bool isExpired() const; protected: void performCalculations() const; //@} private: std::list<component> components_; }; } /* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2006 StatPro Italia srl This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ namespace QuantLib { inline void CompositeInstrument::add( const boost::shared_ptr<Instrument>& instrument, Real multiplier) { components_.push_back(std::make_pair(instrument,multiplier)); registerWith(instrument); update(); // When we ask for the NPV of an expired composite, the // components are not recalculated and thus wouldn't forward // later notifications according to the default behavior of // LazyObject instances. This means that even if the // evaluation date changes so that the composite is no longer // expired, the instrument wouldn't be notified and thus it // wouldn't recalculate. To avoid this, we override the // default behavior of the components. instrument->alwaysForwardNotifications(); } inline void CompositeInstrument::subtract( const boost::shared_ptr<Instrument>& instrument, Real multiplier) { add(instrument, -multiplier); } inline bool CompositeInstrument::isExpired() const { for (const_iterator i=components_.begin(); i!=components_.end(); ++i) { if (!i->first->isExpired()) return false; } return true; } inline void CompositeInstrument::performCalculations() const { NPV_ = 0.0; for (const_iterator i=components_.begin(); i!=components_.end(); ++i) { NPV_ += i->second * i->first->NPV(); } } } #endif
35.383459
79
0.675733
markxio
20d903c9579e738676a1fdb2d947c11586544ad4
280
hpp
C++
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/zzz/position/construct_decl.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/zzz/position/construct_decl.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
RubetekIOS-CPP.framework/Versions/A/Headers/libnet/msw/zzz/position/construct_decl.hpp
yklishevich/RubetekIOS-CPP-releases
7dfbbb45b8de7dbb6fa995ff5dcbca4ec06c2bdb
[ "MIT" ]
null
null
null
#pragma once #include <msw/on_debug.hpp> #include <msw/zzz/position/fwd.hpp> namespace msw { namespace zzz { template <typename Pointer MSW_ON_DEBUG(, typename Validator)> position<typename Pointer::value_type> construct_position(Pointer MSW_ON_DEBUG(, Validator&&)); }}
21.538462
162
0.760714
yklishevich
20dabef488b5fe2e92c48f3a1ea3c48dafaaa30f
2,711
hpp
C++
persist/tests/include/persist/test/mocks/log_manager.hpp
ketgo/persist
623a5c32a9a0fd3e43987421aa1f91ab8284d356
[ "MIT" ]
null
null
null
persist/tests/include/persist/test/mocks/log_manager.hpp
ketgo/persist
623a5c32a9a0fd3e43987421aa1f91ab8284d356
[ "MIT" ]
11
2020-09-30T07:33:10.000Z
2021-05-01T05:59:13.000Z
persist/tests/include/persist/test/mocks/log_manager.hpp
ketgo/persist
623a5c32a9a0fd3e43987421aa1f91ab8284d356
[ "MIT" ]
null
null
null
/** * log_manager.hpp - Persist * * Copyright 2021 Ketan Goyal * * 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 PERSIST_TEST_MOCKS_LOG_MANAGER_HPP #define PERSIST_TEST_MOCKS_LOG_MANAGER_HPP #include <gmock/gmock.h> #include <persist/core/log/log_manager.hpp> using ::testing::_; using ::testing::Invoke; namespace persist { namespace test { /** * @brief Fake Log Manager * */ class FakeLogManager : public LogManager { public: FakeLogManager() : LogManager(nullptr) {} void Start() {} void Stop() {} LogRecord::Location Add(LogRecord &) { return LogRecord::Location(1, 1); } std::unique_ptr<LogRecord> Get(LogRecord::Location) { return std::make_unique<LogRecord>(); } void Flush() {} }; /** * @brief Mock Log Manager * */ class MockLogManager : public LogManager { public: MockLogManager() : LogManager(nullptr) {} MOCK_METHOD(void, Start, (), ()); MOCK_METHOD(void, Stop, (), ()); MOCK_METHOD(LogRecord::Location, Add, (LogRecord &), ()); MOCK_METHOD(std::unique_ptr<LogRecord>, Get, (LogRecord::Location), ()); MOCK_METHOD(void, Flush, (), ()); void UseFake() { ON_CALL(*this, Start()) .WillByDefault(Invoke(&fake, &FakeLogManager::Start)); ON_CALL(*this, Stop()).WillByDefault(Invoke(&fake, &FakeLogManager::Stop)); ON_CALL(*this, Add(_)).WillByDefault(Invoke(&fake, &FakeLogManager::Add)); ON_CALL(*this, Get(_)).WillByDefault(Invoke(&fake, &FakeLogManager::Get)); ON_CALL(*this, Flush()) .WillByDefault(Invoke(&fake, &FakeLogManager::Flush)); } private: FakeLogManager fake; }; } // namespace test } // namespace persist #endif /* PERSIST_TEST_MOCKS_LOG_MANAGER_HPP */
29.791209
80
0.71339
ketgo
20db4e544ba86a2357d0732e1d253be224c9c83d
8,934
hpp
C++
compilation-benchmarks/fmt_compile_args_shuffle.hpp
robhz786/strf-benchmarks
e783700317ef1fea0d9e7217c8c42884c3c0371e
[ "BSL-1.0" ]
1
2021-07-19T11:07:24.000Z
2021-07-19T11:07:24.000Z
compilation-benchmarks/fmt_compile_args_shuffle.hpp
robhz786/strf-benchmarks
e783700317ef1fea0d9e7217c8c42884c3c0371e
[ "BSL-1.0" ]
null
null
null
compilation-benchmarks/fmt_compile_args_shuffle.hpp
robhz786/strf-benchmarks
e783700317ef1fea0d9e7217c8c42884c3c0371e
[ "BSL-1.0" ]
null
null
null
#ifndef FMT_COMPILE_ARGS_SHUFFLE_HPP #define FMT_COMPILE_ARGS_SHUFFLE_HPP // Distributed under the Boost Software License, Version 1.0. // ( See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt ) #ifndef SRC_ID #define SRC_ID 0 #endif #if (SRC_ID % 19) == 0 # define I0 0 # define I1 1 # define I2 2 # define I3 3 # define I4 4 # define I5 5 # define I6 6 # define I7 7 # define I8 8 # define I9 9 # define I10 10 # define I11 11 # define I12 12 # define I13 13 # define I14 14 # define I15 15 # define I16 16 # define I17 17 # define I18 18 # define I19 19 # define I20 0 #elif (SRC_ID % 19) == 1 # define I0 1 # define I1 2 # define I2 3 # define I3 4 # define I4 5 # define I5 6 # define I6 7 # define I7 8 # define I8 9 # define I9 10 # define I10 11 # define I11 12 # define I12 13 # define I13 14 # define I14 15 # define I15 16 # define I16 17 # define I17 18 # define I18 19 # define I19 0 # define I20 1 #elif (SRC_ID % 19) == 2 # define I0 2 # define I1 3 # define I2 4 # define I3 5 # define I4 6 # define I5 7 # define I6 8 # define I7 9 # define I8 10 # define I9 11 # define I10 12 # define I11 13 # define I12 14 # define I13 15 # define I14 16 # define I15 17 # define I16 18 # define I17 19 # define I18 0 # define I19 1 # define I20 2 #elif (SRC_ID % 19) == 3 # define I0 3 # define I1 4 # define I2 5 # define I3 6 # define I4 7 # define I5 8 # define I6 9 # define I7 10 # define I8 11 # define I9 12 # define I10 13 # define I11 14 # define I12 15 # define I13 16 # define I14 17 # define I15 18 # define I16 19 # define I17 1 # define I18 2 # define I19 3 # define I20 4 #elif (SRC_ID % 19) == 4 # define I0 4 # define I1 5 # define I2 6 # define I3 7 # define I4 8 # define I5 9 # define I6 10 # define I7 11 # define I8 12 # define I9 13 # define I10 14 # define I11 15 # define I12 16 # define I13 17 # define I14 18 # define I15 19 # define I16 1 # define I17 2 # define I18 3 # define I19 4 # define I20 5 #elif (SRC_ID % 19) == 5 # define I0 5 # define I1 6 # define I2 7 # define I3 8 # define I4 9 # define I5 10 # define I6 11 # define I7 12 # define I8 13 # define I9 14 # define I10 15 # define I11 16 # define I12 17 # define I13 18 # define I14 19 # define I15 1 # define I16 2 # define I17 3 # define I18 4 # define I19 5 # define I20 6 #elif (SRC_ID % 19) == 6 # define I0 6 # define I1 7 # define I2 8 # define I3 9 # define I4 10 # define I5 11 # define I6 12 # define I7 13 # define I8 14 # define I9 15 # define I10 16 # define I11 17 # define I12 18 # define I13 19 # define I14 1 # define I15 2 # define I16 3 # define I17 4 # define I18 5 # define I19 6 # define I20 7 #elif (SRC_ID % 19) == 7 # define I0 7 # define I1 8 # define I2 9 # define I3 10 # define I4 11 # define I5 12 # define I6 13 # define I7 14 # define I8 15 # define I9 16 # define I10 17 # define I11 18 # define I12 19 # define I13 1 # define I14 2 # define I15 3 # define I16 4 # define I17 5 # define I18 6 # define I19 7 # define I20 8 #elif (SRC_ID % 19) == 8 # define I0 8 # define I1 9 # define I2 10 # define I3 11 # define I4 12 # define I5 13 # define I6 14 # define I7 15 # define I8 16 # define I9 17 # define I10 18 # define I11 19 # define I12 1 # define I13 2 # define I14 3 # define I15 4 # define I16 5 # define I17 6 # define I18 7 # define I19 8 # define I20 9 #elif (SRC_ID % 19) == 9 # define I0 9 # define I1 10 # define I2 11 # define I3 12 # define I4 13 # define I5 14 # define I6 15 # define I7 16 # define I8 17 # define I9 18 # define I10 19 # define I11 1 # define I12 2 # define I13 3 # define I14 4 # define I15 5 # define I16 6 # define I17 7 # define I18 8 # define I19 9 # define I20 10 #elif (SRC_ID % 19) == 10 # define I0 10 # define I1 11 # define I2 12 # define I3 13 # define I4 14 # define I5 15 # define I6 16 # define I7 17 # define I8 18 # define I9 19 # define I10 1 # define I11 2 # define I12 3 # define I13 4 # define I14 5 # define I15 6 # define I16 7 # define I17 8 # define I18 9 # define I19 10 # define I20 11 #elif (SRC_ID % 19) == 11 # define I0 11 # define I1 12 # define I2 13 # define I3 14 # define I4 15 # define I5 16 # define I6 17 # define I7 18 # define I8 19 # define I9 1 # define I10 2 # define I11 3 # define I12 4 # define I13 5 # define I14 6 # define I15 7 # define I16 8 # define I17 9 # define I18 10 # define I19 11 # define I20 12 #elif (SRC_ID % 19) == 12 # define I0 12 # define I1 13 # define I2 14 # define I3 15 # define I4 16 # define I5 17 # define I6 18 # define I7 19 # define I8 1 # define I9 2 # define I10 3 # define I11 4 # define I12 5 # define I13 6 # define I14 7 # define I15 8 # define I16 9 # define I17 10 # define I18 11 # define I19 12 # define I20 13 #elif (SRC_ID % 19) == 13 # define I0 13 # define I1 14 # define I2 15 # define I3 16 # define I4 17 # define I5 18 # define I6 19 # define I7 1 # define I8 2 # define I9 3 # define I10 4 # define I11 5 # define I12 6 # define I13 7 # define I14 8 # define I15 9 # define I16 10 # define I17 11 # define I18 12 # define I19 13 # define I20 14 #elif (SRC_ID % 19) == 14 # define I0 14 # define I1 15 # define I2 16 # define I3 17 # define I4 18 # define I5 19 # define I6 1 # define I7 2 # define I8 3 # define I9 4 # define I10 5 # define I11 6 # define I12 7 # define I13 8 # define I14 9 # define I15 10 # define I16 11 # define I17 12 # define I18 13 # define I19 14 # define I20 15 #elif (SRC_ID % 19) == 15 # define I0 15 # define I1 16 # define I2 17 # define I3 18 # define I4 19 # define I5 1 # define I6 2 # define I7 3 # define I8 4 # define I9 5 # define I10 6 # define I11 7 # define I12 8 # define I13 9 # define I14 10 # define I15 11 # define I16 12 # define I17 13 # define I18 14 # define I19 15 # define I20 16 #elif (SRC_ID % 19) == 16 # define I0 16 # define I1 17 # define I2 18 # define I3 19 # define I4 1 # define I5 2 # define I6 3 # define I7 4 # define I8 5 # define I9 6 # define I10 7 # define I11 8 # define I12 9 # define I13 10 # define I14 11 # define I15 12 # define I16 13 # define I17 14 # define I18 15 # define I19 16 # define I20 17 #elif (SRC_ID % 19) == 17 # define I0 17 # define I1 18 # define I2 19 # define I3 1 # define I4 2 # define I5 3 # define I6 4 # define I7 5 # define I8 6 # define I9 7 # define I10 8 # define I11 9 # define I12 10 # define I13 11 # define I14 12 # define I15 13 # define I16 14 # define I17 15 # define I18 16 # define I19 17 # define I20 18 #elif (SRC_ID % 19) == 18 # define I0 18 # define I1 19 # define I2 1 # define I3 2 # define I4 3 # define I5 4 # define I6 5 # define I7 6 # define I8 7 # define I9 8 # define I10 9 # define I11 10 # define I12 11 # define I13 12 # define I14 13 # define I15 14 # define I16 15 # define I17 16 # define I18 17 # define I19 18 # define I20 19 #endif #define FMT_I_0 "{}" #define FMT_I_1 "{}" #define FMT_I_2 "{}" #define FMT_I_3 "{}" #define FMT_I_4 "{}" #define FMT_I_5 "{}" #define FMT_I_6 "{:e}" #define FMT_I_7 "{:f}" #define FMT_I_8 "{:g}" #define FMT_I_9 "{:x}" #define FMT_I_10 "{:>10x}" #define FMT_I_11 "{:<+10}" #define FMT_I_12 "{:x}" #define FMT_I_13 "{:>10x}" #define FMT_I_14 "{:<10}" #define FMT_I_15 "{:#>10e}" #define FMT_I_16 "{:#>10f}" #define FMT_I_17 "{:#>10g}" #define FMT_I_18 "{:>10}" #define FMT_I_19 "{}" #define ARG_I_0 "abc" #define ARG_I_1 ' ' #define ARG_I_2 ((const void*)0) #define ARG_I_3 1234 #define ARG_I_4 1234u #define ARG_I_5 123.4 #define ARG_I_6 123.4 #define ARG_I_7 123.4 #define ARG_I_8 123.4 #define ARG_I_9 1234 #define ARG_I_10 1234 #define ARG_I_11 1234 #define ARG_I_12 1234u #define ARG_I_13 1234u #define ARG_I_14 1234u #define ARG_I_15 123.4 #define ARG_I_16 123.4 #define ARG_I_17 123.4 #define ARG_I_18 "qwert" #define ARG_I_19 true #define ECHO(X) X #define FMT_3(X) ECHO(X) #define FMT_2(N) FMT_3(FMT_I_ ## N) #define FMT(N) FMT_2(N) #define STR(X) #X #define FMT1 "blah " FMT(I0) #define FMT2 "blah " FMT(I1) " " FMT(I2) #define FMT3 "blah " FMT(I3) " " FMT(I4) " " FMT(I5) #define FMT4 "blah " FMT(I6) " " FMT(I7) " " FMT(I8) " " FMT(I9) #define FMT5 "blah " FMT(I10) " " FMT(I11) " " FMT(I12) " " FMT(I13) " " FMT(I14) #define FMT6 "blah " FMT(I15) " " FMT(I16) " " FMT(I17) " " FMT(I18) " " FMT(I19) " " FMT(I20) #define ARG_3(X) ECHO(ARG_I_ ## X) #define ARG_2(N) ARG_3(N) #define ARG(N) ARG_2(I ## N) #endif // FMT_COMPILE_ARGS_SHUFFLE_HPP
17.975855
94
0.615626
robhz786
22191f233e8cc430fb2698a3080493f1e6262ae4
825
hpp
C++
securenn-public/util/utils.hpp
Rosefield/IDASH2019Submission
3db74c1d79f8ed95153d2a3f2293afa1ca277c86
[ "FSFULLR", "FSFUL" ]
null
null
null
securenn-public/util/utils.hpp
Rosefield/IDASH2019Submission
3db74c1d79f8ed95153d2a3f2293afa1ca277c86
[ "FSFULLR", "FSFUL" ]
null
null
null
securenn-public/util/utils.hpp
Rosefield/IDASH2019Submission
3db74c1d79f8ed95153d2a3f2293afa1ca277c86
[ "FSFULLR", "FSFUL" ]
null
null
null
#ifndef HEADER_UTILS_H_ #define HEADER_UTILS_H_ #include <math.h> #include <string> #include <iostream> #include <vector> using namespace std; #define LOG_DEBUG_UTILS 0 double calculateSD(vector<double> data); int printingFunction(); /**************************************************************************/ double calculateSD(vector<double> data) { double sum = 0, mean, standardDeviation = 0; for(int i = 0; i < data.size(); ++i) sum += data[i]; mean = sum/data.size(); for(int i = 0; i < data.size(); ++i) standardDeviation += (data[i] - mean)*(data[i] - mean); return sqrt(standardDeviation / 10); } int printingFunction() { #if LOG_DEBUG_UTILS cout << "Hello" << endl; #endif return 0; } #endif /* HEADER_UTILS_H_ */
17.1875
77
0.551515
Rosefield
221da64a340ad36ff499b885b93f86865a1eb815
2,427
cpp
C++
C++/LeetCode/0707.cpp
Nimesh-Srivastava/DSA
db33aa138f0df8ab6015d2e8ec3ddde1c6838848
[ "MIT" ]
4
2021-08-28T19:16:50.000Z
2022-03-04T19:46:31.000Z
C++/LeetCode/0707.cpp
Nimesh-Srivastava/DSA
db33aa138f0df8ab6015d2e8ec3ddde1c6838848
[ "MIT" ]
8
2021-10-29T19:10:51.000Z
2021-11-03T12:38:00.000Z
C++/LeetCode/0707.cpp
Nimesh-Srivastava/DSA
db33aa138f0df8ab6015d2e8ec3ddde1c6838848
[ "MIT" ]
4
2021-09-06T05:53:07.000Z
2021-12-24T10:31:40.000Z
class MyLinkedList { int data; MyLinkedList* head; MyLinkedList* next; public: MyLinkedList() { head = NULL; next = NULL; } int get(int index) { MyLinkedList* curr = head; int countNodes = 0; while(curr){ if(countNodes == index) return curr -> data; curr = curr -> next; countNodes++; } return -1; } void addAtHead(int val) { MyLinkedList* newNode = new MyLinkedList; newNode -> data = val; newNode -> next = head; head = newNode; } void addAtTail(int val) { MyLinkedList* newNode = new MyLinkedList; newNode -> data = val; if(!head) head = newNode; else{ MyLinkedList* curr = head; while(curr -> next) curr = curr -> next; curr -> next = newNode; } } void addAtIndex(int index, int val) { int siz = 0; MyLinkedList* curr = head; while(curr){ curr = curr -> next; siz++; } if(index > siz) return; if(index == 0){ addAtHead(val); return; } int countNodes = 0; curr = head; while(curr && countNodes < index - 1){ curr = curr -> next; countNodes++; } MyLinkedList* newNode = new MyLinkedList; newNode -> data = val; MyLinkedList* idx = curr -> next; curr -> next = newNode; newNode -> next = idx; } void deleteAtIndex(int index) { int siz = 0; MyLinkedList* curr = head; while(curr){ curr = curr -> next; siz++; } if(index >= siz) return; if(index == 0){ if(head) head = head -> next; return; } int countNodes = 0; curr = head; while(curr && countNodes < index - 1){ curr = curr -> next; countNodes++; } curr -> next = curr -> next -> next; } };
20.394958
49
0.391842
Nimesh-Srivastava
221ddb34aa17ae49fa55de5b008cc99f21f122c4
1,448
cpp
C++
Teste e exercicios/Evento/main.cpp
Lu1zReis/exercicios-cpp
81fabe4080d75ad88e25f4d3cda9fd5df31cbfa0
[ "MIT" ]
null
null
null
Teste e exercicios/Evento/main.cpp
Lu1zReis/exercicios-cpp
81fabe4080d75ad88e25f4d3cda9fd5df31cbfa0
[ "MIT" ]
null
null
null
Teste e exercicios/Evento/main.cpp
Lu1zReis/exercicios-cpp
81fabe4080d75ad88e25f4d3cda9fd5df31cbfa0
[ "MIT" ]
null
null
null
#include <iostream> #include <stdio.h> #include <stdlib.h> using namespace std; int main() { int contaDia, contaHora, contaMinu, contaSeg; int diaInicial, diaFinal, horaIni, horaFin, minuIni, minuFin, segIni, segFin; cout << "Dia "; cin >> diaInicial; scanf("%d : %d : %d", &horaIni, &minuIni, &segIni); cout << "Dia "; cin >> diaFinal; scanf("%d : %d : %d", &horaFin, &minuFin, &segFin); contaDia = diaFinal - diaInicial; contaHora = (24 + horaFin) - horaIni; contaMinu = minuIni + minuFin; contaSeg = segIni + segFin; if(contaSeg <= 60){ if(segFin >= segIni){ contaSeg = segFin - segIni; }else{ contaSeg = segIni - segFin; } } if(contaMinu <= 60){ if(minuFin >= minuIni){ contaMinu = minuFin - minuIni; }else{ contaMinu = minuIni - minuFin; } } if(contaHora <= 24){ contaDia -= 1; } while(contaSeg >= 60){ contaSeg = contaSeg - 60; contaMinu += 1; } while(contaMinu >= 60){ contaMinu = contaMinu - 60; contaHora += 1; } while(contaHora >= 24){ contaHora = (contaHora - 24); contaDia += 1; } cout << contaDia << " dia(s)" << endl; cout << contaHora << " hora(s)" << endl; cout << contaMinu << " minuto(s)" << endl; cout << contaSeg << " segundo(s)" << endl; return 0; }
22.984127
81
0.520718
Lu1zReis
222072023de13b41f023ed9144064c5a15113186
323
hpp
C++
include/InputPort.hpp
AhmedHumais/flight_controller_temp
2836b4f99b76e856ef0ba0e7ee673669c1c3db7b
[ "BSD-3-Clause" ]
null
null
null
include/InputPort.hpp
AhmedHumais/flight_controller_temp
2836b4f99b76e856ef0ba0e7ee673669c1c3db7b
[ "BSD-3-Clause" ]
null
null
null
include/InputPort.hpp
AhmedHumais/flight_controller_temp
2836b4f99b76e856ef0ba0e7ee673669c1c3db7b
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "common_srv/Port.hpp" class InputPort : public Port{ private: DataMessage* _data; int _id; Block* _block; public: void receiveMsgData(DataMessage* t_msg); void receiveMsgData(DataMessage* t_msg, int channel_id); InputPort(int t_id, Block* t_block); ~InputPort(); };
19
60
0.687307
AhmedHumais
2222a7916d89493ce7c3eae3b23f08dc7873586f
305
cpp
C++
the one with area of circle(function).cpp
chinmoyee-A/C-Language
a5d985e84c953c8dcc4074dfd3e96d1539cb1d3e
[ "MIT" ]
null
null
null
the one with area of circle(function).cpp
chinmoyee-A/C-Language
a5d985e84c953c8dcc4074dfd3e96d1539cb1d3e
[ "MIT" ]
null
null
null
the one with area of circle(function).cpp
chinmoyee-A/C-Language
a5d985e84c953c8dcc4074dfd3e96d1539cb1d3e
[ "MIT" ]
null
null
null
//area of circle using function #include<stdio.h> #include<math.h> float aoc(float radius) { return 3.14*radius*radius; } int main() { float radius,area; printf("\n Enter the radius:"); scanf("%f",&radius); area=aoc(radius); printf("\n area of the circle is: %f",area); return 0; }
17.941176
46
0.636066
chinmoyee-A
2223710d37301a053d8ac094b3b2e10e1c64df71
3,054
cpp
C++
module_05/ex01/Form.cpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
4
2021-12-14T18:02:53.000Z
2022-03-24T01:12:38.000Z
module_05/ex01/Form.cpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
null
null
null
module_05/ex01/Form.cpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
3
2021-11-01T00:34:50.000Z
2022-01-29T19:57:30.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Form.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: phemsi-a <phemsi-a@student.42sp.org.br> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/12 20:11:18 by phemsi-a #+# #+# */ /* Updated: 2021/10/25 19:52:10 by phemsi-a ### ########.fr */ /* */ /* ************************************************************************** */ #include "Form.hpp" #include "Bureaucrat.hpp" #include <iostream> # define GRAY "\e[0;38;5;8m" # define RESET "\e[0m" Form::Form(void) : _name("standardForm"), _isSigned(false), _gradeToSign(75), _gradeToExecute(75) { std::cout << GRAY << "Form created. " << *this << RESET << std::endl; return ; } Form::Form(std::string name, int gradeToSign, int gradeToexecute) : _name(name), _isSigned(false), _gradeToSign(gradeToSign), _gradeToExecute(gradeToexecute) { this->_checkGrade(); std::cout << GRAY << "Form created. " << *this << RESET << std::endl; return ; } Form::Form(Form const& instance) : _name(instance.getName()), _gradeToSign(instance.getGradeToSign()), _gradeToExecute(instance.getGradeToExecute()) { *this = instance; std::cout << GRAY << "Form copied. " << *this << RESET << std::endl; return ; } Form::~Form(void) { std::cout << GRAY << "Form destroyed. " << *this << RESET << std::endl; return ; } Form &Form::operator=(Form const &right_hand_side) { this->_isSigned = right_hand_side.getIsSigned(); return (*this); } void Form::_checkGrade(void) const { if (this->_gradeToExecute < 1 || this->_gradeToSign < 1) throw Form::GradeTooHighException(); if (this->_gradeToExecute > 150 || this->_gradeToSign > 150) throw Form::GradeTooLowException(); } std::string Form::getName(void) const { return (this->_name); } int Form::getGradeToSign(void) const { return (this->_gradeToSign); } int Form::getGradeToExecute(void) const { return (this->_gradeToExecute); } bool Form::getIsSigned(void) const { return (this->_isSigned); } void Form::beSigned(Bureaucrat const &bureaucrat) { if (bureaucrat.getGrade() > this->getGradeToSign()) throw Form::GradeTooLowException(); else this->_isSigned = true; return ; } std::ostream &operator<<(std::ostream &outputFile, Form const &i) { outputFile << GRAY << i.getName() << " Form. Grade to sign: " << i.getGradeToSign() << ". Grade to execute: " << i.getGradeToExecute() << " Is signed: "; if (i.getIsSigned()) outputFile << "Yes." << RESET << std::endl; else outputFile << "No." << RESET << std::endl; return (outputFile); }
29.365385
158
0.502292
paulahemsi
222a9929c37641ff8146097682c686dadf213a5c
1,227
hpp
C++
plugins/opengl/include/sge/opengl/visual/rgb_triple.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/include/sge/opengl/visual/rgb_triple.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/include/sge/opengl/visual/rgb_triple.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_OPENGL_VISUAL_RGB_TRIPLE_HPP_INCLUDED #define SGE_OPENGL_VISUAL_RGB_TRIPLE_HPP_INCLUDED #include <sge/opengl/visual/rgb_triple_fwd.hpp> #include <fcppt/declare_strong_typedef.hpp> #include <fcppt/strong_typedef.hpp> namespace sge::opengl::visual { class rgb_triple { public: FCPPT_DECLARE_STRONG_TYPEDEF(int, red_bits); FCPPT_DECLARE_STRONG_TYPEDEF(int, green_bits); FCPPT_DECLARE_STRONG_TYPEDEF(int, blue_bits); rgb_triple( sge::opengl::visual::rgb_triple::red_bits, sge::opengl::visual::rgb_triple::green_bits, sge::opengl::visual::rgb_triple::blue_bits); [[nodiscard]] sge::opengl::visual::rgb_triple::red_bits red() const; [[nodiscard]] sge::opengl::visual::rgb_triple::green_bits green() const; [[nodiscard]] sge::opengl::visual::rgb_triple::blue_bits blue() const; private: sge::opengl::visual::rgb_triple::red_bits red_; sge::opengl::visual::rgb_triple::green_bits green_; sge::opengl::visual::rgb_triple::blue_bits blue_; }; } #endif
26.106383
74
0.741646
cpreh
222ccb6e4fbf38fa60ea9c020d3ed284cf63eea2
4,255
hh
C++
neb/inc/com/centreon/engine/macros/grab.hh
joe4568/centreon-broker
daf454371520989573c810be1f6dfca40979a75d
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/engine/macros/grab.hh
joe4568/centreon-broker
daf454371520989573c810be1f6dfca40979a75d
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/engine/macros/grab.hh
joe4568/centreon-broker
daf454371520989573c810be1f6dfca40979a75d
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 1999-2010 Ethan Galstad ** Copyright 2011-2013 Merethis ** ** This file is part of Centreon Engine. ** ** Centreon Engine is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Engine 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 Centreon Engine. If not, see ** <http://www.gnu.org/licenses/>. */ #ifndef CCE_MACROS_GRAB_HH # define CCE_MACROS_GRAB_HH # include <iomanip> # include <sstream> # include <time.h> # include "com/centreon/engine/macros/process.hh" # include "com/centreon/engine/namespace.hh" # include "com/centreon/engine/string.hh" CCE_BEGIN() namespace macros { /** * Extract double. * * @param[in] t Host object. * @param[in] mac Unused. * * @return Newly allocated string with value as a fixed point string. */ template <typename T, double (T::* member), unsigned int precision> char* get_double(T& t, nagios_macros* mac) { (void)mac; std::ostringstream oss; oss << std::fixed << std::setprecision(precision) << t.*member; return (string::dup(oss.str())); } /** * Extract duration. * * @param[in] t Base object. * @param[in] mac Unused. * * @return Duration in a newly allocated string. */ template <typename T> char* get_duration(T& t, nagios_macros* mac) { (void)mac; // Get duration. time_t now(time(NULL)); unsigned long duration(now - t.last_state_change); // Break down duration. unsigned int days(duration / (24 * 60 * 60)); duration %= (24 * 60 * 60); unsigned int hours(duration / (60 * 60)); duration %= (60 * 60); unsigned int minutes(duration / 60); duration %= 60; // Stringify duration. std::ostringstream oss; oss << days << "d " << hours << "h " << minutes << "m " << duration << "s"; return (string::dup(oss.str())); } /** * Extract duration in seconds. * * @param[in] t Base object. * @param[in] mac Unused. * * @return Duration in second in a newly allocated string. */ template <typename T> char* get_duration_sec(T& t, nagios_macros* mac) { (void)mac; // Get duration. time_t now(time(NULL)); unsigned long duration(now - t.last_state_change); return (string::dup(duration)); } /** * Copy macro. * * @param[in] t Unused. * @param[in] mac Macro array. * * @return Copy of the requested macro. */ template <typename T, unsigned int macro_id> char* get_macro_copy(T& t, nagios_macros* mac) { (void)t; return (string::dup(mac->x[macro_id] ? mac->x[macro_id] : "")); } /** * Get string copy of object member. * * @param[in] t Base object. * @param[in] mac Unused. * * @return String copy of object member. */ template <typename T, typename U, U (T::* member)> char* get_member_as_string(T& t, nagios_macros* mac) { (void)mac; return (string::dup(t.*member)); } /** * Recursively process macros. * * @param[in] hst Host object. * @param[in] mac Unused. * * @return Newly allocated string with macros processed. */ template <typename T, char* (T::* member), unsigned int options> char* get_recursive(T& t, nagios_macros* mac) { (void)mac; // Get copy of string with macros processed. char* buffer(NULL); process_macros_r(mac, t.*member, &buffer, options); return (buffer); } /** * Extract state type. * * @param[in] t Base object. * @param[in] mac Unused. * * @return Newly allocated state type as a string. */ template <typename T> char* get_state_type(T& t, nagios_macros* mac) { (void)mac; return (string::dup((t.state_type == HARD_STATE) ? "HARD" : "SOFT")); } } CCE_END() #endif // !CCE_MACROS_GRAB_HH
25.327381
72
0.614806
joe4568
222d5012139ae4566370a3d69bf51b7fc3ffcf15
3,234
tpp
C++
libs/visitor/Visitable.tpp
cesiumsolutions/dynamic_generic_visitor
da8fe928bf77270e1a64beae0051bfadba7ea256
[ "MIT" ]
null
null
null
libs/visitor/Visitable.tpp
cesiumsolutions/dynamic_generic_visitor
da8fe928bf77270e1a64beae0051bfadba7ea256
[ "MIT" ]
null
null
null
libs/visitor/Visitable.tpp
cesiumsolutions/dynamic_generic_visitor
da8fe928bf77270e1a64beae0051bfadba7ea256
[ "MIT" ]
null
null
null
#ifndef Visitable_tpp #define Visitable_tpp // ---------------------------------------------------------------------------- // Visitable // ---------------------------------------------------------------------------- template<typename VisiteeType, typename VisitorType, typename ReturnType, typename... ParameterTypes> Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... )>::Visitable( VisiteeType const & visitee ) : VisitableBase<VisitorType, ReturnType( ParameterTypes... )>() , mVisitee( visitee ) { } // Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... // )>::Visitable template<typename VisiteeType, typename VisitorType, typename ReturnType, typename... ParameterTypes> std::type_info const & Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... )>::typeInfo() const { return typeid( VisiteeType ); } // Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... // )>::typeInfo template<typename VisiteeType, typename VisitorType, typename ReturnType, typename... ParameterTypes> ReturnType Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... )>::accept( VisitorType & visitor, ParameterTypes... parameters ) const { return visitor.visit( mVisitee, std::forward<ParameterTypes>( parameters )... ); } // Visitable<VisiteeType, VisitorType, ReturnType( ParameterTypes... // )>::accept // ---------------------------------------------------------------------------- // Smart pointer initialization free functions // ---------------------------------------------------------------------------- template<typename VisitorType, typename SignatureType, typename VisiteeType> VisitableUPtr<VisitorType, SignatureType> makeUniqueVisitable( VisiteeType const & visitee ) { return VisitableUPtr<VisitorType, SignatureType>( new Visitable<VisiteeType, VisitorType, SignatureType>( visitee ) ); } // makeUniqueVisitable template<typename VisitorType, typename VisiteeType> VisitableUPtr<VisitorType, typename VisitorType::SignatureType> makeUniqueVisitable( VisiteeType const & visitee ) { using SignatureType = typename VisitorType::SignatureType; return VisitableUPtr<VisitorType, SignatureType>( new Visitable<VisiteeType, VisitorType, SignatureType>( visitee ) ); } // makeUniqueVisitable template<typename VisitorType, typename SignatureType, typename VisiteeType> VisitableSPtr<VisitorType, SignatureType> makeSharedVisitable( VisiteeType const & visitee ) { return VisitableSPtr<VisitorType, SignatureType>( new Visitable<VisiteeType, VisitorType, ReturnType>( visitee ) ); } // makeSharedVisitable template<typename VisitorType, typename VisiteeType> VisitableSPtr<VisitorType, typename VisitorType::SignatureType> makeSharedVisitable( VisiteeType const & visitee ) { using SignatureType = typename VisitorType::SignatureType; return VisitableSPtr<VisitorType, SignatureType>( new Visitable<VisiteeType, VisitorType, ReturnType>( visitee ) ); } // makeSharedVisitable #endif // Visitable_tpp
36.75
81
0.656772
cesiumsolutions
223207bdf6e9c464046cb7444d4c04c14cdf6375
7,370
cpp
C++
src/unittest/conversion/test_conversion_bearing.cpp
JonasToth/depth-conversions
5c8338276565d846c07673e83f94f6841006872b
[ "BSD-3-Clause" ]
2
2021-09-30T07:09:49.000Z
2022-03-14T09:14:35.000Z
src/unittest/conversion/test_conversion_bearing.cpp
JonasToth/depth-conversions
5c8338276565d846c07673e83f94f6841006872b
[ "BSD-3-Clause" ]
null
null
null
src/unittest/conversion/test_conversion_bearing.cpp
JonasToth/depth-conversions
5c8338276565d846c07673e83f94f6841006872b
[ "BSD-3-Clause" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "intrinsic.h" #include <doctest/doctest.h> #include <sens_loc/conversion/depth_to_bearing.h> #include <sens_loc/conversion/depth_to_laserscan.h> #include <sens_loc/io/image.h> #include <sens_loc/util/correctness_util.h> using namespace sens_loc; using namespace sens_loc::conversion; using namespace sens_loc::math; using namespace std; using doctest::Approx; TEST_CASE("Acces Prior Pixel") { using conversion::detail::pixel; SUBCASE("horizontal") { pixel<int, direction::horizontal> p; const pixel_coord<int> pp = p({1, 1}); REQUIRE(pp.u() == 0); REQUIRE(pp.v() == 1); } SUBCASE("horizontal") { pixel<int, direction::vertical> p; const pixel_coord<int> pp = p({1, 1}); REQUIRE(pp.u() == 1); REQUIRE(pp.v() == 0); } SUBCASE("diagonal") { pixel<int, direction::diagonal> p; const pixel_coord<int> pp = p({1, 1}); REQUIRE(pp.u() == 0); REQUIRE(pp.v() == 0); } SUBCASE("antidiagonal") { pixel<int, direction::antidiagonal> p; const pixel_coord<int> pp = p({1, 1}); REQUIRE(pp.u() == 0); REQUIRE(pp.v() == 2); } } TEST_CASE("iteration range") { using conversion::detail::pixel_range; cv::Mat img(42, 42, CV_8U); SUBCASE("horizontal") { pixel_range<direction::horizontal> r(img); REQUIRE(r.x_start == 1); REQUIRE(r.x_end == 42); REQUIRE(r.y_start == 0); REQUIRE(r.y_end == 42); } SUBCASE("vertical") { pixel_range<direction::vertical> r(img); REQUIRE(r.x_start == 0); REQUIRE(r.x_end == 42); REQUIRE(r.y_start == 1); REQUIRE(r.y_end == 42); } SUBCASE("diagonal") { pixel_range<direction::diagonal> r(img); REQUIRE(r.x_start == 1); REQUIRE(r.x_end == 42); REQUIRE(r.y_start == 1); REQUIRE(r.y_end == 42); } SUBCASE("antidiagonal") { pixel_range<direction::antidiagonal> r(img); REQUIRE(r.x_start == 1); REQUIRE(r.x_end == 42); REQUIRE(r.y_start == 0); REQUIRE(r.y_end == 41); } } TEST_CASE("Convert depth image to vertical bearing angle image") { auto depth_image = io::load_image<ushort>("conversion/data0-depth.png", cv::IMREAD_UNCHANGED); REQUIRE(depth_image); auto laser_double = depth_to_laserscan<double, ushort>(*depth_image, p_double); auto ref_vert = io::load_image<uchar>("conversion/bearing-vertical.png", cv::IMREAD_UNCHANGED); REQUIRE(ref_vert); auto vertical_bearing = depth_to_bearing<direction::vertical>(laser_double, p_double); auto converted = convert_bearing<double, uchar>(vertical_bearing); cv::imwrite("conversion/test_vertical.png", converted.data()); REQUIRE(util::average_pixel_error(converted, *ref_vert) < 0.5); } TEST_CASE("Convert depth image to vertical bearing angle image in parallel") { auto depth_image = io::load_image<ushort>("conversion/data0-depth.png", cv::IMREAD_UNCHANGED); REQUIRE(depth_image); auto laser = depth_to_laserscan<double, ushort>(*depth_image, p_double); auto ref_vert = io::load_image<uchar>("conversion/bearing-vertical.png", cv::IMREAD_UNCHANGED); REQUIRE(ref_vert); cv::Mat out(laser.h(), laser.w(), laser.data().type()); out = 0.; math::image<double> out_img(std::move(out)); { tf::Taskflow flow; par_depth_to_bearing<direction::vertical>(laser, p_double, out_img, flow); tf::Executor().run(flow).wait(); } auto converted = convert_bearing<double, uchar>(out_img); cv::imwrite("conversion/test_vertical_parallel.png", converted.data()); REQUIRE(util::average_pixel_error(converted, *ref_vert) < 0.5); } TEST_CASE("Convert depth image to diagonal bearing angle image") { auto depth_image = io::load_image<ushort>("conversion/data0-depth.png", cv::IMREAD_UNCHANGED); REQUIRE(depth_image); auto laser_double = depth_to_laserscan<double, ushort>(*depth_image, p_double); auto ref_diag = io::load_image<ushort>("conversion/bearing-diagonal.png", cv::IMREAD_UNCHANGED); REQUIRE(ref_diag); auto diagonal_bearing = depth_to_bearing<direction::diagonal>(laser_double, p_double); auto converted = convert_bearing<double, ushort>(diagonal_bearing); cv::imwrite("conversion/test_diagonal.png", converted.data()); REQUIRE(util::average_pixel_error(converted, *ref_diag) < 1.0); } TEST_CASE("Convert depth image to antidiagonal bearing angle image") { auto depth_image = io::load_image<ushort>("conversion/data0-depth.png", cv::IMREAD_UNCHANGED); REQUIRE(depth_image); auto laser_float = depth_to_laserscan<float, ushort>(*depth_image, p_float); auto ref_anti = io::load_image<uchar>("conversion/bearing-antidiagonal.png", cv::IMREAD_UNCHANGED); REQUIRE(ref_anti); auto antidiagonal_bearing = depth_to_bearing<direction::antidiagonal>(laser_float, p_float); auto converted_bearing = convert_bearing<float, uchar>(antidiagonal_bearing); cv::imwrite("conversion/test_antidiagonal.png", converted_bearing.data()); REQUIRE(util::average_pixel_error(converted_bearing, *ref_anti) < 0.5); } TEST_CASE("Convert depth image to horizontal bearing angle image") { auto depth_image = io::load_image<ushort>("conversion/data0-depth.png", cv::IMREAD_UNCHANGED); REQUIRE(depth_image); auto laser_float = depth_to_laserscan<float, ushort>(*depth_image, p_float); auto ref_hor = io::load_image<ushort>("conversion/bearing-horizontal.png", cv::IMREAD_UNCHANGED); REQUIRE(ref_hor); auto hor_bear = depth_to_bearing<direction::horizontal>(laser_float, p_float); auto converted_flt = convert_bearing(hor_bear); cv::imwrite("conversion/test_horizontal.png", converted_flt.data()); REQUIRE(util::average_pixel_error(converted_flt, *ref_hor) < 1.0); } TEST_CASE("convert laserscan to horizontal bearing angle") { auto depth_image = io::load_image<ushort>("conversion/laserscan-depth.png", cv::IMREAD_UNCHANGED); REQUIRE(depth_image); const auto laser_double = math::convert<double>(*depth_image); const auto bearing = conversion::depth_to_bearing<direction::horizontal>( laser_double, e_double); const auto converted = conversion::convert_bearing<double, ushort>(bearing); cv::imwrite("conversion/test_horizontal_bearing_laserscan.png", converted.data()); auto ref_image = io::load_image<ushort>( "conversion/bearing-horizontal-laserscan-reference.png", cv::IMREAD_UNCHANGED); REQUIRE(ref_image); REQUIRE(util::average_pixel_error(*ref_image, converted) < 0.5); }
37.411168
80
0.622659
JonasToth
223343737aa11b7dbc2651a92bd9588e6b90cd8c
2,331
hpp
C++
contracts/token.proton/include/token.proton/token.proton.hpp
phoenixwade/proton.contracts
0df6396b4bbbc401122366b3d6fd519ac0562f60
[ "MIT" ]
5
2020-08-24T22:25:34.000Z
2022-03-21T09:18:11.000Z
contracts/token.proton/include/token.proton/token.proton.hpp
phoenixwade/proton.contracts
0df6396b4bbbc401122366b3d6fd519ac0562f60
[ "MIT" ]
null
null
null
contracts/token.proton/include/token.proton/token.proton.hpp
phoenixwade/proton.contracts
0df6396b4bbbc401122366b3d6fd519ac0562f60
[ "MIT" ]
6
2020-04-08T08:59:07.000Z
2022-03-31T13:43:43.000Z
/*##################################*\ # # # Created by CryptoLions.io # # \*##################################*/ #pragma once #include <eosio/eosio.hpp> #include <eosio/asset.hpp> #include <eosio/singleton.hpp> using namespace eosio; using namespace std; namespace eosiosystem { class system_contract; } namespace eosio { class [[eosio::contract("token.proton")]] tokenproton : public contract { public: using contract::contract; [[eosio::action]] void reg(name tcontract, string tname, string url, string desc, string iconurl, symbol symbol); using reg_action = eosio::action_wrapper<"reg"_n, &tokenproton::reg>; //[[eosio::action]] //void reglog(uint64_t id, name tcontract, string tname, string url, string desc, string iconurl, symbol symbol); //using reglog_action = eosio::action_wrapper<"reglog"_n, &tokenproton::reglog>; [[eosio::action]] void update(uint64_t id, name tcontract, string tname, string url, string desc, string iconurl, symbol symbol); using update_action = eosio::action_wrapper<"update"_n, &tokenproton::update>; [[eosio::action]] void remove(uint64_t id); using remove_action = eosio::action_wrapper<"remove"_n, &tokenproton::remove>; [[eosio::action]] void updblacklist(uint64_t id, bool blisted); using updblacklist_action = eosio::action_wrapper<"updblacklist"_n, &tokenproton::updblacklist>; private: uint64_t getid( ); struct [[eosio::table]] token { uint64_t id; name tcontract; string tname; string url; string desc; string iconurl; symbol symbol; bool blisted; auto primary_key() const { return id; } uint64_t by_tcontract() const { return tcontract.value; } }; typedef eosio::multi_index< "tokens"_n, token, eosio::indexed_by< "tcontract"_n, eosio::const_mem_fun<token, uint64_t, &token::by_tcontract> > > tokens; /* * global singelton table, used for id building. Scope: self */ TABLE global { global() {} uint64_t tid = 1000000; uint64_t spare1 = 0; uint64_t spare2 = 0; EOSLIB_SERIALIZE( global, ( tid )( spare1 )( spare2 ) ) }; typedef eosio::singleton< "global"_n, global > conf; /// singleton global _cstate; /// global state }; } /// namespace eosio
23.545455
116
0.644359
phoenixwade
22363ade6423cb884c11664fe6837c3271d02fd1
1,125
cpp
C++
data/dailyCodingProblem282.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem282.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem282.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Given an array of integers, determine whether it contains a Pythagorean triplet. Recall that a Pythogorean triplet (a, b, c) is defined by the equation a2+ b2= c2. */ // O(n^2) time | O(n) space bool containPythagirian(int arr[], int n){ sort(arr, arr+n, greater<int>()); // sort the array in decresing order for(int i=0;i<n;i++){ int req_num = arr[i]*arr[i]; unordered_set<int> uset; for(int j=i+1;j<n;j++){ if(uset.find(arr[j]*arr[j]) != uset.end()) return true; uset.insert(req_num - arr[j]*arr[j]); } } return false; } // O(n^2) time | O(1) space bool containPythagirian2(int arr[], int n){ sort(arr, arr+n, greater<int>()); for(int i=0;i<n;i++){ int l = i+1; int r = n-1; while(l < r){ if(arr[l]*arr[l] + arr[r]*arr[r] == arr[i]*arr[i]) return true; (arr[l]*arr[l] + arr[r]*arr[r] < arr[i]*arr[i])? l++ : r--; } } return false; } // main function int main(){ int arr[] = {3, 4, 7, 6, 5}; int n = sizeof(arr)/sizeof(arr[0]); if(containPythagirian2(arr, n)) cout << "Yes\n"; else cout << "No\n"; return 0; }
21.634615
82
0.588444
vidit1999
223c56ae9cb5048ec2b73452c1c8cf904392b178
1,079
cc
C++
src/scheduler/gradientdescent.cc
ncic-sugon/blitz
ea9a06dc78ef15d772e36d5d47ffac8d3f46034d
[ "BSD-2-Clause" ]
149
2020-07-14T08:59:59.000Z
2021-12-16T03:06:41.000Z
src/scheduler/gradientdescent.cc
ten1123love/blitz
ea9a06dc78ef15d772e36d5d47ffac8d3f46034d
[ "BSD-2-Clause" ]
null
null
null
src/scheduler/gradientdescent.cc
ten1123love/blitz
ea9a06dc78ef15d772e36d5d47ffac8d3f46034d
[ "BSD-2-Clause" ]
130
2020-07-14T09:00:21.000Z
2021-12-16T03:06:42.000Z
#include "scheduler/gradientdescent.h" #include "blitz.h" namespace blitz { template<template <typename> class TensorType, typename DType> void Gradientdescent<TensorType, DType>::OptimizeImpl( const size_t epoch, const size_t batch_size, const DType learning_rate, LayerParamIterator layer_param_it) { #ifdef BLITZ_DEVELOP LOG(INFO) << "Optimize: " << layer_param_it->first; LOG(INFO) << "batch_size: " << batch_size; LOG(INFO) << "epoch: " << epoch; LOG(INFO) << "learning_rate: " << learning_rate; #endif shared_ptr<LayerParam> layer_param = layer_param_it->second; shared_ptr<TensorType<DType> > weight = layer_param->weight(); shared_ptr<TensorType<DType> > gradient = layer_param->update(); shared_ptr<TensorType<DType> > velocity = layer_param->state(); Backend<TensorType, DType>::GradientdescentFunc( weight.get(), gradient.get(), velocity.get(), momentum_coef_, learning_rate, decay_, batch_size); } INSTANTIATE_CLASS_CPU(Gradientdescent); #ifdef BLITZ_USE_GPU INSTANTIATE_CLASS_GPU(Gradientdescent); #endif } // namespace blitz
31.735294
66
0.746061
ncic-sugon
2248749a03d3b75d4a70e7537818433e71f76921
348
hpp
C++
src/builtin/BuiltInFunctionExpressionBuilder.hpp
jprendes/arrow
b966bf298525a8e153d7002fcca56135e6b13bd6
[ "MIT" ]
19
2019-12-10T07:35:08.000Z
2021-09-27T11:49:37.000Z
src/builtin/BuiltInFunctionExpressionBuilder.hpp
jprendes/arrow
b966bf298525a8e153d7002fcca56135e6b13bd6
[ "MIT" ]
22
2020-02-09T15:39:53.000Z
2020-03-02T19:04:40.000Z
src/builtin/BuiltInFunctionExpressionBuilder.hpp
jprendes/arrow
b966bf298525a8e153d7002fcca56135e6b13bd6
[ "MIT" ]
2
2020-02-17T21:20:43.000Z
2020-03-02T00:42:08.000Z
/// (c) Ben Jones 2019 - present #pragma once #include "expressions/Expression.hpp" #include <string> #include <memory> namespace arrow { class BuiltInFunctionExpressionBuilder { public: virtual std::string getName() const = 0; virtual std::shared_ptr<Expression> build(long const lineNumber) const = 0; }; }
20.470588
82
0.66954
jprendes
2249c3d8f7419754409d53e719c7f922d81a6015
2,319
cpp
C++
src/engine_core/wme_base/BResourceFile.cpp
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
3
2021-03-28T00:11:48.000Z
2022-01-12T13:10:52.000Z
src/engine_core/wme_base/BResourceFile.cpp
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
null
null
null
src/engine_core/wme_base/BResourceFile.cpp
segafan/wme1_jankavan_tlc_edition-repo
72163931f348d5a2132577930362d297cc375a26
[ "MIT" ]
null
null
null
// This file is part of Wintermute Engine // For conditions of distribution and use, see copyright notice in license.txt // http://dead-code.org/redir.php?target=wme #include "dcgf.h" #include "BResourceFile.h" ////////////////////////////////////////////////////////////////////////// CBResourceFile::CBResourceFile(CBGame* inGame):CBFile(inGame) { m_Data = NULL; } ////////////////////////////////////////////////////////////////////////// CBResourceFile::~CBResourceFile() { Close(); } ////////////////////////////////////////////////////////////////////////// HRESULT CBResourceFile::Open(char* Filename) { Close(); // try game first if(SUCCEEDED(OpenModule(Filename, Game->m_ResourceModule))) return S_OK; // now search plugins for(int i=0; i<Game->m_PluginMgr->m_Plugins.GetSize(); i++) { CBPlugin* Plugin = Game->m_PluginMgr->m_Plugins[i]; if(SUCCEEDED(OpenModule(Filename, Plugin->m_DllHandle))) return S_OK; } return E_FAIL; } ////////////////////////////////////////////////////////////////////////// HRESULT CBResourceFile::OpenModule(char* Filename, HMODULE Module) { HRSRC res = FindResource(Module, Filename, "GF_RES"); if(res!=NULL) { m_Size = SizeofResource(Module, res); m_Data = LoadResource(Module, res); if(m_Data != NULL) { m_Pos = 0; return S_OK; } } return E_FAIL; } ////////////////////////////////////////////////////////////////////////// HRESULT CBResourceFile::Close() { m_Data = NULL; m_Pos = 0; m_Size = 0; return S_OK; } ////////////////////////////////////////////////////////////////////////// HRESULT CBResourceFile::Read(void *Buffer, DWORD Size) { if(!m_Data || m_Pos + Size > m_Size) return E_FAIL; memcpy(Buffer, (BYTE*)m_Data+m_Pos, Size); m_Pos+=Size; return S_OK; } ////////////////////////////////////////////////////////////////////////// HRESULT CBResourceFile::Seek(DWORD Pos, TSeek Origin) { if(!m_Data) return E_FAIL; DWORD NewPos=0; switch(Origin){ case SEEK_TO_BEGIN: NewPos = Pos; break; case SEEK_TO_END: NewPos = m_Size + Pos; break; case SEEK_TO_CURRENT: NewPos = m_Pos + Pos; break; } if(NewPos<0 || NewPos > m_Size) return E_FAIL; else m_Pos = NewPos; return S_OK; }
22.960396
79
0.504959
segafan
2252f524739993996b3d5c5451f8c11b28207f28
902
inl
C++
Sources/Engine/Core/Reflection/FieldInfo.inl
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Engine/Core/Reflection/FieldInfo.inl
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Engine/Core/Reflection/FieldInfo.inl
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
/*============================================================================= FieldInfo.inl Project: Sonata Engine Author: Julien Delezenne =============================================================================*/ SE_INLINE MemberTypes FieldInfo::GetMemberType() const { return MemberTypes_Field; } SE_INLINE String FieldInfo::GetName() const { return _FieldName; } SE_INLINE FieldAttributes FieldInfo::GetFieldAttributes() const { return _FieldAttributes; } SE_INLINE TypeInfo* FieldInfo::GetFieldType() const { if (_FieldType != NULL) return _FieldType; _FieldType = TypeFactory::Instance()->GetType((_FieldTypeName)); return _FieldType; } /*template <class T> T& FieldInfo::GetValue(Object* obj) { return *(const T*)(((const byte*)obj) + _Offset); } template <class T> void FieldInfo::SetValue(Object* obj, const T& value) { *(T*)(((const byte*)obj) + _Offset) = value; }*/
21.47619
79
0.604213
jdelezenne
2259de8b52fc386f960d86221ea6b12ed36cb139
16,823
cpp
C++
src/frontends/havannah.cpp
RememberOfLife/mirabel
4ff62d6b9dbb0bde6a9755e9e2b1fca88baed8af
[ "MIT" ]
2
2022-03-29T08:39:24.000Z
2022-03-30T09:22:18.000Z
src/frontends/havannah.cpp
RememberOfLife/mirabel
4ff62d6b9dbb0bde6a9755e9e2b1fca88baed8af
[ "MIT" ]
null
null
null
src/frontends/havannah.cpp
RememberOfLife/mirabel
4ff62d6b9dbb0bde6a9755e9e2b1fca88baed8af
[ "MIT" ]
null
null
null
#include <algorithm> #include <cmath> #include <cstdint> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> #include "nanovg_gl.h" #include "imgui.h" #include "surena/games/havannah.h" #include "surena/game.h" #include "control/client.hpp" #include "control/event_queue.hpp" #include "control/event.hpp" #include "games/game_catalogue.hpp" #include "games/havannah.hpp" #include "meta_gui/meta_gui.hpp" #include "frontends/havannah.hpp" namespace Frontends { void Havannah::sbtn::update(float mx, float my) { const float hex_angle = 2 * M_PI / 6; mx -= x; my -= y; // mouse is auto rotated by update to make this function assume global flat top // rotate in button space to make the collision work with the pointy top local hexes we get from global flat top rotate_cords(mx, my, hex_angle); mx = abs(mx); my = abs(my); // https://stackoverflow.com/questions/42903609/function-to-determine-if-point-is-inside-hexagon hovered = (my < std::round(sqrt(3) * std::min(r - mx, r / 2))); } Havannah::Havannah(): the_game(NULL) { dc = Control::main_client->nanovg_ctx; } Havannah::~Havannah() {} void Havannah::set_game(game* new_game) { the_game = new_game; if (the_game != NULL) { size = ((havannah_options*)the_game->options)->size; the_game_int = (havannah_internal_methods*)the_game->methods->internal_methods; } else { size = 10; } const float hex_angle = 2 * M_PI / 6; const float fitting_hex_radius = button_size+padding; const float flat_radius = sin(hex_angle) * fitting_hex_radius; int board_sizer = (2*size-1); float offset_x = -(size*flat_radius)+flat_radius; float offset_y = -((3*size-3)*fitting_hex_radius)/2; for (int y = 0; y < board_sizer; y++) { for (int x = 0; x < board_sizer; x++) { if (!(x - y < size) || !(y - x < size)) { continue; } int base_x_padding = (y + 1) / 2; float base_x = (x - base_x_padding) * (flat_radius * 2); if (y % 2 != 0) { base_x += flat_radius; } float base_y = y*(fitting_hex_radius*1.5); board_buttons[y*board_sizer+x] = sbtn{ offset_x + base_x, offset_y + base_y, button_size, static_cast<uint8_t>(x), static_cast<uint8_t>(y), false, false }; } } } void Havannah::process_event(SDL_Event event) { if (!the_game) { return; } the_game->methods->players_to_move(the_game, &pbuf_c, &pbuf); if (pbuf_c == 0) { return; } switch (event.type) { case SDL_MOUSEMOTION: { mx = event.motion.x - x_px; my = event.motion.y - y_px; } break; case SDL_MOUSEBUTTONDOWN: case SDL_MOUSEBUTTONUP: { if (event.button.button == SDL_BUTTON_LEFT) { // is proper left mouse button down event, find where it clicked and if applicable push the appropriate event const float hex_angle = 2 * M_PI / 6; const float fitting_hex_radius = button_size+padding; const float flat_radius = sin(hex_angle) * fitting_hex_radius; int board_sizer = (2*size-1); float mX = event.button.x - x_px; float mY = event.button.y - y_px; mX -= w_px / 2; mY -= h_px / 2; if (!flat_top) { rotate_cords(mX, mY, hex_angle); } for (int y = 0; y < board_sizer; y++) { for (int x = 0; x < board_sizer; x++) { if (!(x - y < size) || !(y - x < size)) { continue; } board_buttons[y*board_sizer+x].update(mX, mY); if (event.type == SDL_MOUSEBUTTONUP) { HAVANNAH_PLAYER cp; the_game_int->get_cell(the_game, x, y, &cp); if (board_buttons[y*board_sizer+x].hovered && board_buttons[y*board_sizer+x].mousedown && cp == 0) { uint64_t move_code = y | (x<<8); Control::main_client->inbox.push(Control::event::create_move_event(Control::EVENT_TYPE_GAME_MOVE, move_code)); } board_buttons[y*board_sizer+x].mousedown = false; } board_buttons[y*board_sizer+x].mousedown |= (board_buttons[y*board_sizer+x].hovered && event.type == SDL_MOUSEBUTTONDOWN); } } } } break; } } void Havannah::update() { if (!the_game) { return; } the_game->methods->players_to_move(the_game, &pbuf_c, &pbuf); if (pbuf_c == 0) { return; } // set button hovered const float hex_angle = 2 * M_PI / 6; const float fitting_hex_radius = button_size+padding; const float flat_radius = sin(hex_angle) * fitting_hex_radius; int board_sizer = (2*size-1); float offset_x = -(size*flat_radius)+flat_radius; float offset_y = -((3*size-3)*fitting_hex_radius)/2; float mX = mx; float mY = my; mX -= w_px/2; mY -= h_px/2; if (!flat_top) { // if global board is not flat topped, rotate the mouse so it is, for the collision check rotate_cords(mX, mY, hex_angle); } for (int y = 0; y < board_sizer; y++) { for (int x = 0; x < board_sizer; x++) { if (!(x - y < size) || !(y - x < size)) { continue; } int base_x_padding = (y + 1) / 2; float base_x = (x - base_x_padding) * (flat_radius * 2); if (y % 2 != 0) { base_x += flat_radius; } float base_y = y*(fitting_hex_radius*1.5); board_buttons[y*board_sizer+x].x = offset_x + base_x; board_buttons[y*board_sizer+x].y = offset_y + base_y; board_buttons[y*board_sizer+x].r = button_size; board_buttons[y*board_sizer+x].update(mX, mY); } } } void Havannah::render() { const float hex_angle = 2 * M_PI / 6; const float fitting_hex_radius = button_size+padding; const float flat_radius = sin(hex_angle) * fitting_hex_radius; int board_sizer = (2*size-1); nvgSave(dc); nvgBeginPath(dc); nvgRect(dc, -10, -10, w_px+20, h_px+20); nvgFillColor(dc, nvgRGB(201, 144, 73)); nvgFill(dc); nvgTranslate(dc, w_px/2, h_px/2); if (!flat_top) { nvgRotate(dc, hex_angle/2); } // colored board border for current/winning player pbuf = HAVANNAH_PLAYER_NONE; nvgBeginPath(dc); if (!the_game) { nvgStrokeColor(dc, nvgRGB(161, 119, 67)); } else { the_game->methods->players_to_move(the_game, &pbuf_c, &pbuf); if (pbuf_c == 0) { the_game->methods->get_results(the_game, &pbuf_c, &pbuf); } switch (pbuf) { default: case HAVANNAH_PLAYER_NONE: { nvgStrokeColor(dc, nvgRGB(128, 128, 128)); } break; case HAVANNAH_PLAYER_WHITE: { nvgStrokeColor(dc, nvgRGB(141, 35, 35)); } break; case HAVANNAH_PLAYER_BLACK: { nvgStrokeColor(dc, nvgRGB(25, 25, 25)); } break; } // actually we just want the ptm in there, so reste it back to that the_game->methods->players_to_move(the_game, &pbuf_c, &pbuf); } nvgStrokeWidth(dc, flat_radius*0.5); nvgMoveTo(dc, static_cast<float>(size*2)*flat_radius, 0); for (int i = 0; i < 6; i++) { nvgRotate(dc, M_PI/3); nvgLineTo(dc, static_cast<float>(size*2)*flat_radius, 0); } nvgStroke(dc); // translate back up to board rendering position and render board nvgTranslate(dc, -(size*flat_radius)+flat_radius, -((3*size-3)*fitting_hex_radius)/2); for (int y = 0; y < board_sizer; y++) { for (int x = 0; x < board_sizer; x++) { if (!(x - y < size) || !(y - x < size)) { continue; } int base_x_padding = (y + 1) / 2; float base_x = (x - base_x_padding) * (flat_radius * 2); if (y % 2 != 0) { base_x += flat_radius; } float base_y = y*(fitting_hex_radius*1.5); nvgBeginPath(dc); if (!the_game || pbuf_c == 0) { nvgFillColor(dc, nvgRGB(161, 119, 67)); } else { nvgFillColor(dc, nvgRGB(240, 217, 181)); } nvgSave(dc); nvgTranslate(dc, base_x, base_y); nvgRotate(dc, hex_angle/2); nvgMoveTo(dc, button_size, 0); for (int i = 0; i < 6; i++) { nvgRotate(dc, M_PI/3); nvgLineTo(dc, button_size, 0); } nvgFill(dc); if (!the_game) { nvgRestore(dc); continue; } HAVANNAH_PLAYER cell_color; the_game_int->get_cell(the_game, x, y, &cell_color); switch (cell_color) { case HAVANNAH_PLAYER_NONE: { if (board_buttons[y*board_sizer+x].hovered && pbuf > HAVANNAH_PLAYER_NONE) { nvgBeginPath(dc); nvgFillColor(dc, nvgRGB(220, 197, 161)); nvgMoveTo(dc, button_size*0.9, 0); for (int i = 0; i < 6; i++) { nvgRotate(dc, M_PI/3); nvgLineTo(dc, button_size*0.9, 0); } nvgFill(dc); } } break; case HAVANNAH_PLAYER_WHITE: { nvgBeginPath(dc); nvgFillColor(dc, nvgRGB(141, 35, 35)); if (hex_stones) { nvgMoveTo(dc, button_size*stone_size_mult, 0); for (int i = 0; i < 6; i++) { nvgRotate(dc, M_PI/3); nvgLineTo(dc, button_size*stone_size_mult, 0); } } else { nvgCircle(dc, 0, 0, button_size*stone_size_mult); } nvgFill(dc); } break; case HAVANNAH_PLAYER_BLACK: { nvgBeginPath(dc); nvgFillColor(dc, nvgRGB(25, 25, 25)); if (hex_stones) { nvgMoveTo(dc, button_size*stone_size_mult, 0); for (int i = 0; i < 6; i++) { nvgRotate(dc, M_PI/3); nvgLineTo(dc, button_size*stone_size_mult, 0); } } else { nvgCircle(dc, 0, 0, button_size*stone_size_mult); } nvgFill(dc); } break; case HAVANNAH_PLAYER_INVALID: { assert(false); } break; } // draw colored connections to same player pieces if (connections_width > 0 && cell_color != HAVANNAH_PLAYER_NONE) { float connection_draw_width = button_size * connections_width; // draw for self<->{1(x-1,y),3(x,y-1),2(x-1,y-1)} uint8_t connections_to_draw = 0; HAVANNAH_PLAYER cell_other; the_game_int->get_cell(the_game, x-1, y, &cell_other); if (cell_color == cell_other && cell_other != HAVANNAH_PLAYER_INVALID) { connections_to_draw |= 0b001; } the_game_int->get_cell(the_game, x, y-1, &cell_other); if (cell_color == cell_other && cell_other != HAVANNAH_PLAYER_INVALID) { connections_to_draw |= 0b100; } the_game_int->get_cell(the_game, x-1, y-1, &cell_other); if (cell_color == cell_other && cell_other != HAVANNAH_PLAYER_INVALID) { connections_to_draw |= 0b010; } if (connections_to_draw) { nvgSave(dc); nvgRotate(dc, -M_PI/6); nvgBeginPath(dc); switch (cell_color) { case HAVANNAH_PLAYER_WHITE: { nvgStrokeColor(dc, nvgRGB(141, 35, 35)); } break; case HAVANNAH_PLAYER_BLACK: { nvgStrokeColor(dc, nvgRGB(25, 25, 25)); } break; case HAVANNAH_PLAYER_NONE: case HAVANNAH_PLAYER_INVALID: { assert(false); } break; } nvgRotate(dc, -M_PI-M_PI/3); for (int rot = 0; rot < 3; rot++) { nvgRotate(dc, M_PI/3); if (!((connections_to_draw >> rot)&0b1)) { continue; } nvgRect(dc, -connection_draw_width/2, -connection_draw_width/2, connection_draw_width+flat_radius*2, connection_draw_width); } nvgFill(dc); nvgRestore(dc); } } //TODO draw engine best move /*if (engine && engine->player_to_move() != 0 && engine->get_best_move() == ((x<<8)|y)) { nvgStrokeColor(dc, nvgRGB(125, 187, 248)); nvgStrokeWidth(dc, button_size*0.1); nvgMoveTo(dc, button_size*0.95, 0); for (int i = 0; i < 6; i++) { nvgRotate(dc, M_PI/3); nvgLineTo(dc, button_size*0.95, 0); } nvgStroke(dc); }*/ nvgRestore(dc); } } nvgRestore(dc); } void Havannah::draw_options() { ImGui::Checkbox("flat top", &flat_top); ImGui::SliderFloat("button size", &button_size, 10, 100, "%.3f", ImGuiSliderFlags_AlwaysClamp); ImGui::SliderFloat("padding", &padding, 0, 20, "%.3f", ImGuiSliderFlags_AlwaysClamp); ImGui::SliderFloat("stone size", &stone_size_mult, 0.1, 1, "%.3f", ImGuiSliderFlags_AlwaysClamp); ImGui::Checkbox("hex stones", &hex_stones); ImGui::SliderFloat("connections width", &connections_width, 0, 0.8, "%.3f", ImGuiSliderFlags_AlwaysClamp); } void Havannah::rotate_cords(float& x, float&y, float angle) { // rotate mouse input by +angle float pr = hypot(x, y); float pa = atan2(y, x) + angle; y = -pr * cos(pa); x = pr * sin(pa); } Havannah_FEW::Havannah_FEW(): FrontendWrap("Havannah") {} Havannah_FEW::~Havannah_FEW() {} bool Havannah_FEW::base_game_variant_compatible(Games::BaseGameVariant* base_game_variant) { return (dynamic_cast<Games::Havannah*>(base_game_variant) != nullptr); } Frontend* Havannah_FEW::new_frontend() { return new Havannah(); } void Havannah_FEW::draw_options() { ImGui::TextDisabled("<no options>"); } }
41.435961
152
0.465256
RememberOfLife
2264fc1eab45336fe936d8c924ce9962520f3ad5
39,231
cpp
C++
Lua_Irrlicht_Game/Lua_Irrlicht_Game/Game.cpp
nfginola/Tower_Defense
186c63e3cddccde69bd02d2085cf031e09b6c492
[ "MIT" ]
null
null
null
Lua_Irrlicht_Game/Lua_Irrlicht_Game/Game.cpp
nfginola/Tower_Defense
186c63e3cddccde69bd02d2085cf031e09b6c492
[ "MIT" ]
null
null
null
Lua_Irrlicht_Game/Lua_Irrlicht_Game/Game.cpp
nfginola/Tower_Defense
186c63e3cddccde69bd02d2085cf031e09b6c492
[ "MIT" ]
null
null
null
#include "Game.h" std::wstring s2ws(const std::string& s) { int len; int stringlength = (int)s.length() + 1; len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), stringlength, 0, 0); wchar_t* buf = new wchar_t[len]; MultiByteToWideChar(CP_ACP, 0, s.c_str(), stringlength, buf, len); std::wstring r(buf); delete[] buf; return r; } namespace luaF { static int s_GUI_idstart = 101; static IrrlichtDevice* s_dev = nullptr; static ISceneManager* s_sMgr = nullptr; static EventReceiver* s_evRec = nullptr; static IVideoDriver* s_driver = nullptr; static ISceneCollisionManager* s_collMan = nullptr; static IGUIEnvironment* s_guiEnv = nullptr; static lua_State* s_L = nullptr; // old /* WorldObject* checkWO(lua_State* L, int n) { void* ptr = luaL_testudata(L, n, "mt_WorldObject"); WorldObject* wo = nullptr; if (ptr != nullptr) wo = *(WorldObject**)ptr; return wo; }*/ bool check_lua(lua_State* L, int r) { if (r != LUA_OK) { std::string err = lua_tostring(L, -1); std::cout << err << '\n'; return false; } else return true; } void load_script(lua_State* L, const std::string& fname) { static std::string script_dir{ "LuaScripts/" }; if (check_lua(L, luaL_dofile(L, (script_dir + fname).c_str()))) std::cout << "[C++]: '" << fname << "' successfully started!\n\n\n"; else throw std::runtime_error("Lua script failed to load!"); } void dump_stack(lua_State* L) { std::cout << "------- STACK DUMP -------\n"; for (int i = lua_gettop(L); i > 0; i--) { std::cout << "Index " << i << ": " << lua_typename(L, lua_type(L, i)) << "\n"; } std::cout << "--------------------------\n"; } void pcall_p(lua_State* L, int args, int res, int errFunc) { if (lua_pcall(L, args, res, errFunc) == LUA_ERRRUN) { //dump_stack(L); // print error message if (lua_isstring(L, -1)) std::cout << lua_tostring(L, -1) << '\n'; lua_pop(L, 1); // pop the error message (we dont need it anymore) //dump_stack(L); } } int exitApp(lua_State* L) { s_dev->closeDevice(); return 0; } // Check user data from stack template<typename T> T* checkObject(lua_State* L, int n, const std::string& metatable) { // A ptr is held in the Lua environment! void* ptr = luaL_testudata(L, n, metatable.c_str()); T* obj = nullptr; if (ptr != nullptr) obj = *(T**)ptr; return obj; } // World object int createWO(lua_State* L) { std::string name = lua_tostring(L, -1); if (name != "") { // A ptr is held in the Lua environment. WorldObject** wo = reinterpret_cast<WorldObject**>(lua_newuserdata(L, sizeof(WorldObject*))); *wo = new WorldObject; (*wo)->name = name; luaL_getmetatable(L, "mt_WorldObject"); lua_setmetatable(L, -2); // pops table from stack and sets it as new metatb for the idx value! // mt_WorldObject is at top and we set it on userdata below it } else throw std::runtime_error("No name assigned to WorldObject at creation!"); return 1; } // destroy irrlicht node int destroyWO(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); if (wo != nullptr) { wo->mesh->remove(); wo->mesh = nullptr; } //std::cout << "[C++]: Node removed!\n"; return 0; } int deallocateWO(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); if (wo != nullptr) { if (wo->mesh != nullptr) { wo->mesh->removeAll(); wo->mesh = nullptr; } delete wo; } //std::cout << "[C++]: WO deallocated!\n"; return 0; } int woTest(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); wo->Test(); return 0; } int woAddSphereMesh(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); float rad = lua_tonumber(L, 2); if (rad == 0.f) rad = 1.f; if (wo->mesh != nullptr) wo->mesh->drop(); wo->pos = vector3df(0.0, 0.0, 0.0); wo->mesh = s_sMgr->addSphereSceneNode(rad, 16, 0, -1, wo->pos); wo->mesh->setMaterialFlag(video::EMF_LIGHTING, false); wo->mesh->setID(ID_IsNotPickable); wo->mesh->setName(wo->name.c_str()); return 0; } int woAddCubeMesh(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); if (wo->mesh != nullptr) wo->mesh->drop(); wo->mesh = s_sMgr->addCubeSceneNode(); wo->mesh->setID(ID_IsNotPickable); wo->mesh->setMaterialFlag(video::EMF_LIGHTING, false); //wo->mesh->setMaterialTexture(0, s_driver->getTexture("resources/textures/moderntile.jpg")); //wo->mesh->setPosition(vector3df(10.5f, 0.f, 10.5f)); // Default cubes are 10 big wo->mesh->setName(wo->name.c_str()); return 0; } int woAddTriSelector(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); scene::ITriangleSelector* selector = 0; selector = s_sMgr->createTriangleSelectorFromBoundingBox(wo->mesh); wo->mesh->setTriangleSelector(selector); selector->drop(); return 0; } int woSetPosition(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); float x = lua_tonumber(L, -3); float y = lua_tonumber(L, -2); float z = lua_tonumber(L, -1); wo->pos.X = x; wo->pos.Y = y; wo->pos.Z = z; wo->mesh->setPosition(vector3df(x, y, z)); return 0; } int woSetScale(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); float x = lua_tonumber(L, -3); float y = lua_tonumber(L, -2); float z = lua_tonumber(L, -1); wo->mesh->setScale(vector3df(x, y, z)); return 0; } int woSetTexture(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); io::path fpath = lua_tostring(L, -1); wo->mesh->setMaterialTexture(0, s_driver->getTexture(fpath)); return 0; } int woSetDynamic(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); wo->dynamic = true; return 0; } int woSetTransparent(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); wo->mesh->setMaterialType(EMT_TRANSPARENT_ADD_COLOR); return 0; } int woGetPosition(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); lua_pushnumber(L, wo->pos.X); lua_pushnumber(L, wo->pos.Y); lua_pushnumber(L, wo->pos.Z); return 3; } int woToggleBB(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); if (wo->bbVisible) { wo->mesh->setDebugDataVisible(0); wo->bbVisible = false; } else { wo->mesh->setDebugDataVisible(irr::scene::EDS_BBOX); wo->bbVisible = true; } return 0; } int woSetPickable(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); wo->mesh->setID(IDFlag_IsPickable); return 0; } int woCollides(lua_State* L) { WorldObject* wo1 = checkObject<WorldObject>(L, 2, "mt_WorldObject"); WorldObject* wo2 = checkObject<WorldObject>(L, 1, "mt_WorldObject"); bool intersects = wo1->mesh->getTransformedBoundingBox().intersectsWithBox(wo2->mesh->getTransformedBoundingBox()); lua_pushboolean(L, intersects); return 1; } int woDrawLine(lua_State* L) { WorldObject* wo1 = checkObject<WorldObject>(L, 2, "mt_WorldObject"); WorldObject* wo2 = checkObject<WorldObject>(L, 1, "mt_WorldObject"); s_driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); s_driver->draw3DLine(wo1->mesh->getAbsolutePosition(), wo2->mesh->getAbsolutePosition(), SColor(255, 255, 0, 0)); return 0; } int woToggleVisible(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); if (wo->meshVisible) { wo->mesh->setVisible(false); wo->meshVisible = false; } else { wo->mesh->setVisible(true); wo->meshVisible = true; } return 0; } int woSetMoveNextPoint(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); if (!(wo->dynamic)) throw std::runtime_error("Object is not set to be dynamic!"); vector3df start; start.X = lua_tonumber(L, -7); start.Y = lua_tonumber(L, -6); start.Z = lua_tonumber(L, -5); vector3df end; end.X = lua_tonumber(L, -4); end.Y = lua_tonumber(L, -3); end.Z = lua_tonumber(L, -2); float interpTime = lua_tonumber(L, -1); //std::cout << "Start: (" << start.X << ", " << start.Y << ", " << start.Z << ")\n"; //std::cout << "End: (" << end.X << ", " << end.Y << ", " << end.Z << ")\n"; //std::cout << "Interp time: " << interpTime << '\n'; //std::cout << "Next move assigned to: " << wo->mesh->getName() << '\n'; wo->mover.AssignNextMove(start, end, interpTime); // std::cout << "Assigned\n"; return 0; } int woUpdate(lua_State* L) { WorldObject* wo = checkObject<WorldObject>(L, 1, "mt_WorldObject"); float dt = lua_tonumber(L, -1); if (!(wo->mover.dead) && wo->dynamic) { wo->pos = wo->mover.Update(dt, wo->mesh->getName()); wo->mesh->setPosition(wo->pos); } return 0; } // Input int isLMBPressed(lua_State* L) { bool lmbPressed = s_evRec->isLMBPressed(); lua_pushboolean(L, lmbPressed); return 1; } int isRMBPressed(lua_State* L) { bool rmbPressed = s_evRec->isRMBPressed(); lua_pushboolean(L, rmbPressed); return 1; } int isKeyDown(lua_State* L) { std::string key = lua_tostring(L, -1); bool keyDown = s_evRec->isKeyDown(key); lua_pushboolean(L, keyDown); return 1; } int isKeyPressed(lua_State* L) { std::string key = lua_tostring(L, -1); bool keyPressed = s_evRec->isKeyPressed(key); lua_pushboolean(L, keyPressed); return 1; } // Skybox int setSkyboxTextures(lua_State* L) { io::path topPath = lua_tostring(L, -6); io::path bottomPath = lua_tostring(L, -5); io::path leftPath = lua_tostring(L, -4); io::path rightPath = lua_tostring(L, -3); io::path frontPath = lua_tostring(L, -2); io::path backPath = lua_tostring(L, -1); std::cout << topPath.c_str() << '\n'; auto top = s_driver->getTexture(topPath); auto bottom = s_driver->getTexture(bottomPath); auto left = s_driver->getTexture(leftPath); auto right = s_driver->getTexture(rightPath); auto front = s_driver->getTexture(frontPath); auto back = s_driver->getTexture(backPath); s_sMgr->addSkyBoxSceneNode(top, bottom, left, right, front, back); return 0; } // Utility (Non Lua Func) ISceneNode* irrlichtCastRay(const vector3df& start, vector3df dir) { core::line3d<f32> ray; ray.start = start; ray.end = ray.start + dir.normalize() * 1000.0f; core::vector3df intersection; core::triangle3df hitTriangle; ISceneNode* ret = s_collMan->getSceneNodeAndCollisionPointFromRay( ray, intersection, hitTriangle, IDFlag_IsPickable, 0); return ret; } // Camera int createCamera(lua_State* L) { Camera** cam = reinterpret_cast<Camera**>(lua_newuserdata(L, sizeof(Camera*))); *cam = new Camera; luaL_getmetatable(L, "mt_Camera"); lua_setmetatable(L, -2); std::cout << "Hola!\n"; return 1; } int deallocateCamera(lua_State* L) { Camera* cam = checkObject<Camera>(L, 1, "mt_Camera"); if (cam != nullptr) delete cam; //std::cout << "[C++]: Camera deallocated!\n"; return 0; } int camCreateFPS(lua_State* L) { Camera* cam = checkObject<Camera>(L, 1, "mt_Camera"); float x = lua_tonumber(L, -3); float y = lua_tonumber(L, -2); float z = lua_tonumber(L, -1); if (cam != nullptr) { cam->sceneCam = s_sMgr->addCameraSceneNodeFPS(); cam->sceneCam->setPosition({ x, y, z }); cam->sceneCam->setID(ID_IsNotPickable); } return 0; } int camSetPosition(lua_State* L) { Camera* cam = checkObject<Camera>(L, 1, "mt_Camera"); float x = lua_tonumber(L, -3); float y = lua_tonumber(L, -2); float z = lua_tonumber(L, -1); cam->sceneCam->setPosition(vector3df(x, y, z)); return 0; } int camGetPosition(lua_State* L) { Camera* cam = checkObject<Camera>(L, 1, "mt_Camera"); if (cam != nullptr) { lua_pushnumber(L, cam->sceneCam->getAbsolutePosition().X); lua_pushnumber(L, cam->sceneCam->getAbsolutePosition().Y); lua_pushnumber(L, cam->sceneCam->getAbsolutePosition().Z); } return 3; } int camGetRightVec(lua_State* L) { Camera* cam = checkObject<Camera>(L, 1, "mt_Camera"); if (cam != nullptr) { // the world dirs are in COLUMNS (remember transpose of WM) const matrix4& mat = cam->sceneCam->getViewMatrix(); // normalize incase its not orthonormal (it should be :)) vector3df rightVec = vector3df(mat[0], mat[4], mat[8]).normalize(); lua_pushnumber(L, rightVec.X); lua_pushnumber(L, rightVec.Y); lua_pushnumber(L, rightVec.Z); } return 3; } int camGetUpVec(lua_State* L) { Camera* cam = checkObject<Camera>(L, 1, "mt_Camera"); if (cam != nullptr) { vector3df upVec = cam->sceneCam->getUpVector(); lua_pushnumber(L, upVec.X); lua_pushnumber(L, upVec.Y); lua_pushnumber(L, upVec.Z); } return 3; } int camGetForwardVec(lua_State* L) { Camera* cam = checkObject<Camera>(L, 1, "mt_Camera"); if (cam != nullptr) { const matrix4& mat = cam->sceneCam->getViewMatrix(); vector3df forwardVec = vector3df(mat[2], mat[6], mat[10]).normalize(); lua_pushnumber(L, forwardVec.X); lua_pushnumber(L, forwardVec.Y); lua_pushnumber(L, forwardVec.Z); /* --> in i lua --> create vec --> return vec */ } return 3; } static ISceneNode* s_highlightedSceneNode = nullptr; int camCastRay(lua_State* L) { Camera* cam = checkObject<Camera>(L, 1, "mt_Camera"); if (cam != nullptr) { if (s_highlightedSceneNode) s_highlightedSceneNode->setDebugDataVisible(0); // reset debug bb // get fwd const matrix4& mat = cam->sceneCam->getViewMatrix(); vector3df forwardVec = vector3df(mat[2], mat[6], mat[10]).normalize(); std::string hitName = ""; ISceneNode* selectedSceneNode = irrlichtCastRay(cam->sceneCam->getAbsolutePosition(), forwardVec); if (selectedSceneNode) { s_highlightedSceneNode = selectedSceneNode; hitName = s_highlightedSceneNode->getName(); selectedSceneNode->setDebugDataVisible(irr::scene::EDS_BBOX); // debug bb draw } else { s_highlightedSceneNode = nullptr; } lua_pushstring(L, hitName.c_str()); } return 1; } int camToggleActive(lua_State* L) { Camera* cam = checkObject<Camera>(L, 1, "mt_Camera"); if (cam != nullptr) { cam->active = !(cam->active); cam->sceneCam->setInputReceiverEnabled(cam->active); } return 1; } int drawLine(lua_State* L) { float startX = lua_tonumber(L, -6); float startY = lua_tonumber(L, -5); float startZ = lua_tonumber(L, -4); float endX = lua_tonumber(L, -3); float endY = lua_tonumber(L, -2); float endZ = lua_tonumber(L, -1); s_driver->setTransform(video::ETS_WORLD, core::IdentityMatrix); s_driver->draw3DLine(vector3df(startX, startY, startZ), vector3df(endX, endY, endZ), SColor(255, 255, 0, 255)); return 0; } // GUI int clearGUI(lua_State* L) { s_guiEnv->clear(); return 0; } int setGlobalGUIFont(lua_State* L) { std::string fontpath = lua_tostring(L, -1); IGUISkin* skin = s_guiEnv->getSkin(); IGUIFont* font = s_guiEnv->getFont(s2ws(fontpath).c_str()); if (font) skin->setFont(font); return 0; } // Text int createText(lua_State* L) { float topLeftX = lua_tonumber(L, -6); float topLeftY = lua_tonumber(L, -5); float pixWidth = lua_tonumber(L, -4); float pixHeight = lua_tonumber(L, -3); std::string initText = lua_tostring(L, -2); std::string fontpath = lua_tostring(L, -1); GUIStaticText** txt = reinterpret_cast<GUIStaticText**>(lua_newuserdata(L, sizeof(GUIStaticText*))); *txt = new GUIStaticText; (*txt)->ptr = s_guiEnv->addStaticText(s2ws(initText).c_str(), rect<s32>( topLeftX, topLeftY, topLeftX + pixWidth, topLeftY + pixHeight)); IGUIFont* font = s_guiEnv->getFont(fontpath.c_str()); (*txt)->ptr->setOverrideFont(font); luaL_getmetatable(L, "mt_GUIText"); lua_setmetatable(L, -2); return 1; } int removeText(lua_State* L) { GUIStaticText* txt = checkObject<GUIStaticText>(L, 1, "mt_GUIText"); if (txt != nullptr) { txt->ptr->setVisible(false); delete txt; // let irrlicht take care of the underlying ptr (crash if we drop internal ptr here) } return 0; } int setText(lua_State* L) { std::string newText = lua_tostring(L, -1); GUIStaticText* text = checkObject<GUIStaticText>(L, 1, "mt_GUIText"); text->ptr->setText(s2ws(newText).c_str()); return 0; } int setTextBGColor(lua_State* L) { float r = lua_tonumber(L, -4); float g = lua_tonumber(L, -3); float b = lua_tonumber(L, -2); float a = lua_tonumber(L, -1); GUIStaticText* text = checkObject<GUIStaticText>(L, 1, "mt_GUIText"); text->ptr->setBackgroundColor(SColor(a, r, g, b)); return 0; } int setTextColor(lua_State* L) { float r = lua_tonumber(L, -4); float g = lua_tonumber(L, -3); float b = lua_tonumber(L, -2); float a = lua_tonumber(L, -1); GUIStaticText* text = checkObject<GUIStaticText>(L, 1, "mt_GUIText"); text->ptr->setOverrideColor(SColor(a, r, g, b)); return 0; } // Button int createButton(lua_State* L) { float topLeftX = lua_tonumber(L, -7); float topLeftY = lua_tonumber(L, -6); float pixWidth = lua_tonumber(L, -5); float pixHeight = lua_tonumber(L, -4); float internalID = lua_tonumber(L, -3); int irrID = s_GUI_idstart + internalID; std::string text = lua_tostring(L, -2); std::string fontpath = lua_tostring(L, -1); GUIButton** button = reinterpret_cast<GUIButton**>(lua_newuserdata(L, sizeof(GUIButton*))); *button = new GUIButton; (*button)->ptr = s_guiEnv->addButton(rect<s32>(topLeftX, topLeftY, topLeftX + pixWidth, topLeftY + pixHeight), 0, irrID, s2ws(text).c_str()); IGUIFont* font = s_guiEnv->getFont(fontpath.c_str()); (*button)->ptr->setOverrideFont(font); luaL_getmetatable(L, "mt_GUIButton"); lua_setmetatable(L, -2); return 1; } int removeButton(lua_State* L) { GUIButton* button = checkObject<GUIButton>(L, 1, "mt_GUIButton"); if (button != nullptr) { button->ptr->setVisible(false); delete button; // let irrlicht take care of the underlying ptr (crash if we drop internal ptr here) } return 0; } int openFileDialog(lua_State* L) { float internalID = lua_tonumber(L, -1); int irrID = s_GUI_idstart + internalID; s_guiEnv->addFileOpenDialog(L"Please choose a file!", true, 0, irrID, true); return 0; } // Scrollbar int createScrollbar(lua_State* L) { float topLeftX = lua_tonumber(L, -7); float topLeftY = lua_tonumber(L, -6); float pixWidth = lua_tonumber(L, -5); float pixHeight = lua_tonumber(L, -4); float min = lua_tonumber(L, -3); float max = lua_tonumber(L, -2); float internalID = lua_tonumber(L, -1); int irrID = s_GUI_idstart + internalID; GUIScrollbar** sb = reinterpret_cast<GUIScrollbar**>(lua_newuserdata(L, sizeof(GUIScrollbar*))); *sb = new GUIScrollbar; (*sb)->ptr = s_guiEnv->addScrollBar(true, rect<s32>(topLeftX, topLeftY, topLeftX + pixWidth, topLeftY + pixHeight), 0, irrID); (*sb)->ptr->setPos(min); (*sb)->ptr->setMin(min); (*sb)->ptr->setMax(max); luaL_getmetatable(L, "mt_GUIScrollbar"); lua_setmetatable(L, -2); return 1; } int removeScrollbar(lua_State* L) { GUIScrollbar* sb = checkObject<GUIScrollbar>(L, 1, "mt_GUIScrollbar"); if (sb != nullptr) { sb->ptr->setVisible(false); delete sb; // let irrlicht take care of the underlying ptr (crash if we drop internal ptr here) } return 0; } // Listbox int createListbox(lua_State* L) { float topLeftX = lua_tonumber(L, -5); float topLeftY = lua_tonumber(L, -4); float pixWidth = lua_tonumber(L, -3); float pixHeight = lua_tonumber(L, -2); float internalID = lua_tonumber(L, -1); int irrID = s_GUI_idstart + internalID; GUIListbox** lb = reinterpret_cast<GUIListbox**>(lua_newuserdata(L, sizeof(GUIListbox*))); *lb = new GUIListbox; (*lb)->ptr = s_guiEnv->addListBox(rect<s32>(topLeftX, topLeftY, topLeftX + pixWidth, topLeftY + pixHeight), 0, irrID, true); luaL_getmetatable(L, "mt_GUIListbox"); lua_setmetatable(L, -2); return 1; } int removeListbox(lua_State* L) { GUIListbox* lb = checkObject<GUIListbox>(L, 1, "mt_GUIListbox"); if (lb != nullptr) { lb->ptr->setVisible(false); delete lb; // let irrlicht take care of the underlying ptr (crash if we drop internal ptr here) } return 0; } int addToListbox(lua_State* L) { std::string text = lua_tostring(L, -1); GUIListbox* lb = checkObject<GUIListbox>(L, 1, "mt_GUIListbox"); lb->ptr->addItem(s2ws(text).c_str()); return 0; } int resetListboxContent(lua_State* L) { GUIListbox* lb = checkObject<GUIListbox>(L, 1, "mt_GUIListbox"); lb->ptr->clear(); return 0; } int createEditbox(lua_State* L) { float topLeftX = lua_tonumber(L, -4); float topLeftY = lua_tonumber(L, -3); float pixWidth = lua_tonumber(L, -2); float pixHeight = lua_tonumber(L, -1); GUIEditbox** eb = reinterpret_cast<GUIEditbox**>(lua_newuserdata(L, sizeof(GUIEditbox*))); *eb = new GUIEditbox; (*eb)->ptr = s_guiEnv->addEditBox(L"", rect<s32>(topLeftX, topLeftY, topLeftX + pixWidth, topLeftY + pixHeight) ); luaL_getmetatable(L, "mt_GUIEditbox"); lua_setmetatable(L, -2); return 1; } int removeEditbox(lua_State* L) { GUIEditbox* eb = checkObject<GUIEditbox>(L, 1, "mt_GUIEditbox"); if (eb != nullptr) { eb->ptr->setVisible(false); delete eb; // let irrlicht take care of the underlying ptr (crash if we drop internal ptr here) } return 0; } int getTextEditbox(lua_State* L) { GUIListbox* lb = checkObject<GUIListbox>(L, 1, "mt_GUIEditbox"); std::wstring txt = lb->ptr->getText(); std::string ret = std::string(txt.begin(), txt.end()); lua_pushstring(L, ret.c_str()); return 1; } int setTextEditbox(lua_State* L) { GUIListbox* lb = checkObject<GUIListbox>(L, 1, "mt_GUIEditbox"); std::string txt = lua_tostring(L, -1); lb->ptr->setText(s2ws(txt).c_str()); return 0; } } vector3df LinInterpMover::Update(float dt, const std::string& id) { currTime += dt; vector3df newPos; // StartPos is starting point and (endPos - startPos) is the direction of movement where the rate of change of the // magnitude is linearly proportional to (currTime/maxTime) if (currTime >= maxTime) { newPos = endPos; done = true; currTime = 0.0; // Return to Lua to ask for next move lua_getglobal(luaF::s_L, "getNextWaypoint"); if (lua_isfunction(luaF::s_L, -1)) { lua_pushstring(luaF::s_L, id.c_str()); luaF::pcall_p(luaF::s_L, 1, 1, 0); bool succeeded = lua_toboolean(luaF::s_L, -1); // If coroutine died, don't update movement anymore if (!succeeded) { currTime = 0.f; maxTime = -1.f; dead = true; } } } else if (!done) { // Normal interp newPos = startPos + (endPos - startPos) * (currTime / maxTime); } else if (done) { // Set at end newPos = endPos; } return newPos; } void LinInterpMover::AssignNextMove(const vector3df& start, const vector3df& end, float time) { // Double-check move is indeed done before new interp assignment if (done) { startPos = start; endPos = end; maxTime = time; done = false; } } bool EventReceiver::OnEvent(const SEvent& event) { if (event.EventType == irr::EET_KEY_INPUT_EVENT) { // held down m_keyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown; //// pressed and released //if (event.KeyInput.PressedDown == false) //{ // m_keyWasPressed[event.KeyInput.Key] = true; //} // check first "down" (a.k.a pressed) if (m_not_held) { m_not_held = false; // transition from false to true if (m_keyWasPressed[event.KeyInput.Key] == false) { m_keyWasPressed[event.KeyInput.Key] = true; } } // allow above check again only if has been released if (event.KeyInput.PressedDown == false) { m_not_held = true; m_keyWasPressed[event.KeyInput.Key] = false; // if released, we make sure to turn it off } } if (event.EventType == irr::EET_MOUSE_INPUT_EVENT) { switch (event.MouseInput.Event) { case EMIE_LMOUSE_PRESSED_DOWN: m_lmbPressed = true; m_lmbDown = true; break; case EMIE_LMOUSE_LEFT_UP: m_lmbPressed = false; m_lmbDown = false; break; case EMIE_RMOUSE_PRESSED_DOWN: m_rmbPressed = true; m_rmbDown = true; break; case EMIE_RMOUSE_LEFT_UP: m_rmbPressed = false; m_rmbDown = false; break; default: break; } } if (event.EventType == irr::EET_GUI_EVENT) { s32 id = event.GUIEvent.Caller->getID(); int internalID = id - luaF::s_GUI_idstart; s32 pos = 0; switch (event.GUIEvent.EventType) { case EGET_SCROLL_BAR_CHANGED: pos = ((IGUIScrollBar*)event.GUIEvent.Caller)->getPos(); // call lua with ID and new scrollbar value lua_getglobal(luaF::s_L, "scrollbarEvent"); if (lua_isfunction(luaF::s_L, -1)) { lua_pushnumber(luaF::s_L, internalID); lua_pushnumber(luaF::s_L, pos); luaF::pcall_p(luaF::s_L, 2, 0, 0); } break; case EGET_BUTTON_CLICKED: //// call lua with ID //std::cout << id << " Button clicked!\n"; lua_getglobal(luaF::s_L, "buttonClickEvent"); if (lua_isfunction(luaF::s_L, -1)) { lua_pushnumber(luaF::s_L, internalID); luaF::pcall_p(luaF::s_L, 1, 0, 0); } break; case EGET_FILE_SELECTED: IGUIFileOpenDialog* fileDialog = (IGUIFileOpenDialog*)event.GUIEvent.Caller; lua_getglobal(luaF::s_L, "fileSelected"); if (lua_isfunction(luaF::s_L, -1)) { std::wstring wstr(fileDialog->getFileName()); std::string str(wstr.begin(), wstr.end()); std::cout << "Path: " << str << '\n'; lua_pushstring(luaF::s_L, str.c_str()); luaF::pcall_p(luaF::s_L, 1, 0, 0); } break; } } return false; } Game::Game() : then(0) { // Init Irrlicht { m_dev = createDevice( video::EDT_OPENGL, dimension2d<u32>(1600, 900), 32, false, false, false, &m_evRec); // Pass the event receiver! if (!m_dev) throw std::runtime_error("Irrlicht device failed to initialize!"); m_dev->setWindowCaption(L"Tower Defense"); m_driver = m_dev->getVideoDriver(); m_sMgr = m_dev->getSceneManager(); m_guiEnv = m_dev->getGUIEnvironment(); m_collMan = m_sMgr->getSceneCollisionManager(); // Setup statics for Lua usage luaF::s_dev = m_dev; luaF::s_sMgr = m_sMgr; luaF::s_evRec = &m_evRec; luaF::s_driver = m_driver; luaF::s_collMan = m_collMan; luaF::s_guiEnv = m_guiEnv; } // Init Lua ResetLuaState(); } Game::~Game() { m_dev->drop(); } void Game::Run() { Init(); while (m_dev->run()) { // Get delta time const u32 now = m_dev->getTimer()->getTime(); const f32 dt = (f32)(now - then) / 1000.f; // in sec then = now; m_driver->beginScene(true, true, SColor(255, 100, 101, 140)); Update(dt); // Draw if (m_dev->run()) { m_sMgr->drawAll(); m_guiEnv->drawAll(); m_driver->endScene(); std::wstring title = std::wstring(L"Tower Defense. FPS: ") + std::to_wstring(1.0 / dt); m_dev->setWindowCaption(title.c_str()); } } } void Game::Init() { // Get time now then = m_dev->getTimer()->getTime(); } void Game::Update(float dt) { // Lua main update if (L != nullptr && luaF::s_L != nullptr) { lua_getglobal(L, "update"); if (lua_isfunction(L, -1)) { lua_pushnumber(L, dt); luaF::pcall_p(L, 1, 0, 0); } } if (m_luaShouldReset) { ResetLuaState(); m_luaShouldReset = false; } /* * 1) --> when quitting --> set flag (to reset lua state) * 2) --> after update loop ends * 3) --> actually handle replacement * */ } void Game::ResetLuaState() { if (L != nullptr && luaF::s_L != nullptr) { lua_close(L); L = nullptr; luaF::s_L = nullptr; m_sMgr->clear(); m_guiEnv->clear(); } // Init lua state L = luaL_newstate(); luaF::s_L = L; luaL_openlibs(L); // Open commonly used libs // Register World Object representation { luaL_newmetatable(L, "mt_WorldObject"); luaL_Reg funcRegs[] = { { "new", luaF::createWO }, { "__gc", luaF::deallocateWO }, { "removeNode", luaF::destroyWO }, { "test", luaF::woTest }, { "addSphereMesh", luaF::woAddSphereMesh }, { "addCubeMesh", luaF::woAddCubeMesh }, { "addCasting", luaF::woAddTriSelector }, { "setPosition", luaF::woSetPosition }, { "setScale", luaF::woSetScale }, { "setTexture", luaF::woSetTexture }, { "setPickable", luaF::woSetPickable }, { "setTransparent", luaF::woSetTransparent }, { "setDynamic", luaF::woSetDynamic }, { "setMoveNextPoint", luaF::woSetMoveNextPoint }, { "getPosition", luaF::woGetPosition }, { "toggleBB", luaF::woToggleBB }, { "toggleVisible", luaF::woToggleVisible }, { "collidesWith", luaF::woCollides }, { "drawLine", luaF::woDrawLine }, { "update", luaF::woUpdate }, { NULL, NULL } }; luaL_setfuncs(L, funcRegs, 0); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); lua_setglobal(L, "CWorldObject"); // set the configured metatable to "CWorldObject" } // Register Camera representation { luaL_newmetatable(L, "mt_Camera"); luaL_Reg funcRegs[] = { { "new", luaF::createCamera }, { "__gc", luaF::deallocateCamera }, { "setPosition", luaF::camSetPosition }, { "createFPSCam", luaF::camCreateFPS }, { "getRightVec", luaF::camGetRightVec }, { "getForwardVec", luaF::camGetForwardVec }, { "getUpVec", luaF::camGetUpVec }, { "getPosition", luaF::camGetPosition }, { "castRayForward", luaF::camCastRay }, { "toggleActive", luaF::camToggleActive }, { NULL, NULL } }; luaL_setfuncs(L, funcRegs, 0); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); lua_setglobal(L, "CCamera"); } // Register Button representation { luaL_newmetatable(L, "mt_GUIButton"); luaL_Reg funcRegs[] = { { "new", luaF::createButton }, { "__gc", luaF::removeButton }, { NULL, NULL } }; luaL_setfuncs(L, funcRegs, 0); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); lua_setglobal(L, "CButton"); } // Register Static Text representation { luaL_newmetatable(L, "mt_GUIText"); luaL_Reg funcRegs[] = { { "new", luaF::createText }, { "__gc", luaF::removeText }, { "setText", luaF::setText }, { "setBGColor", luaF::setTextBGColor }, { "setColor", luaF::setTextColor }, { NULL, NULL } }; luaL_setfuncs(L, funcRegs, 0); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); lua_setglobal(L, "CText"); } // Register Scrollbar representation { luaL_newmetatable(L, "mt_GUIScrollbar"); luaL_Reg funcRegs[] = { { "new", luaF::createScrollbar }, { "__gc", luaF::removeScrollbar }, { NULL, NULL } }; luaL_setfuncs(L, funcRegs, 0); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); lua_setglobal(L, "CScrollbar"); } // Register Listbox representation { luaL_newmetatable(L, "mt_GUIListbox"); luaL_Reg funcRegs[] = { { "new", luaF::createListbox }, { "__gc", luaF::removeListbox }, { "addToList", luaF::addToListbox }, { "reset", luaF::resetListboxContent }, { NULL, NULL } }; luaL_setfuncs(L, funcRegs, 0); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); lua_setglobal(L, "CListbox"); } // Register Editbox representation { luaL_newmetatable(L, "mt_GUIEditbox"); luaL_Reg funcRegs[] = { { "new", luaF::createEditbox }, { "__gc", luaF::removeEditbox }, { "getText", luaF::getTextEditbox }, { "setText", luaF::setTextEditbox }, { NULL, NULL } }; luaL_setfuncs(L, funcRegs, 0); lua_pushvalue(L, -1); lua_setfield(L, -1, "__index"); lua_setglobal(L, "CEditbox"); } // Register misc global functions lua_register(L, "isLMBpressed", luaF::isLMBPressed); lua_register(L, "isRMBpressed", luaF::isRMBPressed); lua_register(L, "isKeyDown", luaF::isKeyDown); lua_register(L, "isKeyPressed", luaF::isKeyPressed); lua_register(L, "setSkyboxTextures", luaF::setSkyboxTextures); lua_register(L, "posDrawLine", luaF::drawLine); lua_register(L, "clearGUI", luaF::clearGUI); lua_register(L, "openFileDialog", luaF::openFileDialog); lua_register(L, "setGlobalGUIFont", luaF::setGlobalGUIFont); lua_register(L, "exitApp", luaF::exitApp); // Use Closure to access internal Game state through global lua func lua_pushlightuserdata(L, this); lua_pushcclosure(L, &Game::ResetLuaStateWrapper, 1); lua_setglobal(L, "resetLuaState"); // Load scripts luaF::load_script(L, "main.lua"); // Init Lua lua_getglobal(L, "init"); if (lua_isfunction(L, -1)) luaF::pcall_p(L, 0, 0, 0); } int Game::ResetLuaStateWrapper(lua_State* L) { Game* gm = static_cast<Game*>(lua_touserdata(L, lua_upvalueindex(1))); //gm->ResetLuaState(); gm->m_luaShouldReset = true; luaF::s_highlightedSceneNode = nullptr; return 0; }
26.925875
132
0.546405
nfginola
22663302d55913bd4227ed6c9992db246f5c14e7
7,209
cpp
C++
src/devices/gsound/gsound.cpp
RandomAmbersky/zemu
c212c79bf3fd9fb20faa2f6e1861d1195d360303
[ "MIT" ]
7
2016-04-08T04:11:31.000Z
2022-01-26T08:20:38.000Z
src/devices/gsound/gsound.cpp
RandomAmbersky/zemu
c212c79bf3fd9fb20faa2f6e1861d1195d360303
[ "MIT" ]
1
2019-07-10T11:06:52.000Z
2019-07-10T11:06:52.000Z
src/devices/gsound/gsound.cpp
RandomAmbersky/zemu
c212c79bf3fd9fb20faa2f6e1861d1195d360303
[ "MIT" ]
2
2015-09-26T20:32:49.000Z
2020-08-27T20:03:04.000Z
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++, C#, and Java: http://www.viva64.com #include <string> #include <stdexcept> #include "gsound.h" #include "../mmanager/mmanager.h" C_SndRenderer C_GSound::sndRenderer; bool C_GSound::enabled = false; uint8_t C_GSound::regCommand = 0; uint8_t C_GSound::regStatus = 0x7E; uint8_t C_GSound::regData = 0; uint8_t C_GSound::regOutput = 0; uint8_t C_GSound::volume[4] = { 0, 0, 0, 0 }; uint8_t C_GSound::channel[4] = { 0, 0, 0, 0 }; uint8_t C_GSound::memPage = 0; Z80EX_CONTEXT* C_GSound::gsCpu = nullptr; uint8_t C_GSound::mem[0x8000 * GS_MEM_PAGES]; unsigned C_GSound::gsClk = 0; uint8_t* C_GSound::readMap[4]; uint8_t* C_GSound::writeMap[4]; #define GS_DEV_TO_CLK(clk) ((clk) << 2) #define GS_CLK_TO_DEV(clk) ((clk) >> 2) #define GS_INT_PERIOD (384) void C_GSound::Init(void) { auto config = host->config(); enabled = config->getBool("sound", "enablegs", false); if (!enabled) { return; } AttachZ80InputHandler(InputByteCheckPort, OnInputByte); AttachZ80OutputHandler(OutputByteCheckPort, OnOutputByte); AttachFrameStartHandler(OnFrameStart); AttachAfterFrameRenderHandler(OnAfterFrameRender); soundMixer.AddSource(&sndRenderer); std::string filename; size_t offset; filename = config->getString("sound", "gsrom", "gs105a.rom"); filename = split_romname(filename, &offset); if (host->storage()->readExtras("roms", filename, mem, 0x8000, offset) != 0x8000) { throw std::runtime_error(std::string("Couldn't find \"roms/") + filename + "\""); } gsCpu = z80ex_create( GsReadByte, nullptr, GsWriteByte, nullptr, GsInputByte, nullptr, GsOutputByte, nullptr, GsReadIntVec, nullptr ); Reset(); } void C_GSound::Close(void) { if (gsCpu) { z80ex_destroy(gsCpu); gsCpu = nullptr; } } bool C_GSound::InputByteCheckPort(uint16_t port) { return ((port & 0xFF) == 0xB3 || (port & 0xFF) == 0xBB); } bool C_GSound::OutputByteCheckPort(uint16_t port) { return ((port & 0xFF) == 0xB3 || (port & 0xFF) == 0xBB); } bool C_GSound::OnInputByte(uint16_t port, uint8_t& retval) { Update(devClk); if ((port & 0xFF) == 0xB3) { retval = regOutput; regStatus &= ~0x80; } else { retval = regStatus; } return true; } bool C_GSound::OnOutputByte(uint16_t port, uint8_t value) { Update(devClk); if ((port & 0xFF) == 0xB3) { regData = value; regStatus |= 0x80; } else { regCommand = value; regStatus |= 0x01; } return true; } void C_GSound::OnFrameStart(void) { if (SHOULD_OUTPUT_SOUND) { sndRenderer.StartFrame(); } } void C_GSound::OnAfterFrameRender(void) { Update(lastDevClk); gsClk -= GS_DEV_TO_CLK(lastDevClk); if (SHOULD_OUTPUT_SOUND) { sndRenderer.EndFrame(lastDevClk); } } void C_GSound::Reset(void) { if (!gsCpu) { return; } for (int i = 0; i < 4; i++) { volume[i] = 0; channel[i] = 0; } memPage = 0; UpdateMaps(); z80ex_reset(gsCpu); } void C_GSound::UpdateMaps() { readMap[0] = mem; readMap[1] = &mem[0x8000 + 0x4000]; readMap[2] = &mem[0x8000 * memPage]; readMap[3] = &mem[0x8000 * memPage + 0x4000]; writeMap[0] = nullptr; writeMap[1] = &mem[0x8000 + 0x4000]; writeMap[2] = (memPage == 0 ? nullptr : &mem[0x8000 * memPage]); writeMap[3] = (memPage == 0 ? nullptr : &mem[0x8000 * memPage + 0x4000]); } void C_GSound::Update(unsigned clk) { unsigned nextGsClk = GS_DEV_TO_CLK(clk); unsigned nextIntClk = gsClk - (gsClk % GS_INT_PERIOD) + GS_INT_PERIOD; if ((gsClk % GS_INT_PERIOD) < 32) { unsigned tmp = gsClk - (gsClk % GS_INT_PERIOD) + 32; while (gsClk < tmp && gsClk < nextGsClk) { gsClk += (unsigned)z80ex_int(gsCpu); gsClk += (unsigned)z80ex_step(gsCpu); } } while (gsClk < nextGsClk) { while (gsClk < nextIntClk && gsClk < nextGsClk) { gsClk += (unsigned)z80ex_step(gsCpu); } if (gsClk >= nextIntClk && gsClk < nextGsClk) { unsigned tmp = nextIntClk + 32; while (gsClk < tmp && gsClk < nextGsClk) { gsClk += (unsigned)z80ex_int(gsCpu); gsClk += (unsigned)z80ex_step(gsCpu); } nextIntClk = gsClk - (gsClk % GS_INT_PERIOD) + GS_INT_PERIOD; } } } void C_GSound::UpdateSound() { unsigned lt = (unsigned)volume[0] * (unsigned)channel[0] + (unsigned)volume[1] * (unsigned)channel[1]; unsigned rt = (unsigned)volume[2] * (unsigned)channel[2] + (unsigned)volume[3] * (unsigned)channel[3]; sndRenderer.Update((unsigned)GS_CLK_TO_DEV(gsClk), (lt << 1) + (rt >> 4), (rt << 1) + (lt >> 4)); } uint8_t C_GSound::GsReadByte(Z80EX_CONTEXT_PARAM uint16_t addr, int m1_state, void* userData) { uint8_t value = readMap[(unsigned)addr >> 14][addr & 0x3FFF]; if ((addr & 0xE000) == 0x6000) { channel[(addr >> 8) & 3] = value; if (SHOULD_OUTPUT_SOUND) { UpdateSound(); } } return value; } void C_GSound::GsWriteByte(Z80EX_CONTEXT_PARAM uint16_t addr, uint8_t value, void* userData) { unsigned bank = (unsigned)addr >> 14; if (writeMap[bank]) { writeMap[bank][addr & 0x3FFF] = value; } } uint8_t C_GSound::GsInputByte(Z80EX_CONTEXT_PARAM uint16_t port, void* userData) { switch (port & 0x0F) { case 0x01: return regCommand; case 0x02: regStatus &= ~0x80; return regData; case 0x04: return regStatus; case 0x05: regStatus &= ~0x01; return 0xFF; case 0x0A: regStatus = 0x7E | (regStatus & 0x01) | (((memPage & 0x01) ^ 0x01) << 7); return 0xFF; case 0x0B: regStatus = 0x7E | (regStatus & 0x80) | ((volume[3] & 0x20) >> 5); return 0xFF; } return 0xFF; } void C_GSound::GsOutputByte(Z80EX_CONTEXT_PARAM uint16_t port, uint8_t value, void* userData) { switch (port & 0x0F) { case 0x00: memPage = value & GS_MEMPAGE_MASK; UpdateMaps(); return; case 0x03: regOutput = value; regStatus |= 0x80; return; case 0x05: regStatus &= ~0x01; return; case 0x06: // fallthrough case 0x07: // fallthrough case 0x08: // fallthrough case 0x09: volume[(port & 0x0F) - 0x06] = value & 0x3F; if (SHOULD_OUTPUT_SOUND) { UpdateSound(); } return; case 0x0A: regStatus = 0x7E | (regStatus & 0x01) | (((memPage & 0x01) ^ 0x01) << 7); return; case 0x0B: regStatus = 0x7E | (regStatus & 0x80) | ((volume[3] & 0x20) >> 5); return; } } uint8_t C_GSound::GsReadIntVec(Z80EX_CONTEXT_PARAM void* userData) { return 0xFF; }
25.294737
106
0.582605
RandomAmbersky
2267534e34d63891f44b645b369b0d3e6338c8ec
5,375
cpp
C++
application_kit/Pulse/CPUButton.cpp
return/BeOSSampleCode
ca5a319fecf425a69e944f3c928a85011563a932
[ "BSD-3-Clause" ]
5
2018-09-09T21:01:57.000Z
2022-03-27T10:01:27.000Z
application_kit/Pulse/CPUButton.cpp
return/BeOSSampleCode
ca5a319fecf425a69e944f3c928a85011563a932
[ "BSD-3-Clause" ]
null
null
null
application_kit/Pulse/CPUButton.cpp
return/BeOSSampleCode
ca5a319fecf425a69e944f3c928a85011563a932
[ "BSD-3-Clause" ]
5
2018-04-03T01:45:23.000Z
2021-05-14T08:23:01.000Z
//**************************************************************************************** // // File: CPUButton.cpp // // Written by: Daniel Switkin // // Copyright 1999, Be Incorporated // //**************************************************************************************** #include "CPUButton.h" #include "PulseApp.h" #include "PulseView.h" #include "Common.h" #include <interface/Alert.h> #include <stdlib.h> CPUButton::CPUButton(BRect rect, const char *name, const char *label, BMessage *message) : BControl(rect, name, label, message, B_FOLLOW_NONE, B_WILL_DRAW) { off_color.red = off_color.green = off_color.blue = 184; off_color.alpha = 255; SetValue(B_CONTROL_ON); SetViewColor(B_TRANSPARENT_COLOR); replicant = false; } CPUButton::CPUButton(BMessage *message) : BControl(message) { off_color.red = off_color.green = off_color.blue = 184; off_color.alpha = 255; replicant = true; } // Redraw the button depending on whether it's up or down void CPUButton::Draw(BRect rect) { bool value = (bool)Value(); if (value) SetHighColor(on_color); else SetHighColor(off_color); BRect bounds = Bounds(); BRect color_rect(bounds); color_rect.InsetBy(2, 2); if (value) { color_rect.bottom -= 1; color_rect.right -= 1; } FillRect(bounds); if (value) SetHighColor(80, 80, 80); else SetHighColor(255, 255, 255); BPoint start(0, 0); BPoint end(bounds.right, 0); StrokeLine(start, end); end.Set(0, bounds.bottom); StrokeLine(start, end); if (value) SetHighColor(32, 32, 32); else SetHighColor(216, 216, 216); start.Set(1, 1); end.Set(bounds.right - 1, 1); StrokeLine(start, end); end.Set(1, bounds.bottom - 1); StrokeLine(start, end); if (value) SetHighColor(216, 216, 216); else SetHighColor(80, 80, 80); start.Set(bounds.left + 1, bounds.bottom - 1); end.Set(bounds.right - 1, bounds.bottom - 1); StrokeLine(start, end); start.Set(bounds.right - 1, bounds.top + 1); StrokeLine(start, end); if (value) SetHighColor(255, 255, 255); else SetHighColor(32, 32, 32); start.Set(bounds.left, bounds.bottom); end.Set(bounds.right, bounds.bottom); StrokeLine(start, end); start.Set(bounds.right, bounds.top); StrokeLine(start, end); if (value) { SetHighColor(0, 0, 0); start.Set(bounds.left + 2, bounds.bottom - 2); end.Set(bounds.right - 2, bounds.bottom - 2); StrokeLine(start, end); start.Set(bounds.right - 2, bounds.top + 2); StrokeLine(start, end); } // Try to keep the text centered BFont font; GetFont(&font); int label_width = (int)font.StringWidth(Label()); int rect_width = bounds.IntegerWidth() - 1; int rect_height = bounds.IntegerHeight(); font_height fh; font.GetHeight(&fh); int label_height = (int)fh.ascent; int x_pos = (int)(((double)(rect_width - label_width) / 2.0) + 0.5); int y_pos = (rect_height - label_height) / 2 + label_height; MovePenTo(x_pos, y_pos); SetHighColor(0, 0, 0); SetDrawingMode(B_OP_OVER); DrawString(Label()); } // Track the mouse without blocking the window void CPUButton::MouseDown(BPoint point) { SetValue(!Value()); SetTracking(true); SetMouseEventMask(B_POINTER_EVENTS, B_LOCK_WINDOW_FOCUS); } void CPUButton::MouseUp(BPoint point) { if (Bounds().Contains(point)) Invoke(); SetTracking(false); } void CPUButton::MouseMoved(BPoint point, uint32 transit, const BMessage *message) { if (IsTracking()) { if (transit == B_ENTERED_VIEW || transit == B_EXITED_VIEW) SetValue(!Value()); } } status_t CPUButton::Invoke(BMessage *message) { int my_cpu = atoi(Label()) - 1; if (!LastEnabledCPU(my_cpu)) { _kset_cpu_state_(my_cpu, Value()); } else { BAlert *alert = new BAlert(NULL, "You can't disable the last active CPU.", "OK"); alert->Go(NULL); SetValue(!Value()); } return B_OK; } CPUButton *CPUButton::Instantiate(BMessage *data) { if (!validate_instantiation(data, "CPUButton")) return NULL; return new CPUButton(data); } status_t CPUButton::Archive(BMessage *data, bool deep) const { BControl::Archive(data, deep); data->AddString("add_on", APP_SIGNATURE); data->AddString("class", "CPUButton"); return B_OK; } void CPUButton::MessageReceived(BMessage *message) { switch(message->what) { case B_ABOUT_REQUESTED: { BAlert *alert = new BAlert("Info", "Pulse\n\nBy David Ramsey and Arve Hjønnevåg\nRevised by Daniel Switkin", "OK"); // Use the asynchronous version so we don't block the window's thread alert->Go(NULL); break; } case PV_REPLICANT_PULSE: { // Make sure we're consistent with our CPU int my_cpu = atoi(Label()) - 1; if (_kget_cpu_state_(my_cpu) != Value() && !IsTracking()) SetValue(!Value()); break; } default: BControl::MessageReceived(message); break; } } void CPUButton::UpdateColors(int32 color) { on_color.red = (color & 0xff000000) >> 24; on_color.green = (color & 0x00ff0000) >> 16; on_color.blue = (color & 0x0000ff00) >> 8; Draw(Bounds()); } void CPUButton::AttachedToWindow() { SetTarget(this); SetFont(be_plain_font); SetFontSize(10); if (replicant) { Prefs *prefs = new Prefs(); UpdateColors(prefs->normal_bar_color); delete prefs; } else { PulseApp *pulseapp = (PulseApp *)be_app; UpdateColors(pulseapp->prefs->normal_bar_color); } BMessenger messenger(this); messagerunner = new BMessageRunner(messenger, new BMessage(PV_REPLICANT_PULSE), 200000, -1); } CPUButton::~CPUButton() { delete messagerunner; }
26.875
118
0.674047
return
2269d8058ae221ea5b6ecb45445b5d120fc8466d
12,267
hpp
C++
snark-logic/libs-source/marshalling/include/nil/marshalling/types/adapter/sequence_elem_fixed_ser_length_field_prefix.hpp
idealatom/podlodkin-freeton-year-control
6aa96e855fe065c9a75c76da976a87fe2d1668e6
[ "MIT" ]
1
2021-09-14T18:09:38.000Z
2021-09-14T18:09:38.000Z
include/nil/marshalling/types/adapter/sequence_elem_fixed_ser_length_field_prefix.hpp
tonlabs/marshalling
b50ad116f652cc1d9132bc45a27ab4136dee6109
[ "MIT" ]
16
2020-12-16T15:46:53.000Z
2021-12-13T14:49:49.000Z
include/nil/marshalling/types/adapter/sequence_elem_fixed_ser_length_field_prefix.hpp
tonlabs/marshalling
b50ad116f652cc1d9132bc45a27ab4136dee6109
[ "MIT" ]
1
2022-01-12T10:53:21.000Z
2022-01-12T10:53:21.000Z
//---------------------------------------------------------------------------// // Copyright (c) 2017-2021 Mikhail Komarov <nemo@nil.foundation> // Copyright (c) 2020-2021 Nikita Kaskov <nbering@nil.foundation> // // MIT License // // 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 MARSHALLING_SEQUENCE_ELEM_FIXED_SER_LENGTH_FIELD_PREFIX_HPP #define MARSHALLING_SEQUENCE_ELEM_FIXED_SER_LENGTH_FIELD_PREFIX_HPP #include <iterator> #include <nil/marshalling/assert_type.hpp> #include <nil/marshalling/status_type.hpp> #include <nil/marshalling/types/detail/common_funcs.hpp> namespace nil { namespace marshalling { namespace types { namespace adapter { template<typename TLenField, status_type TStatus, typename TBase> class sequence_elem_fixed_ser_length_field_prefix : public TBase { using base_impl_type = TBase; using len_field_type = TLenField; static_assert(!len_field_type::is_version_dependent(), "Prefix fields must not be version dependent"); public: using value_type = typename base_impl_type::value_type; using element_type = typename base_impl_type::element_type; sequence_elem_fixed_ser_length_field_prefix() = default; explicit sequence_elem_fixed_ser_length_field_prefix(const value_type &val) : base_impl_type(val) { } explicit sequence_elem_fixed_ser_length_field_prefix(value_type &&val) : base_impl_type(std::move(val)) { } sequence_elem_fixed_ser_length_field_prefix(const sequence_elem_fixed_ser_length_field_prefix &) = default; sequence_elem_fixed_ser_length_field_prefix(sequence_elem_fixed_ser_length_field_prefix &&) = default; sequence_elem_fixed_ser_length_field_prefix & operator=(const sequence_elem_fixed_ser_length_field_prefix &) = default; sequence_elem_fixed_ser_length_field_prefix & operator=(sequence_elem_fixed_ser_length_field_prefix &&) = default; std::size_t length() const { return length_internal(Len_field_length_tag()); } static constexpr std::size_t min_length() { return len_field_type::min_length() + base_impl_type::min_length(); } static constexpr std::size_t max_length() { return detail::common_funcs::max_supported_length(); } template<typename TIter> status_type read_element(element_type &elem, TIter &iter, std::size_t &len) const { MARSHALLING_ASSERT(elemLen_ < max_length_limit); if (len < elemLen_) { return status_type::not_enough_data; } std::size_t elemLen = elemLen_; status_type es = base_impl_type::read_element(elem, iter, elemLen); if (es == status_type::not_enough_data) { return TStatus; } if (es != status_type::success) { return es; } MARSHALLING_ASSERT(elemLen <= elemLen_); std::advance(iter, elemLen); len -= elemLen_; return status_type::success; } template<typename TIter> void read_element_no_status(element_type &elem, TIter &iter) const = delete; template<typename TIter> status_type read(TIter &iter, std::size_t len) { status_type es = read_len(iter, len); if (es != status_type::success) { return es; } return detail::common_funcs::read_sequence(*this, iter, len); } template<typename TIter> void read_no_status(TIter &iter) = delete; template<typename TIter> status_type read_n(std::size_t count, TIter &iter, std::size_t &len) { if (0U < count) { status_type es = read_len(iter, len); if (es != status_type::success) { return es; } } else { elemLen_ = 0U; } return detail::common_funcs::read_sequence_n(*this, count, iter, len); } template<typename TIter> void read_no_status_n(std::size_t count, TIter &iter) = delete; template<typename TIter> status_type write(TIter &iter, std::size_t len) const { if (!base_impl_type::value().empty()) { status_type es = write_len(iter, len); // len is updated if (es != status_type::success) { return es; } } return detail::common_funcs::write_sequence(*this, iter, len); } template<typename TIter> void write_no_status(TIter &iter) const { if (!base_impl_type::value().empty()) { write_len_no_status(iter); } detail::common_funcs::write_sequence_no_status(*this, iter); } template<typename TIter> status_type write_n(std::size_t count, TIter &iter, std::size_t &len) const { if (0U < count) { status_type es = write_len(iter, len); // len is updated if (es != status_type::success) { return es; } } return detail::common_funcs::write_sequence_n(*this, count, iter, len); } template<typename TIter> void write_no_status_n(std::size_t count, TIter &iter) const { if (0U < count) { write_len_no_status(iter); } detail::common_funcs::write_sequence_no_status_n(*this, count, iter); } private: struct fixed_length_len_field_tag { }; struct var_length_len_field_tag { }; using Len_field_length_tag = typename std::conditional<len_field_type::min_length() == len_field_type::max_length(), fixed_length_len_field_tag, var_length_len_field_tag>::type; std::size_t length_internal(fixed_length_len_field_tag) const { std::size_t prefixLen = 0U; if (!base_impl_type::value().empty()) { prefixLen = len_field_type::min_length(); } return (prefixLen + base_impl_type::length()); } std::size_t length_internal(var_length_len_field_tag) const { std::size_t prefixLen = 0U; if (!base_impl_type::value().empty()) { len_field_type lenField; lenField.value() = base_impl_type::min_element_length(); prefixLen = lenField.length(); } return (prefixLen + base_impl_type::length()); } template<typename TIter> static void advance_write_iterator(TIter &iter, std::size_t len) { detail::common_funcs::advance_write_iterator(iter, len); } template<typename TIter> status_type read_len(TIter &iter, std::size_t &len) { len_field_type lenField; status_type es = lenField.read(iter, len); if (es != status_type::success) { return es; } len -= lenField.length(); elemLen_ = static_cast<std::size_t>(lenField.value()); if (elemLen_ == max_length_limit) { return TStatus; } return status_type::success; } template<typename TIter> status_type write_len(TIter &iter, std::size_t &len) const { std::size_t elemLength = base_impl_type::min_element_length(); len_field_type lenField; lenField.value() = elemLength; status_type es = lenField.write(iter, len); if (es != status_type::success) { return es; } len -= lenField.length(); return es; } template<typename TIter> void write_len_no_status(TIter &iter) const { std::size_t elemLength = base_impl_type::min_element_length(); len_field_type lenField; lenField.value() = elemLength; lenField.write_no_status(iter); } static_assert( base_impl_type::min_element_length() == base_impl_type::max_element_length(), "Option sequence_elem_fixed_ser_length_field_prefix can be used only with fixed length " "elements."); static_assert(1U <= len_field_type::min_length(), "Invalid min length assumption"); static const std::size_t max_length_limit = std::numeric_limits<std::size_t>::max(); std::size_t elemLen_ = max_length_limit; }; } // namespace adapter } // namespace types } // namespace marshalling } // namespace nil #endif // MARSHALLING_SEQUENCE_ELEM_FIXED_SER_LENGTH_FIELD_PREFIX_HPP
45.265683
119
0.494987
idealatom
226b4a512e525eef70063a4620218c32dbcd0403
2,070
cpp
C++
src/base/base.cpp
salamanderrake/skeleton
1b7a5366be6bd6cfd31a0e3b3bd94fede6bfb547
[ "MIT" ]
2
2019-11-13T05:56:38.000Z
2019-12-20T05:43:18.000Z
src/base/base.cpp
ericwomer/skeleton
1b7a5366be6bd6cfd31a0e3b3bd94fede6bfb547
[ "MIT" ]
null
null
null
src/base/base.cpp
ericwomer/skeleton
1b7a5366be6bd6cfd31a0e3b3bd94fede6bfb547
[ "MIT" ]
1
2019-09-06T08:18:23.000Z
2019-09-06T08:18:23.000Z
#include "base.h" #include "config.h" #include <iostream> #include <string> using std::cerr; using std::cout; using std::exception; using std::string; using std::vector; namespace Base { Application::Application() : app_name(project_name) , version_number({Major, Minor, Patch, Compile}) { log_init("Application"); app_description.emplace_back(std::string(app_name)); app_description.emplace_back(std::string("** nothing else follows ** \n")); }; // This is Base::Application::main auto Application::main(vector<string>& params) -> int { executable_name = params[0]; executable_name.erase(0, 2); // Remove the now un-needed application name from the list of handled parameters. params.erase(params.begin()); vector<string> child; // Process the parameters if applicable at this time. for (auto& param : params) { if (param == "--help" || param == "-h") { version(); help(); child.emplace_back("exit"); break; } else if (param == "--version" || param == "-v") { version(); child.emplace_back("exit"); break; } else { // Eric: set this up to pass the remainder params back to the child for the derived class to handle custom parameters child.emplace_back(param); } } // Pass the non default parameters to the child process that called the derived main params.clear(); params = child; return EXIT_SUCCESS; } auto Application::help() const -> void { std::cout << "Usage: " << executable_name << " [options] files...\n"; std::cout << "Options: \n"; std::cout << " -h, --help \t\t Print this help message and exit the program.\n"; std::cout << " -v, --version \t\t Print the version and exit.\n\n"; }; auto Application::version() const -> void { std::cout << app_name << " version " << version_number << "\n"; std::cout << "Compiler: \t\t" << compiler_name << " " << compiler_version << "\n"; std::cout << "Operating System: \t" << operating_system << "\n"; std::cout << "Architecture: \t\t" << cpu_family << "\n\n"; }; } // namespace Base
26.538462
131
0.637681
salamanderrake
22704c1e14540aefdb497919830b6bc84f15b266
12,624
cpp
C++
ufs/ufsd/src/apfs/apfshash.cpp
hekkihek/paragon_apfs_sdk_ce
d1ea911e20247b349da2701d8db5f80803eb4e4e
[ "BSD-3-Clause-Clear" ]
82
2019-07-01T17:50:01.000Z
2022-03-27T14:27:08.000Z
ufs/ufsd/src/apfs/apfshash.cpp
cheech790/paragon_apfs_sdk_ce
f91e2b65967cbc2b4ded7c78925cc995cb37c8a0
[ "BSD-3-Clause-Clear" ]
2
2019-07-01T22:26:43.000Z
2020-01-09T14:42:45.000Z
ufs/ufsd/src/apfs/apfshash.cpp
cheech790/paragon_apfs_sdk_ce
f91e2b65967cbc2b4ded7c78925cc995cb37c8a0
[ "BSD-3-Clause-Clear" ]
22
2019-07-21T11:29:05.000Z
2022-02-09T17:00:32.000Z
// <copyright file="apfshash.cpp" company="Paragon Software Group"> // // Copyright (c) 2002-2019 Paragon Software Group, All rights reserved. // // The license for this file is defined in a separate document "LICENSE.txt" // located at the root of the project. // // </copyright> ///////////////////////////////////////////////////////////////////////////// // // Decompose functions and tables based on ICU library // // Revision History : // // 05-October-2017 - created. // ///////////////////////////////////////////////////////////////////////////// #include "../h/versions.h" #ifdef UFSD_APFS #ifdef UFSD_TRACE_ERROR static const char s_pFileName[] = __FILE__ ",$Revision: 331828 $"; #endif #include <ufsd.h> #include "../h/crc32.h" #include "../h/assert.h" #ifdef BASE_BIGENDIAN #include "../h/uswap.h" #endif #include "apfshash.h" namespace UFSD { namespace apfs { /////////////////////////////////////////////////////////// static unsigned int decomp_idx(unsigned int cp) { if (cp >= 195102) return 0; return decomp_idx_t2[(decomp_idx_t1[cp >> 6] << 6) + (cp & 63)]; } /////////////////////////////////////////////////////////// static size_t unicode_decompose(unsigned int pt, unsigned int out[4]) { // Special-case: Hangul decomposition if (pt >= 0xAC00 && pt < 0xD7A4) { out[0] = 0x1100 + (pt - 0xAC00) / 588; out[1] = 0x1161 + ((pt - 0xAC00) % 588) / 28; if ((pt - 0xAC00) % 28) { out[2] = 0x11A7 + (pt - 0xAC00) % 28; return 3; } return 2; } // Otherwise, look up in the decomposition table unsigned int decomp_start_idx = decomp_idx(pt); if (!decomp_start_idx) { out[0] = pt; return 1; } size_t length = (decomp_start_idx >> 14) + 1; if (length > 4) { assert(!"Number of code points is too big"); return 0; } decomp_start_idx &= (1 << 14) - 1; for (size_t i = 0; i < length; i++) out[i] = xref[decomp_seq[decomp_start_idx + i]]; return length; } /////////////////////////////////////////////////////////// // utf8ToU32Code // // /////////////////////////////////////////////////////////// int utf8ToU32Code( IN int cp, IN OUT const unsigned char** next, IN const unsigned char* end ) { const unsigned char* n = *next; unsigned char v0 = *n ^ 0x80; if ( cp - 0xE1 <= 0xB && n + 1 < end && v0 <= 0x3F ) { unsigned char v1 = n[1] ^ 0x80; if ( v1 <= 0x3F ) { *next += 2; return v1 | (v0 << 6) | ((cp & 0xF) << 12); } } if ( cp - 0xC2 <= 0x1D && n < end && v0 <= 0x3F ) { *next += 1; return v0 | ((cp & 0x1F) << 6); } unsigned int d; if ( cp <= 0xEF ) d = (cp > 0xBF) + (cp > 0xDF); else if ( cp > 0xFD ) d = 0; else d = (cp > 0xF7) + (cp > 0xFB) + 3; int ret = -1; if ( n + d <= end ) { int v = cp & ((1 << (6 - d)) - 1); if ( d != 1 ) { if ( d != 2 ) { if ( d != 3 || v0 > 0x3F ) return -1; v = v0 | (v << 6); if ( v > 271 ) return -1; ++n; } if ( v0 > 0x3Fu ) return -1; ++n; v = v0 | (v << 6); if ( (v & 0xFFE0) == 864 ) return -1; } v0 = *n++ ^ 0x80; if ( v0 > 0x3Fu ) return -1; ret = (v << 6) | v0; if ( static_cast<unsigned>(ret) < utf8_minLegal[d] ) return -1; } *next = n; return ret; } /////////////////////////////////////////////////////////// static unsigned int lowercase_offset(unsigned int cp) { if (cp >= 66600) return 0; int offset_index = lowercase_offset_t2[(lowercase_offset_t1[cp >> 6] << 6) + (cp & 63)]; return lowercase_offset_values[offset_index]; } /////////////////////////////////////////////////////////// int NormalizeAndCalcHash( IN const unsigned char* Name, IN size_t NameLen, IN bool CaseSensitive, OUT unsigned int* Hash ) { DRIVER_ONLY(const unsigned char* n0 = Name); const unsigned char* NameEnd = Name + NameLen; unsigned int databuf[4] = { 0 }; size_t bytes; while (Name < NameEnd) { const unsigned char* s = Name++; if (*s == 0) break; if (*s < 0x80) { databuf[0] = static_cast<unsigned char>(*s - 0x41) >= 0x1A ? *s : CaseSensitive ? *s : (*s + 0x20); bytes = 1; } else { int uCode = utf8ToU32Code(*s, &Name, NameEnd); if (uCode <= 0) { UFSDTracek(( NULL, "utf8 failed to convert '%.*s' to unicode. Pos %" PZZ "u, error %d, chars %02X %02X %02X", (int)NameLen, n0, PtrOffset(n0, Name), uCode, *s, PtrOffset(Name, NameEnd) > 1 ? s[1] : 0, PtrOffset(Name, NameEnd) > 2 ? s[2] : 0)); return ERR_BADNAME; } bytes = unicode_decompose(uCode, databuf); if (!CaseSensitive) { // TODO: Check wrong decoded symbols if (uCode == 0x3d1) // GREEK THETA SYMBOL --> GREEK SMALL LETTER THETA databuf[0] = 0x3b8; else if (uCode == 0x1fc2) // COMBINING GREEK YPOGEGRAMMENI --> GREEK SMALL LETTER IOTA databuf[2] = 0x3b9; else if (uCode == 0xdf) // U+00DF (c3 9f) --> U+0073 LATIN SMALL LETTER S + U+0073 LATIN SMALL LETTER S { databuf[0] = databuf[1] = 0x73; bytes = 2; } else databuf[0] += lowercase_offset(databuf[0]); } } #ifdef BASE_BIGENDIAN for (size_t i = 0; databuf[i] && (i < 3); ++i) SwapBytesInPlace(&databuf[i]); #endif *Hash = crc32c(*Hash, databuf, 4 * bytes); } return ERR_NOERROR; } ///////////////////////////////////////////////////////////////////////////// static int NamesCmp( IN const unsigned char* Name1, IN size_t Len1, IN const unsigned char* Name2, IN size_t Len2, IN bool bCaseSensitive ) { const unsigned char* Name1End = Name1 + Len1; const unsigned char* Name2End = Name2 + Len2; while (Name1 < Name1End && Name2 < Name2End) { const unsigned char* s1 = Name1++; const unsigned char* s2 = Name2++; int u1; int u2; if (*s1 == 0 || *s2 == 0) break; if (*s1 < 0x80) u1 = static_cast<unsigned char>(*s1 - 0x41) >= 0x1A ? *s1 : bCaseSensitive ? *s1 : (*s1 + 0x20); else { u1 = utf8ToU32Code(*s1, &Name1, Name1End); if (!bCaseSensitive) u1 += lowercase_offset(u1); } if (*s2 < 0x80) u2 = static_cast<unsigned char>(*s2 - 0x41) >= 0x1A ? *s2 : bCaseSensitive ? *s2 : (*s2 + 0x20); else { u2 = utf8ToU32Code(*s2, &Name2, Name2End); if (!bCaseSensitive) u2 += lowercase_offset(u2); } if (u1 <= 0 || u2 <= 0) { assert(!"Bad name"); return ERR_BADNAME; } if (u1 != u2) return u1 - u2; } assert(Len1 != Len2 || (Name1 == Name1End && Name2 == Name2End)); return static_cast<int>(Len1 - Len2); } ///////////////////////////////////////////////////////////////////////////// bool IsNamesEqual( IN const unsigned char* Name1, IN size_t NameLen1, IN const unsigned char* Name2, IN size_t NameLen2, IN bool bCaseSensitive ) { return NamesCmp(Name1, NameLen1, Name2, NameLen2, bCaseSensitive) == 0; } #if 0 #include "../h/utrace.h" ///////////////////////////////////////////////////////////////////////////// static unsigned int GetNameHash(const unsigned char* Name, size_t NameLen) { unsigned int hash = ~0u; int Status = NormalizeAndCalcHash(Name, NameLen, false, &hash); if (!UFSD_SUCCESS(Status)) return 0; return (hash & 0x3FFFFF) << 2; } ///////////////////////////////////////////////////////////////////////////// void BruteHash(api::IBaseLog* Log, unsigned int Expected) { #ifndef UFSD_TRACE UNREFERENCED_PARAMETER(Log); #endif unsigned int data[3] = { 0 }; for (data[0] = 0; data[0] < 0xFFF; ++data[0]) for (data[1] = 0; data[1] < 0xFFF; ++data[1]) //for (data[2] = 0; data[2] < 0xFFF; ++data[2]) { unsigned int size = 4; if (data[1]) size += 4; if (data[2]) size += 4; unsigned int h = crc32c(~0u, data, size); unsigned int hash = (h & 0x3FFFFF) << 2; if (hash == Expected) ULOG_TRACE((Log, "data: %04x %04x %04x", data[0], data[1], data[2])); } ULOG_TRACE((Log, "Bruteforcing finished")); } ///////////////////////////////////////////////////////////////////////////// int TestHash() { const unsigned char root[] = { 'r', 'o', 'o', 't' }; unsigned int hash = GetNameHash(root, sizeof(root)); if (hash != 0xb671e4) return ERR_NOT_SUCCESS; const unsigned char private_dir[] = { 'p', 'r', 'i', 'v', 'a', 't', 'e', '-', 'd', 'i', 'r' }; hash = GetNameHash(private_dir, sizeof(private_dir)); if (hash != 0xaca68c) return ERR_NOT_SUCCESS; assert(IsNamesEqual(root, sizeof(root), root, sizeof(root), true)); assert(NamesCmp(root, sizeof(root), private_dir, sizeof(private_dir), true) > 0); assert(NamesCmp(private_dir, sizeof(private_dir), root, sizeof(root), true) < 0); // 03 50 d6 1e d0 90 00 const unsigned char rusA[] = { 0xd0, 0x90 }; hash = GetNameHash(rusA, sizeof(rusA)); if (hash != 0x1ed650) return ERR_NOT_SUCCESS; // 03 48 c9 44 d0 99 00 const unsigned char rusIi[] = { 0xd0, 0x99 }; hash = GetNameHash(rusIi, sizeof(rusIi)); if (hash != 0x44c948) return ERR_NOT_SUCCESS; // 03 a4 53 92 d0 af 00 const unsigned char rusYa[] = { 0xd0, 0xaf }; hash = GetNameHash(rusYa, sizeof(rusYa)); if (hash != 0x9253a4) return ERR_NOT_SUCCESS; // 05 58 bd f1 d0 90 d0 99 00 const unsigned char rusAIi[] = { 0xd0, 0x90, 0xd0, 0x99 }; hash = GetNameHash(rusAIi, sizeof(rusAIi)); if (hash != 0xf1bd58) return ERR_NOT_SUCCESS; assert(NamesCmp(rusA, sizeof(rusA), rusIi, sizeof(rusIi), true) < 0); assert(NamesCmp(rusYa, sizeof(rusYa), rusIi, sizeof(rusIi), true) > 0); assert(NamesCmp(rusA, sizeof(rusA), rusAIi, sizeof(rusAIi), true) < 0); assert(NamesCmp(rusAIi, sizeof(rusAIi), rusA, sizeof(rusA), true) > 0); const unsigned char jpn[] = { 0xe6, 0x96, 0xb0, 0xe3, 0x81, 0x97, 0xe3, 0x81, 0x84, 0xe3, 0x83, 0x95, 0xe3, 0x82, 0xa1, 0xe3, 0x82, 0xa4, 0xe3, 0x83, 0xab, 0x2e, 0x6a, 0x70, 0x6e }; hash = GetNameHash(jpn, sizeof(jpn)); if (hash != 0xB4101C) return ERR_NOT_SUCCESS; // 03 b4 7b 98 c3 85 00 const unsigned char Angstrem[] = { 0xc3, 0x85 }; hash = GetNameHash(Angstrem, sizeof(Angstrem)); if (hash != 0x987bb4) return ERR_NOT_SUCCESS; // 04 4c 33 83 e2 92 b6 00 const unsigned char u24b6[] = { 0xe2, 0x92, 0xb6 }; hash = GetNameHash(u24b6, sizeof(u24b6)); if (hash != 0x83334c) return ERR_NOT_SUCCESS; // 04 d4 bc 92 e2 92 be 00 const unsigned char u24be[] = { 0xe2, 0x92, 0xbe }; hash = GetNameHash(u24be, sizeof(u24be)); if (hash != 0x92bcd4) return ERR_NOERROR; // 10 c0 08 00 66 69 6c 65 5f 30 78 32 34 62 65 5f e2 92 be 00 - file_0x24be_ const unsigned char File_24be[] = { 0x66, 0x69, 0x6c, 0x65, 0x5f, 0x30, 0x78, 0x32, 0x34, 0x62, 0x65, 0x5f, 0xe2, 0x92, 0xbe }; hash = GetNameHash(File_24be, sizeof(File_24be)); if (hash != 0x0008c0) return ERR_NOT_SUCCESS; // 03 90 ec 4d cf 91 00 const unsigned char u3d1[] = { 0xcf, 0x91 }; hash = GetNameHash(u3d1, sizeof(u3d1)); if (hash != 0x4dec90) return ERR_NOT_SUCCESS; // 04 44 c3 2e e1 bf 82 00 const unsigned char u1fc2[] = { 0xe1, 0xbf, 0x82 }; hash = GetNameHash(u1fc2, sizeof(u1fc2)); if (hash != 0x2ec344) return ERR_NOT_SUCCESS; // 03 ac 79 80 c3 9f 00 - U+00DF --> c3 9f LATIN SMALL LETTER SHARP S const unsigned char udf[] = { 0xc3, 0x9f }; hash = GetNameHash(udf, sizeof(udf)); if (hash != 0x8079ac) return ERR_NOT_SUCCESS; // 04 3c d5 ed ef bc 8b 00 - U+FF0B const unsigned char uPlus[] = { 0xef, 0xbc, 0x8b }; hash = GetNameHash( uPlus, sizeof( uPlus ) ); if ( hash != 0xedd53c ) return ERR_NOT_SUCCESS; return ERR_NOERROR; } #endif } // namespace apfs } // namespace UFSD #endif // UFSD_APFS
26.354906
184
0.51212
hekkihek
227646ac9489a9c4a9cf517de63fd4c49d9e964d
3,432
cpp
C++
Grbl_Esp32/src/WebUI/InputBuffer.cpp
ghjklzx/ESP32-E-support
03e081d3f6df613ff1f215ba311bec3fb7baa8ed
[ "MIT" ]
49
2021-12-15T12:57:20.000Z
2022-02-07T12:22:10.000Z
Firmware/Grbl_Esp32-main/Grbl_Esp32/src/WebUI/InputBuffer.cpp
pspadale/Onyx-Stepper-Motherboard
e94e6cc2e40869f6ee395a3f6e52c81307373971
[ "MIT" ]
null
null
null
Firmware/Grbl_Esp32-main/Grbl_Esp32/src/WebUI/InputBuffer.cpp
pspadale/Onyx-Stepper-Motherboard
e94e6cc2e40869f6ee395a3f6e52c81307373971
[ "MIT" ]
10
2021-12-15T12:57:24.000Z
2022-01-17T22:47:33.000Z
/* InputBuffer.cpp - inputbuffer functions class Copyright (c) 2014 Luc Lebosse. All rights reserved. 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "../Config.h" #include "InputBuffer.h" namespace WebUI { InputBuffer inputBuffer; InputBuffer::InputBuffer() { _RXbufferSize = 0; _RXbufferpos = 0; } void InputBuffer::begin() { _RXbufferSize = 0; _RXbufferpos = 0; } void InputBuffer::end() { _RXbufferSize = 0; _RXbufferpos = 0; } InputBuffer::operator bool() const { return true; } int InputBuffer::available() { return _RXbufferSize; } int InputBuffer::availableforwrite() { return RXBUFFERSIZE - _RXbufferSize; } size_t InputBuffer::write(uint8_t c) { if ((1 + _RXbufferSize) <= RXBUFFERSIZE) { int current = _RXbufferpos + _RXbufferSize; if (current > RXBUFFERSIZE) { current = current - RXBUFFERSIZE; } if (current > (RXBUFFERSIZE - 1)) { current = 0; } _RXbuffer[current] = c; current++; _RXbufferSize += 1; return 1; } return 0; } size_t InputBuffer::write(const uint8_t* buffer, size_t size) { //No need currently //keep for compatibility return size; } int InputBuffer::peek(void) { if (_RXbufferSize > 0) { return _RXbuffer[_RXbufferpos]; } else { return -1; } } bool InputBuffer::push(const char* data) { int data_size = strlen(data); if ((data_size + _RXbufferSize) <= RXBUFFERSIZE) { int current = _RXbufferpos + _RXbufferSize; if (current > RXBUFFERSIZE) { current = current - RXBUFFERSIZE; } for (int i = 0; i < data_size; i++) { if (current > (RXBUFFERSIZE - 1)) { current = 0; } _RXbuffer[current] = data[i]; current++; } _RXbufferSize += strlen(data); return true; } return false; } int InputBuffer::read(void) { if (_RXbufferSize > 0) { int v = _RXbuffer[_RXbufferpos]; _RXbufferpos++; if (_RXbufferpos > (RXBUFFERSIZE - 1)) { _RXbufferpos = 0; } _RXbufferSize--; return v; } else { return -1; } } void InputBuffer::flush(void) { //No need currently //keep for compatibility } InputBuffer::~InputBuffer() { _RXbufferSize = 0; _RXbufferpos = 0; } }
27.902439
81
0.562354
ghjklzx
22773d4c8c48b40b7975e3734befeeddea72fbfe
2,876
hpp
C++
c++/include/objmgr/impl/tse_loadlock.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/include/objmgr/impl/tse_loadlock.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/include/objmgr/impl/tse_loadlock.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef OBJECTS_OBJMGR_IMPL___TSE_LOADLOCK__HPP #define OBJECTS_OBJMGR_IMPL___TSE_LOADLOCK__HPP /* $Id: tse_loadlock.hpp 103491 2007-05-04 17:18:18Z kazimird $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Eugene Vasilchenko * * File Description: * CTSE_Lock -- class to lock TSEs from garbage collector * */ #include <corelib/ncbiobj.hpp> #include <objmgr/impl/tse_info.hpp> #include <objmgr/impl/data_source.hpp> BEGIN_NCBI_SCOPE BEGIN_SCOPE(objects) class CTSE_Info; class NCBI_XOBJMGR_EXPORT CTSE_LoadLock { public: CTSE_LoadLock(void) { } ~CTSE_LoadLock(void) { Reset(); } CTSE_LoadLock(const CTSE_LoadLock& lock) { *this = lock; } CTSE_LoadLock& operator=(const CTSE_LoadLock& lock); DECLARE_OPERATOR_BOOL_REF(m_Info); CTSE_Info& operator*(void) { return *m_Info; } const CTSE_Info& operator*(void) const { return *m_Info; } CTSE_Info* operator->(void) { return &*m_Info; } bool IsLoaded(void) const; void SetLoaded(void); void Reset(void); void ReleaseLoadLock(void); protected: friend class CDataSource; //void x_SetLoadLock(CDataSource* ds, CTSE_Info* info); private: CRef<CTSE_Info> m_Info; mutable CRef<CDataSource> m_DataSource; CRef<CObject> m_LoadLock; }; ///////////////////////////////////////////////////////////////////// // // Inline methods // ///////////////////////////////////////////////////////////////////// END_SCOPE(objects) END_NCBI_SCOPE #endif//OBJECTS_OBJMGR_IMPL___TSE_LOADLOCK__HPP
27.390476
77
0.617177
OpenHero
227b92cac071ce407074f2298d4af170ba53864b
6,344
cc
C++
core/PiiVersionNumber.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-19T22:14:18.000Z
2020-04-13T23:27:20.000Z
core/PiiVersionNumber.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
null
null
null
core/PiiVersionNumber.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-16T05:43:15.000Z
2019-01-29T07:57:11.000Z
/* This file is part of Into. * Copyright (C) Intopii 2013. * All rights reserved. * * Licensees holding a commercial Into license may use this file in * accordance with the commercial license agreement. Please see * LICENSE.commercial for commercial licensing terms. * * Alternatively, this file may be used under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. In addition, Intopii gives you special rights * to use Into as a part of open source software projects. Please * refer to LICENSE.AGPL3 for details. */ #include "PiiVersionNumber.h" #include <QStringList> const QStringList PiiVersionNumber::_lstGreekLetters = QStringList() << "alpha" << "beta" << "gamma" << "delta" << "epsilon" << "zeta" << "eta" << "theta" << "iota" << "kappa" << "lambda" << "mu" << "nu" << "xi" << "omicron" << "pi" << "rho" << "sigma" << "tau" << "upsilon" << "phi" << "chi" << "psi" << "omega"; PiiVersionNumber::Data::Data() { } PiiVersionNumber::Data::Data(const Data& other) : vecParts(other.vecParts), strRevision(other.strRevision), lstRevisionParts(other.lstRevisionParts) { } PiiVersionNumber::PiiVersionNumber(int major, int minor, int patch, const QString& revision) : d(new Data) { d->strRevision = revision; if (major >= 0) { d->vecParts << major; if (minor >= 0) { d->vecParts << minor; if (patch >= 0) d->vecParts << patch; } } d->lstRevisionParts = revision.split('-', QString::SkipEmptyParts); } PiiVersionNumber::PiiVersionNumber(const QString& versionString) : d(new Data) { setVersionString(versionString); } PiiVersionNumber::PiiVersionNumber(const PiiVersionNumber& other) : d(new Data(*other.d)) { } PiiVersionNumber::~PiiVersionNumber() { delete d; } PiiVersionNumber& PiiVersionNumber::operator= (const PiiVersionNumber& other) { if (this != &other) { d->vecParts = other.d->vecParts; d->strRevision = other.d->strRevision; d->lstRevisionParts = other.d->lstRevisionParts; } return *this; } bool PiiVersionNumber::hasRevision() const { return !d->strRevision.isEmpty(); } QString PiiVersionNumber::revision() const { return d->strRevision; } QString PiiVersionNumber::toString() const { QString strResult; for (int i=0; i<d->vecParts.size(); ++i) { if (i > 0) strResult += '.'; strResult += QString::number(d->vecParts[i]); } if (!d->strRevision.isEmpty()) strResult.append('-').append(d->strRevision); return strResult; } bool PiiVersionNumber::setVersionString(const QString& versionString) { int iDashIndex = versionString.indexOf('-'); d->vecParts.clear(); d->lstRevisionParts.clear(); if (iDashIndex >= 0) { d->strRevision = versionString.mid(iDashIndex+1); d->lstRevisionParts = d->strRevision.toLower().split('-', QString::SkipEmptyParts); } if (iDashIndex != 0) { // Split version number into pieces QStringList lstVersionParts = versionString.mid(0, iDashIndex).split('.'); // Check that each piece is a valid number and build a vector of // ints. for (int i=0; i<lstVersionParts.size(); ++i) { bool bSuccess = false; int iPart = lstVersionParts[i].toInt(&bSuccess); if (!bSuccess) { d->vecParts.clear(); return false; } d->vecParts << iPart; } } return true; } int PiiVersionNumber::part(int index) const { if (index >= 0 && index < d->vecParts.size()) return d->vecParts[index]; return 0; } int PiiVersionNumber::partCount() const { return d->vecParts.size(); } int PiiVersionNumber::compare(const PiiVersionNumber& other) const { // First compare version numbers int iMaxLen = qMax(d->vecParts.size(), other.d->vecParts.size()); for (int i=0; i<iMaxLen; ++i) { int iDiff = (i < d->vecParts.size() ? d->vecParts[i] : 0) - (i < other.d->vecParts.size() ? other.d->vecParts[i] : 0); if (iDiff < 0) return -1; else if (iDiff > 0) return 1; } // Compare revision parts iMaxLen = qMin(d->lstRevisionParts.size(), other.d->lstRevisionParts.size()); for (int i=0; i<iMaxLen; ++i) { bool bSuccess1 = false, bSuccess2 = false; int iPart1 = d->lstRevisionParts[i].toInt(&bSuccess1), iPart2 = other.d->lstRevisionParts[i].toInt(&bSuccess2); // Both are numeric if (bSuccess1 && bSuccess2) { if (iPart1 < iPart2) return -1; else if (iPart1 > iPart2) return 1; continue; } iPart1 = _lstGreekLetters.indexOf(d->lstRevisionParts[i]); iPart2 = _lstGreekLetters.indexOf(other.d->lstRevisionParts[i]); // Try to convert from Greek alphabet if (iPart1 != -1 && iPart2 != -1) { if (iPart1 < iPart2) return -1; else if (iPart1 > iPart2) return 1; continue; } // Finally, try alphabetical ordering iPart1 = d->lstRevisionParts[i].compare(other.d->lstRevisionParts[i]); if (iPart1 != 0) return iPart1; } // The version numbers are equal up to the last common part. Now, we // need to check the remaining parts. QString strTailPart; int iMultiplier = 0; if (d->lstRevisionParts.size() > other.d->lstRevisionParts.size()) { strTailPart = d->lstRevisionParts[iMaxLen]; iMultiplier = 1; } else if (d->lstRevisionParts.size() < other.d->lstRevisionParts.size()) { strTailPart = other.d->lstRevisionParts[iMaxLen]; iMultiplier = -1; } if (strTailPart.size() != 0) { // The version number with a numeric suffix is larger. If the // suffix is not a number, then it is smaller. bool bSuccess; strTailPart.toInt(&bSuccess); return bSuccess ? iMultiplier : -iMultiplier; } return 0; } bool PiiVersionNumber::operator== (const PiiVersionNumber& other) const { return d->vecParts == other.d->vecParts && d->strRevision == other.d->strRevision; } bool PiiVersionNumber::operator!= (const PiiVersionNumber& other) const { return d->vecParts != other.d->vecParts || d->strRevision != other.d->strRevision; }
27.111111
94
0.623581
topiolli
2280d9dd7af452d7e0dd043f706041cc4bd7e89a
1,312
cpp
C++
src/sensors/imu.cpp
germanespinosa/BirdFC
45cce791a55f5a4ae88f941038a50ce6935130ba
[ "Apache-2.0" ]
null
null
null
src/sensors/imu.cpp
germanespinosa/BirdFC
45cce791a55f5a4ae88f941038a50ce6935130ba
[ "Apache-2.0" ]
null
null
null
src/sensors/imu.cpp
germanespinosa/BirdFC
45cce791a55f5a4ae88f941038a50ce6935130ba
[ "Apache-2.0" ]
null
null
null
#include"imu.h" namespace bird { Imu::Imu() { sensor_set_.roll.update(); sensor_set_.pitch.update(); sensor_set_.yaw.update(); } bool Imu::update() { Imu::Imu_Data accelerometer = read_accelerometer(); Imu::Imu_Data gyroscope = read_gyroscope(); Imu::Imu_Data magnetometer = read_magnetometer(); sensor_set_.vertical.update_value(1-accelerometer.z * G); sensor_set_.lateral.update_value(accelerometer.x * G); sensor_set_.longitudinal.update_value(accelerometer.y * G); sensor_set_.roll = atan2(accelerometer.x, hypot(accelerometer.y,accelerometer.z)); sensor_set_.roll.variable.change_speed = gyroscope.x; sensor_set_.pitch = atan2(accelerometer.y, hypot(accelerometer.x,accelerometer.z)); sensor_set_.pitch.variable.change_speed = gyroscope.y; sensor_set_.yaw.update_value(gyroscope.z); double mag_x = magnetometer.x * cos(sensor_set_.pitch) + magnetometer.y * sin(sensor_set_.roll) * sin(sensor_set_.pitch) + magnetometer.z * cos(sensor_set_.roll) * sin(sensor_set_.pitch); double mag_y = magnetometer.y * cos(sensor_set_.roll) - magnetometer.z * sin(sensor_set_.roll); sensor_set_.yaw = atan2(-mag_y,mag_x); return true; } }
42.322581
197
0.671494
germanespinosa
2284c5de85fb1567382eb20b7e249d6ef8267cd2
4,668
hpp
C++
include/tone_mapping/ferwerda_tmo.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/tone_mapping/ferwerda_tmo.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/tone_mapping/ferwerda_tmo.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle 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/. */ #ifndef PIC_TONE_MAPPING_FERWERDA_TMO_HPP #define PIC_TONE_MAPPING_FERWERDA_TMO_HPP #include "../base.hpp" #include "../util/array.hpp" #include "../filtering/filter.hpp" #include "../filtering/filter_luminance.hpp" #include "../tone_mapping/tone_mapping_operator.hpp" namespace pic { /** * @brief The FerwerdaTMO class */ class FerwerdaTMO: public ToneMappingOperator { protected: float Ld_Max, Ld_a, Lw_a; FilterLuminance flt_lum; /** * @brief ProcessAux * @param imgIn * @param imgOut * @return */ Image *ProcessAux(ImageVec imgIn, Image *imgOut) { updateImage(imgIn[0]); //compute luminance and its statistics images[0] = flt_lum.Process(imgIn, images[0]); if(Lw_a < 0.0f) { float maxVal; images[0]->getMaxVal(NULL, &maxVal); Lw_a = maxVal / 2.0f; } float mC = Tp(Ld_a) / Tp(Lw_a); float mR = Ts(Ld_a) / Ts(Lw_a); float k = WalravenValetonK(Lw_a); int channels = imgIn[0]->channels; float *scale = new float[channels]; if(channels == 3) { scale[0] = 1.05f; scale[1] = 0.97f; scale[2] = 1.27f; } else { Arrayf::assign(1.0f, scale, channels); } for(int i = 0; i < channels; i++) { scale[i] *= (mR * k); } #pragma omp parallel for for(int i = 0; i < imgIn[0]->size(); i += channels) { int indexL = i / channels; for(int j = 0; j < channels; j++) { int index = i + j; imgOut->data[index] = imgIn[0]->data[index] * mC + images[0]->data[indexL] * scale[j]; } } //NOTE: this is done to have values in [0,1] and not in cd/m^2! *imgOut /= Ld_Max; return imgOut; } public: /** * @brief FerwerdaTMO * @param Ld_Max * @param Ld_a * @param Lw_a */ FerwerdaTMO(float Ld_Max = 100.0f, float Ld_a = 50.0f, float Lw_a = 50.0f) : ToneMappingOperator() { images.push_back(NULL); update(Ld_Max, Ld_a, Lw_a); } ~FerwerdaTMO() { release(); } /** * @brief update * @param Ld_Max * @param Ld_a * @param Lw_a */ void update(float Ld_Max = 100.0f, float Ld_a = 50.0f, float Lw_a = 50.0f) { this->Ld_Max = Ld_Max > 0.0f ? Ld_Max : 100.0f; this->Ld_a = Ld_a > 0.0f ? Ld_a : (this->Ld_Max / 2.0f); this->Lw_a = Lw_a; } /** * @brief Ts computes the gamma function used in Ferwerda TMO for Scotopic levels (rods' cells). * @param x * @return */ static float Ts(float x) { float t = log10f(x); float y; if(t <= -3.94f) { y = -2.86f; } else { if(t >= -1.44) { y = t - 0.395f; } else { y = powf(0.405f * t + 1.6f, 2.18f) - 2.86f; } } y = powf(10.0f, y); return y; } /** * @brief Tp computes the gamma function used in Ferwerda TMO for Photopic levels (cones' cells). * @param x * @return */ static float Tp(float x) { float t = log10f(x); float y; if(t <= -2.6f) { y = -0.72f; } else { if(t >= 1.9f) { y = t - 1.255f; } else { y = powf(0.249f * t + 0.65f, 2.7f) - 0.72f; } } y = powf(10.0f, y); return y; } /** * @brief WalravenValetonK * @param Lw_a is the world adaptation luminance in cd/m^2 * @param sigma * @return */ static float WalravenValetonK(float Lw_a, float sigma = 100.0f) { float k = (sigma - Lw_a / 4.0f) / (sigma + Lw_a); return (k > 0.0f) ? k : 0.0f; } /** * @brief execute * @param imgIn * @param imgOut * @return */ static Image *execute(Image *imgIn, Image *imgOut) { FerwerdaTMO ftmo(200.0f, -1.0f, -1.0f); return ftmo.Process(Single(imgIn), imgOut); } }; } // end namespace pic #endif /* PIC_TONE_MAPPING_FERWERDA_TMO_HPP */
22.660194
102
0.511782
ecarpita93
228c50c8f9af5170a098c7d33955aa6405b8a61e
869
cpp
C++
codeforces/659/d.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codeforces/659/d.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codeforces/659/d.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
#include <iostream> #include <cassert> #include <cstring> #include <vector> using namespace std; long long int msb(long long int n){ n |= n >> 1; n |= n >> 2; n |= n >> 4; n |= n >> 8; n |= n >> 16; n |= n >> 32; n++; return (n>>1); } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--){ int n; cin >> n; vector<long long int> a(n); long long int or_all = 0; for(int i=0 ; i<n ; i++){ cin >> a[i]; or_all |= a[i]; } int msb_num = msb(or_all); while(msb_num!=0){ } int count = 0; for(auto num : a){ if(msb_num&num) count++; } if(count%4==1) cout << "WIN\n"; else cout << "LOSE\n"; } return 0; }
17.734694
37
0.416571
udayan14
22925f5af9616b90feb587053c0d4369570f1072
189
cpp
C++
Source/Runtime/Math/Private/Rectangle.cpp
bbagwang/SoftRendererBook
b38f94e14562ea1ad2a1382278509028be9f08d3
[ "MIT" ]
null
null
null
Source/Runtime/Math/Private/Rectangle.cpp
bbagwang/SoftRendererBook
b38f94e14562ea1ad2a1382278509028be9f08d3
[ "MIT" ]
null
null
null
Source/Runtime/Math/Private/Rectangle.cpp
bbagwang/SoftRendererBook
b38f94e14562ea1ad2a1382278509028be9f08d3
[ "MIT" ]
1
2022-02-25T07:17:38.000Z
2022-02-25T07:17:38.000Z
#include "Precompiled.h" #include "Rectangle.h" Rectangle::Rectangle(const Vector2* InVertices, size_t InCount) { for (int vi = 0; vi < InCount; ++vi) { *this += InVertices[vi]; } }
15.75
63
0.661376
bbagwang
229ca15d98e7599df3fae1311935e31789bd76d5
516
cpp
C++
Code full house/buoi22 nguyen dinh trung duc/New folder/bai 4.cpp
ducyb2001/CbyTrungDuc
0e93394dce600876a098b90ae969575bac3788e1
[ "Apache-2.0" ]
null
null
null
Code full house/buoi22 nguyen dinh trung duc/New folder/bai 4.cpp
ducyb2001/CbyTrungDuc
0e93394dce600876a098b90ae969575bac3788e1
[ "Apache-2.0" ]
null
null
null
Code full house/buoi22 nguyen dinh trung duc/New folder/bai 4.cpp
ducyb2001/CbyTrungDuc
0e93394dce600876a098b90ae969575bac3788e1
[ "Apache-2.0" ]
null
null
null
#include<stdio.h> #include<string.h> int n,a[100],ok; // cau hinh ban dau, n so 0 void init(){ for(int i=1;i<=n;i++){ a[i]=0; } } // ham sinh xau ke tiep void next(){ int i=n; while(i>=1 && a[i]==1){ a[i]=0; i--; } if(i==0){ ok=0; // cau hinh cuoi cung } else{ a[i]=1; } } void in(){ for(int i=1;i<=n;i++){ printf("%d",a[i]); } printf(" "); } int main(){ int T; scanf("%d",&T); while(T--){ scanf("%d",&n); init(); ok=1; while(ok){ in(); next(); } printf("\n"); } }
10.530612
29
0.46124
ducyb2001
229e12fe80b163c1147b0d280fdce7a5e7cc409f
1,523
hpp
C++
solver/include/statetransitionmodel/StateTransitionModel.hpp
laurimi/multiagent-prediction-reward
b89fa52f78bb49447fc0049a7314a87b2b3e903e
[ "MIT" ]
9
2020-10-24T06:14:08.000Z
2021-07-13T13:08:30.000Z
solver/include/statetransitionmodel/StateTransitionModel.hpp
laurimi/multiagent-prediction-reward
b89fa52f78bb49447fc0049a7314a87b2b3e903e
[ "MIT" ]
null
null
null
solver/include/statetransitionmodel/StateTransitionModel.hpp
laurimi/multiagent-prediction-reward
b89fa52f78bb49447fc0049a7314a87b2b3e903e
[ "MIT" ]
null
null
null
#ifndef STATETRANSITIONMODEL_HPP #define STATETRANSITIONMODEL_HPP #include "core/CRTPHelper.hpp" namespace npgi { template <typename Derived> struct state_transition_model_traits; template <typename Derived> struct StateTransitionModel : crtp_helper<Derived> { using state_type = typename state_transition_model_traits<Derived>::state_type; using pmf_type = typename state_transition_model_traits<Derived>::pmf_type; using action_type = typename state_transition_model_traits<Derived>::action_type; using scalar_type = typename state_transition_model_traits<Derived>::scalar_type; using timestep_type = typename state_transition_model_traits<Derived>::timestep_type; scalar_type transition_probability(const state_type& next, const state_type& old, const action_type& a, const timestep_type t) const { return this->underlying().transition_probability(next, old, a, t); } state_type sample_next_state(const state_type& old, const action_type& a, const timestep_type t, const scalar_type random01) const { return this->underlying().sample_next_state(old, a, t, random01); } pmf_type predict(const pmf_type& b, const action_type& a, const timestep_type t) const { return this->underlying().predict(b, a, t); } }; } // namespace npgi #endif // STATETRANSITIONMODEL_HPP
36.261905
77
0.680893
laurimi
229f69b49bd21a746fbff435533495fa49a4baff
495
hpp
C++
src/pi/arg.hpp
cppcoder123/led-server
8ebac31e1241bb203d2cedfd644fe52619007cd6
[ "MIT" ]
1
2021-12-23T13:50:53.000Z
2021-12-23T13:50:53.000Z
src/pi/arg.hpp
cppcoder123/led-server
8ebac31e1241bb203d2cedfd644fe52619007cd6
[ "MIT" ]
null
null
null
src/pi/arg.hpp
cppcoder123/led-server
8ebac31e1241bb203d2cedfd644fe52619007cd6
[ "MIT" ]
null
null
null
// // // #ifndef LED_D_ARG_HPP #define LED_D_ARG_HPP #include <list> #include <string> #include <utility> namespace led_d { class arg_t { public: arg_t (); arg_t (const arg_t&) = default; ~arg_t () = default; static bool init (arg_t &arg, int argc, char **argv); // bool kill; // kill daemon if it is running bool spi_msg; // print spi messages std::list<std::string> subject_regexp_list; }; } // namespace led_d #endif
15.46875
66
0.593939
cppcoder123
22a1d95175f1a85853a691acf8398af6bc98e49e
192
cpp
C++
viewify/src/main/Factory/ComponentFactory.cpp
ii887522/viewify
2bd8ef48a63abeaeca73f7f532992ffb6122c76e
[ "MIT" ]
1
2021-07-13T00:56:09.000Z
2021-07-13T00:56:09.000Z
viewify/src/main/Factory/ComponentFactory.cpp
ii887522/viewify
2bd8ef48a63abeaeca73f7f532992ffb6122c76e
[ "MIT" ]
null
null
null
viewify/src/main/Factory/ComponentFactory.cpp
ii887522/viewify
2bd8ef48a63abeaeca73f7f532992ffb6122c76e
[ "MIT" ]
null
null
null
// Copyright ii887522 #ifndef CONSOLE_TEST #include "ComponentFactory.h" namespace ii887522::viewify { ComponentFactory::~ComponentFactory() { } } // namespace ii887522::viewify #endif
13.714286
41
0.75
ii887522
22a7cea72c68cf2c89ee9ed278861b3855e127a5
5,268
cpp
C++
inference-engine/src/vpu/common/src/ngraph/operations/static_shape_topk.cpp
dbudniko/openvino
6666e5fed3434637e538cf9d3219077c320c3c16
[ "Apache-2.0" ]
1
2021-01-17T03:24:52.000Z
2021-01-17T03:24:52.000Z
inference-engine/src/vpu/common/src/ngraph/operations/static_shape_topk.cpp
dbudniko/openvino
6666e5fed3434637e538cf9d3219077c320c3c16
[ "Apache-2.0" ]
30
2020-11-13T11:44:07.000Z
2022-02-21T13:03:16.000Z
inference-engine/src/vpu/common/src/ngraph/operations/static_shape_topk.cpp
dorloff/openvino
1c3848a96fdd325b044babe6d5cd26db341cf85b
[ "Apache-2.0" ]
1
2020-12-18T15:47:45.000Z
2020-12-18T15:47:45.000Z
// Copyright (C) 2018-2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vpu/ngraph/operations/static_shape_topk.hpp> #include <ngraph/validation_util.hpp> constexpr ngraph::NodeTypeInfo ngraph::vpu::op::StaticShapeTopK::type_info; static const std::uint64_t UNKNOWN_NORMALIZED_AXIS = std::numeric_limits<uint64_t>::max(); ngraph::vpu::op::StaticShapeTopK::StaticShapeTopK( const Output<Node>& data, const Output<Node>& k, const int64_t axis, const std::string& mode, const std::string& sort, const element::Type& index_element_type) : Op{{data, k}} , m_axis{axis} , m_maximumK{-1} , m_normalized_axis{0} , m_mode{as_enum<Mode>(mode)} , m_sort{as_enum<SortType>(sort)} , m_index_element_type{index_element_type} { constructor_validate_and_infer_types(); } ngraph::vpu::op::StaticShapeTopK::StaticShapeTopK( const ngraph::Output<ngraph::Node> &data, const ngraph::Output<ngraph::Node> &k, const int64_t axis, const ngraph::vpu::op::StaticShapeTopK::Mode mode, const ngraph::vpu::op::StaticShapeTopK::SortType sort, const ngraph::element::Type &index_element_type) : Op{{data, k}} , m_axis{axis} , m_maximumK{-1} , m_normalized_axis{0} , m_mode{mode} , m_sort{sort} , m_index_element_type{index_element_type} { constructor_validate_and_infer_types(); } std::shared_ptr<ngraph::Node> ngraph::vpu::op::StaticShapeTopK::clone_with_new_inputs(const OutputVector& new_args) const { check_new_args_count(this, new_args); auto new_v1_topk = std::make_shared<ngraph::vpu::op::StaticShapeTopK>( new_args.at(0), new_args.at(1), m_axis, m_mode, m_sort); new_v1_topk->set_index_element_type(m_index_element_type); return std::move(new_v1_topk); } void ngraph::vpu::op::StaticShapeTopK::validate_and_infer_types() { NODE_VALIDATION_CHECK(this, get_input_element_type(1).is_integral_number(), "K input has to be an integer type, which does match the provided one:", get_input_element_type(1)); const auto& input_partial_shape = get_input_partial_shape(0); const auto input_rank = input_partial_shape.rank(); NODE_VALIDATION_CHECK(this, input_rank.is_static() && input_rank.get_length() > 0, "Input rank must be greater than 0."); const auto& k_partial_shape = get_input_partial_shape(1); NODE_VALIDATION_CHECK( this, k_partial_shape.rank().compatible(0), "The 'K' input must be a scalar."); size_t k = 0; if (auto constant = ngraph::as_type_ptr<ngraph::opset3::Constant>(input_value(1).get_node_shared_ptr())) { const auto value = constant->cast_vector<int64_t>(); NODE_VALIDATION_CHECK(this, value.size() == 1, "Only one value (scalar) should be provided as the 'K' input to TopK", " (got ", value.size(), " elements)."); NODE_VALIDATION_CHECK(this, value[0] > 0, "The value of 'K' must be a positive number.", " (got ", value[0], ")."); k = static_cast<size_t>(value[0]); } PartialShape output_shape{input_partial_shape}; m_normalized_axis = ngraph::normalize_axis(this->description(), m_axis, output_shape.rank()); if (k != 0) { output_shape[m_normalized_axis] = k; } else { auto max_k = maximum_value(input_value(1)); const auto is_max_value_calculated = max_k.first; const auto calculated_max_value = max_k.second; if (is_max_value_calculated) { m_maximumK = calculated_max_value; } } output_shape[m_normalized_axis] = m_maximumK; NODE_VALIDATION_CHECK(this, output_shape.is_static(), "StaticShapeTopK output shape is not fully defined: ", output_shape); set_output_size(2); set_output_type(0, get_input_element_type(0), output_shape); set_output_type(1, m_index_element_type, output_shape); } void ngraph::vpu::op::StaticShapeTopK::set_axis(const int64_t axis) { const auto input_rank = get_input_partial_shape(0).rank(); if (input_rank.is_static()) { m_normalized_axis = ngraph::normalize_axis(this->description(), axis, input_rank); } else { m_normalized_axis = UNKNOWN_NORMALIZED_AXIS; } m_axis = axis; } uint64_t ngraph::vpu::op::StaticShapeTopK::get_axis() const { NODE_VALIDATION_CHECK( this, m_normalized_axis != UNKNOWN_NORMALIZED_AXIS, "Normalized axis of TopK is unknown"); return m_normalized_axis; } bool ngraph::vpu::op::StaticShapeTopK::visit_attributes(AttributeVisitor& visitor) { visitor.on_attribute("axis", m_axis); visitor.on_attribute("mode", m_mode); visitor.on_attribute("sort", m_sort); visitor.on_attribute("index_element_type", m_index_element_type); return true; }
38.452555
123
0.633257
dbudniko
22b6f695c34603987dc4720773008d0bd7644d03
3,140
hpp
C++
Daxa/src/gpu/Queue.hpp
Ipotrick/Daxa
07f3f9717f43b32cbe60761602fc16b3a2789b5a
[ "MIT" ]
3
2021-03-24T21:26:59.000Z
2021-12-28T01:54:17.000Z
Daxa/src/gpu/Queue.hpp
Ipotrick/Daxa
07f3f9717f43b32cbe60761602fc16b3a2789b5a
[ "MIT" ]
1
2021-12-10T01:08:15.000Z
2021-12-15T23:38:33.000Z
Daxa/src/gpu/Queue.hpp
Ipotrick/Daxa
07f3f9717f43b32cbe60761602fc16b3a2789b5a
[ "MIT" ]
1
2022-02-18T16:07:19.000Z
2022-02-18T16:07:19.000Z
#pragma once #pragma once #include "../DaxaCore.hpp" #include <memory> #include <mutex> #include <vector> #include <vulkan/vulkan.h> #include "CommandList.hpp" #include "TimelineSemaphore.hpp" #include "Swapchain.hpp" #include "Signal.hpp" namespace daxa { namespace gpu { struct SubmitInfo { std::vector<CommandListHandle> commandLists = {}; // TODO REPLACE THIS VECTOR WITH HEAPLESS VERSION std::span<std::tuple<TimelineSemaphoreHandle, u64>> waitOnTimelines = {}; std::span<std::tuple<TimelineSemaphoreHandle, u64>> signalTimelines = {}; std::span<SignalHandle> waitOnSignals = {}; std::span<SignalHandle> signalOnCompletion = {}; }; class Queue { public: Queue(VkDevice device, VkQueue queue, u32 batchCount = 0); Queue() = default; Queue(Queue const&) = delete; Queue& operator=(Queue const&) = delete; Queue(Queue&&) noexcept = delete; Queue& operator=(Queue&&) noexcept = delete; ~Queue(); /** * Submit CommandLists to be executed on the GPU. * Per default the submits are NOT synced to wait on each other based on submission ordering. * * It is guaranteed that all ressouces used in the cmdLists and the cmdLists themselfes are kept alive until after the gpu has finished executing it. * * \param submitInfo contains all information about the submit. * \return a fence handle that can be used to check if the execution is complete or waited upon completion. */ void submit(SubmitInfo submitInfo); void submitBlocking(SubmitInfo submitInfo); void present(SwapchainImage&& img, SignalHandle& waitOnSignal); void checkForFinishedSubmits(); void nextBatch(); void waitIdle(); private: friend class Device; VkDevice device = {}; VkQueue queue = {}; TimelineSemaphoreHandle getNextTimeline(); struct PendingSubmit { std::vector<CommandListHandle> cmdLists; TimelineSemaphoreHandle timelineSema; u64 finishCounter = 0; }; std::deque<std::vector<PendingSubmit>> batches; bool bWaitForBatchesToComplete = false; std::vector<TimelineSemaphoreHandle> unusedTimelines = {}; // reused temporary buffers: std::vector<VkCommandBuffer> submitCommandBufferBuffer = {}; std::vector<VkSemaphore> submitSemaphoreWaitOnBuffer = {}; std::vector<VkSemaphore> submitSemaphoreSignalBuffer = {}; std::vector<u64> submitSemaphoreWaitOnValueBuffer = {}; std::vector<u64> submitSemaphoreSignalValueBuffer = {}; }; class QueueHandle { public: QueueHandle(std::shared_ptr<Queue> queue) : queue{ std::move(queue) } {} QueueHandle() = default; Queue const& operator*() const { return *queue; } Queue& operator*() { return *queue; } Queue const* operator->() const { return queue.get(); } Queue* operator->() { return queue.get(); } size_t getRefCount() const { return queue.use_count(); } operator bool() const { return queue.operator bool(); } bool operator!() const { return !queue; } bool valid() const { return *this; } private: std::shared_ptr<Queue> queue = {}; }; } }
29.622642
152
0.682803
Ipotrick
42f469b905828fb90c3598f7e0a9da3484794bb7
6,605
cc
C++
examples/core_usage.cc
jacobmerson/model-traits
e336cd653c91797fcfa9edb018d65b76c271fb54
[ "BSD-3-Clause" ]
2
2021-06-18T22:51:17.000Z
2021-11-20T23:25:34.000Z
examples/core_usage.cc
jacobmerson/boundary-conditions
e336cd653c91797fcfa9edb018d65b76c271fb54
[ "BSD-3-Clause" ]
4
2021-05-13T07:58:49.000Z
2021-08-09T11:47:20.000Z
examples/core_usage.cc
jacobmerson/boundary-conditions
e336cd653c91797fcfa9edb018d65b76c271fb54
[ "BSD-3-Clause" ]
2
2021-08-07T20:07:44.000Z
2021-08-24T20:02:56.000Z
#include "fmt/format.h" #include "model_traits/AssociatedModelTraits.h" #include "model_traits/GeometrySet.h" #include "model_traits/ModelTrait.h" #include "model_traits/ModelTraits.h" #include <cassert> #include <fmt/format.h> struct FunctorPlus { double operator()(double a, double b) const noexcept { return a + b; } friend std::string to_string(const FunctorPlus &f) { return f.name; } std::string name = "functor plus"; }; using mt::AssociatedModelTraits; using mt::BoolMT; using mt::DimIdGeometry; using mt::DimIdGeometrySet; using mt::IdGeometry; using mt::IdGeometrySet; using mt::IntMT; using mt::ModelTraits; using mt::MTCast; using mt::NamedFunction; using mt::ScalarFunctionMT; using mt::ScalarMT; using mt::VectorMT; int main(int, char **) { // Create the base model traits data structure ModelTraits model_traits{"Generic Model"}; auto *case1 = model_traits.AddCase("case1"); case1->AddCategory("solution strategy"); case1->AddCategory("problem definition"); case1->AddCategory("output"); // Since adding categories to case1 will potentially invalidate the pointer, // we don't directly use the output of AddCategory, but instead we find the // category after all the other categories in case1 are added auto *problem_definition = case1->FindCategoryNodeByType("problem definition"); // add a category to the problem definition auto *loads = problem_definition->AddCategory("loads"); // this time we aren't adding any more categories to the solution strategy // before operating on it, so we are safe to use the output of AddCategory // add the first load with the geometry as an id geometry set (geometry is // stored as only the id with no dimension) loads->AddModelTrait("load 1", IdGeometrySet{1, 2, 3}, ScalarMT{10.0}); // add another scalar load from a geometry set initialized from a vector // note that we need to be careful that we don't a model trait (boundary // condition) with the same name to the same geometry. This will cause an // error when we associate the geometry std::vector<int> geometry_vector = {88, 99, 199}; loads->AddModelTrait( "load 1", IdGeometrySet{geometry_vector.begin(), geometry_vector.end()}, ScalarMT{15.0}); // we can also add a model trait with geometry that stores both the dimension // and the id loads->AddModelTrait("load 2", DimIdGeometrySet{{0, 1}, {2, 2}, {2, 3}}, ScalarMT{7.0}); // now lets add a model trait that uses a function. The Exprtk function class // to add a string function evaluation. Here, we will show adding a lambda. // The same method can be used for a functor, or function pointer. For // serialization the function is required to have a name associated with it. // This is accomplished by using the "NamedFunction" type. auto lambda_plus = NamedFunction<double(double, double)>{ "lambda plus", [](double a, double b) { return a + b; }}; // a functor can also be used. If the functor has a to_string function, it can // be created without supplying a name on construction auto functor_plus = NamedFunction<double(double, double)>{FunctorPlus{}}; // but we don't need to explicitly construct values, we can use the typedefs // in ModelTrait.h to add the functions directly loads->AddModelTrait("function load", DimIdGeometrySet{{0, 2}}, ScalarFunctionMT<2>{FunctorPlus{}}); loads->AddModelTrait( "function load", DimIdGeometrySet{{0, 3}}, ScalarFunctionMT<1>{{"single input", [](double a) { return a; }}}); // lets make sure we don't write outputs with a bool trait. // This options isn't associated with a particular geometry, so we leave the // geometry set empty. auto *output_defn = case1->FindCategoryNodeByType("output"); output_defn->AddModelTrait("write to file", IdGeometrySet{}, BoolMT{false}); // and let's set the direction of some output with a vector output_defn->AddModelTrait("my vector output", IdGeometrySet{8}, VectorMT{{1.0, 2.0, 3.0}}); // lets associate the geometry so that we can search by the geometry. // Note that when we associate the model, we choose which geometry type to // include // first let's associate the IdGeometry AssociatedModelTraits<IdGeometry> id_associated_traits{case1}; // now let's associate the dimensional geometry but only on the problem // definition AssociatedModelTraits<DimIdGeometry> dim_associated_traits{ problem_definition}; // lets see if we need to write to the file in the output // note that since this model trait has no geometry associated with it, // we will use a special method to get the correct list of category nodes auto *p = id_associated_traits.GetNullGeometry(); // we put the geometry in, so we better find it auto *write_to_file_trait = p->FindCategoryByType("output")->FindModelTrait("write to file"); // now we need to cast the trait into the appropriate type and we can call it auto *write_to_file_trait_casted = MTCast<BoolMT>(write_to_file_trait); // now lets get the value using the () operator of the model trait bool write_to_file = (*write_to_file_trait_casted)(); fmt::print("Writing to file?: {}\n", write_to_file); // now lets get the function load boundary condition and evaluate it auto *geom_0_2 = dim_associated_traits.Find({0, 2}); auto *associated_load = geom_0_2->FindCategoryByType("loads"); // cast the function to the appropriate model trait type const auto *function = MTCast<ScalarFunctionMT<2>>( associated_load->FindModelTrait("function load")); // now lets evaluate it by getting the function as the data in the model trait // and calling the functions () operator. Note that functions have a bit of an // awkward syntax where the first () gets the function as the data stored in // boundary condition, and second calls the underlying function. The first set // of parens can be removed, but this offers consistency with vectors and // matrices fmt::print("Evaluating function load f(1,2)={}.\n", (*function)(1, 2)); // let's see what is stored in our vector output assert(id_associated_traits.Find({8}) ->FindCategoryByType("output") ->FindModelTrait("my vector output") != nullptr); const VectorMT &my_vec = (*MTCast<VectorMT>(id_associated_traits.Find({8}) ->FindCategoryByType("output") ->FindModelTrait("my vector output"))); fmt::print("Vector: [{}, {}, {}].\n", my_vec(0), my_vec(1), my_vec(2)); return 0; }
45.868056
80
0.709614
jacobmerson
42fc0515d78be0ed537fce7b9b9958782c07a0a3
2,656
cpp
C++
code/engine.vc2008/xrEngine/NvGPUTransferee.cpp
icetorch2001/xray-oxygen
8c210ac2824f794cea69266048fe12d584ee3f04
[ "Apache-2.0" ]
1
2021-09-14T14:28:56.000Z
2021-09-14T14:28:56.000Z
code/engine.vc2008/xrEngine/NvGPUTransferee.cpp
ArtemGen/xray-oxygen
f62d3e1f4e211986c057fd37e97fd03c98b5e275
[ "Apache-2.0" ]
null
null
null
code/engine.vc2008/xrEngine/NvGPUTransferee.cpp
ArtemGen/xray-oxygen
f62d3e1f4e211986c057fd37e97fd03c98b5e275
[ "Apache-2.0" ]
3
2021-11-01T06:21:26.000Z
2022-01-08T16:13:23.000Z
////////////////////////////////////////// // Desc: GPU Info // Model: NVIDIA // Author: ForserX, Mortan ////////////////////////////////////////// // Oxygen Engine (2016-2019) ////////////////////////////////////////// #include "stdafx.h" #include "NvGPUTransferee.h" bool CNvReader::bSupport = false; CNvReader::CNvReader() : AdapterID(0), hNvAPIDLL(NULL) {} CNvReader::~CNvReader() { if (hNvAPIDLL != NULL) { FreeLibrary(hNvAPIDLL); } } void CNvReader::Initialize() { if (bSupport) return; hNvAPIDLL = LoadLibraryA("nvapi64.dll"); if (hNvAPIDLL != NULL) { NvAPI_QueryInterface = (NvAPI_QueryInterface_t)GetProcAddress(hNvAPIDLL, "nvapi_QueryInterface"); if (NvAPI_QueryInterface == nullptr) { FreeLibrary(hNvAPIDLL); hNvAPIDLL = NULL; Msg("! Found nvapi64.dll, but DLL missing \"nvapi_QueryInterface\""); return; } auto TryToInitializeFunctionLambda = [this](void** pFuncPtr, u32 FuncId) -> bool { *pFuncPtr = (*NvAPI_QueryInterface)(FuncId); if (*pFuncPtr == nullptr) { FreeLibrary(hNvAPIDLL); hNvAPIDLL = NULL; Msg("! Found nvapi64.dll, but DLL missing Func ID \"%u\"", FuncId); return false; } return true; }; if (!TryToInitializeFunctionLambda((void**)&NvAPI_Initialize, 0x0150E828)) { return; } if (!TryToInitializeFunctionLambda((void**)&NvAPI_EnumPhysicalGPUs, 0xE5AC921F)) { return; } if (!TryToInitializeFunctionLambda((void**)&NvAPI_EnumLogicalGPUs, 0x48B3EA59)) { return; } if (!TryToInitializeFunctionLambda((void**)&NvAPI_GPU_GetUsages, 0x189A1FDF)) { return; } if (!TryToInitializeFunctionLambda((void**)&NvAPI_GPU_PhysicalFromLogical, 0x0AEA3FA32)) { return; } bSupport = true; InitDeviceInfo(); } else { Msg("! Can't load nvapi64.dll"); } } void CNvReader::InitDeviceInfo() { (*NvAPI_Initialize)(); // gpuUsages[0] must be this value, otherwise NvAPI_GPU_GetUsages won't work gpuUsages[0] = (NVAPI_MAX_USAGES_PER_GPU * 4) | 0x10000; (*NvAPI_EnumPhysicalGPUs)(gpuHandlesPh, &AdapterID); MakeGPUCount(); } void CNvReader::MakeGPUCount() { NvU32 logicalGPUCount; NvAPI_EnumLogicalGPUs(gpuHandlesLg, &logicalGPUCount); for (NvU32 i = 0; i < logicalGPUCount; ++i) { NvAPI_GPU_PhysicalFromLogical(gpuHandlesLg[i], gpuHandlesPh, &AdapterID); AdapterFinal = std::max(AdapterFinal, (u64)AdapterID); } if (AdapterFinal > 1) { Msg("[MSG] NVidia MGPU: %d-Way SLI detected.", AdapterFinal); } } u32 CNvReader::GetPercentActive() { (*NvAPI_GPU_GetUsages)(gpuHandlesPh[0], gpuUsages); int usage = gpuUsages[3]; return (u32)usage; } u32 CNvReader::GetGPUCount() { return u32(AdapterFinal ? AdapterFinal : 1); }
23.095652
99
0.667922
icetorch2001
42fc52e4b2bcca4bbc219ef1a3c508b94bce0813
524
hpp
C++
lib/inc/internal/facts/bsd/uptime_resolver.hpp
mihaibuzgau/facter
451ee4288c61c6185295b454339801b84b8242ef
[ "Apache-2.0" ]
1
2015-03-27T10:33:40.000Z
2015-03-27T10:33:40.000Z
lib/inc/internal/facts/bsd/uptime_resolver.hpp
mihaibuzgau/facter
451ee4288c61c6185295b454339801b84b8242ef
[ "Apache-2.0" ]
null
null
null
lib/inc/internal/facts/bsd/uptime_resolver.hpp
mihaibuzgau/facter
451ee4288c61c6185295b454339801b84b8242ef
[ "Apache-2.0" ]
null
null
null
/** * @file * Declares the BSD uptime fact resolver. */ #pragma once #include "../posix/uptime_resolver.hpp" namespace facter { namespace facts { namespace bsd { /** * Responsible for resolving uptime facts. */ struct uptime_resolver : posix::uptime_resolver { protected: /** * Gets the system uptime in seconds. * @return Returns the system uptime in seconds. */ virtual int64_t get_uptime() override; }; }}} // namespace facter::facts::bsd
20.96
56
0.612595
mihaibuzgau
6e00136138a45b67361e01765696080a7b6cf3f5
244
cpp
C++
threepp/util/impl/utils.cpp
Graphics-Physics-Libraries/three.cpp-imported
788b4202e15fa245a4b60e2da0b91f7d4d0592e1
[ "MIT" ]
76
2017-12-20T05:09:04.000Z
2022-01-24T10:20:15.000Z
threepp/util/impl/utils.cpp
melMass/three.cpp
5a328b40036e359598baec8b3fcddae4f33e410a
[ "MIT" ]
5
2018-06-06T15:41:01.000Z
2019-11-30T15:10:25.000Z
threepp/util/impl/utils.cpp
melMass/three.cpp
5a328b40036e359598baec8b3fcddae4f33e410a
[ "MIT" ]
23
2017-10-12T16:46:33.000Z
2022-03-16T06:16:03.000Z
// // Created by byter on 5/13/18. // #include <threepp/extras/PointsWalker.h> #include <threepp/util/Types.h> namespace three { no_delete DLX _no_delete; namespace extras { namespace points_walker { always_true always_true::empty; } } }
12.2
40
0.729508
Graphics-Physics-Libraries
6e026b06115549223188862ce3d07bbce07995af
1,488
cpp
C++
test/test_binary_tree.cpp
buptlxb/leetcode-utility
49417b7c5f65be60212a89bd4e435f20d277e353
[ "BSD-3-Clause" ]
null
null
null
test/test_binary_tree.cpp
buptlxb/leetcode-utility
49417b7c5f65be60212a89bd4e435f20d277e353
[ "BSD-3-Clause" ]
null
null
null
test/test_binary_tree.cpp
buptlxb/leetcode-utility
49417b7c5f65be60212a89bd4e435f20d277e353
[ "BSD-3-Clause" ]
null
null
null
#include "binary_tree.h" #include <vector> #include <iostream> template <typename T> void access(typename leetcode::Tree<T>::link_type node) { std::cout << std::hex << node << ":" << std::dec << "(" << node->val << "," << std::hex << node->left << ", " << node->right << std::dec << ")" << std::endl; } int main(void) { std::vector<int> vec{5,4,7,3,0,2,0,-1,0,9}; leetcode::Tree<int> tree(vec.begin(), vec.end(), 0); std::cout << "size:" << tree.size() << std::endl; std::cout << "preorder:" << std::endl; tree.preorder(access<int>); std::cout << "preorderIter:" << std::endl; tree.preorderIter(access<int>); std::cout << "preorderThreaded:" << std::endl; tree.preorderThreaded(access<int>); std::cout << "inorder:" << std::endl; tree.inorder(access<int>); std::cout << "inorderIter:" << std::endl; tree.inorderIter(access<int>); std::cout << "inorderThreaded:" << std::endl; tree.inorderThreaded(access<int>); std::cout << "postorder:" << std::endl; tree.postorder(access<int>); std::cout << "postorderIter:" << std::endl; tree.postorderIter(access<int>); std::cout << "postorderThreaded:" << std::endl; tree.postorderThreaded(access<int>); std::cout << tree.serialize() << std::endl; leetcode::Tree<int> alt; if (alt.deserialize(tree.serialize())) std::cout << alt.serialize() << std::endl; else std::cout << "deserialize failed" << std::endl; return 0; }
33.066667
161
0.585349
buptlxb
6e0305bae9eef5fdad9cb96de53f00433d25745f
4,363
cpp
C++
GLTFSDK/Source/AnimationUtils.cpp
ninerdelta/glTF-SDK
db5c8dfd02f1a027cea63194a6472574cfe8d723
[ "MIT" ]
243
2019-05-22T04:35:22.000Z
2022-03-30T21:04:37.000Z
GLTFSDK/Source/AnimationUtils.cpp
ninerdelta/glTF-SDK
db5c8dfd02f1a027cea63194a6472574cfe8d723
[ "MIT" ]
43
2019-05-07T17:37:13.000Z
2022-03-17T12:47:30.000Z
GLTFSDK/Source/AnimationUtils.cpp
ninerdelta/glTF-SDK
db5c8dfd02f1a027cea63194a6472574cfe8d723
[ "MIT" ]
64
2019-05-24T14:09:28.000Z
2022-03-13T02:24:27.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include <GLTFSDK/AnimationUtils.h> #include <GLTFSDK/GLTF.h> #include <GLTFSDK/GLTFResourceReader.h> using namespace Microsoft::glTF; std::vector<float> AnimationUtils::GetKeyframeTimes(const Document& doc, const GLTFResourceReader& reader, const Accessor& accessor) { if (accessor.type != TYPE_SCALAR) { throw GLTFException("Invalid type for animation input accessor " + accessor.id); } if (accessor.componentType != COMPONENT_FLOAT) { throw GLTFException("Invalid componentType for animation input accessor " + accessor.id); } return reader.ReadBinaryData<float>(doc, accessor); } std::vector<float> AnimationUtils::GetKeyframeTimes(const Document& doc, const GLTFResourceReader& reader, const AnimationSampler& sampler) { auto& accessor = doc.accessors[sampler.inputAccessorId]; return GetKeyframeTimes(doc, reader, accessor); } std::vector<float> AnimationUtils::GetInverseBindMatrices(const Document& doc, const GLTFResourceReader& reader, const Accessor& accessor) { if (accessor.type != TYPE_MAT4) { throw GLTFException("Invalid type for inverse bind matrices accessor " + accessor.id); } if (accessor.componentType != COMPONENT_FLOAT) { throw GLTFException("Invalid componentType for inverse bind matrices accessor " + accessor.id); } return reader.ReadBinaryData<float>(doc, accessor); } std::vector<float> AnimationUtils::GetInverseBindMatrices(const Document& doc, const GLTFResourceReader& reader, const Skin& skin) { auto& accessor = doc.accessors[skin.inverseBindMatricesAccessorId]; return GetInverseBindMatrices(doc, reader, accessor); } std::vector<float> AnimationUtils::GetTranslations(const Document& doc, const GLTFResourceReader& reader, const Accessor& accessor) { if (accessor.type != TYPE_VEC3) { throw GLTFException("Invalid type for translations accessor " + accessor.id); } if (accessor.componentType != COMPONENT_FLOAT) { throw GLTFException("Invalid componentType for translations accessor " + accessor.id); } return reader.ReadBinaryData<float>(doc, accessor); } std::vector<float> AnimationUtils::GetTranslations(const Document& doc, const GLTFResourceReader& reader, const AnimationSampler& sampler) { auto& accessor = doc.accessors[sampler.outputAccessorId]; return GetTranslations(doc, reader, accessor); } std::vector<float> AnimationUtils::GetRotations(const Document& doc, const GLTFResourceReader& reader, const Accessor& accessor) { if (accessor.type != TYPE_VEC4) { throw GLTFException("Invalid type for rotations accessor " + accessor.id); } return reader.ReadFloatData(doc, accessor); } std::vector<float> AnimationUtils::GetRotations(const Document& doc, const GLTFResourceReader& reader, const AnimationSampler& sampler) { auto& accessor = doc.accessors[sampler.outputAccessorId]; return GetRotations(doc, reader, accessor); } std::vector<float> AnimationUtils::GetScales(const Document& doc, const GLTFResourceReader& reader, const Accessor& accessor) { if (accessor.type != TYPE_VEC3) { throw GLTFException("Invalid type for scales accessor " + accessor.id); } if (accessor.componentType != COMPONENT_FLOAT) { throw GLTFException("Invalid componentType for scales accessor " + accessor.id); } return reader.ReadBinaryData<float>(doc, accessor); } std::vector<float> AnimationUtils::GetScales(const Document& doc, const GLTFResourceReader& reader, const AnimationSampler& sampler) { auto& accessor = doc.accessors[sampler.outputAccessorId]; return GetScales(doc, reader, accessor); } std::vector<float> AnimationUtils::GetMorphWeights(const Document& doc, const GLTFResourceReader& reader, const Accessor& accessor) { if (accessor.type != TYPE_SCALAR) { throw GLTFException("Invalid type for weights accessor " + accessor.id); } return reader.ReadFloatData(doc, accessor); } std::vector<float> AnimationUtils::GetMorphWeights(const Document& doc, const GLTFResourceReader& reader, const AnimationSampler& sampler) { auto& accessor = doc.accessors[sampler.outputAccessorId]; return GetMorphWeights(doc, reader, accessor); }
34.626984
139
0.738024
ninerdelta
6e0665db59df1b046d730cc17a8279724264d7c9
3,186
cc
C++
src/ring_pb.cc
mbruker/jspec2-python
c82b41cf0a314f15eb84ab15b0de96ac2992bf9c
[ "Unlicense" ]
null
null
null
src/ring_pb.cc
mbruker/jspec2-python
c82b41cf0a314f15eb84ab15b0de96ac2992bf9c
[ "Unlicense" ]
null
null
null
src/ring_pb.cc
mbruker/jspec2-python
c82b41cf0a314f15eb84ab15b0de96ac2992bf9c
[ "Unlicense" ]
null
null
null
#include <pybind11/pybind11.h> #include <pybind11/operators.h> #include <pybind11/stl.h> #include <functional> #include <tuple> #include <vector> #include "jspec2/ring.h" #include "jspec2/twiss.h" #include "jspec2/ion_beam.h" namespace py=pybind11; using namespace pybind11::literals; using std::vector; void init_ring(py::module& m ){ py::class_<Lattice>(m, "Lattice") .def(py::init<std::string &>()) .def("s", (double(Lattice::*)(int)) &Lattice::s, "i"_a) .def("betx", (double(Lattice::*)(int)) &Lattice::betx, "i"_a) .def("alfx", (double(Lattice::*)(int)) &Lattice::alfx, "i"_a) .def("mux", (double(Lattice::*)(int)) &Lattice::mux, "i"_a) .def("dx", (double(Lattice::*)(int)) &Lattice::dx, "i"_a) .def("dpx", (double(Lattice::*)(int)) &Lattice::dpx, "i"_a) .def("bety", (double(Lattice::*)(int)) &Lattice::bety, "i"_a) .def("alfy", (double(Lattice::*)(int)) &Lattice::alfy, "i"_a) .def("muy", (double(Lattice::*)(int)) &Lattice::muy, "i"_a) .def("dy", (double(Lattice::*)(int)) &Lattice::dy, "i"_a) .def("dpy", (double(Lattice::*)(int)) &Lattice::dpy, "i"_a) .def("n_element", &Lattice::n_element) .def("l_element", (double(Lattice::*)(int)) &Lattice::l_element, "i"_a) .def("circ", &Lattice::circ); py::class_<Ring>(m, "Ring") .def(py::init<const Lattice&, const IonBeam *, double, double, double, double, int, double, double>(), py::arg("lattice"), py::arg("ion_beam"), py::arg("qx") = 0, py::arg("qy") = 0, py::arg("qs") = 0, py::arg("rf_voltage") = 0, py::arg("rf_h") = 1, py::arg("rf_phi") = 0, py::arg("gamma_tr") = 0 ) .def_property_readonly("circ", &Ring::circ) .def_property_readonly("f0", &Ring::f0) .def_property_readonly("w0", &Ring::w0) .def_property_readonly("slip_factor", &Ring::slip_factor) .def_property_readonly("qx", &Ring::qx) .def_property_readonly("qy", &Ring::qy) .def_property_readonly("qs", &Ring::qs) .def_property_readonly("rf_voltage", &Ring::rf_voltage) .def_property_readonly("rf_h", &Ring::rf_h) .def_property_readonly("rf_phi", &Ring::rf_phi) .def_property_readonly("gamma_tr", &Ring::gamma_tr); py::class_<Twiss>(m, "Twiss") .def(py::init<double, double, double, double, double, double, double, double>(), py::arg("beta_x"), py::arg("beta_y"), py::arg("alpha_x") = 0, py::arg("alpha_y") = 0, py::arg("disp_x") = 0, py::arg("disp_y") = 0, py::arg("disp_dx") = 0, py::arg("disp_dy") = 0 ) .def_readonly("bet_x", &Twiss::bet_x) .def_readonly("alf_x", &Twiss::alf_x) .def_readonly("disp_x", &Twiss::disp_x) .def_readonly("disp_dx", &Twiss::disp_dx) .def_readonly("bet_y", &Twiss::bet_y) .def_readonly("alf_y", &Twiss::alf_y) .def_readonly("disp_y", &Twiss::disp_y) .def_readonly("disp_dy", &Twiss::disp_dy); }
40.329114
110
0.548023
mbruker
6e08c166f71e46b1affa5f50ca77480817907f40
1,124
cpp
C++
SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.cpp
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.cpp
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
SerialPrograms/Source/PokemonLA/Resources/PokemonLA_AvailablePokemon.cpp
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
/* Available Pokemon * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include "Common/Cpp/Exceptions.h" #include "Common/Qt/QtJsonTools.h" #include "CommonFramework/Globals.h" #include "PokemonLA_AvailablePokemon.h" namespace PokemonAutomation{ namespace NintendoSwitch{ namespace PokemonLA{ std::vector<std::string> load_hisui_dex(){ QString path = RESOURCE_PATH() + "Pokemon/Pokedex/Pokedex-Hisui.json"; QJsonArray json = read_json_file(path).array(); std::vector<std::string> list; for (const auto& item : json){ QString slug_qstr = item.toString(); if (slug_qstr.size() <= 0){ throw FileException( nullptr, PA_CURRENT_FUNCTION, "Expected non-empty string for Pokemon slug.", path.toStdString() ); } list.emplace_back(slug_qstr.toStdString()); } return list; } const std::vector<std::string>& HISUI_DEX_SLUGS(){ static const std::vector<std::string> database = load_hisui_dex(); return database; } } } }
23.914894
75
0.624555
Gin890
6e0f4a8a917a62a459a0ef2ea226408a78db0566
2,150
hpp
C++
libs/core/render/include/bksge/core/render/d3d12/detail/inl/blend_state_inl.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/render/include/bksge/core/render/d3d12/detail/inl/blend_state_inl.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/render/include/bksge/core/render/d3d12/detail/inl/blend_state_inl.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file blend_state_inl.hpp * * @brief BlendState クラスの実装 * * @author myoukaku */ #ifndef BKSGE_CORE_RENDER_D3D12_DETAIL_INL_BLEND_STATE_INL_HPP #define BKSGE_CORE_RENDER_D3D12_DETAIL_INL_BLEND_STATE_INL_HPP #include <bksge/core/render/config.hpp> #if BKSGE_CORE_RENDER_HAS_D3D12_RENDERER #include <bksge/core/render/d3d12/detail/blend_state.hpp> #include <bksge/core/render/d3d12/detail/blend_factor.hpp> #include <bksge/core/render/d3d12/detail/blend_operation.hpp> #include <bksge/core/render/d3d12/detail/bool.hpp> #include <bksge/core/render/d3d12/detail/color_write_flag.hpp> #include <bksge/core/render/d3d12/detail/logic_operation.hpp> #include <bksge/core/render/d3d_common/d3d12.hpp> #include <bksge/core/render/blend_state.hpp> namespace bksge { namespace render { namespace d3d12 { BKSGE_INLINE BlendState::BlendState(bksge::BlendState const& blend_state) : m_desc{} { m_desc.AlphaToCoverageEnable = FALSE; m_desc.IndependentBlendEnable = FALSE; for (auto& rt : m_desc.RenderTarget) { rt.BlendEnable = d3d12::Bool(blend_state.enable()); rt.SrcBlend = d3d12::BlendFactor(blend_state.color_src_factor()); rt.DestBlend = d3d12::BlendFactor(blend_state.color_dst_factor()); rt.BlendOp = d3d12::BlendOperation(blend_state.color_operation()); rt.SrcBlendAlpha = d3d12::BlendFactor(blend_state.alpha_src_factor()); rt.DestBlendAlpha = d3d12::BlendFactor(blend_state.alpha_dst_factor()); rt.BlendOpAlpha = d3d12::BlendOperation(blend_state.alpha_operation()); rt.RenderTargetWriteMask = d3d12::ColorWriteFlag(blend_state.color_write_mask()); rt.LogicOpEnable = d3d12::Bool(blend_state.logic_op_enable()); rt.LogicOp = d3d12::LogicOperation(blend_state.logic_operation()); } } BKSGE_INLINE BlendState::operator ::D3D12_BLEND_DESC() const { return m_desc; } } // namespace d3d12 } // namespace render } // namespace bksge #endif // BKSGE_CORE_RENDER_HAS_D3D12_RENDERER #endif // BKSGE_CORE_RENDER_D3D12_DETAIL_INL_BLEND_STATE_INL_HPP
31.15942
84
0.730233
myoukaku
6e0f72fa79799f18a927e699ae691a668e44dd3e
9,593
cpp
C++
19_4_audio_async_capture/main.cpp
aconstlink/natus_examples
2716ce7481172bcd14035b18d09b44b74ec78a7e
[ "MIT" ]
null
null
null
19_4_audio_async_capture/main.cpp
aconstlink/natus_examples
2716ce7481172bcd14035b18d09b44b74ec78a7e
[ "MIT" ]
null
null
null
19_4_audio_async_capture/main.cpp
aconstlink/natus_examples
2716ce7481172bcd14035b18d09b44b74ec78a7e
[ "MIT" ]
null
null
null
#include "main.h" #include <natus/application/global.h> #include <natus/application/app.h> #include <natus/gfx/camera/pinhole_camera.h> #include <natus/tool/imgui/imgui.h> #include <natus/graphics/variable/variable_set.hpp> #include <natus/math/vector/vector3.hpp> #include <natus/math/vector/vector4.hpp> #include <natus/math/matrix/matrix4.hpp> #include <natus/profile/macros.h> #include <natus/audio/buffer.hpp> #include <natus/device/layouts/three_mouse.hpp> #include <natus/device/global.h> #include <natus/math/dsp/fft.hpp> #include <thread> #include <array> // // This test prints the captured "What U Hear" samples using Imgui. // The program uses the async audio system. // namespace this_file { using namespace natus::core::types ; class test_app : public natus::application::app { natus_this_typedefs( test_app ) ; private: app::window_async_t _wid_async ; natus::audio::async_access_t _audio ; natus::device::three_device_res_t _dev_mouse ; natus::device::ascii_device_res_t _dev_ascii ; bool_t _fullscreen = false ; bool_t _vsync = true ; natus::audio::capture_object_res_t _capture = natus::audio::capture_object_t() ; bool_t _captured_rendered = true ; natus::audio::buffer_t _captured = natus::audio::buffer_t( 48000 ) ; natus::ntd::vector< float_t > _frequencies0 ; natus::ntd::vector< float_t > _frequencies1 ; natus::ntd::vector< float_t > _freq_bands ; natus::graphics::state_object_res_t _root_render_states ; public: test_app( void_t ) { natus::application::app::window_info_t wi ; wi.w = 1200 ; wi.h = 400 ; _wid_async = this_t::create_window( "Frequencies", wi, { natus::graphics::backend_type::d3d11 } ) ; _wid_async.window().fullscreen( _fullscreen ) ; _wid_async.window().vsync( _vsync ) ; _freq_bands.resize( 14 ) ; _audio = this_t::create_audio_engine() ; } test_app( this_cref_t ) = delete ; test_app( this_rref_t rhv ) : app( ::std::move( rhv ) ) { _wid_async = ::std::move( rhv._wid_async ) ; _dev_mouse = ::std::move( rhv._dev_mouse ) ; _dev_ascii = ::std::move( rhv._dev_ascii ) ; _audio = std::move( rhv._audio ) ; _frequencies0 = std::move( rhv._frequencies0 ) ; _freq_bands = std::move( rhv._freq_bands ) ; } virtual ~test_app( void_t ) {} private: virtual natus::application::result on_init( void_t ) noexcept { natus::device::global_t::system()->search( [&] ( natus::device::idevice_res_t dev_in ) { if( natus::device::three_device_res_t::castable( dev_in ) ) { _dev_mouse = dev_in ; } else if( natus::device::ascii_device_res_t::castable( dev_in ) ) { _dev_ascii = dev_in ; } } ) ; if( !_dev_mouse.is_valid() ) { natus::log::global_t::status( "no three mosue found" ) ; } if( !_dev_ascii.is_valid() ) { natus::log::global_t::status( "no ascii keyboard found" ) ; } // root render states { natus::graphics::state_object_t so = natus::graphics::state_object_t( "root_render_states" ) ; { natus::graphics::render_state_sets_t rss ; rss.depth_s.do_change = true ; rss.depth_s.ss.do_activate = false ; rss.polygon_s.do_change = true ; rss.polygon_s.ss.do_activate = true ; rss.polygon_s.ss.ff = natus::graphics::front_face::clock_wise ; rss.polygon_s.ss.cm = natus::graphics::cull_mode::back ; rss.polygon_s.ss.fm = natus::graphics::fill_mode::fill ; rss.blend_s.do_change = true ; rss.blend_s.ss.do_activate = true ; rss.blend_s.ss.src_blend_factor = natus::graphics::blend_factor::src_alpha ; rss.blend_s.ss.dst_blend_factor = natus::graphics::blend_factor::one_minus_src_alpha ; so.add_render_state_set( rss ) ; } _root_render_states = std::move( so ) ; _wid_async.async().configure( _root_render_states ) ; } _audio.configure( natus::audio::capture_type::what_u_hear, _capture ) ; return natus::application::result::ok ; } virtual natus::application::result on_event( window_id_t const, this_t::window_event_info_in_t wei ) noexcept { return natus::application::result::ok ; } virtual natus::application::result on_update( natus::application::app_t::update_data_in_t ) noexcept { { natus::device::layouts::ascii_keyboard_t ascii( _dev_ascii ) ; if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f8 ) == natus::device::components::key_state::released ) { _fullscreen = !_fullscreen ; _wid_async.window().fullscreen( _fullscreen ) ; } else if( ascii.get_state( natus::device::layouts::ascii_keyboard_t::ascii_key::f9 ) == natus::device::components::key_state::released ) { _vsync = !_vsync ; _wid_async.window().vsync( _vsync ) ; } } NATUS_PROFILING_COUNTER_HERE( "Update Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_audio( natus::application::app_t::audio_data_in_t ) noexcept { _frequencies1.resize( _frequencies0.size() ) ; for( size_t i = 0; i < _frequencies0.size(); ++i ) { _frequencies1[ i ] = _frequencies0[ i ] ; } _audio.capture( _capture ) ; _capture->append_samples_to( _captured ) ; _capture->copy_frequencies_to( _frequencies0 ) ; _frequencies1.resize( _frequencies0.size() ) ; NATUS_PROFILING_COUNTER_HERE( "Audio Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_tool( natus::tool::imgui_view_t imgui ) noexcept { ImGui::Begin( "Capture" ) ; // print wave form { auto const mm = _capture->minmax() ; ImGui::PlotLines( "Waveform", _captured.data(), ( int_t ) _captured.size(), 0, 0, mm.x(), mm.y(), ImVec2( ImGui::GetWindowWidth() - 100.0f, 100.0f ) ); } // print frequencies { float_t max_value = std::numeric_limits<float_t>::min() ; for( size_t i = 0 ; i < _frequencies0.size(); ++i ) max_value = std::max( _frequencies0[ i ], max_value ) ; static float_t smax_value = 0.0f ; float_t const mm = ( max_value + smax_value ) * 0.5f; ImGui::PlotHistogram( "Frequencies", _frequencies0.data(), ( int_t ) _frequencies0.size() / 4, 0, 0, 0.0f, mm, ImVec2( ImGui::GetWindowWidth() - 100.0f, 100.0f ) ); smax_value = max_value ; } // tried some sort of peaking, but sucks. if( _frequencies0.size() > 0 ) { natus::ntd::vector< float_t > difs( _frequencies0.size() ) ; for( size_t i = 0; i < _frequencies0.size(); ++i ) { difs[ i ] = _frequencies0[ i ] - _frequencies1[ i ] ; difs[ i ] = difs[ i ] < 0.00001f ? 0.0f : difs[ i ] ; } float_t max_value = std::numeric_limits<float_t>::min() ; for( size_t i = 0; i < 30/*difs.size()*/; ++i ) max_value = std::max( difs[ i ], max_value ) ; static float_t smax_value = 0.0f ; float_t const mm = ( max_value + smax_value ) * 0.5f; ImGui::PlotHistogram( "Difs", difs.data(), 30/*difs.size()*/, 0, 0, 0.0f, mm, ImVec2( ImGui::GetWindowWidth() - 100.0f, 100.0f ) ); smax_value = max_value ; } ImGui::End() ; return natus::application::result::ok ; } virtual natus::application::result on_graphics( natus::application::app_t::render_data_in_t ) noexcept { _wid_async.async().push( _root_render_states ) ; _wid_async.async().pop( natus::graphics::backend::pop_type::render_state ) ; NATUS_PROFILING_COUNTER_HERE( "Render Clock" ) ; return natus::application::result::ok ; } virtual natus::application::result on_shutdown( void_t ) noexcept { return natus::application::result::ok ; } }; natus_res_typedef( test_app ) ; } int main( int argc, char** argv ) { natus::application::global_t::create_application( this_file::test_app_res_t( this_file::test_app_t() ) )->exec() ; natus::memory::global_t::dump_to_std() ; return 0 ; }
35.398524
180
0.545293
aconstlink
6e0fcaf4754d944fd5d1a6768fbf9702c5a04573
1,315
cpp
C++
rete-reasoner/RuleParserAST.cpp
sempr-tk/rete
a6fd29f50f9e6a259d40ac0850acff7874ccdba0
[ "BSD-3-Clause" ]
1
2021-12-04T21:29:04.000Z
2021-12-04T21:29:04.000Z
rete-reasoner/RuleParserAST.cpp
sempr-tk/rete
a6fd29f50f9e6a259d40ac0850acff7874ccdba0
[ "BSD-3-Clause" ]
null
null
null
rete-reasoner/RuleParserAST.cpp
sempr-tk/rete
a6fd29f50f9e6a259d40ac0850acff7874ccdba0
[ "BSD-3-Clause" ]
null
null
null
#include "RuleParserAST.hpp" #include <ostream> #include <string> #include <algorithm> #include <iostream> namespace rete { namespace ast { std::ostream& operator << (std::ostream& s, Precondition& p) { if (p.name_) s << *p.name_; s << "( "; for (auto& arg : p.args_) { s << *arg << " "; } s << ")"; return s; } bool subst(std::string& str, const std::string& pre, const std::string& subst) { if (str.size() < pre.size()) return false; auto match = std::mismatch(pre.begin(), pre.end(), str.begin()); if (match.first == pre.end()) { // pre is prefix of str str.replace(str.begin(), match.second, subst.begin(), subst.end()); // add <...> str.insert(0, "<"); str.push_back('>'); return true; } return false; } // void Triple::substitutePrefixes(std::map<std::string, std::string>& prefixes) // { // bool s, p, o; // s = p = o = false; // // for (auto entry : prefixes) // { // if (!s) s = subst(*subject_->value_, entry.first, entry.second); // if (!p) p = subst(*predicate_->value_, entry.first, entry.second); // if (!o) o = subst(*object_->value_, entry.first, entry.second); // if (s && p && o) break; // } // } } /* ast */ } /* rete */
20.546875
80
0.524715
sempr-tk
6e1004408c254b3cb7185cdf436fc0b21d3e2fd4
2,289
cpp
C++
Optix Code/Optix7.3.0LightFIeldViewer/SDK/lib/DemandLoading/Textures/ImageReader.cpp
hamiltonmj/LF-Render
405faa0b94b5914a94c59152be1a7c6964a0fc7f
[ "MIT" ]
null
null
null
Optix Code/Optix7.3.0LightFIeldViewer/SDK/lib/DemandLoading/Textures/ImageReader.cpp
hamiltonmj/LF-Render
405faa0b94b5914a94c59152be1a7c6964a0fc7f
[ "MIT" ]
null
null
null
Optix Code/Optix7.3.0LightFIeldViewer/SDK/lib/DemandLoading/Textures/ImageReader.cpp
hamiltonmj/LF-Render
405faa0b94b5914a94c59152be1a7c6964a0fc7f
[ "MIT" ]
null
null
null
// // Copyright (c) 2021, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``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. // #include <DemandLoading/ImageReader.h> #include <cstddef> // for size_t namespace demandLoading { bool MipTailImageReader::readMipTail( char* dest, unsigned int mipTailFirstLevel, unsigned int numMipLevels, const uint2* mipLevelDims, unsigned int pixelSizeInBytes ) { size_t offset = 0; for( unsigned int mipLevel = mipTailFirstLevel; mipLevel < numMipLevels; ++mipLevel ) { const uint2 levelDims = mipLevelDims[mipLevel]; if( !readMipLevel( dest + offset, mipLevel, levelDims.x, levelDims.y ) ) { return false; } // Increment offset. offset += levelDims.x * levelDims.y * pixelSizeInBytes; } return true; } } // namespace demandLoading
43.188679
167
0.737003
hamiltonmj
6e14bf5c8a2d011b97bc28d9a1d18fa6575ce710
528
cpp
C++
7DRL 2017/Item.cpp
marukrap/woozoolike
ca16b67bce61828dded707f1c529558646daf0b3
[ "MIT" ]
37
2017-03-26T00:20:49.000Z
2021-02-11T18:23:22.000Z
7DRL 2017/Item.cpp
marukrap/woozoolike
ca16b67bce61828dded707f1c529558646daf0b3
[ "MIT" ]
null
null
null
7DRL 2017/Item.cpp
marukrap/woozoolike
ca16b67bce61828dded707f1c529558646daf0b3
[ "MIT" ]
9
2017-03-24T04:38:35.000Z
2021-08-22T00:02:43.000Z
#include "Item.hpp" #include "Renderer.hpp" #include "World.hpp" EntityType Item::getEntityType() const { return EntityType::Item; } void Item::draw(Renderer& renderer) { if (renderer.getType() == Renderer::Ascii) renderer.setChar(position.x, position.y, glyph, color); else // Renderer::Tile { sf::Color tileColor = sf::Color::White; // HACK: fov if (!world->getLevel().at(position).visible) tileColor.a = 51; renderer.addChar(position.x, position.y, tileNumber, tileColor); } }
20.307692
67
0.657197
marukrap
6e1b59f0f796ff1ab0eddfd809b837a7c547d6c7
3,532
cpp
C++
src/main.cpp
Turpaz/Dig
84270c44bfd783eae15f7231de45f29747274ccd
[ "MIT" ]
null
null
null
src/main.cpp
Turpaz/Dig
84270c44bfd783eae15f7231de45f29747274ccd
[ "MIT" ]
null
null
null
src/main.cpp
Turpaz/Dig
84270c44bfd783eae15f7231de45f29747274ccd
[ "MIT" ]
null
null
null
#include "lexer/lexer.hpp" #include "parser/parser.hpp" #include "codegen/codegen.hpp" #include "preprocessor/preprocessor.hpp" #include <string> #include <fstream> #include <streambuf> #include <string.h> #include <getopt.h> using std::string; string getfile(string name); inline bool does_file_exist(string path); inline void get_options(int argc, char** argv, int &opts, string& path, string& _o); int main(int argc, char** argv) { int cmd_options = cmd_args::None; string path = ""; string output_file; string src; bool dont_compile = false; // -----=+*/ PARSE COMMAND LINE ARGUMENTS \*+=----- // Make sure that there are command line arguments if (argc < 2) { fprintf(stderr, "No input file\n\n" USAGE_HELPER); exit(-1); } // Get the path, unless the first argument is a flag, then we'll stop comipilng before getting the file if (argv[1][0] != '-') path.assign(argv[1]); else dont_compile = true; // Get the options get_options(argc, argv, cmd_options, path, output_file); // -----=+*/ IMPLEMENT THE COMMAND LINE FLAGS THAT WE CAN \*+=----- // If the -h flag is set, print the help page and continue if (cmd_options & cmd_args::_h) { printf("%s", USAGE_HELPER); } // If the -v flag is set, print the version continue if (cmd_options & cmd_args::_v) { printf("%s", "Dig version: " DIG_VERSION "\n"); } // If the don't compile variable is true - exit here with exit code 0 if (dont_compile) exit(0); // -----=+*/ GET THE FILE AND SET THE OUTPUT FILE NEEDED \*+=----- // Check if file exist if (!does_file_exist(path)) { fprintf(stderr, "Input file \"%s\" doesn't exist\n\n", path.c_str()); exit(-1); } // set output_file if needed if (!(cmd_options & cmd_args::_o)) output_file = path.substr(0, path.find_last_of('.')) + ".exe"; // Get the file src = getfile(path); // -----=+*/ BEGINNING OF THE COMPILATION PROCESS! \*+=----- // Preprocess preprocess(src); // FIXME: Might be problematic, may interfere with the error position. we might have to skip comments in the lexer // If the -E flag is set, print the code and exit with exit code 0 if (cmd_options & cmd_args::_E) { printf("%s", src.c_str()); exit(0); } Lexer lexer(src, path); Parser parser(&lexer); Codegen codegen(&parser); TokenNode* root = new TokenNode(); Token tok; while (lexer.get_token(tok)) { root->add_child(tok); } root->add_child(Token()); // root->print(); parser.parse(*root); // parser.print(); codegen.generate(); codegen.print(); // TODO: write to output_file return 0; } string getfile(string name) { std::string str; std::ifstream f(name); f.seekg(0, std::ios::end); str.reserve(f.tellg()); f.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); return str; } inline bool does_file_exist(string path) { std::ifstream f(path.c_str()); return f.good(); } inline void get_options(int argc, char** argv, int &opts, string& path, string& _o) { int opt; while ((opt = getopt(argc, argv, ":" CMD_OPTIONS_STRING)) != -1) { switch(opt) { case 'o': opts |= cmd_args::_o; _o.assign(optarg); break; case 'h': opts |= cmd_args::_h; break; case 'v': opts |= cmd_args::_v; break; case 'E': opts |= cmd_args::_E; break; case ':': printf("Option -%c requires a value.\n", optopt); exit(-1); case '?': printf("Unknown option: -%c.\n", optopt); exit(-1); default: fprintf(stderr, ERROR_WE_DONT_KNOW); exit(-1); } } }
24.527778
132
0.643545
Turpaz
6e1fe96c035f4d0bc61f9b487973085b626d6784
1,787
hpp
C++
Axis.SystemBase/services/messaging/EventTag.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.SystemBase/services/messaging/EventTag.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.SystemBase/services/messaging/EventTag.hpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#pragma once #include "foundation/Axis.SystemBase.hpp" #include "foundation/collections/Collectible.hpp" namespace axis { namespace services { namespace messaging { /**********************************************************************************************//** * @brief Represents any tag attached to an event message. * * @author Renato T. Yamassaki * @date 24 ago 2012 * * @sa axis::foundation::collections::Collectible **************************************************************************************************/ class AXISSYSTEMBASE_API EventTag : public axis::foundation::collections::Collectible { public: /**********************************************************************************************//** * @brief Destructor. * * @author Renato T. Yamassaki * @date 24 ago 2012 **************************************************************************************************/ virtual ~EventTag(void); /**********************************************************************************************//** * @brief Destroys this object. * * @author Renato T. Yamassaki * @date 24 ago 2012 **************************************************************************************************/ virtual void Destroy(void) const = 0; /**********************************************************************************************//** * @brief Makes a deep copy of this object. * * @author Renato T. Yamassaki * @date 24 ago 2012 * * @return A copy of this object. **************************************************************************************************/ virtual EventTag& Clone(void) const = 0; }; } } }
33.716981
104
0.338556
renato-yuzup
6e235bbd18852f6d50b94c9aafef1bec5cb64a22
325
hpp
C++
Raytracer/include/Raytracer/Model/Model.hpp
YousifKako/Raytracer
78599f7170893b8bd37c12fc15e4cc6995625018
[ "MIT" ]
null
null
null
Raytracer/include/Raytracer/Model/Model.hpp
YousifKako/Raytracer
78599f7170893b8bd37c12fc15e4cc6995625018
[ "MIT" ]
null
null
null
Raytracer/include/Raytracer/Model/Model.hpp
YousifKako/Raytracer
78599f7170893b8bd37c12fc15e4cc6995625018
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <Model/Mesh.hpp> class Model { private: std::string model_name = ""; std::vector<Mesh*>* model = new std::vector<Mesh*>(); std::uint32_t num_objs = 0; public: Model(const std::string_view& model_name); void load(); const std::vector<Mesh*>* const get(); };
17.105263
57
0.633846
YousifKako
6e29a5e02246a187972d422250ac24200079d6e8
394
cpp
C++
src/allegro_flare/appearance2d.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
25
2015-03-30T02:02:43.000Z
2019-03-04T22:29:12.000Z
src/allegro_flare/appearance2d.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
122
2015-04-01T08:15:26.000Z
2019-10-16T20:31:22.000Z
src/allegro_flare/appearance2d.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
4
2016-09-02T12:14:09.000Z
2018-11-23T20:38:49.000Z
#include <allegro_flare/appearance2d.h> #include <AllegroFlare/Useful.hpp> // for tostring() namespace allegro_flare { appearance2d::appearance2d() : color(al_map_rgba_f(1,1,1,1)) , blender(BLENDER_NORMAL) , opacity(1) { } void appearance2d::clear() { color = al_map_rgba_f(1,1,1,1); opacity = 1; blender = BLENDER_NORMAL; } }
11.939394
52
0.611675
MarkOates
6e2a17c8d7a0870676aa8afddb4bfce21e89f404
4,314
hpp
C++
animake/GUIManager.hpp
KoreanGinseng/AniMake
509599c778c46d9d19d7cfa0acbfe9e4a6590ca6
[ "MIT" ]
null
null
null
animake/GUIManager.hpp
KoreanGinseng/AniMake
509599c778c46d9d19d7cfa0acbfe9e4a6590ca6
[ "MIT" ]
null
null
null
animake/GUIManager.hpp
KoreanGinseng/AniMake
509599c778c46d9d19d7cfa0acbfe9e4a6590ca6
[ "MIT" ]
null
null
null
#pragma once #include <Siv3D.hpp> #include "Define.hpp" namespace s3d { namespace SasaGUI { class GUIManager; } } namespace siapp { struct AnimationPattern { double wait = 1.0; int no = 0; int step = 0; AnimationPattern(void) : wait(1.0), no(0), step(0) { } AnimationPattern(const AnimationPattern& obj) { wait = obj.wait; no = obj.no; step = obj.step; } void operator= (const AnimationPattern& obj) { wait = obj.wait; no = obj.no; step = obj.step; } }; struct AnimationInfo { double offsetX = 0.0; double offsetY = 0.0; double width = 0.0; double height = 0.0; bool bLoop = false; Array<AnimationPattern> pattern; AnimationInfo(void) : offsetX(0.0), offsetY(0.0), width(0.0), height(0.0), bLoop(false) { for (int i : step(30)) { pattern << AnimationPattern(); } } AnimationInfo(const AnimationInfo& obj) { offsetX = obj.offsetX; offsetY = obj.offsetY; width = obj.width; height = obj.height; bLoop = obj.bLoop; pattern.clear(); for (size_t i : step(obj.pattern.size())) { pattern << AnimationPattern(); pattern[i] = obj.pattern[i]; } } void operator= (const AnimationInfo& obj) { offsetX = obj.offsetX; offsetY = obj.offsetY; width = obj.width; height = obj.height; bLoop = obj.bLoop; pattern.clear(); for (size_t i : step(obj.pattern.size())) { pattern << AnimationPattern(); pattern[i] = obj.pattern[i]; } } }; class GUIManager { private: SasaGUI::GUIManager* m_pGui; uint16 m_SelectListNo; Array<AnimationInfo> m_AnimationArray; Array<String> m_AnimNameArray; String m_AnimationName; int m_SelectPattern; double m_AllFrame; FilePath m_CurrentDir; FilePath m_TextureFilePath; FilePath m_AnimFilePath; FilePath m_TextFilePath; bool m_bDeleteAssert; Texture m_Texture; double m_TexScale; double m_AnimScale; double m_EditScale; double m_MotionSpeedRate; int m_PatternCount; double m_MotionTime; int m_Pattern; bool m_bTextureScaleWindow; bool m_bAnimationScaleWindow; bool m_bEditScaleWindow; Vec2 m_TextureOffset; Vec2 m_AnimationOffset; Vec2 m_EditOffset; bool m_bGrid; int m_GridScale; HSV m_Color; public: GUIManager(void); ~GUIManager(void); void Initialize(void); void Update(void); private: void AnimationAddTimer(const double& s); void ResetAnimTimer(void); void LoadTexture(const FilePath& path); double RectScale(const Vec2& rectSize, const Vec2& drawSize); void LoadData(const FilePath& path); void SaveData(const FilePath& path); void AnimationViewWindow(void); void TextureScaleWindow(const RectF& rect, const double& def, bool& outOver); void AnimaitonScaleWindow(const RectF& rect, const double& def, bool& outOver); void EditScaleWindow(const RectF& rect, const double& def, bool& outOver); void GridGroup(void); void GridView(const RectF& rect, const double& scale); void AnimationDataWindow(void); void AnimationNameList(void); void AnimationDataGroup(void); void AnimationPatternGroup(void); void AnimationAddGroup(void); void AnimationDeleteWindow(void); void AnimationBtnWindow(void); void AnimationFileGroup(void); void AnimationSaveBtnGroup(void); void AnimationFileDataGroup(void); void AnimationAllFrameGroup(void); void AnimationListWindow(void); RectF GetSrcRect(void); RectF GetPtnRect(void); }; }
24.372881
81
0.556328
KoreanGinseng
6e331c1a185f5ff33ac7ac4f1ff750160129e46e
494
cpp
C++
lib/Rudder/Rudder.cpp
andyrobinson/ard-nav
8162b2c9b882393ffd44e42d3f0816d7b1090760
[ "MIT" ]
null
null
null
lib/Rudder/Rudder.cpp
andyrobinson/ard-nav
8162b2c9b882393ffd44e42d3f0816d7b1090760
[ "MIT" ]
null
null
null
lib/Rudder/Rudder.cpp
andyrobinson/ard-nav
8162b2c9b882393ffd44e42d3f0816d7b1090760
[ "MIT" ]
null
null
null
#include "Rudder.h" #include "Angle.h" using namespace Angle; Rudder::Rudder() {} Rudder::Rudder(VSServoSamd *servo) { rudder_servo = servo; } void Rudder::set_position(angle position) { if (position > RUDDER_MAX_DISPLACEMENT) { position = RUDDER_MAX_DISPLACEMENT; } else if (position < -RUDDER_MAX_DISPLACEMENT) { position = -RUDDER_MAX_DISPLACEMENT; } int servo_0_to_180_angle = RUDDER_CENTRE + position; rudder_servo->write(servo_0_to_180_angle, RUDDER_SPEED); }
20.583333
58
0.734818
andyrobinson
6e3869a618c4739067546fa0cb505b76efd69953
2,404
cpp
C++
core/connections/wim/packets/set_avatar.cpp
mail-ru-im/im-desktop
d6bb606650ad84b31046fe39b81db1fec4e6050b
[ "Apache-2.0" ]
81
2019-09-18T13:53:17.000Z
2022-03-19T00:44:20.000Z
core/connections/wim/packets/set_avatar.cpp
mail-ru-im/im-desktop
d6bb606650ad84b31046fe39b81db1fec4e6050b
[ "Apache-2.0" ]
4
2019-10-03T15:17:00.000Z
2019-11-03T01:05:41.000Z
core/connections/wim/packets/set_avatar.cpp
mail-ru-im/im-desktop
d6bb606650ad84b31046fe39b81db1fec4e6050b
[ "Apache-2.0" ]
25
2019-09-27T16:56:02.000Z
2022-03-14T07:11:14.000Z
#include "stdafx.h" #include "set_avatar.h" #include "../../../http_request.h" #include "../../../tools/system.h" #include "../../../../common.shared/json_helper.h" #include "../../urls_cache.h" using namespace core; using namespace wim; set_avatar::set_avatar(wim_packet_params _params, tools::binary_stream _image, const std::string& _aimid, const bool _chat) : wim_packet(std::move(_params)) , aimid_(_aimid) , chat_(_chat) , image_(_image) { } set_avatar::~set_avatar() = default; std::string_view set_avatar::get_method() const { return "avatarSet"; } int32_t set_avatar::init_request(const std::shared_ptr<core::http_request_simple>& _request) { std::stringstream ss_url; ss_url << urls::get_url(urls::url_type::avatars) << "/set?" << "aimsid=" << escape_symbols(get_params().aimsid_); if (!chat_ && !aimid_.empty()) ss_url << "&targetSn=" << escape_symbols(aimid_); else if (chat_) ss_url << "&beforehandUpload=1"; _request->set_normalized_url(get_method()); _request->set_custom_header_param("Content-Type: multipart/form-data"); _request->set_post_form(true); _request->push_post_form_filedata("image", image_); image_.reset_out(); _request->set_need_log(true); _request->set_write_data_log(params_.full_log_); _request->set_url(ss_url.str()); _request->set_keep_alive(); if (!params_.full_log_) { log_replace_functor f; f.add_marker("aimsid", aimsid_range_evaluator()); _request->set_replace_log_function(f); } return 0; } int32_t set_avatar::execute_request(const std::shared_ptr<core::http_request_simple>& request) { url_ = request->get_url(); if (auto error_code = get_error(request->post())) return *error_code; http_code_ = (uint32_t)request->get_response_code(); if (http_code_ != 200) return wpie_http_error; // for chat avatar id is returned in the response header as X-Avatar-Hash if (std::string val = http_header::get_attribute(request->get_header(), "X-Avatar-Hash"); !val.empty()) id_ = std::move(val); else if (chat_) return wpie_http_empty_response; return 0; } int32_t set_avatar::parse_response(const std::shared_ptr<core::tools::binary_stream>& response) { return 0; } int32_t set_avatar::parse_response_data(const rapidjson::Value& _data) { return 0; }
26.711111
123
0.680532
mail-ru-im
6e3e86b41db938a5f01dd3b1834882a5526fae2e
524
cpp
C++
cppdot/chainspec.cpp
sanblch/prototypes
f8e17041062211c05e861bcb8ed395d9fa1c0080
[ "MIT" ]
null
null
null
cppdot/chainspec.cpp
sanblch/prototypes
f8e17041062211c05e861bcb8ed395d9fa1c0080
[ "MIT" ]
null
null
null
cppdot/chainspec.cpp
sanblch/prototypes
f8e17041062211c05e861bcb8ed395d9fa1c0080
[ "MIT" ]
1
2021-05-25T10:49:57.000Z
2021-05-25T10:49:57.000Z
#include "chainspec.hpp" OUTCOME_CPP_DEFINE_CATEGORY(chainspec, ChainSpecError, e) { using E = chainspec::ChainSpecError; switch (e) { case E::MISSING_ENTRY: return "A required entry is missing in the config file"; case E::MISSING_PEER_ID: return "Peer id is missing in a multiaddress provided in the config file"; case E::PARSER_ERROR: return "Internal parser error"; case E::NOT_IMPLEMENTED: return "Known entry name, but parsing not implemented"; } return "Unknown error in ChainSpec"; }
30.823529
78
0.729008
sanblch
6e4753d0099246f7270e415f26e14955771f702f
129
cc
C++
echo_srv/main.cc
anton4o123/websocket-library
fe1a4b9d8721fe06e10229aff1cd7859015a1672
[ "BSD-2-Clause" ]
null
null
null
echo_srv/main.cc
anton4o123/websocket-library
fe1a4b9d8721fe06e10229aff1cd7859015a1672
[ "BSD-2-Clause" ]
null
null
null
echo_srv/main.cc
anton4o123/websocket-library
fe1a4b9d8721fe06e10229aff1cd7859015a1672
[ "BSD-2-Clause" ]
null
null
null
#include "server.hh" int main(){ WebSock_Server ws("127.0.0.1",80,5); ws.start(); int i = ws.accept_conn(); return 0; }
10.75
37
0.604651
anton4o123
6e48163d0e24cf2676971c9b04a76dcb8ff07b2a
617
cpp
C++
LeetCode/Array/MinimumValuetoGetPositiveStepbyStepSum.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
3
2021-07-26T15:58:45.000Z
2021-09-08T14:55:11.000Z
LeetCode/Array/MinimumValuetoGetPositiveStepbyStepSum.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
null
null
null
LeetCode/Array/MinimumValuetoGetPositiveStepbyStepSum.cpp
a4org/Angorithm4
d2227d36608491bed270375bcea67fbde134209a
[ "MIT" ]
2
2021-05-31T11:27:59.000Z
2021-10-03T13:26:00.000Z
/* * LeetCode 1413 Minimum Value to Get Positive Step by Step Sum * Easy * Shuo Feng * 2021.11.11 */ #include<iostream> #include<vector> using namespace std; /* * Solution: Brute Force. */ class Solution { public: int minStartValue(vector<int>& nums) { int res = 1; while (1) { int sum = res; for (int i = 0; i < nums.size(); ++i) { sum += nums[i]; if (sum < 1) break; if (sum >= 1 && i == nums.size() - 1) return res; } res += 1; } } };
18.147059
63
0.435981
a4org
6e48aee306cacd93641abd6cb59f878b258cf385
6,683
hpp
C++
src/PluginSegmentation/Gui/SegmentationWidget.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
4
2016-06-03T18:41:43.000Z
2020-04-17T20:28:58.000Z
src/PluginSegmentation/Gui/SegmentationWidget.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
src/PluginSegmentation/Gui/SegmentationWidget.hpp
voxie-viewer/voxie
d2b5e6760519782e9ef2e51f5322a3baa0cb1198
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2022 The Voxie Authors * * 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. */ #pragma once // QDBusConnection should be included as early as possible: // https://bugreports.qt.io/browse/QTBUG-48351 / // https://bugreports.qt.io/browse/QTBUG-48377 #include <QtDBus/QDBusConnection> #include <qlabel.h> #include <qlistview.h> #include <qlistwidget.h> #include <qpushbutton.h> #include <qspinbox.h> #include <qtableview.h> #include <qwidget.h> #include <PluginSegmentation/SegmentationUtils.hpp> #include <PluginSegmentation/StepManager.hpp> #include <QRadioButton> #include <QTimer> #include <QToolBar> #include <Voxie/Data/LabelViewModel.hpp> #include <Voxie/Gui/ColorizerGradientWidget.hpp> #include <Voxie/Gui/ColorizerWidget.hpp> #include <Voxie/Gui/LabelTableView.hpp> #include <Voxie/Vis/HistogramWidget.hpp> #include "PluginSegmentation/Gui/HistoryViewModel.hpp" namespace vx { class SegmentationWidget : public QWidget { Q_OBJECT public: SegmentationWidget(LabelViewModel* labelViewModel, HistoryViewModel* historyViewModel, StepManager* stepManager); /** * @brief Returns the row indices of the currently selected labels */ QList<int> getSelectedIndices(); /** * @brief Returns the labelIDs of the currently selected labels */ QList<SegmentationType> getSelectedLabelIDs(); /** * @brief Returns all LabelIDs of the labelTable */ QList<SegmentationType> getLabelIDs(); /** * @brief Returns the not selected labelIDs (e.g. diff between AllLabelIDs and * SelectedLabelIDs) */ QList<SegmentationType> getNotSelectedLabelIDs(); /** * @brief Uncheck brush and eraser selection buttons */ void uncheckBrushes(); /** * @brief Uncheck lasso selection button */ void uncheckLasso(); /** * @param incremental Flag to indicate if voxelCount is added to the existing * value or if the existing value is overwritten * @param voxelCount Voxel count of the selection * @param totalVoxelCount Voxel count of the whole volume */ void setActiveSelectionInfo(bool incremental, qint64 voxelCount, qint64 totalVoxelCount); /** * @brief Set the info text of the hovered voxel */ void setHoverInfo(double voxelValue, QString voxelLabel); /** * @brief Sets histogram variable provider for slices */ void setSliceHistogramProvider( QSharedPointer<vx::HistogramProvider> provider); /** * @brief Gets the segmentation histogram widget colorizer */ ColorizerWidget* getColorizerWidget(); private Q_SLOTS: /** * @brief Add a new label and update the GUI */ int addLabel(); /** * @brief Add a new label and update the GUI * @param color Color of the new label */ int addLabelByColor(Color color); /** * @brief Open a color picker and set the selected labels colors to the chosen * color */ void colorizeLabels(); /** * @brief Set the selected labels voxels as active selection */ void selectLabelVoxels(); /** * @brief Delete the selected labels */ void deleteLabels(); /** * @brief Add the active selection to the selected label */ void addSelectionToLabel(); /** * @brief Subtract the active selection from the selected labels */ void subtractSelectionFromLabels(); /** * @brief Reset the active selection */ void resetSelection(); /** * @brief Reset the segmentation widgets to their default values */ void resetSegmentationWidgets(); Q_SIGNALS: /** * @brief Called when the input volume is set/removed */ void isInputExisting(bool isExisting); /** * @brief Called when the brush or eraser is toggled using its button */ void toggledBrush(bool isSet); /** * @brief Called when the radius is changed using its spinbox */ void changedRadius(int radius); /** * @brief Called when the lasso is toggled using its button */ void toggledLasso(bool isSet); /** * @brief Called when the active selection is reset */ void resetActiveSelection(); /** * @brief Called, when all UI widgets should be resetted to the default state */ void resetUIWidgets(); private: LabelViewModel* labelViewModel; HistoryViewModel* historyViewModel; StepManager* stepManager; QPushButton* addLabelButton; QPushButton* colorLabelButton; QPushButton* selectLabelButton; QPushButton* deleteLabelButton; QTableView* tableView; QTabWidget* stepTabs; // Colorizer ColorizerWidget* segmentationColorizer; // Histogram HistogramWidget* histogram; QRadioButton* sliceRadioButton; QRadioButton* volumeRadioButton; QSharedPointer<vx::HistogramProvider> sliceHistogramProvider; QSharedPointer<vx::HistogramProvider> volumeHistogramProvider; QPushButton* addSelectionButton; QPushButton* subtractSelectionButton; QPushButton* resetSelectionButton; /** * @brief Indicates if the segmentation fields are beeing reset */ bool isResettingFields = false; /** * @brief Indicates if the brush is currently in the process of changing. This * exists to prevent recursive behaviour. */ bool isChangingBrushState = false; QPushButton* brushToggleButton; QPushButton* eraserToggleButton; QSpinBox* brushRadiusBox; QPushButton* lassoToggleButton; QLabel* selectedVoxelCount; QLabel* selectedVoxelPercentage; /** * @brief Current voxel count of the active selection (used for incremental * changes) */ qint64 activeSelectionVoxelCount = 0; QLabel* hoveredVoxelValue; QLabel* hoveredVoxelLabel; QListView* historyListView; }; } // namespace vx
29.311404
80
0.723477
voxie-viewer
6e49d4112d815f19dff10f0a20256342e47fb172
1,817
cpp
C++
workshop/SettingsPage.cpp
Zackmon/SeventhUmbral
25580111b361d2fdc2c15fd2cd150e4c763ca774
[ "BSD-2-Clause" ]
92
2015-01-30T01:57:18.000Z
2022-02-14T00:05:30.000Z
workshop/SettingsPage.cpp
Zackmon/SeventhUmbral
25580111b361d2fdc2c15fd2cd150e4c763ca774
[ "BSD-2-Clause" ]
6
2015-08-18T19:57:17.000Z
2022-01-31T14:48:33.000Z
workshop/SettingsPage.cpp
Zackmon/SeventhUmbral
25580111b361d2fdc2c15fd2cd150e4c763ca774
[ "BSD-2-Clause" ]
44
2015-01-03T13:01:21.000Z
2022-01-31T14:24:40.000Z
#include "SettingsPage.h" #include "resource.h" #include "Utf8.h" #include "AppConfig.h" #include "AppPreferences.h" #include "string_cast.h" CSettingsPage::CSettingsPage(HWND parentWnd) : CDialog(MAKEINTRESOURCE(IDD_SETTINGSPAGE), parentWnd) { SetClassPtr(); m_gameLocationEdit = Framework::Win32::CEdit(GetItem(IDC_SETTINGSPAGE_GAMELOCATION_EDIT)); UpdateGameLocation(); } CSettingsPage::~CSettingsPage() { } std::string CSettingsPage::GetName() const { return "General Settings"; } long CSettingsPage::OnCommand(unsigned short cmd, unsigned short, HWND) { switch(cmd) { case IDC_SETTINGSPAGE_BROWSE_GAMELOCATION: BrowseGameLocation(); break; } return TRUE; } void CSettingsPage::UpdateGameLocation() { auto gameLocation = Framework::Utf8::ConvertFrom(CAppConfig::GetInstance().GetPreferenceString(PREF_WORKSHOP_GAME_LOCATION)); m_gameLocationEdit.SetText(string_cast<std::tstring>(gameLocation).c_str()); } void CSettingsPage::BrowseGameLocation() { auto gameLocation = BrowseForFolder(_T("Specify FFXIV folder")); if(!gameLocation.empty()) { CAppConfig::GetInstance().SetPreferenceString(PREF_WORKSHOP_GAME_LOCATION, Framework::Utf8::ConvertTo(string_cast<std::wstring>(gameLocation)).c_str()); UpdateGameLocation(); } } std::tstring CSettingsPage::BrowseForFolder(const TCHAR* title) { std::tstring folder; BROWSEINFO browseInfo = {}; browseInfo.hwndOwner = m_hWnd; browseInfo.lpszTitle = title; browseInfo.ulFlags = BIF_RETURNONLYFSDIRS | BIF_USENEWUI; PIDLIST_ABSOLUTE result = SHBrowseForFolder(&browseInfo); if(result != NULL) { TCHAR selectedPath[MAX_PATH]; if(SHGetPathFromIDList(result, selectedPath)) { folder = selectedPath; } CoTaskMemFree(result); } return folder; }
24.226667
127
0.735828
Zackmon
6e50e918cba38564ef86b76d22b8a56601b65a53
1,862
cc
C++
algo/stack/stack_queue.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
algo/stack/stack_queue.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
algo/stack/stack_queue.cc
liuheng/recipes
6f3759ab4e4fa64d9fd83a60ee6b6846510d910b
[ "MIT" ]
null
null
null
//Implement a MyQueue class which implements a queue using two stacks. #include <cassert> #include "stack.hpp" using namespace std; class MyQueue { public: MyQueue() : m_len(0) {} int Enqueue(int value) { if (m_len >= MAX_STACK_SIZE) { return -1; } else { m_s1.Push(value); return 0; } } int Dequeue() { if (m_s2.IsEmpty()) { while(true) { int a = m_s1.Pop(); if (a == -1) { break; } else { m_s2.Push(a); } } } return m_s2.Pop(); } int Front() { if (m_s2.IsEmpty()) { while(true) { int a = m_s1.Pop(); if (a == -1) { break; } else { m_s2.Push(a); } } } return m_s2.Top(); } int Back() { if (m_s1.IsEmpty() && !m_s2.IsEmpty()) { while(true) { int a = m_s2.Pop(); if (a == -1) { break; } else { m_s1.Push(a); } } } return m_s1.Top(); } private: Stack<int> m_s1; Stack<int> m_s2; size_t m_len; }; int main() { MyQueue q; assert(0 == q.Enqueue(1)); assert(0 == q.Enqueue(2)); assert(0 == q.Enqueue(3)); assert(0 == q.Enqueue(4)); assert(0 == q.Enqueue(5)); assert(1 == q.Dequeue()); assert(2 == q.Dequeue()); assert(3 == q.Front()); assert(5 == q.Back()); assert(0 == q.Enqueue(6)); assert(3 == q.Front()); assert(3 == q.Dequeue()); assert(4 == q.Dequeue()); assert(0 == q.Enqueue(7)); assert(7 == q.Back()); return 0; }
20.23913
70
0.392052
liuheng
6e51b55da014c4cc0ad06e790640f4a32edc231c
6,538
cpp
C++
src/Modules/Helpers/Helpers/libhelpers/TypeConverter.cpp
sssr33/LuaModules
357a8c9445a237f2c98685000f6c7da668ea0e72
[ "MIT" ]
1
2020-02-24T22:21:04.000Z
2020-02-24T22:21:04.000Z
src/Modules/Helpers/Helpers/libhelpers/TypeConverter.cpp
sssr33/LuaModules
357a8c9445a237f2c98685000f6c7da668ea0e72
[ "MIT" ]
null
null
null
src/Modules/Helpers/Helpers/libhelpers/TypeConverter.cpp
sssr33/LuaModules
357a8c9445a237f2c98685000f6c7da668ea0e72
[ "MIT" ]
1
2019-10-11T12:48:44.000Z
2019-10-11T12:48:44.000Z
#include "TypeConverter.h" #include "HMath.h" #include "HText.h" std::wstring TypeConverter<std::wstring, std::string>::Convert(const std::string &v) { std::wstring tmp(v.begin(), v.end()); return tmp; } std::string TypeConverter<std::string, std::wstring>::Convert(const std::wstring &v) { std::string tmp(v.begin(), v.end()); return tmp; } std::wstring TypeConverter<std::wstring, string_u8>::Convert(const string_u8 &v) { return H::Text::ConvertUTF8ToWString(v.val); } string_u8 TypeConverter<string_u8, std::wstring>::Convert(const std::wstring &v) { return H::Text::ConvertWStringToUTF8(v); } std::wstring TypeConverter<std::wstring, LPCSTR>::Convert(const LPCSTR v) { size_t len = (size_t)strlen(v); std::wstring tmp(v, v + len); return tmp; } D2D1_SIZE_F TypeConverter<D2D1_SIZE_F, D2D1_SIZE_U>::Convert(const D2D1_SIZE_U &v) { D2D1_SIZE_F tmp; tmp.width = (float)v.width; tmp.height = (float)v.height; return tmp; } D2D1_COLOR_F TypeConverter<D2D1_COLOR_F, D2D1::ColorF>::Convert(const D2D1::ColorF &v) { D2D1_COLOR_F color; color.a = v.a; color.r = v.r; color.g = v.g; color.b = v.b; return color; } D2D1::ColorF TypeConverter<D2D1::ColorF, D2D1_COLOR_F>::Convert(const D2D1_COLOR_F &v) { D2D1::ColorF color(v.r, v.g, v.b, v.a); return color; } // Structs::Rgba <-> D2D1::ColorF Structs::Rgba TypeConverter<Structs::Rgba, D2D1::ColorF>::Convert(const D2D1::ColorF &v) { const float scale = 255.0f; Structs::Rgba res; res.r = (uint8_t)H::Math::Clamp(v.r * scale, 0.0f, scale); res.g = (uint8_t)H::Math::Clamp(v.g * scale, 0.0f, scale); res.b = (uint8_t)H::Math::Clamp(v.b * scale, 0.0f, scale); res.a = (uint8_t)H::Math::Clamp(v.a * scale, 0.0f, scale); return res; } D2D1::ColorF TypeConverter<D2D1::ColorF, Structs::Rgba>::Convert(const Structs::Rgba &v) { const float scale = 1.0f / 255.0f; D2D1::ColorF res( (float)v.r * scale, (float)v.g * scale, (float)v.b * scale, (float)v.a * scale); return res; } // Structs::Rgba <-> D2D1_COLOR_F Structs::Rgba TypeConverter<Structs::Rgba, D2D1_COLOR_F>::Convert(const D2D1_COLOR_F &v) { auto res = TypeConverter<Structs::Rgba, D2D1::ColorF>::Convert(D2D1::ColorF(v.r, v.g, v.b, v.a)); return res; } D2D1_COLOR_F TypeConverter<D2D1_COLOR_F, Structs::Rgba>::Convert(const Structs::Rgba &v) { return TypeConverter<D2D1::ColorF, Structs::Rgba>::Convert(v); } // Structs::Rect <-> D2D1_RECT_F Structs::Rect TypeConverter<Structs::Rect, D2D1_RECT_F>::Convert(const D2D1_RECT_F &v) { Structs::Rect res(v.left, v.top, v.right, v.bottom); return res; } D2D1_RECT_F TypeConverter<D2D1_RECT_F, Structs::Rect>::Convert(const Structs::Rect &v) { D2D1_RECT_F res = D2D1::RectF(v.left, v.top, v.right, v.bottom); return res; } // Structs::Float2 <-> D2D1_POINT_2F Structs::Float2 TypeConverter<Structs::Float2, D2D1_POINT_2F>::Convert(const D2D1_POINT_2F &v) { Structs::Float2 res(v.x, v.y); return res; } D2D1_POINT_2F TypeConverter<D2D1_POINT_2F, Structs::Float2>::Convert(const Structs::Float2 &v) { D2D1_POINT_2F res = D2D1::Point2F(v.x, v.y); return res; } #if HAVE_WINRT == 1 Windows::UI::Color TypeConverter<Windows::UI::Color, D2D1::ColorF>::Convert(const D2D1::ColorF &v) { Windows::UI::Color color; color.A = (uint8_t)(v.a * 255.0f); color.R = (uint8_t)(v.r * 255.0f); color.G = (uint8_t)(v.g * 255.0f); color.B = (uint8_t)(v.b * 255.0f); return color; } D2D1::ColorF TypeConverter<D2D1::ColorF, Windows::UI::Color>::Convert(const Windows::UI::Color &v) { const float Scale = 1.0f / 255.0f; float a, r, g, b; a = (float)v.A * Scale; r = (float)v.R * Scale; g = (float)v.G * Scale; b = (float)v.B * Scale; auto compColor = Windows::UI::Colors::Transparent; if (v.A == compColor.A && v.R == compColor.R && v.G == compColor.G && v.B == compColor.B) { a = r = g = b = 0.0f; } return D2D1::ColorF(r, g, b, a); }; Windows::UI::Color TypeConverter<Windows::UI::Color, D2D1_COLOR_F>::Convert(const D2D1_COLOR_F &v) { D2D1::ColorF tmp(v.r, v.g, v.b, v.a); return TypeConverter<Windows::UI::Color, D2D1::ColorF>::Convert(tmp); } D2D1_COLOR_F TypeConverter<D2D1_COLOR_F, Windows::UI::Color>::Convert(const Windows::UI::Color &v) { D2D1_COLOR_F res = TypeConverter<D2D1::ColorF, Windows::UI::Color>::Convert(v); return res; } Platform::String ^TypeConverter<Platform::String ^, std::wstring>::Convert(const std::wstring &v) { Platform::String ^tmp = ref new Platform::String(v.data(), (int)v.size()); return tmp; } std::wstring TypeConverter<std::wstring, Platform::String ^>::Convert(Platform::String ^v) { std::wstring tmp(v->Data(), v->Length()); return tmp; } Platform::String ^TypeConverter<Platform::String ^, std::string>::Convert(const std::string &v) { std::wstring tmpWStr(v.begin(), v.end()); Platform::String ^tmp = ref new Platform::String(tmpWStr.data(), (int)tmpWStr.size()); return tmp; } std::string TypeConverter<std::string, Platform::String ^>::Convert(Platform::String ^v) { std::wstring tmpWStr(v->Data(), v->Length()); std::string tmp(tmpWStr.begin(), tmpWStr.end()); return tmp; } Platform::String ^TypeConverter<Platform::String ^, string_u8>::Convert(const string_u8 &v) { auto wstr = TypeConverter<std::wstring, string_u8>::Convert(v); return TypeConverter<Platform::String ^, std::wstring>::Convert(wstr); } string_u8 TypeConverter<string_u8, Platform::String ^>::Convert(Platform::String ^v) { auto wstr = TypeConverter<std::wstring, Platform::String ^>::Convert(v); return TypeConverter<string_u8, std::wstring>::Convert(wstr); } Windows::Foundation::TimeSpan TypeConverter<Windows::Foundation::TimeSpan, int64_t>::Convert(const int64_t &v) { Windows::Foundation::TimeSpan res; res.Duration = v; return res; } int64_t TypeConverter<int64_t, Windows::Foundation::TimeSpan>::Convert(Windows::Foundation::TimeSpan v) { return v.Duration; } Windows::Foundation::Point TypeConverter<Windows::Foundation::Point, D2D1_SIZE_U>::Convert(D2D1_SIZE_U v) { Windows::Foundation::Point res; res.X = (float)v.width; res.Y = (float)v.height; return res; } D2D1_SIZE_U TypeConverter<D2D1_SIZE_U, Windows::Foundation::Point>::Convert(Windows::Foundation::Point v) { D2D1_SIZE_U res = { (uint32_t)std::roundf(v.X), (uint32_t)std::roundf(v.Y) }; return res; } #endif
32.366337
112
0.665035
sssr33
6e54655695d344678c8c867f95a45e069fa0aa09
18,193
cpp
C++
thcrap_configure/src/winconsole.cpp
zero318/thcrap
dff0f66d486aae9e19f0237527a0c3d5163fb34c
[ "Unlicense" ]
null
null
null
thcrap_configure/src/winconsole.cpp
zero318/thcrap
dff0f66d486aae9e19f0237527a0c3d5163fb34c
[ "Unlicense" ]
null
null
null
thcrap_configure/src/winconsole.cpp
zero318/thcrap
dff0f66d486aae9e19f0237527a0c3d5163fb34c
[ "Unlicense" ]
null
null
null
#include <thcrap.h> #include <windows.h> #include <windowsx.h> #include "console.h" #include "resource.h" #include <string.h> #include <CommCtrl.h> #include <queue> #include <mutex> #include <future> #include <memory> #include <thread> template<typename T> using EventPtr = const std::shared_ptr<std::promise<T>>*; #define APP_READQUEUE (WM_APP+0) /* lparam = const std::shared_ptr<std::promise<char>>* */ #define APP_ASKYN (WM_APP+1) /* wparam = length of output string */ /* lparam = const std::shared_ptr<std::promise<wchar_t*>>* */ #define APP_GETINPUT (WM_APP+2) /* wparam = WM_CHAR */ #define APP_LISTCHAR (WM_APP+3) #define APP_UPDATE (WM_APP+4) #define APP_PREUPDATE (WM_APP+5) /* lparam = const std::shared_ptr<std::promise<void>>* */ #define APP_PAUSE (WM_APP+6) /* wparam = percent */ #define APP_PROGRESS (WM_APP+7) /* Reads line queue */ #define Thcrap_ReadQueue(hwndDlg) ((void)::PostMessage((hwndDlg), APP_READQUEUE, 0, 0L)) #define Thcrap_Askyn(hwndDlg,a_promise) ((void)::PostMessage((hwndDlg), APP_ASKYN, 0, (LPARAM)(EventPtr<char>)(a_promise))) /* Request input */ /* UI thread will signal g_event when user confirms input */ #define Thcrap_GetInput(hwndDlg,len,a_promise) ((void)::PostMessage((hwndDlg), APP_GETINPUT, (WPARAM)(DWORD)(len), (LPARAM)(EventPtr<wchar_t*>)(a_promise))) /* Should be called after adding/appending bunch of lines */ #define Thcrap_Update(hwndDlg) ((void)::PostMessage((hwndDlg), APP_UPDATE, 0, 0L)) /* Should be called before adding lines*/ #define Thcrap_Preupdate(hwndDlg) ((void)::PostMessage((hwndDlg), APP_PREUPDATE, 0, 0L)) /* Pause */ #define Thcrap_Pause(hwndDlg,a_promise) ((void)::PostMessage((hwndDlg), APP_PAUSE, 0, (LPARAM)(EventPtr<void>)(a_promise))) /* Updates progress bar */ #define Thcrap_Progress(hwndDlg, pc) ((void)::PostMessage((hwndDlg), APP_PROGRESS, (WPARAM)(DWORD)(pc), 0L)) enum LineType { LINE_ADD, LINE_APPEND, LINE_CLS, LINE_PENDING }; struct LineEntry { LineType type; std::wstring content; }; template<typename T> class WaitForEvent { std::shared_ptr<std::promise<T>> promise; std::future<T> future; public: WaitForEvent() { promise = std::make_shared<std::promise<T>>(); future = promise->get_future(); } EventPtr<T> getEvent() { return &promise; } T getResponse() { return future.get(); } }; template<typename T> void SignalEvent(std::shared_ptr<std::promise<T>>& ptr, T val) { if (ptr) { ptr->set_value(val); ptr.reset(); } } void SignalEvent(std::shared_ptr<std::promise<void>>& ptr) { if (ptr) { ptr->set_value(); ptr.reset(); } } static HWND g_hwnd = NULL; static std::mutex g_mutex; // used for synchronizing the queue static std::queue<LineEntry> g_queue; static std::vector<std::wstring> q_responses; static std::shared_ptr<std::promise<void>> g_exitguithreadevent; static bool* CurrentMode = nullptr; static void SetMode(HWND hwndDlg, bool* mode) { if (CurrentMode == mode) return; CurrentMode = mode; int items[] = { IDC_BUTTON1, IDC_EDIT1, IDC_PROGRESS1, IDC_STATIC1, IDC_BUTTON_YES, IDC_BUTTON_NO}; for (int i = 0; i < _countof(items); i++) { HWND item = GetDlgItem(hwndDlg, items[i]); ShowWindow(item, mode[i] ? SW_SHOW : SW_HIDE); EnableWindow(item, mode[i] ? TRUE : FALSE); } } static bool InputMode[] = { true, true, false, false, false, false }; static bool PauseMode[] = { true, false, false, false, false, false }; static bool ProgressBarMode[] = { false, false, true, false, false, false}; static bool NoMode[] = { false, false, false, true, false, false}; static bool AskYnMode[] = { false, false, false, false, true, true}; WNDPROC origEditProc = NULL; LRESULT CALLBACK EditProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (uMsg == WM_KEYDOWN && wParam == VK_RETURN) { SendMessage(GetParent(hwnd), WM_COMMAND, MAKELONG(IDC_BUTTON1, BN_CLICKED), (LPARAM)hwnd); return 0; } else if (uMsg == WM_GETDLGCODE && wParam == VK_RETURN) { // nescessary for control to recieve VK_RETURN return origEditProc(hwnd, uMsg, wParam, lParam) | DLGC_WANTALLKEYS; } else if (uMsg == WM_KEYDOWN && (wParam == VK_UP || wParam == VK_DOWN)) { // Switch focus to list on up/down arrows HWND list = GetDlgItem(GetParent(hwnd), IDC_LIST1); SetFocus(list); return 0; } else if ((uMsg == WM_KEYDOWN || uMsg == WM_KEYUP) && (wParam == VK_PRIOR || wParam == VK_NEXT)) { // Switch focus to list on up/down arrows HWND list = GetDlgItem(GetParent(hwnd), IDC_LIST1); SendMessage(list, uMsg, wParam, lParam); return 0; } return origEditProc(hwnd,uMsg,wParam,lParam); } WNDPROC origListProc = NULL; LRESULT CALLBACK ListProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { if (uMsg == WM_KEYDOWN && wParam == VK_RETURN) { // if edit already has something in it, clicking on the button // otherwise doubleclick the list int len = GetWindowTextLength(GetDlgItem(GetParent(hwnd), IDC_EDIT1)); SendMessage(GetParent(hwnd), WM_COMMAND, len ? MAKELONG(IDC_BUTTON1, BN_CLICKED) : MAKELONG(IDC_LIST1, LBN_DBLCLK), (LPARAM)hwnd); return 0; } else if (uMsg == WM_GETDLGCODE && wParam == VK_RETURN) { // nescessary for control to recieve VK_RETURN return origListProc(hwnd, uMsg, wParam, lParam) | DLGC_WANTALLKEYS; } else if (uMsg == WM_CHAR) { // let parent dialog process the keypresses from list SendMessage(GetParent(hwnd), APP_LISTCHAR, wParam, lParam); return 0; } return origListProc(hwnd, uMsg, wParam, lParam); } bool con_can_close = false; INT_PTR CALLBACK DlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam) { static int input_len = 0; static int last_index = 0; static std::wstring pending = L""; static std::shared_ptr<std::promise<char>> promiseyn; // APP_ASKYN event static std::shared_ptr<std::promise<wchar_t*>> promise; // APP_GETINPUT event static std::shared_ptr<std::promise<void>> promisev; // APP_PAUSE event static HICON hIconSm = NULL, hIcon = NULL; switch (uMsg) { case WM_INITDIALOG: { g_hwnd = hwndDlg; SendMessage(GetDlgItem(hwndDlg, IDC_PROGRESS1), PBM_SETRANGE, 0, MAKELONG(0, 100)); origEditProc = (WNDPROC)SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_EDIT1), GWLP_WNDPROC, (LONG)EditProc); origListProc = (WNDPROC)SetWindowLongPtr(GetDlgItem(hwndDlg, IDC_LIST1), GWLP_WNDPROC, (LONG)ListProc); // set icon hIconSm = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, GetSystemMetrics(SM_CXSMICON), GetSystemMetrics(SM_CYSMICON), 0); hIcon = (HICON)LoadImage(GetModuleHandle(NULL), MAKEINTRESOURCE(IDI_ICON1), IMAGE_ICON, GetSystemMetrics(SM_CXICON), GetSystemMetrics(SM_CYICON), 0); if (hIconSm) { SendMessage(hwndDlg, WM_SETICON, ICON_SMALL, (LPARAM)hIconSm); } if (hIcon) { SendMessage(hwndDlg, WM_SETICON, ICON_BIG, (LPARAM)hIcon); } SetMode(hwndDlg, NoMode); RECT workarea, winrect; SystemParametersInfo(SPI_GETWORKAREA, 0, (PVOID)&workarea, 0); GetWindowRect(hwndDlg, &winrect); int width = winrect.right - winrect.left; MoveWindow(hwndDlg, workarea.left + ((workarea.right - workarea.left) / 2) - (width / 2), workarea.top, width, workarea.bottom - workarea.top, TRUE); (*(EventPtr<void>)lParam)->set_value(); return TRUE; } case WM_COMMAND: switch (LOWORD(wParam)) { case IDC_BUTTON1: { if (CurrentMode == InputMode) { wchar_t* input_str = new wchar_t[input_len]; GetDlgItemTextW(hwndDlg, IDC_EDIT1, input_str, input_len); SetDlgItemTextW(hwndDlg, IDC_EDIT1, L""); SetMode(hwndDlg, NoMode); SignalEvent(promise, input_str); } else if (CurrentMode == PauseMode) { SetMode(hwndDlg, NoMode); SignalEvent(promisev); } return TRUE; } case IDC_BUTTON_YES: case IDC_BUTTON_NO: { if (CurrentMode == AskYnMode) { SetMode(hwndDlg, NoMode); SignalEvent(promiseyn, LOWORD(wParam) == IDC_BUTTON_YES ? 'y' : 'n'); } return TRUE; } case IDC_LIST1: switch (HIWORD(wParam)) { case LBN_DBLCLK: { int cur = ListBox_GetCurSel((HWND)lParam); if (CurrentMode == InputMode && cur != LB_ERR && (!q_responses[cur].empty() || cur == last_index)) { wchar_t* input_str = new wchar_t[q_responses[cur].length() + 1]; wcscpy(input_str, q_responses[cur].c_str()); SetDlgItemTextW(hwndDlg, IDC_EDIT1, L""); SetMode(hwndDlg, NoMode); SignalEvent(promise, input_str); } else if (CurrentMode == PauseMode) { SetMode(hwndDlg, NoMode); SignalEvent(promisev); } return TRUE; } } } return FALSE; case APP_LISTCHAR: { HWND edit = GetDlgItem(hwndDlg, IDC_EDIT1); if (CurrentMode == InputMode) { SetFocus(edit); SendMessage(edit, WM_CHAR, wParam, lParam); } else if (CurrentMode == AskYnMode) { char c = wctob(towlower(wParam)); if (c == 'y' || c == 'n') { SetMode(hwndDlg, NoMode); SignalEvent(promiseyn, c); } } return TRUE; } case APP_READQUEUE: { HWND list = GetDlgItem(hwndDlg, IDC_LIST1); std::lock_guard<std::mutex> lock(g_mutex); while (!g_queue.empty()) { LineEntry& ent = g_queue.front(); switch (ent.type) { case LINE_ADD: last_index = ListBox_AddString(list, ent.content.c_str()); q_responses.push_back(pending); pending = L""; break; case LINE_APPEND: { int origlen = ListBox_GetTextLen(list, last_index); int len = origlen + ent.content.length() + 1; VLA(wchar_t, wstr, len); ListBox_GetText(list, last_index, wstr); wcscat_s(wstr, len, ent.content.c_str()); ListBox_DeleteString(list, last_index); ListBox_InsertString(list, last_index, wstr); VLA_FREE(wstr); if (!pending.empty()) { q_responses[last_index] = pending; pending = L""; } break; } case LINE_CLS: ListBox_ResetContent(list); q_responses.clear(); pending = L""; break; case LINE_PENDING: pending = ent.content; break; } g_queue.pop(); } return TRUE; } case APP_GETINPUT: SetMode(hwndDlg, InputMode); input_len = wParam; promise = *(EventPtr<wchar_t*>)lParam; return TRUE; case APP_PAUSE: SetMode(hwndDlg, PauseMode); promisev = *(EventPtr<void>)lParam; return TRUE; case APP_ASKYN: SetMode(hwndDlg, AskYnMode); promiseyn = *(EventPtr<char>)lParam; return TRUE; case APP_PREUPDATE: { HWND list = GetDlgItem(hwndDlg, IDC_LIST1); SetWindowRedraw(list, FALSE); return TRUE; } case APP_UPDATE: { HWND list = GetDlgItem(hwndDlg, IDC_LIST1); //SendMessage(list, WM_VSCROLL, SB_BOTTOM, 0L); ListBox_SetCurSel(list, last_index);// Just scrolling doesn't work well SetWindowRedraw(list, TRUE); // this causes unnescessary flickering //RedrawWindow(list, NULL, NULL, RDW_ERASE | RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN); return TRUE; } case APP_PROGRESS: { HWND progress = GetDlgItem(hwndDlg, IDC_PROGRESS1); if (wParam == -1) { SetWindowLong(progress, GWL_STYLE, GetWindowLong(progress, GWL_STYLE) | PBS_MARQUEE); SendMessage(progress, PBM_SETMARQUEE, 1, 0L); } else { SendMessage(progress, PBM_SETMARQUEE, 0, 0L); SetWindowLong(progress, GWL_STYLE, GetWindowLong(progress, GWL_STYLE) & ~PBS_MARQUEE); SendMessage(progress, PBM_SETPOS, wParam, 0L); } SetMode(hwndDlg, ProgressBarMode); return TRUE; } case WM_SIZE: { RECT baseunits; baseunits.left = baseunits.right = 100; baseunits.top = baseunits.bottom = 100; MapDialogRect(hwndDlg, &baseunits); int basex = 4 * baseunits.right / 100; int basey = 8 * baseunits.bottom / 100; long origright = LOWORD(lParam) * 4 / basex; long origbottom = HIWORD(lParam) * 8 / basey; RECT rbutton1, rbutton2, rlist, redit, rwide; const int MARGIN = 7; const int PADDING = 2; const int BTN_WIDTH = 50; const int BTN_HEIGHT = 14; // |-----------wide----------| // |-----edit-------| | // | |--btn2--|--btn1--| // Button size rbutton1 = { origright - MARGIN - BTN_WIDTH, origbottom - MARGIN - BTN_HEIGHT, origright - MARGIN, origbottom - MARGIN }; MapDialogRect(hwndDlg, &rbutton1); // Progress/staic size rwide = { MARGIN, origbottom - MARGIN - BTN_HEIGHT, origright - MARGIN, origbottom - MARGIN }; MapDialogRect(hwndDlg, &rwide); // Edit size redit = { MARGIN, origbottom - MARGIN - BTN_HEIGHT, origright - MARGIN - BTN_WIDTH - PADDING, origbottom - MARGIN }; MapDialogRect(hwndDlg, &redit); // Button2 size rbutton2 = { origright - MARGIN - BTN_WIDTH - PADDING - BTN_WIDTH, origbottom - MARGIN - BTN_HEIGHT, origright - MARGIN - BTN_WIDTH - PADDING, origbottom - MARGIN }; MapDialogRect(hwndDlg, &rbutton2); // List size rlist = { MARGIN, MARGIN, origright - MARGIN, origbottom - MARGIN - BTN_HEIGHT - PADDING}; MapDialogRect(hwndDlg, &rlist); #define MoveToRect(hwnd,rect) MoveWindow((hwnd), (rect).left, (rect).top, (rect).right - (rect).left, (rect).bottom - (rect).top, TRUE) MoveToRect(GetDlgItem(hwndDlg, IDC_BUTTON1), rbutton1); MoveToRect(GetDlgItem(hwndDlg, IDC_EDIT1), redit); MoveToRect(GetDlgItem(hwndDlg, IDC_LIST1), rlist); MoveToRect(GetDlgItem(hwndDlg, IDC_PROGRESS1), rwide); MoveToRect(GetDlgItem(hwndDlg, IDC_STATIC1), rwide); MoveToRect(GetDlgItem(hwndDlg, IDC_BUTTON_YES), rbutton2); MoveToRect(GetDlgItem(hwndDlg, IDC_BUTTON_NO), rbutton1); InvalidateRect(hwndDlg, &rwide, FALSE); // needed because static doesn't repaint on move return TRUE; } case WM_CLOSE: if (con_can_close || MessageBoxW(hwndDlg, L"Patch configuration is not finished.\n\nQuit anyway?", L"Touhou Community Reliant Automatic Patcher", MB_YESNO | MB_ICONWARNING) == IDYES) { EndDialog(hwndDlg, 0); } return TRUE; case WM_NCDESTROY: g_hwnd = NULL; if (hIconSm) { DestroyIcon(hIconSm); } if (hIcon) { DestroyIcon(hIcon); } return TRUE; } return FALSE; } static bool needAppend = false; static bool dontUpdate = false; void log_windows(const char* text) { if (!g_hwnd) return; if (!dontUpdate) Thcrap_Preupdate(g_hwnd); int len = strlen(text) + 1; VLA(wchar_t, wtext, len); StringToUTF16(wtext, text, len); wchar_t *start = wtext, *end = wtext; while (end) { int mutexcond = 0; { std::lock_guard<std::mutex> lock(g_mutex); end = wcschr(end, '\n'); if (!end) end = wcschr(start, '\0'); wchar_t c = *end++; if (c == '\n') { end[-1] = '\0'; // Replace newline with null } else if (c == '\0') { if (end != wtext && end == start) { break; // '\0' right after '\n' } end = NULL; } else continue; if (needAppend == true) { LineEntry le = { LINE_APPEND, start }; g_queue.push(le); needAppend = false; } else { LineEntry le = { LINE_ADD, start }; g_queue.push(le); } mutexcond = g_queue.size() > 10; } if (mutexcond) { Thcrap_ReadQueue(g_hwnd); if (dontUpdate) { Thcrap_Update(g_hwnd); Thcrap_Preupdate(g_hwnd); } } start = end; } VLA_FREE(wtext); if (!end) needAppend = true; if (!dontUpdate) { Thcrap_ReadQueue(g_hwnd); Thcrap_Update(g_hwnd); } } void log_nwindows(const char* text, size_t len) { VLA(char, ntext, len+1); memcpy(ntext, text, len); ntext[len] = '\0'; log_windows(ntext); VLA_FREE(ntext); } /* --- code proudly stolen from thcrap/log.cpp --- */ #define VLA_VSPRINTF(str, va) \ size_t str##_full_len = _vscprintf(str, va) + 1; \ VLA(char, str##_full, str##_full_len); \ /* vs*n*printf is not available in msvcrt.dll. Doesn't matter anyway. */ \ vsprintf(str##_full, str, va); void con_vprintf(const char *str, va_list va) { if (str) { VLA_VSPRINTF(str, va); log_windows(str_full); //printf("%s", str_full); VLA_FREE(str_full); } } void con_printf(const char *str, ...) { if (str) { va_list va; va_start(va, str); con_vprintf(str, va); va_end(va); } } /* ------------------- */ void con_clickable(const char* response) { int len = strlen(response) + 1; VLA(wchar_t, wresponse, len); StringToUTF16(wresponse, response, len); { std::lock_guard<std::mutex> lock(g_mutex); LineEntry le = { LINE_PENDING, wresponse }; g_queue.push(le); } VLA_FREE(wresponse); } void con_clickable(int response) { size_t response_full_len = _scprintf("%d", response) + 1; VLA(char, response_full, response_full_len); sprintf(response_full, "%d", response); con_clickable(response_full); } void console_init() { INITCOMMONCONTROLSEX iccex; iccex.dwSize = sizeof(iccex); iccex.dwICC = ICC_PROGRESS_CLASS; InitCommonControlsEx(&iccex); log_set_hook(log_windows, log_nwindows); WaitForEvent<void> e; std::thread([](LPARAM lParam) { DialogBoxParamW(GetModuleHandle(NULL), MAKEINTRESOURCE(IDD_DIALOG1), NULL, DlgProc, lParam); log_set_hook(NULL, NULL); if (!g_exitguithreadevent) { exit(0); // Exit the entire process when exiting this thread } else { SignalEvent(g_exitguithreadevent); } }, (LPARAM)e.getEvent()).detach(); e.getResponse(); } char* console_read(char *str, int n) { dontUpdate = false; Thcrap_ReadQueue(g_hwnd); Thcrap_Update(g_hwnd); WaitForEvent<wchar_t*> e; Thcrap_GetInput(g_hwnd, n, e.getEvent()); wchar_t* input = e.getResponse(); StringToUTF8(str, input, n); delete[] input; needAppend = false; // gotta insert that newline return str; } void cls(SHORT top) { { std::lock_guard<std::mutex> lock(g_mutex); LineEntry le = { LINE_CLS, L"" }; g_queue.push(le); Thcrap_ReadQueue(g_hwnd); needAppend = false; } if (dontUpdate) { Thcrap_Update(g_hwnd); Thcrap_Preupdate(g_hwnd); } } void pause(void) { dontUpdate = false; con_printf("Press ENTER to continue . . . "); // this will ReadQueue and Update for us needAppend = false; WaitForEvent<void> e; Thcrap_Pause(g_hwnd, e.getEvent()); e.getResponse(); } void console_prepare_prompt(void) { Thcrap_Preupdate(g_hwnd); dontUpdate = true; } void console_print_percent(int pc) { Thcrap_Progress(g_hwnd, pc); } char console_ask_yn(const char* what) { dontUpdate = false; log_windows(what); needAppend = false; WaitForEvent<char> e; Thcrap_Askyn(g_hwnd, e.getEvent()); return e.getResponse(); } void con_end(void) { WaitForEvent<void> e; g_exitguithreadevent = *e.getEvent(); SendMessage(g_hwnd, WM_CLOSE, 0, 0L); e.getResponse(); } HWND con_hwnd(void) { return g_hwnd; } int console_width(void) { return 80; }
29.82459
186
0.687352
zero318
6e5557f2582c6890a47cf2648c7406d58276d3db
9,826
cpp
C++
NWNXLib/Platform/Assembly.cpp
chaoticplanes/nwnx-ee-unified
bea7c70609842850ca37825ff4c7e121fbbec72c
[ "MIT" ]
null
null
null
NWNXLib/Platform/Assembly.cpp
chaoticplanes/nwnx-ee-unified
bea7c70609842850ca37825ff4c7e121fbbec72c
[ "MIT" ]
null
null
null
NWNXLib/Platform/Assembly.cpp
chaoticplanes/nwnx-ee-unified
bea7c70609842850ca37825ff4c7e121fbbec72c
[ "MIT" ]
null
null
null
#include "Platform/Assembly.hpp" #include "API/Version.hpp" #include "Assert.hpp" #include "Platform/ASLR.hpp" #include "External/BeaEngine/include/BeaEngine.h" #include <cstring> #include <unordered_map> namespace { uintptr_t CalculateRelativeAddress(const uintptr_t from, const uintptr_t to, const uintptr_t instSize) { return to + (0xFFFFFFFF - (from + instSize)) + 1; } } namespace NWNXLib { namespace Platform { namespace Assembly { std::vector<uint8_t> AddRegImmByteInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x83; // ADD r32, imm8 const uint8_t extended = 0xC0 + static_cast<uint8_t>(m_register); return { opcode, extended, m_value }; } std::vector<uint8_t> AddRegImmDwordInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x81; // ADD r32, imm32 const uint8_t extended = 0xC0 + static_cast<uint8_t>(m_register); std::vector<uint8_t> encoded; encoded.resize(6); encoded[0] = opcode; encoded[1] = extended; memcpy(encoded.data(), &opcode, 1); memcpy(encoded.data() + 1, &extended, 1); memcpy(encoded.data() + 2, &m_value, 4); return encoded; } std::vector<uint8_t> CallRelInstruction::ToBytes(const uintptr_t address) const { const uint8_t opcode = 0xE8; // CALL near relative std::vector<uint8_t> encoded; encoded.resize(5); const uintptr_t relAddress = CalculateRelativeAddress(address, m_address, 5); memcpy(encoded.data(), &opcode, 1); memcpy(encoded.data() + 1, &relAddress, 4); return encoded; } std::vector<uint8_t> JmpRelInstruction::ToBytes(const uintptr_t address) const { const uint8_t opcode = 0xE9; // JMP near relative std::vector<uint8_t> encoded; encoded.resize(5); const uintptr_t relAddress = CalculateRelativeAddress(address, m_address, 5); memcpy(encoded.data(), &opcode, 1); memcpy(encoded.data() + 1, &relAddress, 4); return encoded; } std::vector<uint8_t> MovRegRegInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x89; // MOV r32, r32 const uint8_t extended = 0xC0 + static_cast<uint8_t>(m_destination) + (static_cast<uint8_t>(m_source) * 8); return { opcode, extended }; } std::vector<uint8_t> MovRegRegMemInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x8B; // MOV r32, r/m32 const uint8_t extended = (static_cast<uint8_t>(m_destination) * 8) + static_cast<uint8_t>(m_source); return { opcode, extended }; } std::vector<uint8_t> MovRegImmInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0xB8 + static_cast<uint8_t>(m_destination); // MOV r32, imm32 std::vector<uint8_t> encoded; encoded.resize(5); memcpy(encoded.data(), &opcode, 1); memcpy(encoded.data() + 1, &m_value, 4); return encoded; } std::vector<uint8_t> NoopInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x90; // NOOP return { opcode }; } std::vector<uint8_t> PushImmInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x68; // PUSH imm32 std::vector<uint8_t> encoded; encoded.resize(5); memcpy(encoded.data(), &opcode, 1); memcpy(encoded.data() + 1, &m_value, 4); return encoded; } std::vector<uint8_t> PopRegInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x58 /* PUSH r32 */ + static_cast<uint8_t>(m_register); return { opcode }; } std::vector<uint8_t> PushRegInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x50 /* PUSH r32 */ + static_cast<uint8_t>(m_register); return { opcode }; } std::vector<uint8_t> PushRegMemByteInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0xFF; // PUSH r/m32 const uint8_t extended = 0x70 + static_cast<uint8_t>(m_register); return { opcode, extended, *reinterpret_cast<const uint8_t*>(&m_offset) }; } std::vector<uint8_t> PushRegMemDwordInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0xFF; // PUSH r/m32 const uint8_t extended = 0xB0 + static_cast<uint8_t>(m_register); std::vector<uint8_t> encoded; encoded.resize(6); memcpy(encoded.data(), &opcode, 1); memcpy(encoded.data() + 1, &extended, 1); memcpy(encoded.data() + 2, &m_offset, 4); return encoded; } std::vector<uint8_t> RetInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0xC3; // RET return { opcode }; } std::vector<uint8_t> SubRegImmByteInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x83; // SUB r32, imm8 const uint8_t extended = 0xE8 + static_cast<uint8_t>(m_register); return { opcode, extended, m_value }; } std::vector<uint8_t> SubRegImmDwordInstruction::ToBytes(const uintptr_t) const { const uint8_t opcode = 0x81; // SUB r32, imm32 const uint8_t extended = 0xE8 + static_cast<uint8_t>(m_register); std::vector<uint8_t> encoded; encoded.resize(6); memcpy(encoded.data(), &opcode, 1); memcpy(encoded.data() + 1, &extended, 1); memcpy(encoded.data() + 2, &m_value, 4); return encoded; } void CorrectRelativeAddresses(const uintptr_t address, const uintptr_t originalAddress, const uintptr_t length) { ASSERT(length > 0); DISASM disassembler = {}; disassembler.EIP = address; disassembler.VirtualAddr = originalAddress; uintptr_t bytesChecked = 0; while (bytesChecked < length) { const int len = Disasm(&disassembler); if (len == OUT_OF_BLOCK || len == UNKNOWN_OPCODE || len < 0) { break; } const uintptr_t lengthChecked = static_cast<uintptr_t>(len); static constexpr uint8_t RELATIVE_CALL = 0xE8; static constexpr uint8_t RELATIVE_SHORT_JMP = 0xEB; static constexpr uint8_t RELATIVE_JMP = 0xE9; switch (disassembler.Instruction.Opcode) { case RELATIVE_CALL: case RELATIVE_JMP: { uint32_t* offsetAddr = reinterpret_cast<uint32_t*>(address + bytesChecked + 1); uintptr_t originalOffset; memcpy(&originalOffset, offsetAddr, 4); const uintptr_t targetAddress = originalAddress + bytesChecked + lengthChecked + originalOffset; const uintptr_t trampolineAddress = reinterpret_cast<uintptr_t>(address + bytesChecked + lengthChecked); const uintptr_t newAddress = targetAddress + (0xFFFFFFFF - trampolineAddress) + 1; memcpy(offsetAddr, &newAddress, 4); break; } case RELATIVE_SHORT_JMP: { ASSERT_FAIL_MSG("No short jmp support"); break; } } bytesChecked += lengthChecked; disassembler.EIP += lengthChecked; disassembler.VirtualAddr += lengthChecked; } } uintptr_t GetSmallestLengthToFitInstruction(const uintptr_t address, const uintptr_t instLen) { ASSERT(instLen > 0); DISASM disassembler = {}; disassembler.EIP = address; uintptr_t bytesChecked = 0; while (true) { const int len = Disasm(&disassembler); if (len == OUT_OF_BLOCK || len == UNKNOWN_OPCODE || len < 0) { return 0; } const uintptr_t lengthChecked = static_cast<uintptr_t>(len); bytesChecked += lengthChecked; if (bytesChecked >= instLen) { return bytesChecked; } disassembler.EIP += lengthChecked; } } void RewriteGCCThunks(uint8_t* data, uintptr_t originalAddress, uintptr_t length) { ASSERT(length > 0); std::unordered_map<uintptr_t, Register> thunkMap = { { ASLR::GetRelocatedAddress(0x0001E155), Register::EAX }, // __x86_get_pc_thunk_ax { ASLR::GetRelocatedAddress(0x00016010), Register::EBX }, // __x86_get_pc_thunk_bx { ASLR::GetRelocatedAddress(0x0003997F), Register::ECX }, // __x86_get_pc_thunk_cx { ASLR::GetRelocatedAddress(0x00029CD1), Register::EDX }, // __x86_get_pc_thunk_dx { ASLR::GetRelocatedAddress(0x00039B8B), Register::ESI }, // __x86_get_pc_thunk_si { ASLR::GetRelocatedAddress(0x0005244D), Register::EDI } // __x86_get_pc_thunk_di }; NWNX_EXPECT_VERSION(8179); DISASM disassembler = {}; disassembler.EIP = reinterpret_cast<uintptr_t>(data); uintptr_t bytesChecked = 0; while (bytesChecked < length) { const int len = Disasm(&disassembler); if (len == OUT_OF_BLOCK || len == UNKNOWN_OPCODE || len < 0) { break; } const uintptr_t lengthChecked = static_cast<uintptr_t>(len); static constexpr uint8_t RELATIVE_CALL = 0xE8; if (disassembler.Instruction.Opcode == RELATIVE_CALL) { ASSERT(lengthChecked == 5); // The address to the argument of the call instruction. uint8_t* offsetAddr = (data + bytesChecked + 1); uintptr_t location; memcpy(&location, offsetAddr, sizeof(uintptr_t)); // It's a relative (to next inst) call, so let's account for that. location += reinterpret_cast<uintptr_t>(data) + lengthChecked + 1; auto thunkRegister = thunkMap.find(location); if (thunkRegister != std::end(thunkMap)) { // We're calling a thunk, so replace with a move. uintptr_t nextInstAddr = originalAddress + bytesChecked + lengthChecked; auto assembly = MovRegImmInstruction(thunkRegister->second, nextInstAddr).ToBytes(); ASSERT(assembly.size() == 5); memcpy(data + bytesChecked, assembly.data(), lengthChecked); } } bytesChecked += lengthChecked; disassembler.EIP += lengthChecked; } } } } }
31.292994
120
0.658355
chaoticplanes
6e5625f12d0419824f07e98f36e4ac0bdb0c350e
1,678
cpp
C++
cpp/src/competition/double_20/e5323.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/competition/double_20/e5323.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/competition/double_20/e5323.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
// https://leetcode-cn.com/problems/sort-integers-by-the-number-of-1-bits/ #include "extern.h" class Solution { struct BitsCompare { inline bool operator()(pair<int, int>& p1, pair<int, int>& p2) { if (p2.second != p1.second) return p1.second < p2.second; else return p1.first < p2.first; } }; public: vector<int> sortByBits(vector<int>& arr) { vector<pair<int, int>> digits; for (int w : arr) { int v = w; int n = 0; while (v > 0) { if (v % 2 != 0) ++n; v /= 2; } digits.push_back(make_pair(w, n)); } sort(digits.begin(), digits.end(), BitsCompare()); vector<int> results; for (auto p : digits) results.push_back(p.first); return results; } }; TEST(double20, e5323) { vector<int> arr, ans; arr = str_to_vec<int>("[0,1,2,3,4,5,6,7,8]"); ans = str_to_vec<int>("[0,1,2,4,8,3,5,6,7]"); ASSERT_THAT(Solution().sortByBits(arr), ans); arr = str_to_vec<int>("[1024,512,256,128,64,32,16,8,4,2,1]"); ans = str_to_vec<int>("[1,2,4,8,16,32,64,128,256,512,1024]"); ASSERT_THAT(Solution().sortByBits(arr), ans); arr = str_to_vec<int>("[10000,10000]"); ans = str_to_vec<int>("[10000,10000]"); ASSERT_THAT(Solution().sortByBits(arr), ans); arr = str_to_vec<int>("[2,3,5,7,11,13,17,19]"); ans = str_to_vec<int>("[2,3,5,17,7,11,13,19]"); ASSERT_THAT(Solution().sortByBits(arr), ans); arr = str_to_vec<int>("[10,100,1000,10000]"); ans = str_to_vec<int>("[10,100,10000,1000]"); ASSERT_THAT(Solution().sortByBits(arr), ans); }
34.244898
74
0.553635
ajz34
6e5757c435675bb2425892ada4ac8d1b357f3d4d
2,632
cpp
C++
program2/src/Reel.cpp
CharlesBarone/datastructures-unh-spring2020
0d3365ede7d4ecd0ea9d76f41966e72d75e1cf48
[ "MIT" ]
null
null
null
program2/src/Reel.cpp
CharlesBarone/datastructures-unh-spring2020
0d3365ede7d4ecd0ea9d76f41966e72d75e1cf48
[ "MIT" ]
null
null
null
program2/src/Reel.cpp
CharlesBarone/datastructures-unh-spring2020
0d3365ede7d4ecd0ea9d76f41966e72d75e1cf48
[ "MIT" ]
null
null
null
// // Reel.cpp // program2 // // Created by Charles Barone on 3/21/20. // Copyright © 2020 Charles Barone. All rights reserved. // #include "Reel.hpp" #include <iostream> void Reel::MakeEmpty(){ ReelNode* temp = nullptr; ReelNode* temp2 = head; while(head->next != nullptr){ temp = head; if(head->next == temp2) { head->next = nullptr; } else { head = head->next; } delete temp; } length = 0; } void Reel::PutItem(Item item){ ReelNode* temp = new ReelNode; temp->data = item; if(length == 0) { //First Item temp->next = temp; head = temp; } else if(length == 1) { //Second Item head->next = temp; temp->next = head; } else if(length > 1) { //All Items past second Item ReelNode* temp2 = head->next; head->next = temp; temp->next = temp2; } length++; } Item Reel::GetItem(Item item){ ReelNode* temp = head; if(temp->data == item){ return temp->data; } temp = temp->next; while(temp != head){ if(temp->data == item){ return temp->data; } temp = temp->next; } throw "not found"; } void Reel::DeleteItem(Item item){ // Empty case if(head == nullptr) return; ReelNode* temp; // Deleting head if(head->data == item){ temp = head->next; ReelNode* temp2 = new ReelNode(); temp2 = head->next; while(temp2->next != head) { //Find the node that points to the head temp2 = temp2->next; } temp2->next = temp; delete head; head = temp; length--; return; } // Deleting further in the list temp = head; while(temp->next != head){ if(temp->next->data == item){ ReelNode* temp2 = temp->next; temp->next = temp->next->next; delete temp2; length--; return; } temp = temp->next; } } void Reel::ResetList(){ currentPos = head; } Item Reel::GetNextItem(){ if(currentPos == nullptr) throw "Out of range"; Item data = currentPos->data; currentPos = currentPos->next; return data; } int Reel::GetLength(){ return length; } Reel::~Reel(){ MakeEmpty(); } std::ostream& operator<<(std::ostream& os, Reel& o){ o.ResetList(); os << "List: ["; for(int i = 0; i < o.GetLength(); ++i){ os << "(" << o.GetNextItem() << ")"; if (i < o.GetLength() - 1) os << ", "; } os << "]"; return os; }
20.888889
76
0.50152
CharlesBarone
6e5e8b61b3f4dff3ab440678c160c9c7fe5522d4
889
cpp
C++
tst/algorithms_data_structs/zip_test.cpp
LesnyRumcajs/ModernCppChallenge
175601d4c3d3ae88240c190c891261696f777ef1
[ "MIT" ]
5
2021-05-28T22:40:49.000Z
2022-03-11T20:48:38.000Z
tst/algorithms_data_structs/zip_test.cpp
LesnyRumcajs/ModernCppChallenge
175601d4c3d3ae88240c190c891261696f777ef1
[ "MIT" ]
3
2018-10-29T21:56:12.000Z
2019-10-13T17:04:06.000Z
tst/algorithms_data_structs/zip_test.cpp
LesnyRumcajs/ModernCppChallenge
175601d4c3d3ae88240c190c891261696f777ef1
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <gmock/gmock.h> #include "../../src/algorithms_data_structs/zip.h" namespace { using namespace testing; using cppchallenge::algorithms_data_structs::zip; TEST(ZipTest, NoDataShouldReturnEmpty) { auto result = zip(std::vector<int>{}, std::vector<std::string>{}); ASSERT_THAT(result, IsEmpty()); } TEST(ZipTest, EvenDataShouldZip) { using namespace std::string_literals; auto result = zip(std::vector{1,2,3}, std::vector{"a"s, "b"s, "c"s}); ASSERT_THAT(result, ElementsAre(Pair(1, "a"s), Pair(2, "b"s), Pair(3, "c"s))); } TEST(ZipTest, OddShouldDiscardUnused) { using namespace std::string_literals; auto result = zip(std::vector{1,2,3,4,5}, std::vector{"a"s, "b"s, "c"s}); ASSERT_THAT(result, ElementsAre(Pair(1, "a"s), Pair(2, "b"s), Pair(3, "c"s))); } }
34.192308
86
0.620922
LesnyRumcajs
6e5eacfc47b9f1c88d2fe00331b6dc1295b779fe
1,100
hpp
C++
module_01/ex04/replace.hpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
4
2021-12-14T18:02:53.000Z
2022-03-24T01:12:38.000Z
module_01/ex04/replace.hpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
null
null
null
module_01/ex04/replace.hpp
paulahemsi/piscine_cpp
f98feefd8e70308f77442f9b4cb64758676349a7
[ "MIT" ]
3
2021-11-01T00:34:50.000Z
2022-01-29T19:57:30.000Z
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* replace.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: phemsi-a <phemsi-a@student.42sp.org.br> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/16 18:25:16 by phemsi-a #+# #+# */ /* Updated: 2021/09/16 19:01:03 by phemsi-a ### ########.fr */ /* */ /* ************************************************************************** */ # ifndef REPLACE_HPP # define REPLACE_HPP # include <iostream> char *readFile(long *size, std::ifstream *inputFile); void writeFile(char **argv, std::ofstream *outputFile, char *buffer, long size); #endif
50
80
0.234545
paulahemsi
6e623f47047a5d46aea09b78f95ccc878f77d232
1,132
cpp
C++
Interface/Register/using_axi_lite_with_user_defined_offset/example.cpp
ramanan-radhakrishnan/Vitis-HLS-Introductory-Examples
689ccbf41af440d5851c1ff1bc994dd9e69ba20a
[ "Apache-2.0" ]
188
2019-11-05T01:09:15.000Z
2021-09-08T16:10:26.000Z
Interface/Register/using_axi_lite_with_user_defined_offset/example.cpp
HITECHNOTACH/Vitis-HLS-Introductory-Examples
6ec6726a43c96e48a4ee3d6cb1e6ff6c5723d488
[ "Apache-2.0" ]
2
2020-09-08T04:55:52.000Z
2021-04-14T11:19:32.000Z
Interface/Register/using_axi_lite_with_user_defined_offset/example.cpp
HITECHNOTACH/Vitis-HLS-Introductory-Examples
6ec6726a43c96e48a4ee3d6cb1e6ff6c5723d488
[ "Apache-2.0" ]
73
2019-11-04T21:24:02.000Z
2021-09-14T23:33:43.000Z
/* * Copyright 2021 Xilinx, Inc. * * 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 <stdio.h> // In this example the user uses to define the offset and the range is dependent on the // datatype and port protocol it usese. See the saxi lite documentation which explains // the example in more detail void example(char *a, char *b, char *c) { #pragma HLS INTERFACE s_axilite port=a bundle=BUS_A offset=0x20 #pragma HLS INTERFACE s_axilite port=b bundle=BUS_A offset=0x28 #pragma HLS INTERFACE s_axilite port=c bundle=BUS_A offset=0x30 #pragma HLS INTERFACE s_axilite port=return bundle=BUS_A *c += *a + *b; }
36.516129
87
0.748233
ramanan-radhakrishnan
6e67ae48ef5734a028699861c650e736f8425218
8,006
cpp
C++
Plugins/PLSoundOpenAL/src/StreamWav.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Plugins/PLSoundOpenAL/src/StreamWav.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Plugins/PLSoundOpenAL/src/StreamWav.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: StreamWav.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLCore/File/File.h> #include "PLSoundOpenAL/SoundManager.h" #include "PLSoundOpenAL/Buffer.h" #include "PLSoundOpenAL/StreamWav.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] using namespace PLCore; namespace PLSoundOpenAL { //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Constructor */ StreamWav::StreamWav(ALuint nSource, const Buffer &cBuffer) : Stream(nSource, cBuffer), m_pFile(nullptr), m_pnData(nullptr), m_nStreamSize(0), m_nStreamPos(0), m_nFormat(0), m_nFrequency(0), m_nSwapSize(0), m_pnSwap(nullptr) { // Create front and back buffers alGenBuffers(2, m_nBuffers); } /** * @brief * Destructor */ StreamWav::~StreamWav() { DeInit(); alDeleteBuffers(2, m_nBuffers); } //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Opens the stream */ bool StreamWav::OpenStream() { // If already opened, restart it if (m_pFile) { // Restart m_pFile->Seek(sizeof(Header)); m_nStreamPos = 0; } else if (m_pnData) { // Restart if (!GetBuffer().GetData()) return false; // Error! m_pnData = GetBuffer().GetData(); m_pnData += sizeof(Header); m_nStreamPos = 0; } else { // Check buffer if (!GetBuffer().IsStreamed()) return false; // Error! // Prepare for streaming Header sWavHeader; if (GetBuffer().GetData()) { // Stream from memory // Set data stream m_pnData = GetBuffer().GetData(); // Set stream size m_nStreamSize = GetBuffer().GetDataSize() - sizeof(Header); // Read wav header MemoryManager::Copy(&sWavHeader, m_pnData, sizeof(Header)); m_pnData += sizeof(Header); } else { // Stream from file m_pFile = GetBuffer().OpenFile(); if (!m_pFile) { // Error! return false; } // Set stream size m_nStreamSize = m_pFile->GetSize() - sizeof(Header); // Read wav header m_pFile->Read(&sWavHeader, sizeof(Header), 1); } // Set stream position m_nStreamPos = 0; // Check the number of channels... and bits per sample if (sWavHeader.Channels == 1) m_nFormat = (sWavHeader.BitsPerSample == 16) ? AL_FORMAT_MONO16 : AL_FORMAT_MONO8; else m_nFormat = (sWavHeader.BitsPerSample == 16) ? AL_FORMAT_STEREO16 : AL_FORMAT_STEREO8; // Get frequency m_nFrequency = sWavHeader.SamplesPerSec; // Setup the swap buffer, we want a buffer size that can hold 2 seconds if (m_nSwapSize != sWavHeader.BytesPerSec*2) { m_nSwapSize = sWavHeader.BytesPerSec*2; if (m_pnSwap) delete [] m_pnSwap; m_pnSwap = new uint8[m_nSwapSize]; } } // Done return true; } /** * @brief * Fill a buffer */ bool StreamWav::FillBuffer(ALuint nBuffer) { if (m_pnSwap && m_nSwapSize) { bool bEndOfStream = false; int nSizeToRead; // Stream finished? if (m_nStreamPos+m_nSwapSize >= m_nStreamSize) { nSizeToRead = m_nStreamSize - m_nStreamPos; m_nStreamPos = m_nStreamSize; bEndOfStream = true; } else { nSizeToRead = m_nSwapSize; m_nStreamPos += m_nSwapSize; } if (!nSizeToRead) return false; // Error! // Read data if (m_pFile) m_pFile->Read(m_pnSwap, nSizeToRead, 1); if (m_pnData) { MemoryManager::Copy(m_pnSwap, m_pnData, nSizeToRead); m_pnData += nSizeToRead; } // Fill buffer alBufferData(nBuffer, m_nFormat, m_pnSwap, nSizeToRead, m_nFrequency); // Done return !bEndOfStream; } else { // Error! return false; } } //[-------------------------------------------------------] //[ Public virtual Stream functions ] //[-------------------------------------------------------] bool StreamWav::Init() { // First, de-initialize old stream DeInit(); // Open stream if (OpenStream()) { // Start streaming if (FillBuffer(m_nBuffers[0]) && FillBuffer(m_nBuffers[1])) { alSourceQueueBuffers(GetSource(), 2, m_nBuffers); // Done return true; } } // Error! return false; } bool StreamWav::IsInitialized() const { return (m_pFile || m_pnData); } void StreamWav::DeInit() { // Is the stream initialized? if (m_pFile || m_pnData) { // Unqeue buffers int nQueued; alGetSourcei(GetSource(), AL_BUFFERS_QUEUED, &nQueued); while (nQueued--) { ALuint nBuffer; alSourceUnqueueBuffers(GetSource(), 1, &nBuffer); } // Close streaming source if (m_pFile) { m_pFile->Close(); delete m_pFile; m_pFile = nullptr; } m_pnData = nullptr; // Don't delete the shared data! m_nStreamSize = 0; m_nStreamPos = 0; m_nFormat = 0; m_nFrequency = 0; } if (m_pnSwap) { delete [] m_pnSwap; m_nSwapSize = 0; m_pnSwap = nullptr; } } bool StreamWav::Update() { int nActive = 0; // Currently initialized? if (IsInitialized()) { // Update all processed buffers int nProcessed = 0; alGetSourcei(GetSource(), AL_BUFFERS_PROCESSED, &nProcessed); while (nProcessed--) { ALuint nBuffer; alSourceUnqueueBuffers(GetSource(), 1, &nBuffer); if (!FillBuffer(nBuffer)) { bool bKeepPlaying = false; // This stream is now finished, perform looping? if (IsLooping()) { // Open stream if (OpenStream()) { // Fill buffer if (FillBuffer(nBuffer)) { // This stream is now active, again nActive++; alSourceQueueBuffers(GetSource(), 1, &nBuffer); bKeepPlaying = true; } } } // De-initialize the stream right now? if (!bKeepPlaying) DeInit(); } else { // This stream is still in processing nActive++; alSourceQueueBuffers(GetSource(), 1, &nBuffer); } } // Get source state and start the source if necessary (the buffers may have been completely emptied and the source therefore been stopped) if (nActive != 0) { ALint nValue = AL_STOPPED; alGetSourcei(GetSource(), AL_SOURCE_STATE, &nValue); if (nValue == AL_STOPPED) alSourcePlay(GetSource()); } } // Return active state return (nActive != 0); } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // PLSoundOpenAL
25.825806
140
0.581689
ktotheoz
6e6d3e6f9c81ee2ade4785555e1ef15b500de373
5,464
cpp
C++
unimodularity-library-1.2c/src/determinant.cpp
vios-fish/CompetitiveProgramming
6953f024e4769791225c57ed852cb5efc03eb94b
[ "MIT" ]
2
2016-07-05T21:14:40.000Z
2020-03-08T01:33:12.000Z
src/determinant.cpp
vbraun/unimodularity-library
d329571908a84ed98713721a2fe873ad534901c8
[ "BSL-1.0" ]
null
null
null
src/determinant.cpp
vbraun/unimodularity-library
d329571908a84ed98713721a2fe873ad534901c8
[ "BSL-1.0" ]
null
null
null
/** * Copyright Matthias Walter 2010. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **/ #include "../config.h" #include <map> #include <vector> #include <boost/numeric/ublas/lu.hpp> #include <boost/dynamic_bitset.hpp> #include "total_unimodularity.hpp" #include "combinations.hpp" namespace unimod { /** * Calculates a subdeterminant of the given matrix. * * @param matrix A given integer matrix * @param submatrix Matrix-indices describing a submatrix * @return The submatrix' determinant */ int submatrix_determinant(const integer_matrix& matrix, const submatrix_indices& submatrix) { typedef boost::numeric::ublas::matrix_indirect <const integer_matrix, submatrix_indices::indirect_array_type> indirect_matrix_t; assert (submatrix.rows.size() == submatrix.columns.size()); const indirect_matrix_t indirect_matrix(matrix, submatrix.rows, submatrix.columns); boost::numeric::ublas::matrix <float> float_matrix(indirect_matrix); boost::numeric::ublas::permutation_matrix <size_t> permutation_matrix(float_matrix.size1()); /// LU-factorize int result = boost::numeric::ublas::lu_factorize(float_matrix, permutation_matrix); if (result != 0) return 0; /// Calculate the determinant as a product of the diagonal entries, taking the permutation matrix into account. float det = 1.0f; for (size_t i = 0; i < float_matrix.size1(); ++i) { det *= float_matrix(i, i); if (i != permutation_matrix(i)) det = -det; } return (int) det; } /** * Checks Camion's criterion for total unimodularity. * * @param matrix A given integer matrix * @param submatrix Matrix-indices describing a submatrix B of A * @return true iff B is not Eulerian or 1^T * B * 1 = 0 (mod 4) */ bool submatrix_camion(const integer_matrix& matrix, const submatrix_indices& submatrix) { typedef boost::numeric::ublas::matrix_indirect <const integer_matrix, submatrix_indices::indirect_array_type> indirect_matrix_t; assert (submatrix.rows.size() == submatrix.columns.size()); const indirect_matrix_t indirect_matrix(matrix, submatrix.rows, submatrix.columns); // Test whether submatrix is eulerian. for (size_t row = 0; row < indirect_matrix.size1(); ++row) { size_t count = 0; for (size_t column = 0; column < indirect_matrix.size2(); ++column) count += indirect_matrix(row, column); if (count % 2 == 1) return true; } for (size_t column = 0; column < indirect_matrix.size2(); ++column) { size_t count = 0; for (size_t row = 0; row < indirect_matrix.size1(); ++row) count += indirect_matrix(row, column); if (count % 2 == 1) return true; } // Matrix is eulerian. size_t count = 0; for (size_t row = 0; row < indirect_matrix.size1(); ++row) { for (size_t column = 0; column < indirect_matrix.size2(); ++column) count += indirect_matrix(row, column); } return (count % 4 == 0); } /** * Checks all subdeterminants to test a given matrix for total unimodularity. * * @param matrix The given matrix * @return true if and only if this matrix is totally unimdular */ bool determinant_is_totally_unimodular(const integer_matrix& matrix) { submatrix_indices indices; return determinant_is_totally_unimodular(matrix, indices); } /** * Checks all subdeterminants to test a given matrix for total unimodularity. * If this is not the case, violator describes a violating submatrix. * * @param matrix The given matrix * @param violator The violating submatrix, if the result is false * @return true if and only if the this matrix is totally unimodular */ bool determinant_is_totally_unimodular(const integer_matrix& matrix, submatrix_indices& violator) { for (size_t size = 1; size <= matrix.size1(); ++size) { combination row_combination(matrix.size1(), size); while (true) { combination column_combination(matrix.size2(), size); while (true) { submatrix_indices sub; submatrix_indices::vector_type indirect_array(size); for (size_t i = 0; i < size; ++i) indirect_array[i] = row_combination[i]; sub.rows = submatrix_indices::indirect_array_type(size, indirect_array); for (size_t i = 0; i < size; ++i) { indirect_array[i] = column_combination[i]; } sub.columns = submatrix_indices::indirect_array_type(size, indirect_array); /// Examine the determinant bool camion = submatrix_camion(matrix, sub); #ifndef NDEBUG int det = submatrix_determinant(matrix, sub); bool is_violator = det < -1 || det > +1; assert((is_violator && !camion) || (!is_violator && camion)); #pragma message("\n\n\nWARNING: Submatrix Test uses subdeterminants for verification and is much slower!\n\n ") #endif if (!camion) { violator = sub; return false; } if (column_combination.is_last()) break; column_combination.next(); } if (row_combination.is_last()) break; row_combination.next(); } } return true; } }
31.583815
132
0.650439
vios-fish
6e6f84fa9058aa5cb6808bf27abba8f7c3614776
1,590
cpp
C++
co-op/TmpProjectArea.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
co-op/TmpProjectArea.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
co-op/TmpProjectArea.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
//------------------------------------------- // TmpProjectArea.cpp // (c) Reliable Software, 1998 -- 2002 //------------------------------------------- #include "precompiled.h" #include "TmpProjectArea.h" #include "PathFind.h" #include <File/File.h> void TmpProjectArea::RememberVersion (std::string const & comment, long timeStamp) { _versionComment = comment; _versionTimeStamp = timeStamp; } void TmpProjectArea::FileMove (GlobalId gid, Area::Location areaFrom, PathFinder & pathFinder) { std::string from (pathFinder.GetFullPath (gid, areaFrom)); char const * to = pathFinder.GetFullPath (gid, GetAreaId ()); File::Move (from.c_str (), to); _files.insert (gid); } void TmpProjectArea::FileCopy (GlobalId gid, Area::Location areaFrom, PathFinder & pathFinder) { std::string from (pathFinder.GetFullPath (gid, areaFrom)); char const * to = pathFinder.GetFullPath (gid, GetAreaId ()); File::Copy (from.c_str (), to); _files.insert (gid); } void TmpProjectArea::CreateEmptyFile (GlobalId gid, PathFinder & pathFinder) { char const * to = pathFinder.GetFullPath (gid, GetAreaId ()); File file (to, File::CreateAlwaysMode ()); _files.insert (gid); } bool TmpProjectArea::IsReconstructed (GlobalId gid) const { GidSet::const_iterator iter = _files.find (gid); return iter != _files.end (); } void TmpProjectArea::Cleanup (PathFinder & pathFinder) { // Delete reconstructed files for (GidSet::const_iterator iter = _files.begin (); iter != _files.end (); ++iter) { char const * path = pathFinder.GetFullPath (*iter, GetAreaId ()); File::DeleteNoEx (path); } }
28.392857
94
0.677358
BartoszMilewski
6e7ce97142cbb4e3c32a5ae5b786374730b45109
2,568
hpp
C++
testspr/header_all.hpp
EzoeRyou/Sprout
12e12373d0f70543eac5f2ecfbec8f5112765f98
[ "BSL-1.0" ]
1
2016-09-29T21:55:58.000Z
2016-09-29T21:55:58.000Z
testspr/header_all.hpp
EzoeRyou/Sprout
12e12373d0f70543eac5f2ecfbec8f5112765f98
[ "BSL-1.0" ]
null
null
null
testspr/header_all.hpp
EzoeRyou/Sprout
12e12373d0f70543eac5f2ecfbec8f5112765f98
[ "BSL-1.0" ]
null
null
null
/*============================================================================= Copyright (c) 2011-2014 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef TESTSPR_HEADER_ALL_HPP #define TESTSPR_HEADER_ALL_HPP #include <sprout/adapt/std/array.hpp> #include <sprout/adapt/std/utility.hpp> #include <sprout/adl/not_found.hpp> #include <sprout/algorithm.hpp> #include <sprout/algorithm/string.hpp> #include <sprout/array.hpp> #include <sprout/assert.hpp> #include <sprout/bit/operation.hpp> #include <sprout/bitset.hpp> #include <sprout/brainfuck.hpp> #include <sprout/cctype.hpp> #include <sprout/checksum.hpp> #include <sprout/cinttypes.hpp> #include <sprout/cmath.hpp> #include <sprout/complex.hpp> #include <sprout/compost.hpp> #include <sprout/compressed_pair.hpp> #include <sprout/config.hpp> #include <sprout/container.hpp> #include <sprout/cstdint.hpp> #include <sprout/cstdlib.hpp> #include <sprout/cstring.hpp> #include <sprout/ctype.hpp> #include <sprout/current_function.hpp> #include <sprout/cwchar.hpp> #include <sprout/cwctype.hpp> #include <sprout/darkroom.hpp> #include <sprout/endian_traits.hpp> #include <sprout/functional.hpp> #include <sprout/generator.hpp> #include <sprout/index_tuple.hpp> #include <sprout/io.hpp> #include <sprout/integer.hpp> #include <sprout/iterator.hpp> #include <sprout/limits.hpp> #include <sprout/logic.hpp> #include <sprout/math.hpp> #include <sprout/none.hpp> #include <sprout/numeric.hpp> #include <sprout/numeric/dft.hpp> #include <sprout/numeric/fft.hpp> #include <sprout/operation.hpp> #include <sprout/optional.hpp> #include <sprout/pit.hpp> #include <sprout/preprocessor.hpp> #include <sprout/random.hpp> #include <sprout/rational.hpp> #include <sprout/range.hpp> #include <sprout/range/adaptor.hpp> #include <sprout/range/algorithm.hpp> #include <sprout/range/numeric.hpp> #include <sprout/range/numeric/dft.hpp> #include <sprout/string.hpp> #include <sprout/sub_array.hpp> #include <sprout/tpp/algorithm.hpp> #include <sprout/tuple.hpp> #include <sprout/type.hpp> #include <sprout/type_traits.hpp> #include <sprout/utility.hpp> #include <sprout/uuid.hpp> #include <sprout/variant.hpp> #include <sprout/weed.hpp> #include <sprout/workaround.hpp> #endif // #ifndef TESTSPR_HEADER_ALL_HPP
33.789474
80
0.70366
EzoeRyou
6e82b50896cd82df5c1ab03e4618d24dfba94e4c
9,890
hh
C++
cxx/include/ora/lib/math.hh
alexhsamuel/ora
89358d9193d86fbc7752270f1e35ee6ddcdcd206
[ "BSD-3-Clause" ]
10
2018-03-03T02:02:19.000Z
2020-04-02T22:47:55.000Z
cxx/include/ora/lib/math.hh
alexhsamuel/ora
89358d9193d86fbc7752270f1e35ee6ddcdcd206
[ "BSD-3-Clause" ]
13
2018-01-28T15:20:55.000Z
2022-01-27T23:32:41.000Z
cxx/include/ora/lib/math.hh
alexhsamuel/ora
89358d9193d86fbc7752270f1e35ee6ddcdcd206
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <cassert> #include <limits> #include <iostream> namespace ora { namespace lib { //------------------------------------------------------------------------------ using float32_t = float; using float64_t = double; static_assert(sizeof(float32_t) == 4, "float32_t isn't 32 bits"); static_assert(sizeof(float64_t) == 8, "float64_t isn't 64 bits"); using int128_t = __int128; using uint128_t = unsigned __int128; static_assert(sizeof(int128_t) == 16, "int128_t isn't 128 bits"); static_assert(sizeof(uint128_t) == 16, "uint128_t isn't 128 bits"); /* * Constructs an unisgned 128-bit integer out of high and low 64 bit parts. */ inline constexpr uint128_t make_uint128( uint64_t hi, uint64_t lo) { return ((uint128_t) hi) << 64 | lo; } //------------------------------------------------------------------------------ /* * Returns -1 if x0 < x1, 0 if x0 == x1, or 1 if x0 > x1. */ template<class T, typename std::enable_if<std::is_integral<T>::value, int>::type=0> inline int compare( T const x0, T const x1) { return x0 == x1 ? 0 : x0 < x1 ? -1 : 1; } inline unsigned long pow10( unsigned exp) { // FIXME: Bogosity. static unsigned long pows[] = { (unsigned long) 1ul, (unsigned long) 10ul, (unsigned long) 100ul, (unsigned long) 1000ul, (unsigned long) 10000ul, (unsigned long) 100000ul, (unsigned long) 1000000ul, (unsigned long) 10000000ul, (unsigned long) 100000000ul, (unsigned long) 1000000000ul, (unsigned long) 10000000000ul, (unsigned long) 100000000000ul, (unsigned long) 1000000000000ul, (unsigned long) 10000000000000ul, (unsigned long) 100000000000000ul, (unsigned long) 1000000000000000ul, (unsigned long) 10000000000000000ul, (unsigned long) 100000000000000000ul, (unsigned long) 1000000000000000000ul, (unsigned long) 10000000000000000000ul, }; assert(exp < sizeof(pows) / sizeof(unsigned long)); return pows[exp]; } /** * Returns true if 'val' is in the (closed) range ['min', 'max']. */ template<class T> inline constexpr bool in_range( T min, T val, T max) { return min <= val && val <= max; } /** * Returns true if 'val' is in the half-open range ['min', 'bound'). */ template<class T> inline constexpr bool in_interval( T min, T val, T bound) { return min <= val && val < bound; } // FIXME: Not used. (?) And probably doesn't work for __int128. /* * True if `val` overflows when conveted from integer types `FROM` to `TO`. */ template<class TO, class FROM> inline bool constexpr overflows( FROM val) { static_assert( std::numeric_limits<FROM>::is_integer, "overflows() for integer types only"); static_assert( std::numeric_limits<TO>::is_integer, "overflows() for integer types only"); return std::numeric_limits<TO>::is_signed ? ( !std::numeric_limits<FROM>::is_signed && (uintmax_t) val > (uintmax_t) INTMAX_MAX) || (intmax_t) val < (intmax_t) std::numeric_limits<TO>::min() || (intmax_t) val > (intmax_t) std::numeric_limits<TO>::max() : val < 0 || (uintmax_t) val > (uintmax_t) std::numeric_limits<TO>::max(); } template<class T> inline T round_div( T num, T den) { return (num >= 0 ? num + den / 2 : num - den / 2) / den; } template<class T0, class T1> inline T1 rescale_int( T0 const val, T0 const old_den, T1 const new_den) { if (val == 0) return 0; else if (old_den == (T0) new_den) return val; else if (old_den == 1) return val * new_den; else if (new_den == 1) return round_div(val, old_den); else if (old_den % new_den == 0) return round_div(val, old_den / (T0) new_den); else if (new_den % old_den == 0) return val * (new_den / old_den); else // FIXME: Try to do better! return round_div<int128_t>((int128_t) val * new_den, old_den); } // FIXME: Casting from uint128_t to int128_t won't work for large values. // Hack this for now by ignoring the least significant bit. // This is horrible. template<class T0> inline uint128_t rescale_int( T0 const val, T0 const old_den, uint128_t const new_den) { if (old_den % new_den == 0) return round_div(val, old_den / (T0) new_den); else if (new_den % old_den == 0) return val * (new_den / old_den); else // FIXME: Try to do better! return round_div<int128_t>((int128_t) (val >> 1) * new_den, old_den >> 1); } /** * Rescales a value from one denominator to another, rounding if necessary. */ // FIXME: Is this really necessary? Won't the above be inlined well enough? template<class T, T OLD_DEN, T NEW_DEN> inline T rescale_int( T val) { if (OLD_DEN % NEW_DEN == 0) return round_div(val, OLD_DEN / NEW_DEN); else if (NEW_DEN % OLD_DEN == 0) return val * (NEW_DEN / OLD_DEN); else // FIXME: Try to do better! return round_div<int128_t>((int128_t) val * NEW_DEN, OLD_DEN); } template<class T> struct div_t { T quot; T rem; }; /* * Like <std::div>, except the remainder has the same sign as the denominator. * * Returns `{quot, rem}` such that, * * num == quot * den + rem * 0 <= abs(rem) < abs(den) * sgn(rem) == sgn(den) * */ template<class T> inline div_t<T> sgndiv( T const num, T const den) { auto const res = std::div(num, den); if ((den < 0) ^ (res.rem < 0)) return {.quot = res.quot - 1, .rem = res.rem + den}; else return {.quot = res.quot, .rem = res.rem}; } template<> inline div_t<unsigned int> sgndiv( unsigned int const num, unsigned int const den) { return { .quot = num / den, .rem = num % den, }; } template<> inline div_t<unsigned long> sgndiv( unsigned long const num, unsigned long const den) { return { .quot = num / den, .rem = num % den, }; } template<> inline div_t<unsigned long long> sgndiv( unsigned long long const num, unsigned long long const den) { return { .quot = num / den, .rem = num % den, }; } template<> inline div_t<uint128_t> sgndiv( uint128_t const num, uint128_t const den) { return { .quot = num / den, .rem = num % den, }; } //------------------------------------------------------------------------------ inline bool add_overflow(unsigned int a, unsigned int b, unsigned int & r) { return __builtin_uadd_overflow (a, b, &r); } inline bool add_overflow(unsigned long a, unsigned long b, unsigned long & r) { return __builtin_uaddl_overflow (a, b, &r); } inline bool add_overflow(unsigned long long a, unsigned long long b, unsigned long long& r) { return __builtin_uaddll_overflow(a, b, &r); } inline bool add_overflow( int a, int b, int & r) { return __builtin_sadd_overflow (a, b, &r); } inline bool add_overflow( long a, long b, long & r) { return __builtin_saddl_overflow (a, b, &r); } inline bool add_overflow( long long a, long long b, long long& r) { return __builtin_saddll_overflow(a, b, &r); } inline bool sub_overflow(unsigned short a, unsigned short b, unsigned short & r) { return a < b || ((r = a - b) && false); } inline bool sub_overflow(unsigned int a, unsigned int b, unsigned int & r) { return __builtin_usub_overflow (a, b, &r); } inline bool sub_overflow(unsigned long a, unsigned long b, unsigned long & r) { return __builtin_usubl_overflow (a, b, &r); } inline bool sub_overflow(unsigned long long a, unsigned long long b, unsigned long long& r) { return __builtin_usubll_overflow(a, b, &r); } inline bool sub_overflow( int a, int b, int & r) { return __builtin_ssub_overflow (a, b, &r); } inline bool sub_overflow( long a, long b, long & r) { return __builtin_ssubl_overflow (a, b, &r); } inline bool sub_overflow( long long a, long long b, long long& r) { return __builtin_ssubll_overflow(a, b, &r); } inline bool mul_overflow(unsigned int a, unsigned int b, unsigned int & r) { return __builtin_umul_overflow (a, b, &r); } inline bool mul_overflow(unsigned long a, unsigned long b, unsigned long & r) { return __builtin_umull_overflow (a, b, &r); } inline bool mul_overflow(unsigned long long a, unsigned long long b, unsigned long long& r) { return __builtin_umulll_overflow(a, b, &r); } inline bool mul_overflow( int a, int b, int & r) { return __builtin_smul_overflow (a, b, &r); } inline bool mul_overflow( long a, long b, long & r) { return __builtin_smull_overflow (a, b, &r); } inline bool mul_overflow( long long a, long long b, long long& r) { return __builtin_smulll_overflow(a, b, &r); } // FIXME inline bool add_overflow( uint128_t a, uint128_t b, uint128_t& r) { r = a + b; return false; } // FIXME inline bool mul_overflow( uint128_t a, uint128_t b, uint128_t& r) { r = a * b; return false; } //------------------------------------------------------------------------------ } // namespace lib } // namespace ora //------------------------------------------------------------------------------ namespace std { // FIXME: Hack to print uint128_t. This is not allowed! inline std::ostream& operator<<( std::ostream& os, ora::lib::uint128_t x) { char buf[40]; char* p = &buf[39]; *p = 0; if (x == 0) *--p = '0'; else while (x > 0) { *--p = '0' + x % 10; x /= 10; } os << p; return os; } inline std::ostream& operator<<( std::ostream& os, ora::lib::int128_t x) { if (x < 0) os << '-' << (ora::lib::uint128_t) -x; else os << (ora::lib::uint128_t) x; return os; } } // anonymous namespace
25.165394
139
0.596057
alexhsamuel
6e83ac5072636167774570914efd395e58fc2ab1
6,027
hpp
C++
src/sdl/form.hpp
circled-square/helium
97b2f3079ca435554b86a235ff3ff2b4ae8a880c
[ "Apache-2.0" ]
1
2021-05-24T19:58:13.000Z
2021-05-24T19:58:13.000Z
src/sdl/form.hpp
circled-square/helium
97b2f3079ca435554b86a235ff3ff2b4ae8a880c
[ "Apache-2.0" ]
null
null
null
src/sdl/form.hpp
circled-square/helium
97b2f3079ca435554b86a235ff3ff2b4ae8a880c
[ "Apache-2.0" ]
null
null
null
#ifndef sdl_FORM_HPP #define sdl_FORM_HPP #include <SDL2/SDL_blendmode.h> #include <SDL2/SDL.h> #include <SDL2/SDL_events.h> #include <SDL2/SDL_render.h> #include <SDL2/SDL_video.h> #include <SDL2/SDL_ttf.h> #include <ostream> #include <string> #include <functional> #include <vector> #include <optional> #include <scluk/language_extension.hpp> namespace sdl { using namespace scluk::language_extension; struct color : public SDL_Color { color() : SDL_Color() { } color(u8 r, u8 g, u8 b, u8 a) : SDL_Color({r,g,b,a}) { } color(SDL_Color other) : SDL_Color(other) { } color(const color& other) : SDL_Color(other) { } color& operator=(color o) { r = o.r; g = o.g; b = o.b; a = o.a; return *this; } //a couple of shitty colors mainly for debug static constexpr SDL_Color transparent { 0, 0, 0, 0 }, white { 255, 255, 255, 255 }, black { 0, 0, 0, 255 }, grey { 128, 128, 128, 255 }, dark_grey { 64, 64, 64, 255 }, light_grey { 160, 160, 160, 255 }, red { 255, 0, 0, 255 }, green { 0, 255, 0, 255 }, blue { 0, 0, 255, 255 }, yellow { 255, 255, 0, 255 }; }; template<typename T = i32> struct point { /* A pair of homogenous variables (+ utility functions). The point (pun intended) is to have some kind of struct that can be used to hold coordinates in both floating point (needed for calculations) and integer types (needed for input/output/APIs as numbers of pixels are integers), allowing automatic conversions between the two. */ T x, y; point<T>(T x, T y) : x(x), y(y) { } point<T>() { } template <typename target_t> operator point<target_t>() const { return { static_cast<target_t>(x), static_cast<target_t>(y) }; } operator SDL_Point() const {//SDL_Point is internally identical to (and thus trivially constructible from) point<int> return this->operator point<int>(); } template <typename distance_t, typename angle_t> inline point<T> get_point_at(distance_t distance, angle_t degrees) const noexcept {//utility function to avoid duplication of code. Returns the coordinates of the point at a certain angle and at a certain distance angle_t& angle = (degrees*=0.0174532925199);//convert from degrees to radians return { this->x + distance * cos(angle), this->y + distance * sin(angle) }; } }; using rect = SDL_Rect; template<typename T> std::ostream& operator<<(std::ostream& os, const point<T>& p) { return os << p.x << ", " << p.y; } struct sdl_error : std::runtime_error { sdl_error(std::string message) : std::runtime_error(message) { } virtual ~sdl_error(); }; class font { TTF_Font* font_ptr = nullptr; public: int size() const { return TTF_FontHeight(font_ptr); } [[gnu::always_inline]] font(const char* path, int size) : font_ptr(TTF_OpenFont(path, size)){ if(!font_ptr) throw sdl_error(sout("TTF_OpenFont error: %", SDL_GetError())); } [[gnu::always_inline]] ~font() { TTF_CloseFont(font_ptr); } friend class window; friend class button; }; class window; class button : rect { bool pressed = false; public: enum : int { null_sz = -1 }; std::string text; std::optional<font> font_info; std::function<void(window&)> cb; color fg, bg; button(rect bounds,const std::string& text, const std::optional<font>& font, const std::function<void(window&)>& cb, color fg = color::black, color bg = color::white) : rect(bounds), text(text), font_info(font), cb(cb), fg(fg), bg(bg) { //if the size was set to null_sz initialise it as the size of the text + 20 if(font && (bounds.w < 0 || bounds.h < 0)) { TTF_SizeText(font->font_ptr, text.c_str(), &bounds.w, &bounds.h); if(w < 0) w = bounds.w + 20; if(h < 0) h = bounds.h + 20; } } bool is_pressed() { return pressed; } friend class window; }; class window { SDL_Window* win_ptr = nullptr; SDL_Renderer* renderer_ptr = nullptr; const u8* kbd_ptr; std::function<void(window&)> draw_cb, quit_cb; std::function<void(window&,SDL_KeyboardEvent)> key_cb; color text_fg, text_bg; static u32 window_count; public: point<int> res; std::vector<button> buttons; //non inline function declaration window(const char* name, point<int> res, std::optional<point<int>> pos = {}, bool resizeable = true); ~window(); void poll_events(); void render_frame(); void draw_text(const font& font, const std::string& text, point<int> pos); void draw_button(const button& b); void set_icon(const char* path); //inline functions definition inline const u8* kbd() { return kbd_ptr; } inline void draw_line(point<int> a, point<int> b) { SDL_RenderDrawLine(renderer_ptr, a.x, a.y, b.x, b.y); } inline void set_draw_color(color c) { SDL_SetRenderDrawColor(renderer_ptr, c.r, c.g, c.b, c.a); } inline void clear(color c) { set_draw_color(c); SDL_RenderClear(renderer_ptr); } inline void set_text_color(color fg, color bg) { text_fg = fg; text_bg = bg; } inline void set_draw_cb(const std::function<void(window&)>& cb) { draw_cb = cb; } inline void set_quit_cb(const std::function<void(window&)>& cb) { quit_cb = cb; } inline void set_key_cb(const std::function<void(window&, SDL_KeyboardEvent)>& cb) { key_cb = cb; } inline void draw_rect(point<int> p, point<int> sz) { rect r {p.x, p.y, sz.x, sz.y}; draw_rect(r); } inline void draw_rect(rect r) { SDL_RenderFillRect(renderer_ptr, &r); } template<typename T = int> [[gnu::always_inline]] inline point<T> get_mouse_pos() { point<int> ret; SDL_GetMouseState(&ret.x, &ret.y); return point<T>(ret); } }; } #endif //SDL_FORM_HPP
33.115385
217
0.622034
circled-square
6e8421f55784486b76494a15bbc185e4a31870b5
1,003
hpp
C++
libcaf_core/caf/flow/op/fail.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_core/caf/flow/op/fail.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
libcaf_core/caf/flow/op/fail.hpp
seewpx/actor-framework
65ecf35317b81d7a211848d59e734f43483fe410
[ "BSD-3-Clause" ]
null
null
null
// This file is part of CAF, the C++ Actor Framework. See the file LICENSE in // the main distribution directory for license terms and copyright or visit // https://github.com/actor-framework/actor-framework/blob/master/LICENSE. #pragma once #include "caf/error.hpp" #include "caf/flow/observable.hpp" #include "caf/flow/observer.hpp" #include "caf/flow/op/cold.hpp" #include "caf/flow/subscription.hpp" namespace caf::flow::op { template <class T> class fail : public cold<T> { public: // -- member types ----------------------------------------------------------- using super = cold<T>; // -- constructors, destructors, and assignment operators -------------------- fail(coordinator* ctx, error err) : super(ctx), err_(std::move(err)) { // nop } // -- implementation of observable_impl<T> ----------------------------------- disposable subscribe(observer<T> out) override { out.on_error(err_); return {}; } private: error err_; }; } // namespace caf::flow::op
25.075
80
0.613161
seewpx
6e85914a7de9150147db797b84a5aeba4f6ba8a0
615
cpp
C++
black-f407ve/zhello/src/main.cpp
Paolo-Maffei/stm32x
790aa03a365952c8a3cf8fd334ae307c2130fedb
[ "Unlicense" ]
2
2021-03-11T10:33:37.000Z
2022-02-12T19:35:55.000Z
black-f407ve/zhello/src/main.cpp
Paolo-Maffei/stm32x
790aa03a365952c8a3cf8fd334ae307c2130fedb
[ "Unlicense" ]
null
null
null
black-f407ve/zhello/src/main.cpp
Paolo-Maffei/stm32x
790aa03a365952c8a3cf8fd334ae307c2130fedb
[ "Unlicense" ]
null
null
null
// Minimal "hello" example with z80 emu, loaded directly into RAM. #include <jee.h> #include <string.h> extern "C" { #include "zextest.h" #include "z80emu.h" } const uint8_t rom [] = { #include "hello.h"; }; UartDev< PinA<9>, PinA<10> > console; ZEXTEST zex; void SystemCall (ZEXTEST*) { for (int i = zex.state.registers.word[Z80_DE]; zex.memory[i] != '$'; i++) console.putc(zex.memory[i & 0xffff]); } int main() { console.init(); memcpy(zex.memory, rom, sizeof rom); Z80Reset(&zex.state); while (!zex.is_done) Z80Emulate(&zex.state, 4000000, &zex); while (1) {} }
17.571429
77
0.613008
Paolo-Maffei
6e87e427988c601afdae3926243a067d400e2626
2,444
hpp
C++
include/eepp/ui/uipushbutton.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
37
2020-01-20T06:21:24.000Z
2022-03-21T17:44:50.000Z
include/eepp/ui/uipushbutton.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
null
null
null
include/eepp/ui/uipushbutton.hpp
jayrulez/eepp
09c5c1b6b4c0306bb0a188474778c6949b5df3a7
[ "MIT" ]
9
2019-03-22T00:33:07.000Z
2022-03-01T01:35:59.000Z
#ifndef EE_UICUIPUSHBUTTON_HPP #define EE_UICUIPUSHBUTTON_HPP #include <eepp/ui/uiimage.hpp> #include <eepp/ui/uitextview.hpp> #include <eepp/ui/uiwidget.hpp> namespace EE { namespace UI { enum class InnerWidgetOrientation { Left, Right, Center }; class EE_API UIPushButton : public UIWidget { public: static UIPushButton* New(); static UIPushButton* NewWithTag( const std::string& tag ); static UIPushButton* NewWithOpt( const std::string& tag, const std::function<UITextView*()>& newTextViewCb ); UIPushButton(); virtual ~UIPushButton(); virtual Uint32 getType() const; virtual bool isType( const Uint32& type ) const; virtual void setTheme( UITheme* Theme ); virtual UIPushButton* setIcon( Drawable* icon ); virtual UIImage* getIcon() const; virtual UIPushButton* setText( const String& text ); virtual const String& getText(); UITextView* getTextBox() const; void setIconMinimumSize( const Sizei& minIconSize ); const Sizei& getIconMinimumSize() const; virtual bool applyProperty( const StyleSheetProperty& attribute ); virtual std::string getPropertyString( const PropertyDefinition* propertyDef, const Uint32& propertyIndex = 0 ); void setTextAlign( const Uint32& align ); virtual Sizef getContentSize() const; const InnerWidgetOrientation& getInnerWidgetOrientation() const; void setInnerWidgetOrientation( const InnerWidgetOrientation& innerWidgetOrientation ); virtual UIWidget* getExtraInnerWidget() const; UIWidget* getFirstInnerItem() const; virtual Sizef updateLayout(); protected: UIImage* mIcon; UITextView* mTextBox; Sizei mIconMinSize; InnerWidgetOrientation mInnerWidgetOrientation{ InnerWidgetOrientation::Right }; explicit UIPushButton( const std::string& tag ); explicit UIPushButton( const std::string& tag, const std::function<UITextView*()>& cb ); virtual Rectf calculatePadding() const; virtual void onSizeChange(); virtual void onAlphaChange(); virtual void onStateChange(); virtual void onAlignChange(); virtual void onThemeLoaded(); virtual void onAutoSize(); virtual void onPaddingChange(); virtual Uint32 onKeyDown( const KeyEvent& Event ); virtual Uint32 onKeyUp( const KeyEvent& Event ); Vector2f packLayout( const std::vector<UIWidget*>& widgets, const Rectf& padding ); Vector2f calcLayoutSize( const std::vector<UIWidget*>& widgets, const Rectf& padding ) const; }; }} // namespace EE::UI #endif
23.960784
94
0.755319
jayrulez
6e920e21a7f353b7d733f45f75c6ff605a72a2ec
842
cpp
C++
Command Prototype Steve 02142017/src/Commands/geardown.cpp
SteelRidgeRobotics/Steamworks
395c88294da0bd3426b0c886e7fbbb887ffdce8c
[ "BSD-2-Clause" ]
null
null
null
Command Prototype Steve 02142017/src/Commands/geardown.cpp
SteelRidgeRobotics/Steamworks
395c88294da0bd3426b0c886e7fbbb887ffdce8c
[ "BSD-2-Clause" ]
null
null
null
Command Prototype Steve 02142017/src/Commands/geardown.cpp
SteelRidgeRobotics/Steamworks
395c88294da0bd3426b0c886e7fbbb887ffdce8c
[ "BSD-2-Clause" ]
null
null
null
#include "geardown.h" //Call on the commands from the constructor of the header file. geardown::geardown(): Command() { // Declare what subsystem the command depends on. Requires(Robot::gears.get()); } // Called just before this Command runs the first time void geardown::Initialize() { } // Called repeatedly when this Command is scheduled to run void geardown::Execute() { //Calls on the movegeardown method declared in the Gears.h and Gears.cpp file Robot::gears->movegeardown(); } // Make this return true when this Command no longer needs to run execute() bool geardown::IsFinished() { return false; } // Called once after isFinished returns true void geardown::End() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run void geardown::Interrupted() { }
21.589744
78
0.724466
SteelRidgeRobotics
6e95453db731ae34e8f79777e1b9917239a6651c
503
cpp
C++
SVEngine/src/file/SVParseParticles.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
34
2018-09-28T08:28:27.000Z
2022-01-15T10:31:41.000Z
SVEngine/src/file/SVParseParticles.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
null
null
null
SVEngine/src/file/SVParseParticles.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
8
2018-10-11T13:36:35.000Z
2021-04-01T09:29:34.000Z
// // SVParseParticles.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include "SVParseParticles.h" #include "../node/SVParticlesNode.h" SVNodePtr SVParseParticles::parseParticles(SVInst *_app, RAPIDJSON_NAMESPACE::Value &item, s32 _resid, cptr8 _path) { SVParticlesNodePtr t_particlesNode = MakeSharedPtr<SVParticlesNode>(_app); t_particlesNode->m_rootPath = _path; t_particlesNode->fromJSON(item); return t_particlesNode; }
26.473684
107
0.759443
SVEChina
6e96e9642af1e5691358739ac3a65fc37293902f
633
cpp
C++
leetcode.com/0703 Kth Largest Element in a Stream/main2.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0703 Kth Largest Element in a Stream/main2.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0703 Kth Largest Element in a Stream/main2.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> #include <queue> #include <vector> using namespace std; // just use priority_queue class KthLargest { private: priority_queue<int, vector<int>, greater<int>> pq; int size; public: KthLargest(int k, vector<int> nums) { size = k; for (int i = 0; i < nums.size(); i++) { pq.push(nums[i]); if (pq.size() > k) pq.pop(); } } int add(int val) { pq.push(val); if (pq.size() > size) pq.pop(); return pq.top(); } }; /** * Your KthLargest object will be instantiated and called as such: * KthLargest* obj = new KthLargest(k, nums); * int param_1 = obj->add(val); */
19.181818
66
0.597156
sky-bro
6e9b17bd71b7edbae4e50f3ed0152d040cd252f5
1,706
cpp
C++
P2422.cpp
Thomitics/MyOI
72f75b61b79230835a65ca313896031ba9d4665f
[ "MIT" ]
140
2021-02-14T02:41:48.000Z
2021-07-08T02:59:13.000Z
P2422.cpp
LikiBlaze/MyOI
72f75b61b79230835a65ca313896031ba9d4665f
[ "MIT" ]
1
2021-02-16T02:46:45.000Z
2021-02-16T02:46:45.000Z
P2422.cpp
Thomitics/MyOI
72f75b61b79230835a65ca313896031ba9d4665f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define INF 999999999 using namespace std; inline long long read() { long long x = 0; int f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * f; } void write(const long long &x) { if (!x) { putchar('0'); return; } char f[100]; long long tmp = x; if (tmp < 0) { tmp = -tmp; putchar('-'); } long long s = 0; while (tmp > 0) { f[s++] = tmp % 10 + '0'; tmp /= 10; } while (s > 0) { putchar(f[--s]); } } #ifdef THODEBUG const long long maxN = 90; #else const long long maxN = 100090; #endif long long totN; long long nums[maxN]; struct Node { long long ID; long long num; }; stack<Node> S; long long sum[maxN]; long long DP[maxN]; long long totANS; int main() { totN = read(); for (int i = 1; i <= totN; ++i) { nums[i] = read(); sum[i] = nums[i] + sum[i - 1]; } for (int i = 1; i <= totN; ++i) { while (!S.empty() and S.top().num > nums[i]) { DP[S.top().ID] += (sum[i - 1] - sum[S.top().ID]); S.pop(); } if (!S.empty()) { DP[i] = sum[i] - sum[S.top().ID]; } else { DP[i] = sum[i]; } S.push({i, nums[i]}); } for (int i = 1; i <= totN; ++i) { totANS = max(totANS, DP[i] * nums[i]); } write(totANS); return 0; } //Thomitics Code
17.06
61
0.407386
Thomitics
6e9bdd825ab6720d3b428c47266e48d4d9c5684a
834
hpp
C++
ActiveCampaignCpp/include/Tasks.hpp
icarus3/ActiveCampaignCpp
c2389b4c9469251e6f3adb6b574402eca2e353ac
[ "MIT" ]
null
null
null
ActiveCampaignCpp/include/Tasks.hpp
icarus3/ActiveCampaignCpp
c2389b4c9469251e6f3adb6b574402eca2e353ac
[ "MIT" ]
null
null
null
ActiveCampaignCpp/include/Tasks.hpp
icarus3/ActiveCampaignCpp
c2389b4c9469251e6f3adb6b574402eca2e353ac
[ "MIT" ]
null
null
null
#ifndef TASKS_HPP #define TASKS_HPP #include <iostream> #include <string> #include <functional> #include "json.hpp" #include "Config.hpp" #include "ActiveCampaign.hpp" #include "AutoRegister.hpp" using json = nlohmann::json; class Tasks : public ActiveCampaign, public AutoRegister<Tasks> { public: Tasks(const std::shared_ptr<Config> & config) : ActiveCampaign(config, { "tasks_get" }, { std::bind(&Tasks::tasksGet, this, std::placeholders::_1, std::placeholders::_2) }) { (void)s_bRegistered; } static std::unique_ptr<ActiveCampaign> CreateMethod(const std::shared_ptr<Config> & config) { return std::make_unique<Tasks>(config); } static std::string GetFactoryName() { return "Tasks"; } json tasksGet(const std::string & action, const json & data) { return get(action, data); } }; #endif
17.744681
92
0.701439
icarus3
6e9f28b33c1f55b12007f53a5c305eb03c5dffad
4,006
hpp
C++
cpp/godot-cpp/include/gen/Theme.hpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
1
2021-03-16T09:51:00.000Z
2021-03-16T09:51:00.000Z
cpp/godot-cpp/include/gen/Theme.hpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
cpp/godot-cpp/include/gen/Theme.hpp
GDNative-Gradle/proof-of-concept
162f467430760cf959f68f1638adc663fd05c5fd
[ "MIT" ]
null
null
null
#ifndef GODOT_CPP_THEME_HPP #define GODOT_CPP_THEME_HPP #include <gdnative_api_struct.gen.h> #include <stdint.h> #include <core/CoreTypes.hpp> #include <core/Ref.hpp> #include "Resource.hpp" namespace godot { class Theme; class Font; class Texture; class StyleBox; class Theme : public Resource { struct ___method_bindings { godot_method_bind *mb__emit_theme_changed; godot_method_bind *mb_clear; godot_method_bind *mb_clear_color; godot_method_bind *mb_clear_constant; godot_method_bind *mb_clear_font; godot_method_bind *mb_clear_icon; godot_method_bind *mb_clear_stylebox; godot_method_bind *mb_copy_default_theme; godot_method_bind *mb_copy_theme; godot_method_bind *mb_get_color; godot_method_bind *mb_get_color_list; godot_method_bind *mb_get_constant; godot_method_bind *mb_get_constant_list; godot_method_bind *mb_get_default_font; godot_method_bind *mb_get_font; godot_method_bind *mb_get_font_list; godot_method_bind *mb_get_icon; godot_method_bind *mb_get_icon_list; godot_method_bind *mb_get_stylebox; godot_method_bind *mb_get_stylebox_list; godot_method_bind *mb_get_stylebox_types; godot_method_bind *mb_get_type_list; godot_method_bind *mb_has_color; godot_method_bind *mb_has_constant; godot_method_bind *mb_has_font; godot_method_bind *mb_has_icon; godot_method_bind *mb_has_stylebox; godot_method_bind *mb_set_color; godot_method_bind *mb_set_constant; godot_method_bind *mb_set_default_font; godot_method_bind *mb_set_font; godot_method_bind *mb_set_icon; godot_method_bind *mb_set_stylebox; }; static ___method_bindings ___mb; public: static void ___init_method_bindings(); static inline const char *___get_class_name() { return (const char *) "Theme"; } static inline Object *___get_from_variant(Variant a) { godot_object *o = (godot_object*) a; return (o) ? (Object *) godot::nativescript_1_1_api->godot_nativescript_get_instance_binding_data(godot::_RegisterState::language_index, o) : nullptr; } // enums // constants static Theme *_new(); // methods void _emit_theme_changed(); void clear(); void clear_color(const String name, const String type); void clear_constant(const String name, const String type); void clear_font(const String name, const String type); void clear_icon(const String name, const String type); void clear_stylebox(const String name, const String type); void copy_default_theme(); void copy_theme(const Ref<Theme> other); Color get_color(const String name, const String type) const; PoolStringArray get_color_list(const String type) const; int64_t get_constant(const String name, const String type) const; PoolStringArray get_constant_list(const String type) const; Ref<Font> get_default_font() const; Ref<Font> get_font(const String name, const String type) const; PoolStringArray get_font_list(const String type) const; Ref<Texture> get_icon(const String name, const String type) const; PoolStringArray get_icon_list(const String type) const; Ref<StyleBox> get_stylebox(const String name, const String type) const; PoolStringArray get_stylebox_list(const String type) const; PoolStringArray get_stylebox_types() const; PoolStringArray get_type_list(const String type) const; bool has_color(const String name, const String type) const; bool has_constant(const String name, const String type) const; bool has_font(const String name, const String type) const; bool has_icon(const String name, const String type) const; bool has_stylebox(const String name, const String type) const; void set_color(const String name, const String type, const Color color); void set_constant(const String name, const String type, const int64_t constant); void set_default_font(const Ref<Font> font); void set_font(const String name, const String type, const Ref<Font> font); void set_icon(const String name, const String type, const Ref<Texture> texture); void set_stylebox(const String name, const String type, const Ref<StyleBox> texture); }; } #endif
36.752294
245
0.801548
GDNative-Gradle
6ea2e47a17339d79bdc13d9e5ba14e4fa0adb8c1
2,371
cpp
C++
Old/Source/Animation.cpp
TinoTano/Games_Factory_2D
116ec94f05eb805654f3d30735134e81eb873c60
[ "MIT" ]
1
2020-02-07T04:50:57.000Z
2020-02-07T04:50:57.000Z
Old/Source/Animation.cpp
TinoTano/Games_Factory_2D
116ec94f05eb805654f3d30735134e81eb873c60
[ "MIT" ]
null
null
null
Old/Source/Animation.cpp
TinoTano/Games_Factory_2D
116ec94f05eb805654f3d30735134e81eb873c60
[ "MIT" ]
1
2020-02-07T04:51:00.000Z
2020-02-07T04:51:00.000Z
#include "Animation.h" #include "Texture.h" #include "Data.h" #include "Application.h" #include "FileSystemModule.h" #include "ResourceManagerModule.h" Animation::Animation(std::string name, std::string assetsPath, std::string fullPath) : Resource(name, assetsPath, fullPath, Resource::RESOURCE_ANIM) { speed = 1.0f; loop = false; currentAnimTextureIndex = 0; } Animation::~Animation() { animationTextures.clear(); } void Animation::AddTexture(Texture & texture) { animationTextures.emplace_back(&texture); } void Animation::RemoveTexture(Texture & texture) { for (int i = 0; i < animationTextures.size(); i++) { if (animationTextures[i] == &texture) { animationTextures.erase(animationTextures.begin() + i); break; } } } void Animation::SetSpeed(float speed) { this->speed = speed; } float Animation::GetSpeed() const { return speed; } void Animation::SetLoop(bool loop) { this->loop = loop; } bool Animation::GetIsLoop() const { return loop; } void Animation::StopAnimation() { currentAnimTextureIndex = 0; } Texture * Animation::GetCurrentTexture() const { return animationTextures[(int)currentAnimTextureIndex]; } Texture * Animation::GetNextTexture() { currentAnimTextureIndex += speed * App->GetDeltaTime(); if (currentAnimTextureIndex >= animationTextures.size()) { currentAnimTextureIndex = (loop) ? 0.0f : animationTextures.size() - 1; } return animationTextures[(int)currentAnimTextureIndex]; } void Animation::UpdateTextures(std::vector<Texture*> textures) { animationTextures.clear(); animationTextures = textures; } std::vector<Texture*> Animation::GetTextures() const { return animationTextures; } bool Animation::LoadFromFile(std::string path) { bool ret = false; if (App->fileSystemModule->FileExist(path)) { Data data; if (data.LoadData(path)) { speed = data.GetFloat("Speed"); loop = data.GetBool("Loop"); int imagesCount = data.GetInt("ImagesCount"); for (int i = 0; i < imagesCount; i++) { std::string assetPath = data.GetString("ImagePath" + std::to_string(i)); std::string fullPath = App->fileSystemModule->GetWorkingPath() + "/Data/" + assetPath; Texture* texture = (Texture*)App->resourceManagerModule->CreateResource(fullPath); if(texture != nullptr) { animationTextures.emplace_back(texture); } } ret = true; } } return ret; }
20.09322
90
0.705609
TinoTano
6ea54776c20ecee4d964c09656bcdbd7eca1e89b
1,986
cpp
C++
Week3-Greedy Algorithms/Fractional_Knapsack/fract_knap.cpp
Godcreatebugs/Algorithm_Toolbox
1dcfb09af7f806cf5d6835f244f8f6c2064396f8
[ "Apache-2.0" ]
null
null
null
Week3-Greedy Algorithms/Fractional_Knapsack/fract_knap.cpp
Godcreatebugs/Algorithm_Toolbox
1dcfb09af7f806cf5d6835f244f8f6c2064396f8
[ "Apache-2.0" ]
null
null
null
Week3-Greedy Algorithms/Fractional_Knapsack/fract_knap.cpp
Godcreatebugs/Algorithm_Toolbox
1dcfb09af7f806cf5d6835f244f8f6c2064396f8
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> //#include <algorithm> using std::vector; /*----->>>TRIAL AND NOT USEFUL TO USE POP METHODS WHICH IS TAKEN CARE OF BY get_index FUNCTION. std::vector<double> ratio(vector<int> weights, vector<int> values){ int size_weights=weights.size(); std::vector<double> ratio_arr; for(int i=0;i<size_weights;++i){ ratio_arr.push_back(values[i]/weights[i]); } return ratio_arr; } /* int max_ele_index(vector<int> weights, vector<int> values){ int size_arr=weights.sizeof(); int max_element; int max_ele_index; for(int i=0;i<size_arr,++i){ max_element=std::max_element() } } */ int get_index(vector<int> weights, vector<int> values){ double max_ele=0; int max_index=0; for (int i=0;i<weights.size();++i){ if(weights[i]>0 && (double) values[i] / weights[i]>max_ele){ max_ele = (double) values[i] / weights[i]; max_index= i; } } return max_index; } double get_optimal_value(int capacity, vector<int> weights, vector<int> values) { double value = 0.0; for (int i=0;i<weights.size();++i) { if (capacity==0) return value; int index=get_index(weights,values); int a=std::min(capacity,weights[index]); value +=a*(double) values[index]/weights[index]; weights[index] -=a; //this line ensures the removal of selected material and reducing its weights, most important line of program capacity -=a; } // write your code here return value; } int main() { int n; int capacity; std::cin >> n >> capacity; vector<int> values(n); vector<int> weights(n); for (int i = 0; i < n; i++) { std::cin >> values[i] >> weights[i]; } double optimal_value = get_optimal_value(capacity, weights, values); std::cout.precision(10); std::cout << optimal_value << std::endl; return 0; } /* int main(){ vector<int> values{20,40,60}; vector<int> weights{20,10,20}; std::cout << "and the ratio function"; std::cout<<ratio(weights, values) << '\n' return 0; } */
24.825
133
0.655086
Godcreatebugs
6ea617d6fd75731fadecc311d7c71b804421a457
2,952
cpp
C++
src/game/client/tf/vgui/panels/tf_pausemenupanel.cpp
mastercoms/TF2Classic
012960d85c6782aeb79b7dff4fe878cc8161008b
[ "Unlicense" ]
9
2019-07-18T15:01:29.000Z
2020-09-15T22:10:08.000Z
src/game/client/tf/vgui/panels/tf_pausemenupanel.cpp
mastercoms/TF2Classic
012960d85c6782aeb79b7dff4fe878cc8161008b
[ "Unlicense" ]
null
null
null
src/game/client/tf/vgui/panels/tf_pausemenupanel.cpp
mastercoms/TF2Classic
012960d85c6782aeb79b7dff4fe878cc8161008b
[ "Unlicense" ]
9
2019-08-14T15:05:18.000Z
2022-03-06T16:35:47.000Z
#include "cbase.h" #include "tf_pausemenupanel.h" #include "controls/tf_advbutton.h" #include "tf_notificationmanager.h" using namespace vgui; // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //----------------------------------------------------------------------------- // Purpose: Constructor //----------------------------------------------------------------------------- CTFPauseMenuPanel::CTFPauseMenuPanel(vgui::Panel* parent, const char *panelName) : CTFMenuPanelBase(parent, panelName) { Init(); } //----------------------------------------------------------------------------- // Purpose: Destructor //----------------------------------------------------------------------------- CTFPauseMenuPanel::~CTFPauseMenuPanel() { } bool CTFPauseMenuPanel::Init() { BaseClass::Init(); m_pNotificationButton = NULL; bInMenu = false; bInGame = true; return true; }; void CTFPauseMenuPanel::ApplySchemeSettings(vgui::IScheme *pScheme) { BaseClass::ApplySchemeSettings(pScheme); LoadControlSettings("resource/UI/main_menu/PauseMenuPanel.res"); m_pNotificationButton = dynamic_cast<CTFButton*>(FindChildByName("NotificationButton")); } void CTFPauseMenuPanel::PerformLayout() { BaseClass::PerformLayout(); OnNotificationUpdate(); }; void CTFPauseMenuPanel::OnCommand(const char* command) { if (!Q_strcmp(command, "newquit")) { MAINMENU_ROOT->ShowPanel(QUIT_MENU); } else if (!Q_strcmp(command, "newoptionsdialog")) { MAINMENU_ROOT->ShowPanel(OPTIONSDIALOG_MENU); } else if (!Q_strcmp(command, "newloadout")) { MAINMENU_ROOT->ShowPanel(LOADOUT_MENU); } else if (!Q_strcmp(command, "shownotification")) { if (m_pNotificationButton) { m_pNotificationButton->SetGlowing(false); } MAINMENU_ROOT->ShowPanel(NOTIFICATION_MENU); } else { BaseClass::OnCommand(command); } } void CTFPauseMenuPanel::OnNotificationUpdate() { if (m_pNotificationButton) { if (GetNotificationManager()->GetNotificationsCount() > 0) { m_pNotificationButton->SetVisible(true); } else { m_pNotificationButton->SetVisible(false); } if (GetNotificationManager()->GetUnreadNotificationsCount() > 0) { m_pNotificationButton->SetGlowing(true); } else { m_pNotificationButton->SetGlowing(false); } } }; void CTFPauseMenuPanel::OnTick() { BaseClass::OnTick(); }; void CTFPauseMenuPanel::OnThink() { BaseClass::OnThink(); }; void CTFPauseMenuPanel::Show() { BaseClass::Show(); vgui::GetAnimationController()->RunAnimationCommand(this, "Alpha", 255, 0.0f, 0.5f, vgui::AnimationController::INTERPOLATOR_SIMPLESPLINE); }; void CTFPauseMenuPanel::Hide() { BaseClass::Hide(); vgui::GetAnimationController()->RunAnimationCommand(this, "Alpha", 0, 0.0f, 0.1f, vgui::AnimationController::INTERPOLATOR_LINEAR); }; void CTFPauseMenuPanel::DefaultLayout() { BaseClass::DefaultLayout(); }; void CTFPauseMenuPanel::GameLayout() { BaseClass::GameLayout(); };
21.705882
139
0.658537
mastercoms
6eacc50808057f83294a34bca27dfccdadd74491
4,327
cpp
C++
src/servo.cpp
Leon0402/Project-Hexapod
98aebd80282560fb7ac86d72b78a798e78f86ab1
[ "MIT" ]
6
2018-08-10T14:29:16.000Z
2022-03-31T12:53:28.000Z
src/servo.cpp
Leon0402/Project-Hexapod
98aebd80282560fb7ac86d72b78a798e78f86ab1
[ "MIT" ]
null
null
null
src/servo.cpp
Leon0402/Project-Hexapod
98aebd80282560fb7ac86d72b78a798e78f86ab1
[ "MIT" ]
1
2020-06-18T17:23:14.000Z
2020-06-18T17:23:14.000Z
#include "Servo.h" #ifndef X86_64 #include <time.h> #include <math.h> #else #include <cmath> #endif /******************************************************************************************************************************************************/ // public /******************************************************************************************************************************************************/ Servo::Servo(Servocontroller& servocontroller, uint8_t pin, uint16_t servoMin, uint16_t servoMax) : servocontroller {servocontroller}, pin {pin}, servoMin {servoMin}, servoMax {servoMax} {} void Servo::update(uint32_t currentMillis) { if(this->active) { int16_t velocityAddition; if(this->acceleration > 0) { velocityAddition = this->acceleration*(currentMillis - this->lastUpdate) + 0.5; if(velocityAddition == 0) { velocityAddition = 1; } if(velocityAddition > (this->targetVelocity - this->velocity)) { this->velocity = this->targetVelocity; } else { this->velocity += velocityAddition; } } else if (this->acceleration < 0) { velocityAddition = this->acceleration*(currentMillis - this->lastUpdate) - 0.5; if(velocityAddition == 0) { velocityAddition = -1; } if(velocityAddition < (this->targetVelocity - this->velocity)) { this->velocity = this->targetVelocity; } else { this->velocity += velocityAddition; } } int16_t movementAddition; if(this->velocity > 0) { movementAddition = this->velocity*(currentMillis - this->lastUpdate) + 0.5; if(movementAddition == 0) { movementAddition = 1; //"Please make ISR slower or movement faster" } if(movementAddition >= ((int16_t)this->destinationPulseWidth - (int16_t)this->pulseWidth)) { this->pulseWidth = this->destinationPulseWidth; //Movement is finished at the end of the update method, so set active to false this->active = false; } else { this->pulseWidth += movementAddition; } } else if(this->velocity < 0){ movementAddition = this->velocity*(currentMillis - this->lastUpdate) - 0.5; if(movementAddition == 0) { movementAddition = -1; //"Please make ISR slower or movement faster" } if(movementAddition <= ((int16_t)this->destinationPulseWidth - (int16_t)this->pulseWidth)) { this->pulseWidth = this->destinationPulseWidth; //Movement is finished at the end of the update method, so set active to false this->active = false; } else { this->pulseWidth += movementAddition; } } //Move servo this->servocontroller.setPWM(this->pin, 0, this->pulseWidth); } #ifndef X86_64 this->lastUpdate = time(nullptr); #endif } void Servo::move(float speed, float targetSpeed, float acceleration) { while(this->active); //If servo has already reached its destinationPulseWidth do not change status to active if(this->pulseWidth == this->destinationPulseWidth || speed == 0.0f) { return; } if(this->pulseWidth < this->destinationPulseWidth) { this->velocity = speed; this->targetVelocity = targetSpeed; this->acceleration = acceleration; } else { this->velocity = -speed; this->targetVelocity = -targetSpeed; this->acceleration = -acceleration; } this->active = true; } void Servo::move(uint16_t time) { float difference = fabs((float)this->destinationPulseWidth - (float)this->pulseWidth); uint16_t pulseWidthRange = mapToPulseWidth(Servo::angleRange); if(time != 0) { move(difference/time, pulseWidthRange, 0.0f); } else { move(pulseWidthRange, pulseWidthRange, 0.0f); } } void Servo::setAngle(uint8_t angle) { this->destinationPulseWidth = mapToPulseWidth(angle); } /******************************************************************************************************************************************************/ // private /******************************************************************************************************************************************************/ uint16_t Servo::mapToPulseWidth(float angle) { return ((angle * (this->servoMax - this->servoMin) * 2.0f) / Servo::angleRange + 1.0f) / 2.0f + this->servoMin; }
35.178862
152
0.56159
Leon0402