text stringlengths 1 2.12k | source dict |
|---|---|
c++, design-patterns, c++14, type-safety
template< typename T >
struct Nop_impl {
// char make_struct_to_size_zero[0]; // Adding this member would make this struct have size 0, but this is not Standards compliant
// This function shall accept anything and do nothing.
// Type checking is not necessary, since it is done when "this class is disabled" and the underlying type is used (i.e. in Debug mode).
template< typename ... Types > constexpr Nop_impl( Types && ... ) noexcept {}
// This macro adds a typedef
#define NOP_TYPEDEF( name, type ) using name = type;
NOP_TYPEDEF( value_type, T )
#undef NOP_TYPEDEF
// This macro defines a member function, taking any arguments
#define NOP_MEMBER_FUNCTION( func ) template< typename ... Types > constexpr Nop_impl func( Types && ... ) const noexcept { return Nop_impl{}; }
NOP_MEMBER_FUNCTION( operator() )
NOP_MEMBER_FUNCTION( empty )
NOP_MEMBER_FUNCTION( size )
#undef NOP_MEMBER_FUNCTION
// Defining a function here takes any arguments, one of which a Nop_t,
// defining a function outside the class using the NOP_FUNCTION macro, generates only a function taking one argument, a Nop_t.
#define NOP_FRIEND_FUNCTION( func ) template< typename ... Types > friend constexpr Nop_impl func( Types && ... ) noexcept { return Nop_impl{}; }
NOP_FRIEND_FUNCTION( sin )
NOP_FRIEND_FUNCTION( swap )
#undef NOP_FRIEND_FUNCTION
// This macro defines a unary operator
#define NOP_UNARY( op ) constexpr Nop_impl op noexcept { return Nop_impl{}; }
NOP_UNARY( operator+() )
NOP_UNARY( operator-() )
NOP_UNARY( operator++() )
NOP_UNARY( operator++(int) ) // NOLINT(cert-dcl21-cpp)
NOP_UNARY( operator--() )
NOP_UNARY( operator--(int) ) // NOLINT(cert-dcl21-cpp)
NOP_UNARY( operator!() )
NOP_UNARY( operator~() ) | {
"domain": "codereview.stackexchange",
"id": 42793,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, c++14, type-safety",
"url": null
} |
c++, design-patterns, c++14, type-safety
NOP_UNARY( operator!() )
NOP_UNARY( operator~() )
#undef NOP_UNARY
// This macro defines a binary operator
#define NOP_BINARY_OPERATOR( op ) template< typename L, typename R > friend constexpr Nop_impl operator op ( L &&, R && ) noexcept { return Nop_impl{}; }
NOP_BINARY_OPERATOR( + )
NOP_BINARY_OPERATOR( - )
NOP_BINARY_OPERATOR( * )
NOP_BINARY_OPERATOR( / )
NOP_BINARY_OPERATOR( % )
NOP_BINARY_OPERATOR( += )
NOP_BINARY_OPERATOR( -= )
NOP_BINARY_OPERATOR( *= )
NOP_BINARY_OPERATOR( /= )
NOP_BINARY_OPERATOR( %= )
NOP_BINARY_OPERATOR( < )
NOP_BINARY_OPERATOR( <= )
NOP_BINARY_OPERATOR( >= )
NOP_BINARY_OPERATOR( > )
NOP_BINARY_OPERATOR( != )
NOP_BINARY_OPERATOR( == )
NOP_BINARY_OPERATOR( && )
NOP_BINARY_OPERATOR( || )
NOP_BINARY_OPERATOR( & )
NOP_BINARY_OPERATOR( | )
NOP_BINARY_OPERATOR( ^ ) | {
"domain": "codereview.stackexchange",
"id": 42793,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, c++14, type-safety",
"url": null
} |
c++, design-patterns, c++14, type-safety
NOP_BINARY_OPERATOR( &= )
NOP_BINARY_OPERATOR( |= )
NOP_BINARY_OPERATOR( ^= )
#undef NOP_BINARY_OPERATOR
// Section for special functions
template< typename U > constexpr Nop_impl operator[]( const U & ) noexcept { return Nop_impl{}; }
friend constexpr std::ostream& operator<<( std::ostream & os, Nop_impl ) noexcept { return os; };
};
// Since partial specialization of typedefs/using-directions is not allowed,
// we use a helper struct with a function returning the wanted type.
// This function can be used in a using directive then.
template< typename T, bool E = !T_NDEBUG > struct make_nop;
template< typename T >
struct make_nop< T, true > {
template< typename ... Args > constexpr static T make( Args && ... args ) noexcept( noexcept(T( std::forward< Args >( args ) ... )) ) {
return T( std::forward< Args >( args ) ... );
};
};
template< typename T >
struct make_nop< T, false > {
template< typename ... Args > constexpr static Nop_impl< T > make( Args && ... args ) noexcept {
return Nop_impl< T >( std::forward< Args >( args ) ... );
};
};
}
template< typename T, bool E = !T_NDEBUG > using Nop_t = decltype( detail::make_nop<T,E>::make() );
// This macro defines a function taking exactly one argument of type Nop_t< T, false >, where T is any type
#define NOP_FUNCTION( func ) template< typename T > static inline constexpr \
::detail::Nop_impl< T > func( const ::detail::Nop_impl<T> & ) noexcept { return ::detail::Nop_impl< T >{}; } | {
"domain": "codereview.stackexchange",
"id": 42793,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, c++14, type-safety",
"url": null
} |
c++, design-patterns, c++14, type-safety
// This macro defines user defined literals
// Example:
#define NOP_LITERAL( ... ) OVERLOADED_MACRO( NOP_LITERAL, __VA_ARGS__ )
#define NOP_LITERAL1( name ) \
NOP_LITERAL2( name, !T_NDEBUG )
#define NOP_LITERAL2( name, condition ) \
namespace nop { namespace T_JOIN( line, __LINE__ ) { \
inline constexpr Nop_t< unsigned long long int, condition > operator""_ ## name ( unsigned long long int lit ) { return Nop_t< unsigned long long int, condition >{ lit }; } \
inline constexpr Nop_t< long double, condition > operator ""_ ## name( long double lit ) { return Nop_t< long double, condition >{ lit }; } \
inline constexpr Nop_t< char, condition > operator ""_ ## name( char lit ) { return Nop_t< char, condition >{ lit }; } \
inline constexpr Nop_t< wchar_t, condition > operator ""_ ## name( wchar_t lit ) { return Nop_t< wchar_t, condition >{ lit }; } \
inline constexpr Nop_t< char16_t, condition > operator ""_ ## name( char16_t lit ) { return Nop_t< char16_t, condition >{ lit }; } \
inline constexpr Nop_t< char32_t, condition > operator ""_ ## name( char32_t lit ) { return Nop_t< char32_t, condition >{ lit }; } \
inline constexpr Nop_t< const char *, condition > operator ""_ ## name( const char * lit, size_t ) { return Nop_t< const char *, condition >{ lit }; } \
inline constexpr Nop_t< const wchar_t *, condition > operator ""_ ## name( const wchar_t * lit, size_t ) { return Nop_t< const wchar_t *, condition >{ lit }; } \
inline constexpr Nop_t< const char16_t *, condition > operator ""_ ## name( const char16_t * lit, size_t ) { return Nop_t< const char16_t *, condition >{ lit }; } \
inline constexpr Nop_t< const char32_t *, condition > operator ""_ ## name( const char32_t * lit, size_t ) { return Nop_t< const char32_t *, condition >{ lit }; } \
} } \
using nop:: T_JOIN( line, __LINE__ )::operator""_ ## name;
main/tests:
///
/// main / tests
/// | {
"domain": "codereview.stackexchange",
"id": 42793,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, c++14, type-safety",
"url": null
} |
c++, design-patterns, c++14, type-safety
main/tests:
///
/// main / tests
///
#include <cassert>
#include <iostream>
#include <cmath>
#include <type_traits>
#include <vector>
NOP_LITERAL( nop ) // must compile
NOP_FUNCTION( atan )
NOP_LITERAL( nop1, true )
NOP_LITERAL( nop2, false )
int main() {
static_assert( std::is_standard_layout<Nop_t<int,true>>::value, "Is standard layout" );
static_assert( std::is_pod<Nop_t<int,true>>::value, "Is standard layout" ); | {
"domain": "codereview.stackexchange",
"id": 42793,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, c++14, type-safety",
"url": null
} |
c++, design-patterns, c++14, type-safety
{
struct S {};
volatile Nop_t< S, false > n1( S{} ); // volatile to supress warning
volatile Nop_t< S, false > n2;
volatile Nop_t< int, false > n3( S{} );
volatile Nop_t< int, false > n4( "asd" );
MAYBE_UNUSED( n1 );
MAYBE_UNUSED( n2 );
MAYBE_UNUSED( n3 );
MAYBE_UNUSED( n4 );
}
{
struct S {};
volatile Nop_t< S, true > n1( S{} );
volatile Nop_t< S, true > n2;
Nop_t< int, true > n3a( 1 );
// Nop_t<int,true> n3b( S{} );
// Nop_t<int,true> n3c( "asd" );
Nop_t< std::string, true > n4;
assert( n3a == 1 );
assert( n4.empty() );
MAYBE_UNUSED( n1 );
MAYBE_UNUSED( n2 );
}
{
Nop_t< float, true > t = 10;
Nop_t< float, false > f = 10;
(void) atan( t );
(void) atan( f );
}
{
Nop_t< std::vector<int>, true > vec1{1,2,3};
Nop_t< std::vector<int>, false > vec2{1,2,3};
assert( vec1[2] == 3 );
(void) vec2[2]; // must compile
}
{
Nop_t< std::vector<int>, true > vec1(3,1);
Nop_t< std::vector<int>, false > vec2(3,1);
assert( vec1[2] == 1 );
MAYBE_UNUSED( vec2 );
}
{
Nop_t< int, true > n = 2;
int m = n;
assert( n == 2);
assert( m == 2);
}
{
struct S {};
Nop_t< const volatile S, false > s;
sin( s );
s.size();
}
{
Nop_t< std::string, true > n1 = "ABC";
Nop_t< std::string, false > n2 = "ERROR";
std::cout << Nop_t< std::string, true >{"123"} << n1;
std::cout << Nop_t< std::string, false >{"ERROR"} << n2 << std::endl;
// Output must be "123ABC"
}
{
std::cout << (Nop_t< std::string, true >)"123";
std::cout << (Nop_t< std::string, false >)"ERROR" << std::endl;
// Output must be "123"
}
{ | {
"domain": "codereview.stackexchange",
"id": 42793,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, c++14, type-safety",
"url": null
} |
c++, design-patterns, c++14, type-safety
// Output must be "123"
}
{
auto i1 = 123_nop1;
assert( i1 == 123 );
auto i2 = "ERROR"_nop2;
std::cout << i2 << std::endl;
// No output must be produced
}
{
// must compile
struct S {};
Nop_t< int, false > n;
S s;
n * 1 * n * n;
1 * n * 1;
n % 1 % n % n;
s % n % s % s ;
n += s += n;
n -= s -= n -= n;
n *= n;
n /= n;
sin( n );
n( 1, 2 );
n( s );
!n;
(void) (n==s<=n<s!=n>=n>s);
n && n && s || n &= 2;
n = 5;
}
{
Nop_t< double, true > nf(0);
Nop_t< double, true > nd(0);
(void) sin( nf );
(void) sin( nd );
}
} | {
"domain": "codereview.stackexchange",
"id": 42793,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, c++14, type-safety",
"url": null
} |
c++, design-patterns, c++14, type-safety
My main questions are:
Does the use of this class really occurs no overhead? Did I oversee something?
Is the interface sensible?
Is the documentation ok? Can the use of the class be understood from the documentation?
Are the user defined literals correctly implemented? Do they also no incur any overhead?
I found nothing like this class in the internet, but the idea is not very exotic. So I wonder: Is this a bad approach?
Is there a more easy approach for the definition of Nop_t which becomes a typedef for a type or a class than using the helper function make_nop
Answer: I would like to get the elephant out of the room first by saying that the code doesn't really solve the problems it wants to solve. My post will compare the code in the question with the following code:
#ifdef NDEBUG
#define DEBUG_ONLY_STATEMENTS(statements)
#else
#define DEBUG_ONLY_STATEMENTS(statements) (statements)
#endif | {
"domain": "codereview.stackexchange",
"id": 42793,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, c++14, type-safety",
"url": null
} |
c++, design-patterns, c++14, type-safety
Clarity of intent
I am not well versed in preprocessor metaprogramming so I will spend quite a bit of time understanding what the code in question does. If I am searching for a bug, it might lead me to assume that the bug is somewhere in the preprocessor generated code. My IDE shows a replacement, fortunately, but I believe it is still far from just either including the statements or just removing them completely.
Integration with tools
The piece of usage code shown in question will not be greyed out in release mode, hence it will lead to assumption that it is somehow important either way. Combined with previous point, this leads to a serious problem. With the NDEBUG version, the code will be greyed out and combined with its simplicity it will be clear that the code is really debug only.
Not so lightweight
May be it will not have any significant events at runtime, it might cause generation of extra symbols in the resulting executable. I am not familiar with ABI, but there might some other very subtle effects.
Unclear purpose
To debug a program I usually pull out gdb and try to come up with some fancy python to solve my problem. In the worst case I usually branch out and cherry pick last commits onto my branch. I rarely leave the debug code there (when left out it is usually commented out).
Instrumentation on the other hand is usually present regardless of compilation mode. It usually contains performance metrics along with some logging.
I'm not saying that macros are evil in all of the cases and I believe knowing how to use them is important, but this particular usage is not something I would put in my codebase.
Besides, the goal was to solve this problem: But that clobbers up my source code with preprocessor directives.. My impression was that the code in question made it worse, in a sense that there was more preprocessor involved. | {
"domain": "codereview.stackexchange",
"id": 42793,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, design-patterns, c++14, type-safety",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
Title: C++ basic bank money class
Question: I am trying to create a basic money class that fits into a small console banking application I am making.
Money.h
#pragma once
#include <string>
class Money {
private:
long pounds;
int pence;
public:
Money();
// Overloaded constructors
explicit Money(long pounds);
Money(long pounds, int pence);
/* Overload operators to allow easier arithmetic of money objects, we will
not overload * or / as it does not make logical sense for money to be multiplied
or divided.
*/
Money operator+(const Money& moneyRhs) const;
Money operator-(const Money& moneyRhs) const;
friend std::ostream& operator<<(std::ostream& os, const Money& money);
// toString method to print out money object
std::string toString() const;
// Getters
long getPounds() const;
int getPence() const;
};
Money.cpp
#include "Money.h"
#include <iomanip>
Money::Money(): pounds(0), pence(0) {}
Money::Money(const long pounds): pounds(pounds), pence(0) {}
Money::Money(const long pounds, const int pence): pounds(pounds), pence(pence) {}
Money Money::operator+(const Money& moneyRhs) const {
// Convert all money to pence then do addition
const long poundsInPence = (pounds + moneyRhs.pounds) * 100;
const int totalPence = pence + moneyRhs.pence;
const long allPence = poundsInPence + totalPence;
const Money m3 = Money(allPence / 100, allPence % 100);
return m3;
}
Money Money::operator-(const Money& moneyRhs) const {
// Convert all money to pence then do subtraction
const long poundsInPence = (pounds - moneyRhs.pounds) * 100;
const int totalPence = pence - moneyRhs.pence;
const long allPence = poundsInPence + totalPence;
const Money m3 = Money(allPence / 100, allPence % 100);
return m3;
}
std::string Money::toString() const {
std::string strMoneyFormat; | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
std::string Money::toString() const {
std::string strMoneyFormat;
// Check so see if the pence value is 1 digit, if so we need to add a trailing 0 for output
// e.g £150.5 becomes £150.05
if((getPence() > 0 ? static_cast<int>(log10(static_cast<double>(getPence()))) + 1 : 1) < 2) {
strMoneyFormat = std::to_string(getPounds()) + "." + "0" + std::to_string(getPence());
}
else {
strMoneyFormat = std::to_string(getPounds()) + "." + std::to_string(getPence());
}
return strMoneyFormat;
}
std::ostream& operator<<(std::ostream& os, const Money& money) {
os << money.toString();
return os;
}
long Money::getPounds() const {
return pounds;
}
int Money::getPence() const {
return pence;
}
I'm relatively new to C++ still and want to know what I could improve in this code, especially what should I do about the + and / operator as I know when you overload arithmetic operators you should try to overload all, however you cant really dvided and multiply money. Any other tips would be appreciated. | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
Answer: Store Money as Fixed-Point
Monetary quantities are the classic example of something that might have fractional values, but you do not want to represent as a floating-point number, because you need exact arithmetic, not fast approximations.
At the same time, it’s a good idea to store at least one extra digit of precision, so that fractions of a penny will round and add up correctly.
You also definitely want to store this in a single integral value. Otherwise, you’ll constantly need to be checking whether your pence overflowed or underflowed. This integral type needs to be more than 32 bits long, so it can hold numbers in the billions and trillions, and to be signed. So, use long long int to hold the quantity
It’s a good exercise in how to write a class that encapsulates an opaque internal representation. In my tests, I used mills.
Mind Your Signs
Does Money( -12, 50 ) represent £-12.50 or £-11.50? Are your member functions consistent about this?
This is another problem that a fixed-point representation will solve.
Declare Default Copy Constructor and Assignment
You should ignore what I said here before; it was a bad explanation. (I’m grateful to Sebastian Redl for pointing out my error.) Here’s what’s actually going on. The compiler will create a default copy constructor and = operator for each class. In many cases, you will want to write one of your own, instead of using the defaults. For example, a move might be more efficient than a copy, and declaring a move constructor would replace the default copy constructor from being created. You might want copying and assignment to be private. You might have some non-trivial initialization to do.
None of these apply here; what you wrote will work. I think it’s good practice to declare these implicit functions as part of the interface and remove all ambiguity about them. Otherwise, some other code could make the compiler delete one of them. | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
The Rule of Three holds that, if your class is complicated that it needs an explicit copy constructor, assignment or destructor, it should have all three. If it’s managing any resources that can’t be trivially copied, the assignment operator also needs to copy them, and usually they can’t be trivially deleted either. This doesn’t really apply to the default constructors, but, because the rule is so widely recommended, I normally declare all three, even if it’s as default or delete. (There is also a Rule of Five, which says that, if you need either a move constructor or move assignment, you should declare both of those two, plus the other three, which they would otherwise replace. Here, we don’t need them.)
Use the Standard Library’s Formatting
With <iomanip> you can set the fixed and precision specifiers to make all quantities display exactly two digits after the decimal point.
Edit: Since long double conversion on some platforms (including MSVC) could improperly round off the lower digits. I wrote a new version that uses the <iomanip> manipulators
Check for Errors
If your library is ever managing trillions and trillions of dollars, it should definitely be checking for out-of-range errors!
A good way to do this, especially in constructors, is to throw exceptions from <stdexcept>, such as invalid_argument, overflow_error and underflow_error.
This is trickier than it sounds, because signed overflow or underflow is undefined behavior. The instructions on modern CPUs will wrap around, but compiler writers feel this gives them permission to break your error-checking code. What you actually need to do is find the difference between the maximum/minimum representable value, and one operand, then compare that to the other operand to see if you have room to add or subtract it.
Name Your Constants When Possible | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
Name Your Constants When Possible
You should prefer defining constants such as Money::pence_per_GBP to constants such as 100. This makes it much easier to change the type, easier to understand why you are using the constants you do and whether they are correct, and harder to make typos.
And besides, the number of pence in a pound has changed before.
These should be either static constexpr class members, or declared in the module that uses them.
Edit: Contrary to what I said before, static constexpr data members do not need to be defined outside the class declaration any longer, and doing so was deprecated in C++17. I’ve deleted that part of the code.
Declare Your Functions constexpr and noexcept where Appropriate
This helps optimize, and also allows them to be used to initialize compile-time constant expressions.
Don’t Have More Friends than You Need
If the stream output operator calls the public string conversion function, it doesn’t need to be a friend of the class. That allows it to breach encapsulation and access non-public members.
Speaking of which:
Follow Standard Naming Conventions
I like camelCase, but the STL uses snake_case consistently. In particular, the STL classes that convert to string call that function .to_string(), not .toString(), and several templates duck-type to the former.
CapitalizedCamelCase class names (also called PascalCase) are widely-used, though, so that’s fine.
Optionally: What Other Functions Make Sense
You have a stream output operator << but no stream input operator >>. There’s no += or -=. You have a comment that multiplication and division wouldn’t make sense, but what about scalar multiplication and division, such as full_price * discounted_rate? What about a negation operator, such as borrower_liability = -loan_amount;? What about comparisons, like income >= expenses?
Consider User-Defined Suffixes
I went ahead and put two of these in for fun, _L for monetary values in pounds and _p for monetary values in pence. | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
If these might clash with someone else’s _L or _p, a good solution is to put their declarations in a namespace, like the STL does for string literals. This way, it doesn’t overload _s for either strings or seconds unless I add the line:
using namespace std::literals::string_literals; | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
Putting it All Together
#include <iostream>
#include <limits>
#include <string>
class Money {
private:
/* “The mill is a unit of currency, used in several countries as one-
* thousandth of the main unit.” (In this case, the GBP.) This is
* at least 64 bits wide, to be able to represent amounts larger than
* £2,147,483.64. It has one extra digit of precision, to ensure
* proper rounding.
*
* If a long double has fewer than 63 mantissa bits, this implementation
* might incorrectly round off extremely large credits or debits. You
* might want to flag this and throw a std::range_error exception.
*/
long long mills;
/* Compile-time constants. I originally had definitions of these in
* namespace scope as well, but that is no longer necessary and is now
* deprecated.
*/
static constexpr auto money_max =
std::numeric_limits<decltype(mills)>::max();
static constexpr auto money_min =
std::numeric_limits<decltype(mills)>::min();
static constexpr int mills_per_GBP = 1000;
static constexpr int mills_per_penny = 10;
/* Used internally to bypass round-trip conversion. The dummy parameter is
* there only to distinguish this constructor from the one that takes a
* value in pounds.
*/
struct dummy_t {};
explicit constexpr Money (long long source, dummy_t) noexcept; | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
public:
// Use the trivial default constructor instead of a custom one.
constexpr Money() noexcept = default;
/* Allow either Money(12.34) or Money(12,34). Note that Money(12.345)
* is legal, but Money(12,345) should throw a std::invalid_argument
* exception.
*/
constexpr Money(long double pounds);
constexpr Money( long long int pounds, unsigned pence );
// The implicit members would have sufficed.
constexpr Money(const Money&) noexcept = default;
Money& operator= (const Money&) noexcept = default;
~Money() = default;
/* If this class can be a base class, it would need a virtual destructor.
* Otherwise, trivial destruction suffices.
*/
/* These are constexpr, but not noexcept, because they could throw a
* std::overflow_error or std::underflow_error exception.
*/
constexpr Money operator+(const Money&) const;
constexpr Money operator-(const Money&) const;
// This should be named in snake_case, not camelCase:
std::string to_string() const;
/* Returns the quantity denominated in pounds, rounded to the nearest
* penny. You might throw an exception rather than return an incorrectly-
* rounded result.
*/
constexpr long double to_pounds() const noexcept;
/* Returns only the part of the currency string beginning with the
* point. E.g., for £12.34, returns 0.34, and for £-56.78, returns 0.78.
*/
constexpr double pence() const noexcept;
static constexpr int pence_per_GBP = 100;
};
// This only needs to be a friend if it uses an interface that isn’t public:
std::ostream& operator<< ( std::ostream&, Money );
// Unimplemented:
std::istream& operator>> ( std::istream&, Money& );
// User-defined literal for money in pounds, e.g. 12.34_L.
constexpr Money operator""_L (long double);
// User-defined literal for money in pence, e.g. 56_p.
constexpr Money operator""_p (long double); | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
#include <cmath>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#include <string>
using namespace std::literals::string_literals;
static const std::string invalid_arg_msg = "Monetary quantity out of range.",
overflow_msg = "Monetary overflow.",
underflow_msg = "Monetary underflow.";
constexpr Money::Money(const long double pounds)
/* Converts the quantity in GBP to the internal representation, or throws a
* std::invalid_argument exception. Rounds to the nearest mill.
*/
{
/* Refactored so that a NaN value will fall through this test and correctly
* raise an exception, rather than, as before, be spuriously converted.
* On an implementation where the precision of long double is less than that
* of long long int, such as MSVC, the bounds tests below could spuriously
* reject some values between the bounds and the next representable value
* closer to zero, but it will only convert values that are in range.
*/
if ( mills_per_GBP * pounds < static_cast<long double>(money_max) &&
mills_per_GBP * pounds > static_cast<long double>(money_min) ) {
// We unfortunately cannot use llroundl in a constexpr function.
mills = static_cast<decltype(mills)>( mills_per_GBP * pounds );
} else {
throw std::invalid_argument(invalid_arg_msg);
}
}
constexpr Money::Money( const long long pounds, const unsigned pence )
/* Converts the quantity in pounds and pence to the internal representation,
* or throws a std::invalid_argument exception.
*
* For example, Money(-1234,56) represents £-1234.56.
*/
{
if ( pounds > money_max / mills_per_GBP ) {
throw std::invalid_argument(invalid_arg_msg);
}
if ( pence >= pence_per_GBP ) {
throw std::invalid_argument(invalid_arg_msg);
} | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
if ( pence >= pence_per_GBP ) {
throw std::invalid_argument(invalid_arg_msg);
}
const long long base = mills_per_GBP * pounds;
const long long change = mills_per_penny *
( (pounds >= 0) ? pence : -(long long)pence );
if ( base > 0 && money_max - base < change ) {
throw std::invalid_argument(invalid_arg_msg);
}
if ( base < 0 && money_min - base > change ) {
throw std::invalid_argument(invalid_arg_msg);
}
mills = base + change;
}
constexpr Money::Money ( const long long source,
[[maybe_unused]] Money::dummy_t dummy // Only to disambiguate.
) noexcept
: mills(source)
/* Used internally to bypass unnecessary conversions and range-checking.
*/
{}
constexpr Money Money::operator+(const Money& other) const
/* Adds this and other, checking for overflow and underflow. We cannot
* portably rely on signed integer addition to wrap around, as signed
* overflow and underflow are undefined behavior.
*/
{
if ( mills > 0 && money_max - mills < other.mills ) {
throw std::overflow_error(overflow_msg);
}
if ( mills < 0 && money_min - mills > other.mills ) {
throw std::underflow_error(underflow_msg);
}
return Money( mills+other.mills, dummy_t() );
}
constexpr Money Money::operator-(const Money& other) const
/* Subtracts other from this, checking for overflow and underflow.
*/
{
if ( mills > 0 && money_max - mills < -other.mills ) {
throw std::overflow_error(overflow_msg);
}
if ( mills < 0 && money_min - mills > -other.mills ) {
throw std::underflow_error(underflow_msg);
}
return Money( mills-other.mills, dummy_t() );
} | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
std::string Money::to_string() const
/* In the future, you may be able to use std::format instead. You might also
* use snprintf.
*
* Changed to do integer math rather than a FP conversion that might display a
* spuriously-rounded value.
*/
{
std::stringstream to_return;
const auto pounds = mills/mills_per_GBP;
const auto pence = (mills >= 0) ? ( mills % mills_per_GBP )/mills_per_penny
: -( mills % mills_per_GBP )/mills_per_penny;
to_return << "£" << pounds << '.'
<< std::setw(2) << std::setfill('0') << std::right
<< pence;
return to_return.str();
}
constexpr long double Money::to_pounds() const noexcept
{
return static_cast<long double>(mills) / mills_per_GBP;
}
constexpr double Money::pence() const noexcept
{
const double remainder = (double)(mills % mills_per_GBP);
return (remainder >= 0) ? remainder/mills_per_GBP
: -remainder/mills_per_GBP;
}
std::ostream& operator<< ( std::ostream& os, const Money x )
{
return os << x.to_string();
}
// User-defined literal for money in pounds, e.g. 12.34_L.
constexpr Money operator""_L (const long double pounds)
{
return Money(pounds);
}
// User-defined literal for money in pence, e.g. 56_p.
constexpr Money operator""_p (const long double pence)
{
return Money(pence/Money::pence_per_GBP);
}
#include <cstdlib> // for EXIT_SUCCESS
#include <iostream>
#include <limits>
#include <stdexcept>
using std::cout; | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
using std::cout;
int main()
{
constexpr Money one_million_GBP(1e6),
minus_twelve_forty_GBP( -12, 40 ),
lotta_money = 4.62e15_L;
try {
const Money invalid_value = Money(1.0e16L);
cout << "Stored unexpectedly large value " << invalid_value << ".\n";
} catch (const std::invalid_argument&) {
cout << "Properly caught a value too high.\n";
}
try {
const Money invalid_value = Money(-1.0e16L);
cout << "Stored unexpectedly small value " << invalid_value << ".\n";
} catch (const std::invalid_argument&) {
cout << "Properly caught a value too low.\n";
}
try {
const Money invalid_value = lotta_money + lotta_money;
cout << "Added unexpectedly large quantity " << invalid_value << ".\n";
} catch (const std::overflow_error&) {
cout << "Properly caught arithmetic overflow.\n";
}
try {
const Money invalid_value = Money() - lotta_money - lotta_money;
cout << "Added unexpectedly large liabilty " << invalid_value << ".\n";
} catch (const std::underflow_error&) {
cout << "Properly caught arithmetic underflow.\n";
}
try {
const Money invalid_value =
Money(std::numeric_limits<long double>::quiet_NaN());
cout << "Improperly interpreted a NaN value as " << invalid_value << ".\n";
} catch (const std::invalid_argument&) {
cout << "Properly caught initialization of money from NaN.\n";
}
// Expected output: £0.10, £1000000.00, £-12.40, £999987.60 and £1000012.40.
cout << 10.1_p << ", "
<< one_million_GBP << ", "
<< minus_twelve_forty_GBP << ", "
<< (one_million_GBP + minus_twelve_forty_GBP) << " and "
<< (one_million_GBP - minus_twelve_forty_GBP) << ".\n";
cout << one_million_GBP.to_pounds() << " pounds and "
<< Money::pence_per_GBP*minus_twelve_forty_GBP.pence() << " pence.\n";
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
c++, algorithm, object-oriented, c++20, number-systems
Update: I decided to take my own advice about declaring functions constexpr where possible, and made all the constructors constexpr. Now the declaration,
constexpr Money one_million_GBP(1e6),
minus_twelve_forty_GBP( -12, 40 ),
lotta_money = 4.62e15_L;
compiles (on clang++13 with std=c++20 -O3 -march=x86-64-v4) to:
mov qword ptr [rsp + 72], 1000000000
mov qword ptr [rsp + 64], -12400
movabs rax, 4620000000000000000
It could be a huge boost in performance if your Money objects can be optimized into compile-time integer constants.
There’s another way to optimize this class, and other tiny classes, that I did not do. Since it’s trivially-copyable and so small that an object can fit in a register, there is no reason to pass it by const reference. If you pass it by value instead, some variables that might otherwise need to be spilled onto the stack to take their address can instead stay in registers.
This code outputs the non-ASCII pound sign. This should work on modern OSes, but if you’re having some difficulty on an older version of Windows, you might want to give CL.EXE the flag /utf-8 and set chcp 65001 in your console window.
One word of explanation about something that might not be obvious: because I made the public constructors more complicated, I wanted to add a more lightweight private constructor that set the internal field directly. Since the compiler would otherwise be unable to tell when I was calling the public or private constructor, I created a nullary Money::dummy_t type solely to make sure the type signature of the private constructor was unique. This solution was a bit ungainly, but it’s not part of the public interface anyway. | {
"domain": "codereview.stackexchange",
"id": 42794,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, object-oriented, c++20, number-systems",
"url": null
} |
python
Title: Decrease the number of lines of code needed to create a list and verify one value
Question: What can I do to reduce the number of steps until I get to the final code result?
Is it possible or is this the way with the least number of lines of code?
import requests
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
}
url = f'https://api.sofascore.com/api/v1/event/9567795/graph'
response = requests.get(url, headers=headers).json()
goal_minute = 88
graphs = response['graphPoints']
graph_minutes = graphs[-5:]
minutes_list = []
for minute in graph_minutes:
minutes_list.append(minute["minute"])
if goal_minute in minutes_list:
print('Ok')
Answer: Lines of code is typically not a useful metric. Many other characteristics are more
important: correctness, robustness, readability, simplicity, and so forth. But even if
we focus narrowly on code size, number of lines if usually the wrong way to
think about it. Less code can be beneficial sometimes: if done well, for
example, less code is easier to read than more code. But it's quite possible to
have both more lines and less code (if the lines are short). Many short lines,
especially if well organized into meaningful groups prefaced by substantive
comments, are often easier to read and understand than a small number of long,
dense lines of code.
You might need more code. HTTP requests can fail. You should probably be
writing code to handle that scenario.
try:
response = requests.get(url, headers=headers).json()
except Exception as e:
# Adjust after you decide how you want to respond to failure.
print(e)
quit() | {
"domain": "codereview.stackexchange",
"id": 42795,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
The primary opportunity for brevity. You can collect the needed minutes
in less code by dropping intermediate variables and using a comprehension. Although it could be written in a single
line, why not help your reader a bit by laying it out nicely? Whitespace
imposes no tax on the reader: be generous with it.
minutes = [
d['minute']
for d in response['graphPoints'][-5:]
] | {
"domain": "codereview.stackexchange",
"id": 42795,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
c, strings, parsing, http
Title: Better ways to parse the Content-Length from the HTTP header
Question: I have a buffer that contains the HTTP header, which contains the Content-Length string indicating how big the file is that needs to be downloaded.
I am looking to write a generic function for parsing a substring and eventually a value that needs to be converted to an int from a string.
The following approach seems to work but seems more like a "brute-force" approach. Any better ideas?
void parse(char *src, char *dst, const char *firstKey, const char *secKey)
{
char *start = strstr(src, firstKey) + 2;
char *end = strstr(start, secKey);
size_t bytes = end - start;
memcpy(dst, start, bytes);
}
int main()
{
char httpHeader[] = {72, 84, 84, 80, 47, 49, 46, 49, 32, 50, 48, 49, 32, 67, 114, 101, 97, 116, 101, 100, 13, 10, 68, 97, 116, 101, 58, 32, 77, 111, 110, 44, 32, 49, 55, 32, 74, 97, 110, 32, 50, 48, 50, 50, 32, 50, 49, 58, 53, 56, 58, 52, 51, 32, 71, 77, 84, 13, 10, 83, 101, 114, 118, 101, 114, 58, 32, 65, 112, 97, 99, 104, 101, 47, 50, 46, 52, 46, 50, 57, 32, 40, 85, 98, 117, 110, 116, 117, 41, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 76, 101, 110, 103, 116, 104, 58, 32, 48, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 84, 121, 112, 101, 58, 32, 116, 101, 120, 116, 47, 104, 116, 109, 108, 13, 10, 13, 10};
/*
what httpHeader above stores:
HTTP/1.1 201 Created
Date: Mon, 17 Jan 2022 21:58:43 GMT
Server: Apache/2.4.29 (Ubuntu)
Content-Length: 0
Content-Type: text/html
*/
char dst[100] = {0};
parse(httpHeader, dst, "Content-Length", "\n"); // dst => Content-Length: 0
char dst1[100] = {0};
parse(dst, dst1, ":", "\r");
// get the int value
int contentLenVal = atoi(dst1);
printf ("dst: %s\ndst1: %s\n\nContent value: %d\n", dst, dst1, contentLenVal);
}
Answer:
Any better ideas? | {
"domain": "codereview.stackexchange",
"id": 42796,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings, parsing, http",
"url": null
} |
c, strings, parsing, http
}
Answer:
Any better ideas?
Consume the buffer
Rather than leave the buffer "as-is" while parsing, adjust its start and end while parsing.
char *s = httpHeader;
s = parse(s, "Content-Length", "\n");
if (s == NULL) Handle_Error();
s = parse(s, ":", "\r");
if (s == NULL) Handle_Error();
long contentLenVal = strtol(s, ...); // See below for details.
Avoid bugs.
Avoid going off the end
Below may + 2 past the end of the string. Better to walk carefully.
// char *start = strstr(src, firstKey) + 2;
char *start = strstr(src, firstKey);
if (start == NULL || start[0] == '\0' || start[1] == '\0') {
Handle_Error();
}
start += 2;
....
if (end == NULL) {
Handle_Error();
}
IAC, the + 2 is strange. I'd expect:
char *start = strstr(src, firstKey);
if (start == NULL) {
Handle_Error();
}
start += strlen(firstKey);
dst lacks a certain null character
Presently code relies on the caller to pre-fill with '\0. Better to pass in buffer size and append a '\0' explicitly in the function.
// void parse(char *src, char *dst, ...
void parse(const char *src, size_t sz, char *dst, ...
...
ptrdiff_t diff = end - start;
if (diff > sz) {
Handle_Error();
} else {
size_t bytes = (size_t) diff;
memcpy(dst, start, bytes);
dest[bytes] = '\0';
}
Use strtol()
Robust code looks for errors,
// int contentLenVal = atoi(dst1);
char *endptr;
errno = 0;
long contentLenVal = strtol(dst1, &endptr, 10);
if (dst1 == endptr || errno || contentLenVal < LEN_MIN || contentLenVal > LEN_MAX) {
Handle_Error();
}
Minor: Use const
// void parse(char *src, char *dst, ...
void parse(const char *src, char *dst, ... | {
"domain": "codereview.stackexchange",
"id": 42796,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings, parsing, http",
"url": null
} |
c, strings, parsing, http
Minor: Use const
// void parse(char *src, char *dst, ...
void parse(const char *src, char *dst, ...
If code is to consume src, leave as is.
Minor: Wrap
// char httpHeader[] = {72, 84, 84, 80, 47, 49, 46, 49, 32, 50, 48, 49, 32, 67, 114, 101, 97, 116, 101, 100, 13, 10, 68, 97, 116, 101, 58, 32, 77, 111, 110, 44, 32, 49, 55, 32, 74, 97, 110, 32, 50, 48, 50, 50, 32, 50, 49, 58, 53, 56, 58, 52, 51, 32, 71, 77, 84, 13, 10, 83, 101, 114, 118, 101, 114, 58, 32, 65, 112, 97, 99, 104, 101, 47, 50, 46, 52, 46, 50, 57, 32, 40, 85, 98, 117, 110, 116, 117, 41, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 76, 101, 110, 103, 116, 104, 58, 32, 48, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 84, 121, 112, 101, 58, 32, 116, 101, 120, 116, 47, 104, 116, 109, 108, 13, 10, 13, 10};
Versus
char httpHeader[] = {72, 84, 84, 80, 47, 49, 46, 49, 32, 50, 48, 49, 32, 67,
114, 101, 97, 116, 101, 100, 13, 10, 68, 97, 116, 101, 58, 32, 77, 111, 110,
44, 32, 49, 55, 32, 74, 97, 110, 32, 50, 48, 50, 50, 32, 50, 49, 58, 53, 56,
58, 52, 51, 32, 71, 77, 84, 13, 10, 83, 101, 114, 118, 101, 114, 58, 32, 65,
112, 97, 99, 104, 101, 47, 50, 46, 52, 46, 50, 57, 32, 40, 85, 98, 117, 110,
116, 117, 41, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 76, 101, 110,
103, 116, 104, 58, 32, 48, 13, 10, 67, 111, 110, 116, 101, 110, 116, 45, 84,
121, 112, 101, 58, 32, 116, 101, 120, 116, 47, 104, 116, 109, 108, 13, 10,
13, 10};
Tip: Use an auto-formatter. | {
"domain": "codereview.stackexchange",
"id": 42796,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, strings, parsing, http",
"url": null
} |
beginner, makefile
Title: Makefile that places object files into an alternate directory (bin/)
Question: I'm trying to learn how to use makefiles, and this is my attempt at making a makefile that compiles source files in a source directory (src/) into object files that are created in a bin directory.
##########################################
# Editable options #
##########################################
# Compiler options
CC=g++
CFLAGS=-c -Wall
LDFLAGS=
EXECUTABLE_NAME=testes
# Folders
SRC=src
BIN=bin
OBJ=$(BIN)/obj
# Files
SOURCE_FILES=\
main.cpp \
test.cpp
##########################################
# Don't touch anything below this #
##########################################
OBJECT_FILES=$(addprefix $(OBJ)/, $(SOURCE_FILES:.cpp=.o))
build: create_directories create_executable
@echo "Build successful!"
create_executable: create_objects
@$(CC) $(LDFLAGS) $(OBJECT_FILES) -o $(BIN)/$(EXECUTABLE_NAME)
@echo "Created executable."
create_objects: $(SOURCE_FILES)
@echo "Created objects."
create_directories:
@mkdir -p $(OBJ)
%.cpp:
@echo "Compiling "$@
@$(CC) $(LDFLAGS) -c $(SRC)/$@ -o $(OBJ)/$(patsubst %.cpp,%.o,$@)
clean:
@rm -r -f $(BIN)
This makefile works, I just want to make sure I'm doing everything correctly. Any changes you guys would suggest?
Answer: You are not using the make system properly. As a result, it will always relink the executable, even when everything is already up to date. On the other hand, it might fail to recompile some source files into object files.
When you run make…
It will try to create the build target. No file named build exists, so…
It will try to create the prerequisites of build, namely create_directories and create_executable, neither of which are names of existing files.
In an attempt to create a file called create_directories, it runs mkdir -p $(OBJ).
For create_executable, it needs to rebuild create_objects. | {
"domain": "codereview.stackexchange",
"id": 42797,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, makefile",
"url": null
} |
beginner, makefile
For create_objects, it just verifies that all of the source files are present.
For any of the $(SOURCE_FILES) that is missing, it "creates" it using the %.cpp: rule, which actually tries to compile the missing .cpp into a .o.
Once all of the $(SOURCE_FILES) are present, it echoes "Created objects.". That's a false claim due to the error above.
Having thus falsely satisfied the prerequisites for create_executable, it proceeds to attempt to link the executable, even if any of the $(OBJECT_FILES) is missing.
The main remedy is to specify real targets and real dependencies, rather than phony labels like create_executable.
Here is how I would write it. Other than the major problems cited above, I have also noted many minor issues in the comments.
#########################################################
# Replacing everything that you told me not to touch... #
#########################################################
EXECUTABLE_FILES = $(EXECUTABLE_NAME:%=$(BIN)/%)
OBJECT_FILES = $(SOURCE_FILES:%.cpp=$(OBJ)/%.o)
# ^^^ A more succinct expression for $(OBJECT_FILES), using
# http://www.gnu.org/software/make/manual/make.html#Substitution-Refs
build: $(EXECUTABLE_FILES)
clean:
rm -r -f $(BIN)
@# ^^^ I don't recommend suppressing the echoing of the command using @
# http://www.gnu.org/software/make/manual/make.html#Phony-Targets
.PHONY: build clean
$(EXECUTABLE_FILES): $(OBJECT_FILES)
@$(CC) $(LDFLAGS) -o $@ $^
@# ^^^ http://www.gnu.org/software/make/manual/make.html#Automatic-Variables
@echo "Build successful!"
# http://www.gnu.org/software/make/manual/make.html#Static-Pattern
$(OBJECT_FILES): $(OBJ)/%.o: %.cpp
@echo Compiling $<
@# ^^^ Your terminology is weird: you "compile a .cpp file" to create a .o file.
@mkdir -p $(@D)
@# ^^^ http://www.gnu.org/software/make/manual/make.html#index-_0024_0028_0040D_0029
@$(CC) $(CFLAGS) -o $@ $<
@# ^^^ Use $(CFLAGS), not $(LDFLAGS), when compiling. | {
"domain": "codereview.stackexchange",
"id": 42797,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, makefile",
"url": null
} |
c#, excel, winforms, ms-word
Title: User interface for a simple tool that generates Word documents from Excel data
Question: This question provides the code behind the dialogs in the C# refactoring question. I'd like a review of this code as well. I'm not currently using databinding anywhere, and there is really only one place that it might help which is in the add or edit tenant form. This question is separate from the other question because there is too much code to present in one question.
Visual Studio generated code is not included in this question.
Features
Generate MS Word documents from the data in the Excel spreadsheet for use as directories by mailboxes.
Add or Edit a tenant to the complex.
Delete a tenant from the complex.
Set preferences for when to save or print a file. Where to store saved Word documents. Where to find the Excel spreadsheet file.
Save any current changes.
The data is saved automatically when the program exits.
If the Excel file is open in another application it warns the user and will not start. If the user open it in Excel after the program starts it warns them that the changes can't be saved until the Excel file is closed.
RentRosterApp.cs
This is the main form started by the Program.cs module, consider it a control panel, it only contains buttons that open other dialogs. It does however contain some program logic for global initialization.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TenantRosterAutomation
{
public partial class RentRosterApp : Form
{
private bool globalsInitialized;
public RentRosterApp()
{
globalsInitialized = Globals.InitializeAllModels();
InitializeComponent();
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void RentRosterApp_Load(object sender, EventArgs e)
{
RR_Quit_BTN.BackColor = Color.Red;
if (!globalsInitialized)
{
PrintMailboxLists_Button.Enabled = false;
AddNewResident_Button.Enabled = false;
DeleteRenter_Button.Enabled = false;
using (EditPreferencesDlg preferences_dlg = new EditPreferencesDlg())
{
if (preferences_dlg.ShowDialog() == DialogResult.OK)
{
PrintMailboxLists_Button.Enabled = true;
AddNewResident_Button.Enabled = true;
DeleteRenter_Button.Enabled = true;
}
}
}
}
private void PrintMailboxLists_Button_Click(object sender, EventArgs e)
{
PrintMailboxListsDlg printMailboxLists_dialog = new PrintMailboxListsDlg();
printMailboxLists_dialog.Show();
}
private void AddNewResident_Button_Click(object sender, EventArgs e)
{
ApartmentNumberVerifier verifier_Form = new ApartmentNumberVerifier();
verifier_Form.NextAction = ApartmentNumberVerifier.NextActionEnum.ADD;
verifier_Form.Show();
}
private void DeleteRenter_Button_Click(object sender, EventArgs e)
{
ApartmentNumberVerifier verifier_Form = new ApartmentNumberVerifier();
verifier_Form.NextAction = ApartmentNumberVerifier.NextActionEnum.DELETE;
verifier_Form.Show();
}
private void EditPreferences_BTN_Click(object sender, EventArgs e)
{
EditPreferencesDlg preferences_dlg = new EditPreferencesDlg();
preferences_dlg.Show();
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void RR_Quit_BTN_Click(object sender, EventArgs e)
{
try
{
Globals.Save();
Globals.ReleaseAllModels();
Close();
}
catch (AlreadyOpenInExcelException ao)
{
MessageBox.Show(ao.Message);
}
}
private void RR_SAVEEDITS_BTN_Click(object sender, EventArgs e)
{
try
{
Globals.SaveTenantData();
}
catch (AlreadyOpenInExcelException ao)
{
MessageBox.Show(ao.Message);
}
}
private void RentRosterApp_FormClosing(object sender, FormClosingEventArgs e)
{
// Save all changes before quiting.
Globals.Save();
Globals.ReleaseAllModels();
}
}
}
EditPreferencesDlg.cs
This form allows the users to edit their preferences, it is called with a button on the main control panel, but if the preferences have never been created before then the control panel opens it automatically. There might be a fairly strong coupling between this class and the UserPreferences class.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace TenantRosterAutomation
{
public partial class EditPreferencesDlg : Form
{
private UserPreferences localPreferences;
public EditPreferencesDlg()
{
localPreferences = new UserPreferences();
localPreferences.CopyValues(Globals.Preferences, true);
InitializeComponent();
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void EditPreferencesDlg_Load(object sender, EventArgs e)
{
EP_Cancel_BTN.BackColor = Color.Red;
EP_SavePreferences_BTN.BackColor = Color.Green;
EP_DefaultFileFolder_TB.Text = localPreferences.DefaultSaveDirectory;
EP_RentRosterLocation_TB.Text = localPreferences.ExcelWorkBookFullFileSpec;
EP_SheetName_TB.Text = localPreferences.ExcelWorkSheetName;
switch (localPreferences.PrintSaveOptions)
{
case PrintSavePreference.PrintSave.PrintAndSave:
EP_PrintAndSave_RB.Checked = true;
break;
case PrintSavePreference.PrintSave.SaveOnly:
EP_SavelOnly_RB.Checked = true;
break;
default:
EP_PrintOnly_RB.Checked = true;
break;
}
EP_SheetName_TB.Enabled = false;
EP_RentRosterSheetName_LISTBOX.Visible = false;
}
private void EP_PrintAndSave_RB_CheckedChanged(object sender, EventArgs e)
{
localPreferences.PrintSaveOptions = PrintSavePreference.PrintSave.PrintAndSave;
}
private void EP_SavelOnly_RB_CheckedChanged(object sender, EventArgs e)
{
localPreferences.PrintSaveOptions = PrintSavePreference.PrintSave.SaveOnly;
}
private void EP_PrintOnly_RB_CheckedChanged(object sender, EventArgs e)
{
localPreferences.PrintSaveOptions = PrintSavePreference.PrintSave.PrintOnly;
}
private void EP_DefaultFileFolder_TB_TextChanged(object sender, EventArgs e)
{
localPreferences.DefaultSaveDirectory = EP_DefaultFileFolder_TB.Text;
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void findDefaultFolderLocationExecute(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
EP_DefaultFileFolder_TB.Text = fbd.SelectedPath;
localPreferences.DefaultSaveDirectory = fbd.SelectedPath;
}
}
}
private void EP_DefaultFileFolder_TB_Click(object sender, EventArgs e)
{
findDefaultFolderLocationExecute(sender, e);
}
private void EP_BrowseFolderLocation_BTN_Click(object sender, EventArgs e)
{
findDefaultFolderLocationExecute(sender, e);
}
private void EP_RentRosterLocation_TB_TextChanged(object sender, EventArgs e)
{
localPreferences.ExcelWorkBookFullFileSpec = EP_RentRosterLocation_TB.Text;
}
private void findTenantRosterExcelFile(object sender, EventArgs e)
{
string tenantRosterFile = "";
OpenFileDialog FindTenantRoster = new OpenFileDialog();
FindTenantRoster.InitialDirectory = "c:\\";
FindTenantRoster.Filter = "Excel Files| *.xls; *.xlsx; *.xlsm";
if (FindTenantRoster.ShowDialog() == DialogResult.OK)
{
tenantRosterFile = FindTenantRoster.FileName;
EP_RentRosterLocation_TB.Text = tenantRosterFile;
localPreferences.ExcelWorkBookFullFileSpec = tenantRosterFile;
}
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void fillSheetSelectorListBox()
{
List<string> sheetNames = null;
if (!string.IsNullOrEmpty(localPreferences.ExcelWorkBookFullFileSpec))
{
ExcelFileData ExcelFile = new ExcelFileData(localPreferences.ExcelWorkBookFullFileSpec,
localPreferences.ExcelWorkSheetName);
sheetNames = ExcelFile.GetWorkSheetCollection();
}
if (sheetNames == null)
{
return;
}
EP_RentRosterSheetName_LISTBOX.DataSource = sheetNames;
EP_RentRosterSheetName_LISTBOX.Visible = true;
EP_SheetName_TB.Enabled = true;
}
private void EP_FindRenterRoster_BTN_Click(object sender, EventArgs e)
{
findTenantRosterExcelFile(sender, e);
fillSheetSelectorListBox();
}
private void EP_RentRosterLocation_TB_Click(object sender, EventArgs e)
{
findTenantRosterExcelFile(sender, e);
fillSheetSelectorListBox();
}
private void EP_RentRosterSheetName_LISTBOX_SelectedIndexChanged(object sender, EventArgs e)
{
localPreferences.ExcelWorkSheetName = EP_RentRosterSheetName_LISTBOX.SelectedItem.ToString();
EP_SheetName_TB.Text = localPreferences.ExcelWorkSheetName;
}
private void EP_SheetName_TB_Click(object sender, EventArgs e)
{
fillSheetSelectorListBox();
}
private void EP_SavePreferences_BTN_Click(object sender, EventArgs e)
{
// Make sure any previous edits to the tenant are saved
// then reset all the models.
Globals.Save();
Globals.ReInitizeAllModels(localPreferences);
Globals.SavePreferences();
DialogResult = DialogResult.OK;
Close();
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void EP_Cancel_Button_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
Close();
}
}
}
PrintMailboxListsDlg.cs
This form allows the user to print and or save word documents created from the excel data. It also allows the user to override some of their preferences on a case by case basis.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace TenantRosterAutomation
{
public partial class PrintMailboxListsDlg : Form
{
private PrintSavePreference.PrintSave printSave;
private bool addDateToFileName = false;
private bool addDateToTitle = false;
private string selectedBuildings;
private MSWordInterface wordInteropMethods;
public PrintMailboxListsDlg()
{
InitializeComponent();
wordInteropMethods = new MSWordInterface(Globals.Preferences);
}
private void PrintMailboxLists_Form_Load(object sender, EventArgs e)
{
List<string> buildings = Globals.Complex.BuildingAddressList;
foreach (string building in buildings)
{
SelectBuilding2Print_listBox.Items.Add(building);
}
SelectBuilding2Print_listBox.Items.Add("All Buildings");
if (Globals.Preferences.HavePreferenceData)
{
printSave = Globals.Preferences.PrintSaveOptions;
PrintSaveChange();
}
AddDateToFileName_CB.Checked = addDateToFileName;
AddDateUnderAddress_CB.Checked = addDateToTitle;
PML_SaveAndPrint_Button.Enabled = false;
}
private void AddDateToFileName_CB_CheckedChanged(object sender, EventArgs e)
{
addDateToFileName = !addDateToFileName;
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void AddDateUnderAddress_CB_CheckedChanged(object sender, EventArgs e)
{
addDateToTitle = !addDateToTitle;
}
private void PML_SaveAndPrint_Button_Click(object sender, EventArgs e)
{
if (String.Compare(selectedBuildings, "All Buildings") == 0)
{
List<int> StreetNumbers = Globals.Complex.StreetNumbers;
foreach (int streetNumber in StreetNumbers)
{
printAndOrSaveMailList(streetNumber);
}
}
else
{
string streetAddress = selectedBuildings.Substring(0, 5);
printAndOrSaveMailList(streetAddress);
}
Close();
}
private void printAndOrSaveMailList(string streetAddress)
{
int iStreetNumber = 0;
if (Int32.TryParse(streetAddress, out iStreetNumber))
{
printAndOrSaveMailList(iStreetNumber);
}
else
{
MessageBox.Show("Non Numeric string passed into PrintMailboxLists_Form::printAndOrSaveMailList().");
}
}
private void PML_PrintOnly_RB_CheckedChanged(object sender, EventArgs e)
{
printSave = PrintSavePreference.PrintSave.PrintOnly;
}
private void PML_SavelOnly_RB_CheckedChanged(object sender, EventArgs e)
{
printSave = PrintSavePreference.PrintSave.SaveOnly;
}
private void PML_PrintAndSave_RB_CheckedChanged(object sender, EventArgs e)
{
printSave = PrintSavePreference.PrintSave.PrintAndSave;
}
private void PrintSaveChange()
{
switch (printSave)
{
case PrintSavePreference.PrintSave.PrintAndSave:
PML_PrintAndSave_RB.Checked = true;
break; | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
case PrintSavePreference.PrintSave.SaveOnly:
PML_SavelOnly_RB.Checked = true;
break;
default:
PML_PrintOnly_RB.Checked = true;
break;
}
}
private void SelectBuilding2Print_listBox_SelectedIndexChanged(object sender, EventArgs e)
{
if (SelectBuilding2Print_listBox.SelectedItem != null)
{
selectedBuildings = SelectBuilding2Print_listBox.SelectedItem.ToString();
PML_SaveAndPrint_Button.Enabled = true;
}
}
private void printAndOrSaveMailList(int streetAddress)
{
bool save = ((printSave == PrintSavePreference.PrintSave.PrintAndSave) ? true :
(printSave == PrintSavePreference.PrintSave.SaveOnly) ? true : false);
bool print = ((printSave == PrintSavePreference.PrintSave.PrintAndSave) ? true :
(printSave == PrintSavePreference.PrintSave.PrintOnly) ? true : false);
string documentName = "MailboxList_" + streetAddress;
string statusMessage = (print && save) ? "Printing and Saving " :
(print) ? "Printing " : "Saving ";
statusMessage += "the mailbox list for " + streetAddress;
ReportCurrentStatusWindow psStatus = new ReportCurrentStatusWindow();
psStatus.MessageText = statusMessage;
psStatus.Show();
Building building = Globals.Complex.GetBuilding(streetAddress);
if (building != null)
{
MailboxData mailboxList = Globals.Complex.GetMailBoxList(building);
if (mailboxList != null)
{
wordInteropMethods.CreateMailistPrintAndOrSave(documentName,
mailboxList, addDateToFileName, addDateToTitle, save, print);
}
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
psStatus.Close();
}
}
}
ApartmentNumberVerifier.cs
This form presents only a textbox and a button. It is called prior to calling either the Add or Edit Tenant Dialog or the Delete Tenant Dialog. The purpose of the dialog is to find the correct tenant by apartment number.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TenantRosterAutomation
{
public partial class ApartmentNumberVerifier : Form
{
public enum NextActionEnum
{
ADD,
DELETE,
EDIT
}
public int ApartmentNumber;
public Tenant TenantData { get; private set; }
public NextActionEnum NextAction { get; set; }
public ApartmentNumberVerifier()
{
TenantData = null;
InitializeComponent();
}
private void APV_FindApartment_BTN_Click(object sender, EventArgs e)
{
VerifyApartmentNumber();
}
private void ANV_ApartmentNumber_TB_TextChanged(object sender, EventArgs e)
{
ANV_FindApartment_BTN.Enabled = true;
}
private void ApartmentNumberVerifier_Form_Load(object sender, EventArgs e)
{
ANV_FindApartment_BTN.Enabled = false;
ANV_ApartmentNumber_TB.KeyDown += new KeyEventHandler(ANV_ApartmentNumber_TB_KeyDown);
}
private void ANV_ApartmentNumber_TB_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
VerifyApartmentNumber();
}
}
private void ErrorActions(string errorMessage)
{
ANV_ApartmentNumber_TB.BackColor = Color.Yellow;
ANV_ApartmentNumber_TB.Text = "";
MessageBox.Show(errorMessage);
ActiveControl = ANV_ApartmentNumber_TB;
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private bool ReportErrors(int aptNumber, PropertyComplex.ApartmentNumberValid validApartmentId)
{
bool hasErrors = false;
string errorMessage = null;
switch (validApartmentId)
{
case PropertyComplex.ApartmentNumberValid.APARTMENT_NUMBER_NONNUMERIC:
errorMessage = "Please enter a number in the box.";
break;
case PropertyComplex.ApartmentNumberValid.APARTMENT_NUMBER_OUT_OF_RANGE:
int minAptNo = Globals.Complex.MinApartmentNumber;
int maxAptNo = Globals.Complex.MaxApartmentNumber;
errorMessage = "The apartment number: " + aptNumber.ToString() +
" is out of range[" + minAptNo.ToString() +
", " + maxAptNo.ToString() + "] please enter a valid apartment number.";
break;
case PropertyComplex.ApartmentNumberValid.APARTMENT_NUMBER_NOT_FOUND:
errorMessage = "The number entered: " + aptNumber +
" was not found in the list of apartments.";
break;
default:
break;
}
if (!string.IsNullOrEmpty(errorMessage))
{
ErrorActions(errorMessage);
hasErrors = true;
}
return hasErrors;
}
private void VerifyApartmentNumber()
{
int aptNumber = 0;
PropertyComplex.ApartmentNumberValid validApartmentId =
Globals.Complex.VerifyApartmentNumber(ANV_ApartmentNumber_TB.Text, out aptNumber);
if (ReportErrors(aptNumber, validApartmentId))
{
return;
}
ExecuteNextgAction(aptNumber);
Close();
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
ExecuteNextgAction(aptNumber);
Close();
}
private void ExecuteNextgAction(int aptNumber)
{
TenantData = Globals.TenantRoster.GetTenant(aptNumber);
switch (NextAction)
{
case NextActionEnum.EDIT:
case NextActionEnum.ADD:
AddOrEditResidentDlg addNewResident = new AddOrEditResidentDlg();
addNewResident.CurrentTenant = TenantData;
addNewResident.ApartmentNumber = aptNumber;
addNewResident.Show();
break;
case NextActionEnum.DELETE:
DeleteRenterDlg deleteRenter_dlg = new DeleteRenterDlg();
deleteRenter_dlg.CurrentTenant = TenantData;
deleteRenter_dlg.ApartmentNumber = aptNumber;
deleteRenter_dlg.Show();
break;
default:
MessageBox.Show("Programmer error: NextAction = " +
NextAction.ToString() +
" this action is not implemented.");
break;
}
}
}
}
AddOrEditResidentDlg.cs
This form allows the data in the excel file to be changed by either adding or editing the tenant information. This changes are saved in the TenantDataTable until the user either clicks the Save button or the Quit button. Both actions will save the data to the Excel spreadsheet.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TenantRosterAutomation
{
public partial class AddOrEditResidentDlg : Form
{
public int ApartmentNumber { get; set; }
public Tenant CurrentTenant { get; set; }
public AddOrEditResidentDlg()
{
InitializeComponent();
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
public AddOrEditResidentDlg()
{
InitializeComponent();
}
private void ANR_SaveNewTenant_BTN_Click(object sender, EventArgs e)
{
CurrentTenant.LastName = ANR_TenantLastName_TB.Text;
CurrentTenant.FirstName = ANR_TenantFirstName_TB.Text;
CurrentTenant.LeaseStart = ANR_MoveInDate_TB.Text;
CurrentTenant.LeaseEnd = ANR_LeaseEnd_TB.Text;
CurrentTenant.HomePhone = ANR_HomePhone_TB.Text;
CurrentTenant.CoTenantLastName = ANR_CoTenantLastName_TB.Text;
CurrentTenant.CoTenantFirstName = ANR_AdditionalOccupantFirstName_TB.Text;
CurrentTenant.RentersInsurancePolicy = ANR_RenterInsurance_TB.Text;
CurrentTenant.Email = ANR_AlternateContact_TB.Text;
Globals.TenantRoster.AddEditTenant(ApartmentNumber, CurrentTenant);
Close();
}
private void AddNewResident_Form_Load(object sender, EventArgs e)
{
SetUpApartmentAddressLabel();
ANR_SaveNewTenant_BTN.BackColor = Color.Green;
ANR_Cancel_BTN.BackColor = Color.Red;
if (CurrentTenant != null)
{
ANR_TenantLastName_TB.Text = CurrentTenant.LastName;
ANR_TenantFirstName_TB.Text = CurrentTenant.FirstName;
ANR_HomePhone_TB.Text = CurrentTenant.HomePhone;
ANR_MoveInDate_TB.Text = CurrentTenant.LeaseStart;
ANR_LeaseEnd_TB.Text = CurrentTenant.LeaseEnd;
ANR_CoTenantLastName_TB.Text = CurrentTenant.CoTenantLastName;
ANR_AdditionalOccupantFirstName_TB.Text = CurrentTenant.CoTenantFirstName;
ANR_AlternateContact_TB.Text = CurrentTenant.Email;
ANR_RenterInsurance_TB.Text = CurrentTenant.RentersInsurancePolicy;
}
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void SetUpApartmentAddressLabel()
{
string apartmentFullAddress = ApartmentNumber.ToString();
string buildingAddress =
Globals.Complex.FindBuildingByApartment(ApartmentNumber);
if (!string.IsNullOrEmpty(buildingAddress))
{
apartmentFullAddress = buildingAddress + " Apartment " + ApartmentNumber.ToString();
ANR_ApartmentNumber_Label.Text = apartmentFullAddress;
}
else
{
ANR_ApartmentNumber_Label.Text = "Apartment Number: " + apartmentFullAddress;
}
ANR_ApartmentNumber_Label.Font = new Font("Arial", 12, FontStyle.Bold);
}
private void ANR_Cancel_BTN_Click(object sender, EventArgs e)
{
Close();
}
}
}
DeleteRenterDlg.cs
This form allow sht user to delete a tenant from the apartment complex. The changes are also stored in the TenantDataTable.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TenantRosterAutomation
{
public partial class DeleteRenterDlg : Form
{
public int ApartmentNumber { get; set; }
public Tenant CurrentTenant { get; set; }
public DeleteRenterDlg()
{
ApartmentNumber = 0;
CurrentTenant = null;
InitializeComponent();
}
private void DR_DeleteRenter_BTN_Click(object sender, EventArgs e)
{
Globals.TenantRoster.DeleteTenant(ApartmentNumber);
Close();
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void DeleteRenter_Load(object sender, EventArgs e)
{
if (ApartmentNumber != 0 && CurrentTenant != null)
{
SetUpApartmentAddressLabel();
DR_DeleteRenter_BTN.Enabled = false;
DR_DeleteRenter_BTN.BackColor = Color.Red;
DR_Cancel_BTN.BackColor = Color.Green;
DR_TenantName_TB.Enabled = false;
DR_TenantName_TB.Text = CurrentTenant.mergedName();
}
}
private void SetUpApartmentAddressLabel()
{
string apartmentFullAddress = ApartmentNumber.ToString();
string buildingAddress =
Globals.Complex.FindBuildingByApartment(ApartmentNumber);
if (!string.IsNullOrEmpty(buildingAddress))
{
apartmentFullAddress = buildingAddress + " Apartment " + ApartmentNumber.ToString();
DR_AptNumber_LAB.Text = apartmentFullAddress;
}
else
{
DR_AptNumber_LAB.Text = "Apartment Number: " + apartmentFullAddress;
}
DR_AptNumber_LAB.Font = new Font("Arial", 12, FontStyle.Bold);
}
private void DR_Renter2DeleteYes_RB_CheckedChanged(object sender, EventArgs e)
{
DR_DeleteRenter_BTN.Enabled = true;
DR_DeleteRenter_BTN.BackColor = Color.Green;
DR_Cancel_BTN.BackColor = Color.Red;
}
private void DR_Renter2DeleteNo_RB_CheckedChanged(object sender, EventArgs e)
{
DR_DeleteRenter_BTN.Enabled = false;
DR_DeleteRenter_BTN.BackColor = Color.Red;
DR_Cancel_BTN.BackColor = Color.Green;
}
private void DR_Cancel_BTN_Click(object sender, EventArgs e)
{
Close();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
ReportCurrentStatusWindow.cs
This form is used to present information to the user about the current status of the program it is only used during operations that can take noticible time such as reading the excel data file or writing the updates to the excel data file.
using System;
using System.Drawing;
using System.Windows.Forms;
namespace TenantRosterAutomation
{
public partial class ReportCurrentStatusWindow : Form
{
public string MessageText { get; set; }
public ReportCurrentStatusWindow()
{
InitializeComponent();
}
private void Form_CurrentProgressStatus_Load(object sender, EventArgs e)
{
CPS_Message_TB.Text = MessageText;
CPS_Message_TB.Font = new Font("Arial", 12, FontStyle.Bold);
Size size = TextRenderer.MeasureText(CPS_Message_TB.Text, CPS_Message_TB.Font);
Height = (size.Height * 3) + 84;
Width = size.Width + 84;
CPS_Message_TB.Width = size.Width;
CPS_Message_TB.Height = size.Height * 3;
CPS_Message_TB.Left = 40;
CPS_Message_TB.Height = 40;
}
}
}
Answer: RentRosterApp
If you have read any of my reviews then you know I do value consistent naming
Here I can see occasional abbreviations which does not help legibility
..._Button_Click vs ..._BTN_Click
ApartmentNumberVerifier vs EditPreferencesDlg
EditPreferences_... vs RR_Quit_...
The Load method can be greatly simplified
private void RentRosterApp_Load(object sender, EventArgs e)
{
RR_Quit_BTN.BackColor = Color.Red;
if (globalsInitialized) return; //early exit
SetButtonsEnablement(false);
using (EditPreferencesDlg preferences_dlg = new EditPreferencesDlg())
if (preferences_dlg.ShowDialog() == DialogResult.OK)
SetButtonsEnablement(true);
} | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void SetButtonsEnablement(bool isEnabled)
{
PrintMailboxLists_Button.Enabled = isEnabled;
AddNewResident_Button.Enabled = isEnabled;
DeleteRenter_Button.Enabled = isEnabled;
}
Inside the Load method you have used using around EditPreferencesDlg whereas in EditPreferences_BTN_Click you haven't
You can extract the common part for the RR button event handlers into a separate method
private void RR_Quit_BTN_Click(object sender, EventArgs e)
{
SafeExcelCall(() =>
{
Globals.Save();
Globals.ReleaseAllModels();
Close();
});
}
private void RR_SAVEEDITS_BTN_Click(object sender, EventArgs e)
{
SafeExcelCall(Globals.SaveTenantData);
}
//Since I don't know your domain I can't find a really good name here
//Usually we prefix a method with `SafeXYZ` if it handles `XYZ` exceptions
private void SafeExcelCall(Action excelCall)
{
try
{
excelCall();
}
catch (AlreadyOpenInExcelException ao)
{
MessageBox.Show(ao.Message);
}
}
EditPreferencesDlg
I don't see the need why do we need using block around this form
Please note that I haven't used WinForms in the last 10 years so I might be wrong on using
The Load method's switch statement can be rewritten like this to avoid repetitive code
RadioButton shouldBeCheckedRB;
switch (localPreferences.PrintSaveOptions)
{
case PrintSavePreference.PrintSave.PrintAndSave:
shouldBeCheckedRB = EP_PrintAndSave_RB;
break;
case PrintSavePreference.PrintSave.SaveOnly:
shouldBeCheckedRB = EP_SavelOnly_RB;
break;
default:
shouldBeCheckedRB = EP_PrintOnly_RB;
break;
}
shouldBeCheckedRB.Checked = true;
Or if you can use switch expression (depending on your C# version) then you can end up with an even more concise code | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
RadioButton shouldBeCheckedRB = localPreferences.PrintSaveOptions switch
{
PrintSavePreference.PrintSave.PrintAndSave => EP_PrintAndSave_RB,
PrintSavePreference.PrintSave.SaveOnly => EP_SavelOnly_RB,
_ => EP_PrintOnly_RB,
};
shouldBeCheckedRB.Checked = true;
Yet again if you want to reduce the repetitive code of your XYZ_CheckedChanged handlers then you can do the following
private void EP_PrintAndSave_RB_CheckedChanged(object sender, EventArgs e)
=> SetPrintSaveOptions(PrintSavePreference.PrintSave.PrintAndSave);
private void EP_SavelOnly_RB_CheckedChanged(object sender, EventArgs e)
=> SetPrintSaveOptions(PrintSavePreference.PrintSave.SaveOnly);
private void EP_PrintOnly_RB_CheckedChanged(object sender, EventArgs e)
=> SetPrintSaveOptions(PrintSavePreference.PrintSave.PrintOnly);
private void SetPrintSaveOptions(PrintSavePreference.PrintSave option)
=> localPreferences.PrintSaveOptions = option;
Or you define a mapping between the RadioButtons and the PrintSave values and then dynamically specify the event handlers (for example inside Load)
Dictionary<RadioButtion, PrintSavePreference.PrintSave> mappings = new Dictionary<RadioButtion, PrintSavePreference.PrintSave>
{
{ EP_PrintAndSave_RB, PrintSavePreference.PrintSave.PrintAndSave },
{ EP_SavelOnly_RB, PrintSavePreference.PrintSave.SaveOnly },
{ EP_PrintOnly_RB, PrintSavePreference.PrintSave.PrintOnly }
};
foreach (var mapping in mappings)
{
mapping.Key.CheckedChanged += (s, e) =>
localPreferences.PrintSaveOptions = mapping.Value;
}
findDefaultFolderLocationExecute: this does not follow your snake casing naming
Once again the naming of your variables are inconsistent
findDefaultFolderLocationExecute's fbd vs findTenantRosterExcelFile's FindTenantRoster
Minor but you can use object initializer to reduce the initialization code | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
Minor but you can use object initializer to reduce the initialization code
var FindTenantRoster = new OpenFileDialog()
{
InitialDirectory = "c:\\",
Filter = "Excel Files| *.xls; *.xlsx; *.xlsm"
};
And here comes my favourite control name: EP_RentRosterSheetName_LISTBOX
Please try to consolidate your variables names as well (ExcelFile vs sheetNames)
You can reduce the level of indention of the fillSheetSelectorListBox method by using early exits
if (string.IsNullOrEmpty(localPreferences.ExcelWorkBookFullFileSpec))
return;
var excelFile = new ExcelFileData(
localPreferences.ExcelWorkBookFullFileSpec,
localPreferences.ExcelWorkSheetName);
List<string> sheetNames = excelFile.GetWorkSheetCollection();
if (sheetNames == null)
return;
PrintMailboxListsDlg
Inside the Load please prefer AddRange over multiple Add method calls
SelectBuilding2Print_listBox.Items.AddRange(Globals.Complex.BuildingAddressList);
SelectBuilding2Print_listBox.Items.Add("All Buildings");
If you move the CheckedChanged handlers inside the Load method then those piece of code that are related to each other (high cohesion) then they are next to each other
AddDateToFileName_CB.Checked = addDateToFileName;
AddDateToFileName_CB.CheckedChanged += (s, e) => addDateToFileName = !addDateToFileName;
AddDateUnderAddress_CB.Checked = addDateToTitle;
AddDateUnderAddress_CB.CheckedChanged += (s, e) => addDateToTitle = !addDateToTitle;
Inside the PML_SaveAndPrint_Button_Click you are using the same hard-coded string ("All Buildings") as you have used in the Load
Please prefer class level constants
String.Compare(...) == 0 could be replaced with string.Equals
string.Equals(selectedBuildings, allBuildings)
The printAndOrSaveMailList could be rewritten in a way that the core functionality is on the top indentation level | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
private void PrintAndOrSaveMailList(string streetAddress)
{
if (!int.TryParse(streetAddress, out int streetNumber))
{
MessageBox.Show("Non Numeric string passed into PrintMailboxLists_Form::printAndOrSaveMailList().");
return;
}
PrintAndOrSaveMailList(streetNumber);
}
BTW this iStreetNumber does sound like an apple product :)
Since the number suffix already indicates the data type I would not recommend to prefix it with i
Inside your SelectBuilding2Print_listBox_SelectedIndexChanged method I don't think that null check is needed
At least based on my intuition a listbox will not fire an selected index changed event for a null item
Inside your PrintAndOrSaveMailList I think you have overcomplicated the two bool variables' assignment
bool save = printSave == PrintSavePreference.PrintSave.PrintAndSave
|| printSave == PrintSavePreference.PrintSave.SaveOnly;
bool print = printSave == PrintSavePreference.PrintSave.PrintAndSave
|| printSave == PrintSavePreference.PrintSave.PrintOnly;
Or with Linq you can write something like this
bool save = new[] { PrintSavePreference.PrintSave.PrintAndSave, PrintSavePreference.PrintSave.SaveOnly }.Contains(printSave);
bool print = new[] { PrintSavePreference.PrintSave.PrintAndSave, PrintSavePreference.PrintSave.PrintOnly }.Contains(printSave);
For string concatenations please prefer string interpolation or StringBuilder instead of + or += operators
If you want to you get rid of one level of indentation at the end of this method then you can change the mailboxList assignment like this
Building building = Globals.Complex.GetBuilding(streetAddress);
MailboxData mailboxList = building != null ? Globals.Complex.GetMailBoxList(building) : null;
if (mailboxList != null)
{
wordInteropMethods.CreateMailistPrintAndOrSave(documentName,
mailboxList, addDateToFileName, addDateToTitle, save, print);
}
ApartmentNumberVerifier | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
ApartmentNumberVerifier
If you follow the C# naming convention for enums then you should end up with this
public enum NextAction
{
Add,
Delete,
Edit
}
It is perfectly normal to have properties like this
public NextAction NextAction { get; set; }
Inside your ANV_ApartmentNumber_TB_KeyDown please prefer early exit over guard expression to streamline the method's implementation
private void ANV_ApartmentNumber_TB_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode != Keys.Enter)
return;
VerifyApartmentNumber();
}
The ReportError can be written in so many different ways, let me show two
A) With switch statement + hasError re-assignment in default case
bool hasError = true;
string errorMessage = null;
switch (validApartmentId)
{
case PropertyComplex.ApartmentNumberValid.APARTMENT_NUMBER_NONNUMERIC:
errorMessage = "Please enter a number in the box.";
break;
case PropertyComplex.ApartmentNumberValid.APARTMENT_NUMBER_OUT_OF_RANGE:
errorMessage = $"The apartment number: {aptNumber} is out of range[{Globals.Complex.MinApartmentNumber}, {Globals.Complex.MaxApartmentNumber}] please enter a valid apartment number.";
break;
case PropertyComplex.ApartmentNumberValid.APARTMENT_NUMBER_NOT_FOUND:
errorMessage = $"The number entered: {aptNumber} was not found in the list of apartments.";
break;
default:
hasError = false;
break;
}
if (hasError)
ErrorActions(errorMessage);
return hasError;
B) With switch expression + hasError calculation after switch | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
return hasError;
B) With switch expression + hasError calculation after switch
string errorMessage = validApartmentId switch
{
PropertyComplex.ApartmentNumberValid.APARTMENT_NUMBER_NONNUMERIC =>
"Please enter a number in the box.",
PropertyComplex.ApartmentNumberValid.APARTMENT_NUMBER_OUT_OF_RANGE =>
$"The apartment number: {aptNumber} is out of range[{Globals.Complex.MinApartmentNumber}, {Globals.Complex.MaxApartmentNumber}] please enter a valid apartment number.",
PropertyComplex.ApartmentNumberValid.APARTMENT_NUMBER_NOT_FOUND =>
$"The number entered: {aptNumber} was not found in the list of apartments.",
_ => null
};
var hasError = !string.IsNullOrEmpty(errorMessage);
if (hasError)
ErrorActions(errorMessage);
return hasError;
ExecuteNextgAction: I assume the g is just a typo here
If you want to execute more than a single line in each case branch (+ break) then prefer to use code block {} statement
case NextActionEnum.Add:
{
AddOrEditResidentDlg addNewResident = new AddOrEditResidentDlg();
addNewResident.CurrentTenant = TenantData;
addNewResident.ApartmentNumber = aptNumber;
addNewResident.Show();
break;
}
Or try to convert your multiline block into a single statement if possible
case NextAction.Add:
new AddOrEditResidentDlg()
{
CurrentTenant = TenantData,
ApartmentNumber = aptNumber
}.Show();
break;
AddOrEditResidentDlg
As you have already seen I'm not a huge fan of a repetitive code
When I saw here the manual DataBinding between the TextBoxes and the Tenant object I though I can come up with an easier solution
I did, but it relies on building expression trees dynamically which needs a bit more explanation than simply just sharing it with you
So, I decided to make another post with that code | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
The SetUpApartmentAddressLabel method can be greatly simplified, where there is no need for the if-else blocks and for the apartmentFullAddress variable
string buildingAddress =
Globals.Complex.FindBuildingByApartment(ApartmentNumber);
ANR_ApartmentNumber_Label.Text = string.IsNullOrEmpty(buildingAddress)
? $"Apartment Number: {ApartmentNumber}"
: $"{buildingAddress} Apartment {ApartmentNumber}";
ANR_ApartmentNumber_Label.Font = new Font("Arial", 12, FontStyle.Bold);
DeleteRenterDlg
Inside the ctor you don't need to initialize the CurrentTenant with null, since that's the default value for reference types
Same applies for ApartmentNumber where the default value is 0
By the way it seems a bit unsafe that you do not perform any checks on the ApartmentNumber property before you call the DeleteTenant
Inside the Load method you can use the default operator/literal to check the properties' values
//prior C# 7.1
if (ApartmentNumber != default(int) && CurrentTenant != default(Tenant))
//since C# 7.1 we can use default literal
if (ApartmentNumber != default && CurrentTenant != default)
Yet again please prefer early exit instead of guard expression
if (ApartmentNumber == default || CurrentTenant == default)
return;
SetUpApartmentAddressLabel();
...
The SetUpApartmentAddressLabel can be simplified in the same way as I suggested it for the AddOrEditResidentDlg class
You can combine the DR_Renter2DeleteYes_RB_CheckedChanged and DR_Renter2DeleteNo_RB_CheckedChanged event handlers into one:
private void DR_Renter2Delete_RB_CheckedChanged(object sender, EventArgs e)
{
var rb = (RadioButton)sender;
var canBeDeleted = string.Equals(rb.Name, nameof(DR_Renter2DeleteYes_RB));
DR_DeleteRenter_BTN.Enabled = canBeDeleted;
DR_DeleteRenter_BTN.BackColor = canBeDeleted ? Color.Green : Color.Red;
DR_Cancel_BTN.BackColor = canBeDeleted ? Color.Red : Color.Green;
}
ReportCurrentStatusWindow | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c#, excel, winforms, ms-word
ReportCurrentStatusWindow
Either call the property Text or Message, you don't need to use both
It's like you name your warning label, which is very important to WarningVeryImporantInformationLabel
Either WarningLabel or ImportantInfoLabel would be sufficient
<sarcasm> I love magic numbers </sarcasm>
They can break your application really easily if you don't pay enough attention
A better way can be the utilization of constants
const int WindowMargin = 84;
const int MessageTBMargin = 40;
const int HeightMultipler = 3;
private void Form_CurrentProgressStatus_Load(object sender, EventArgs e)
{
CPS_Message_TB.Text = MessageText;
CPS_Message_TB.Font = new Font("Arial", 12, FontStyle.Bold);
Size size = TextRenderer.MeasureText(CPS_Message_TB.Text, CPS_Message_TB.Font);
Height = (size.Height * HeightMultipler) + WindowMargin;
Width = size.Width + WindowMargin;
CPS_Message_TB.Width = size.Width;
CPS_Message_TB.Height = size.Height * HeightMultipler;
CPS_Message_TB.Left = MessageTBMargin;
CPS_Message_TB.Height = MessageTBMargin; //Did you mean Top?
}
By the way you are setting the CPS_Message_TB.Height twice
I suppose you wanted to set the Top property instead | {
"domain": "codereview.stackexchange",
"id": 42798,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, excel, winforms, ms-word",
"url": null
} |
c++
Title: How can I remove the duplicated code in this code?
Question: this is some function:
RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
{
RequestResult requestResult;
JoinRoomRequest joinRoomReq;
joinRoomReq = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
JoinRoomResponse joinRoomRes;
if (this->m_roomManager.isRoomExists(joinRoomReq.roomId) &&
!this->m_roomManager.getRoomState(joinRoomReq.roomId) &&
!this->m_roomManager.isRoomFull(joinRoomReq.roomId))
{
joinRoomRes.status = 1;
this->m_roomManager.addUserToRoom(this->m_user, joinRoomReq.roomId);
try {
requestResult.newHandler = m_handlerFactory->createRoomMemberRequestHandler(m_user, this->m_roomManager.getRoomDataById(joinRoomReq.roomId));
}
catch (MyException& e) {
Log(e.what());
// *this*
joinRoomRes.status = 0;
// *and this*
requestResult.newHandler = nullptr;
}
}
else {
// *appear here*
joinRoomRes.status = 0;
// *and here*
requestResult.newHandler = nullptr;
}
requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
return requestResult;
}
i want to remove the duplicated code but i can't figure out a way to do it.
it tried another way but that's another duplicated code, like this:
RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
{
RequestResult requestResult;
JoinRoomRequest joinRoomReq;
joinRoomReq = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
JoinRoomResponse joinRoomRes;
if (this->m_roomManager.isRoomExists(joinRoomReq.roomId) &&
!this->m_roomManager.getRoomState(joinRoomReq.roomId) &&
!this->m_roomManager.isRoomFull(joinRoomReq.roomId))
{
joinRoomRes.status = 1; | {
"domain": "codereview.stackexchange",
"id": 42799,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
this->m_roomManager.addUserToRoom(this->m_user, joinRoomReq.roomId);
try {
requestResult.newHandler = m_handlerFactory->createRoomMemberRequestHandler(m_user, this->m_roomManager.getRoomDataById(joinRoomReq.roomId));
// *this below*
requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
return requestResult;
}
catch (MyException& e) {
Log(e.what());
}
}
joinRoomRes.status = 0;
requestResult.newHandler = nullptr;
// *appear here below*
requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
return requestResult;
}
```
Answer:
RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
Is it necessary to copy the RequestInfo? or could we pass it by const &?
JoinRoomRequest joinRoomReq;
joinRoomReq = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
There's no need to split this into two lines. We should initialize variables to useful values immediately where possible.
if (this->m_roomManager.isRoomExists(joinRoomReq.roomId) &&
!this->m_roomManager.getRoomState(joinRoomReq.roomId) &&
!this->m_roomManager.isRoomFull(joinRoomReq.roomId))
{
Rather than checking for success (which means indenting code, and adding an else statement further down), it's better to check for failure and return early.
We should avoid using this-> unless it's actually necessary (which it isn't here).
Whatever getRoomState() returns, it seems unintuitive to treat it as a boolean (where true means something went wrong???). We should either give the function a better name (e.g. isRoomActive), or use an enum class for the result.
joinRoomRes.status = 1; | {
"domain": "codereview.stackexchange",
"id": 42799,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
joinRoomRes.status = 1;
this->m_roomManager.addUserToRoom(this->m_user, joinRoomReq.roomId);
try {
requestResult.newHandler = m_handlerFactory->createRoomMemberRequestHandler(m_user, this->m_roomManager.getRoomDataById(joinRoomReq.roomId));
// *this below*
requestResult.buffer = JsonResponsePacketSerializer::serializeResponse(joinRoomRes);
return requestResult;
}
catch (MyException& e) {
Log(e.what());
}
Is this really correct if the handler creation fails? We've already added the user to the room, and set the status to 1. I suspect this might result in problems later. Perhaps we need to remove the user from the room again and return failure (or restructure our code so that the user isn't added until we get the handle - perhaps addUserToRoom could return the handle)?
Also, we shouldn't use "magic numbers" (the status of 1 doesn't mean anything to someone reading the code for the first time) We should use an enum class for the status instead, which would give each value a meaningful name.
I wonder if exception handling is really the right thing to use in case of failure here... but it's impossible to tell without seeing more code. Perhaps the logging could be moved into the handle creation function, which could return a nullptr.
Putting the above points together (and taking some liberties by removing the exception handling), I'd suggest something like:
RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
{
auto const req = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
auto const roomId = req.roomId;
if (!m_roomManager.isRoomExists(roomId) || m_roomManager.getRoomState(roomId) || m_roomManager.isRoomFull(roomId))
return { nullptr, JsonResponsePacketSerializer::serializeResponse(JoinResponseStatus::Failed) };
auto handler = addUserToRoom(m_user, roomId); | {
"domain": "codereview.stackexchange",
"id": 42799,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
auto handler = addUserToRoom(m_user, roomId);
if (!handler)
return { nullptr, JsonResponsePacketSerializer::serializeResponse(JoinResponseStatus::Failed) };
return { handler, JsonResponsePacketSerializer::serializeResponse(JoinResponseStatus::Success) };
}
There's some duplication but it's easy to factor it out into a helper function (or the RequestResult constructor).
This still isn't very clean though. Note that we're doing two separate things: messing around with JSON, and performing the actual logic of adding the user to the room.
We should probably put all the logic for adding the user (and getting the handle) in the addUserToRoom function, and do the JSON stuff in the joinRoom function, e.g.:
RequestResult MenuRequestHandler::joinRoom(RequestInfo requestInfo)
{
auto const req = JsonRequestPacketDeserializer::deserializeJoinRoomRequest(requestInfo.buffer);
auto const roomId = req.roomId;
auto const handler = addUserToRoom(m_userId, req.roomId);
auto const status = (handler ? JoinResponseStatus::Success : JoinResponseStatus::Failed);
return { handler, JsonResponsePacketSerializer::serializeResponse(status) };
} | {
"domain": "codereview.stackexchange",
"id": 42799,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
lisp, installer, elisp
Title: Installing packages when needed
Question: I decided to create a portable Emacs config and install packages I use if it's necessary on a fresh computer.
Here is what I've done:
; loop through names of packages and install them if needed
(let ((packages '('use-package 'yasnippet 'expand-region 'bm 'undo-tree))
(content-not-refreshed t)
)
(mapc
(lambda (name)
(unless (package-installed-p (eval name))
(when content-not-refreshed
(package-refresh-contents)
(setq content-not-refreshed nil))
(package-install (eval name))))
packages
))
; load packages
(require 'use-package)
(require 'yasnippet)
(require 'expand-region)
(require 'bm)
(require 'undo-tree)
Is this code good? Can it be improved?
Answer: When quoting a list of symbols, it's redundant to quote each symbol within the list.
There's no need to eval a symbol.
This sequence looks strange:
(require 'use-package)
(require 'yasnippet)
(require 'expand-region)
(require 'bm)
(require 'undo-tree)
Since we're looping over those same names in the preceding loop, why not just (require name) as the last form within the lambda?
Addressing these issues gives somewhat improved code:
; loop through names of packages: install if needed, then load
(let ((packages '(use-package yasnippet expand-region bm undo-tree))
(content-not-refreshed t)
)
(mapc
(lambda (name)
(unless (package-installed-p name)
(when content-not-refreshed
(package-refresh-contents)
(setq content-not-refreshed nil))
(package-install name))
(require name))
packages
))
Further improvement would maintain the list of packages as a customisable variable. | {
"domain": "codereview.stackexchange",
"id": 42800,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "lisp, installer, elisp",
"url": null
} |
python, parsing
Title: Implementation of a Parser for Analysis Description Language
Question: I have created a script for parsing ADL and the code looks like below. Example ADL file
I am looking for suggestions to divide the code in multiple methods and make it more readable. Thanks
block_names = ("object", "region", "info", "table ")
keywords = ("define", "select", "reject", "take", "using", "sort", "weight", "histo")
table_k_v = "# val err- err+ xmin xmax"
def adl_parser(adl_file='adl.adl'):
"""Returns the ADL parsed file as JSON object
:param type: File
:param adl_file: Input .adl from the user.
:return : JSON object
"""
block_data = {}
parsing_block = False
parsing_table = False
json_parsed = {
"object": [],
"region": [],
"info": [],
"table": [],
"define": [],
}
# Read the ADL file
f = open(adl_file, 'r')
for line in f:
# Skip comment lines outside block
if line.startswith("#"):
continue
# Skip empty lines w/o whitespaces or tabs
if line in ['\n', '\r\n']:
# Pop out the previous block when new line appears
if parsing_block:
json_parsed[block_type].append(block_data)
block_data = {}
parsing_block = False
parsing_table = False
else:
continue
line = line.strip()
if not line:
continue
# Check for block types and parse the block data
if line.startswith(block_names) and not block_data:
block = line.split(" ", 1)
block_type = block[0]
block_data["name"] = block[-1]
parsing_block = True
continue | {
"domain": "codereview.stackexchange",
"id": 42801,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing",
"url": null
} |
python, parsing
# Pop out the block when new block starts without empty line
elif line.startswith(block_names) and block_data:
json_parsed[block_type].append(block_data)
block_data = {}
block_data["name"] = line.split(" ", 1)[-1]
parsing_block = True
parsing_table = False
continue
elif line.startswith("define"):
line_data = line.split("=")
variable_name = line_data[0].strip().split(" ")[-1]
variable_value = line_data[1].strip()
json_parsed["define"].append({variable_name: variable_value})
continue
try:
# Parse the keyword value pair under a block
if parsing_block:
# Skip comment lines inside the block
if line.startswith("#") and line != table_k_v:
continue | {
"domain": "codereview.stackexchange",
"id": 42801,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing",
"url": null
} |
python, parsing
# Parse the rows for the table block
if block_type == "table":
if line == table_k_v:
parsing_table = True
block_data["data"] = []
continue
if parsing_table:
values = list(filter(None, line.split(" ")))
if len(values) == 5:
block_data["data"].append({
"val": values[0],
"err-": values[1],
"err+": values[2],
"xmin": values[3],
"xmax": values[4],
})
continue
keyword_value = line.split(" ", 1)
if keyword_value[0] in keywords:
if keyword_value[0] == "select":
# use list for storing `select` values
if block_data.get(keyword_value[0]):
block_data[keyword_value[0]].append(keyword_value[-1])
else:
block_data[keyword_value[0]] = [keyword_value[-1]]
else:
block_data[keyword_value[0]] = keyword_value[-1]
elif block_type == "region" and len(keyword_value) == 1:
block_data["parent"] = keyword_value[-1]
else:
raise ValueError('Parsing of Keyword {} is not supported.'.format(keyword_value[0]))
except Exception:
block_data = {}
parsing_block = False
parsing_table = False
return json_parsed | {
"domain": "codereview.stackexchange",
"id": 42801,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing",
"url": null
} |
python, parsing
return json_parsed
Answer: You already have one useful code review, so I'll focus less on those
details and more on parsing strategy and your question about organizing
the parsing into smaller, more-focused functions.
When building a parser, don't forget error reporting. It's tempting when
building a parser to sanitize the input as early as possible, for example by
stripping lines or filtering out comment lines. If done crudely, however, that
preliminary work can undermine error reporting because you lose basic facts
like the line number where the error occurred. Here's a simple illustration of
one way to avoid that. The initial processing step will convert the raw lines
of text into simple data objects that also know their original (pre-sanitized)
line number.
from typing import List, Optional
from dataclasses import dataclass, field
BLOCK_NAMES = ('object', 'region', 'info', 'table')
KEYWORDS = ('define', 'select', 'reject', 'take', 'using', 'sort', 'weight', 'histo')
TABLE_K_V = '# val err- err+ xmin xmax'
COMMENT = '#'
@dataclass(frozen = True)
class Line:
n: int
text: str
def collect_lines(fh):
# Takes an iterable (eg opened file handle).
# Yields Line instances.
# Filters out blank lines and comment lines (other than TABLE_K_V).
for i, line in enumerate(fh):
text = line.strip()
if not text:
continue
elif text.startswith(TABLE_K_V):
yield Line(i + 1, text)
elif not text.startswith(COMMENT):
yield Line(i + 1, text) | {
"domain": "codereview.stackexchange",
"id": 42801,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing",
"url": null
} |
python, parsing
Parsing block by block rather than line by line. Parsing a block-oriented
language line by line is tricky: on each line you have to know what kind of
structure you are currently embedded in, which usually involves the management
of various status variables. This kind of code tends to be complex, hard to
modify, and thus bug-prone. A simpler approach is to organize the data very
early into the larger units -- the blocks. Not all syntaxes are amenable to
this kind of approach, but I think ADL is. Here's an illustration that uses a
Block data object, which knows its kind and has a list of Line instances.
@dataclass
class Block:
kind: Optional[str] = None
lines: List[Line] = field(default_factory = list)
def collect_blocks(lines):
# Takes an iterable of Line instances.
# Yields Block instances.
b = Block()
for line in lines:
first_word = line.text.split()[0]
if first_word in BLOCK_NAMES:
if b.lines:
yield b
b = Block(kind = first_word)
b.lines.append(line)
if b.lines:
yield b
def main():
# Usage demo.
path = sys.argv[1]
with open(path) as fh:
for b in collect_blocks(collect_lines(fh)):
print(b.kind, len(b.lines))
if __name__ == '__main__':
main()
Next steps. Once you have a way to work with entire blocks at a time, you
just need to build a parsing function for each kind of block. And those
functions might use smaller functions that focus on the next level down in the
hierarchy: the entities declared by KEYWORDS. | {
"domain": "codereview.stackexchange",
"id": 42801,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing",
"url": null
} |
java, object-oriented, json, serialization
Title: Jackson deserialization of subset of enums
Question: I have several enums that all implement this interface:
public interface SelectOption {
String getId();
String getLabel();
}
Here's an example:
public enum AuthType implements SelectOption {
BASIC("basic", "Basic Auth"),
OAUTH("oauth", "OAuth"),
TOKEN("token", "Bearer Token");
private final String id;
private final String label;
private AuthType(String id, String label) {
this.id = id;
this.label = label;
}
@Override
public String getId() {
return this.id;
}
@Override
public String getLabel() {
return this.label;
}
} | {
"domain": "codereview.stackexchange",
"id": 42802,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented, json, serialization",
"url": null
} |
java, object-oriented, json, serialization
@Override
public String getLabel() {
return this.label;
}
}
I receive this enum from the API client. First, the client asks for available select options (in this case it's the authentication type), so it needs both the id (the one to refer internally and in JSON that goes to the backend) and label (the user-friendly name to display in the UI). I want to use a snake case (bla_bla) or kebab case (bla-bla) notation because I feel it's more natural for any API and so that it does not depend on my java enum constants so that I can rename them as I like. The actual use-case is that the UI will display a drop-down of available authentication methods, the user will pick one and fill out method-specific parameter, i.e. for BASIC, that'd be username and password, for TOKEN, that'd be the token.
The default deserialization behavior is to match up enum constant names, i.e. BASIC string would match with AuthType#BASIC automatically. I'm using Jackson for deserialization.
Every time I get an enum that implements SelectOption in a serialized form (as a String), I get it as id that is equal to SelectOption#getId(). So, if I supply basic, it would error saying something like "basic" not found in enumeration "AuthType", allowed values are: "BASIC", "OAUTH", "TOKEN". And for every other enum, I get it as the enum constant name, so the default deserialization works.
I couldn't create a JsonDeserializer for SelectOption, because there is a built-in EnumDeserializer that takes precedence, so I decided to register a deserializer that works with all enums (registered to ObjectMapper for Enum.class) and delegates to EnumDeserializer if it's not a SelectOption.
The following solution works but I'm not sure if it's the best way to do it:
public class SelectOptionDeserializer extends JsonDeserializer<Enum<?>> implements ContextualDeserializer {
JavaType type;
public SelectOptionDeserializer() {
} | {
"domain": "codereview.stackexchange",
"id": 42802,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented, json, serialization",
"url": null
} |
java, object-oriented, json, serialization
public SelectOptionDeserializer() {
}
public SelectOptionDeserializer(JavaType type) {
this.type = type;
}
@Override
public Enum<?> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
if (!SelectOption.class.isAssignableFrom(type.getRawClass())) {
EnumDeserializer enumDeserializer = new EnumDeserializer(EnumResolver.constructFor(ctxt.getConfig(), type.getRawClass()), false);
return (Enum<?>) enumDeserializer.deserialize(p, ctxt);
}
String id = p.getText();
return (Enum<?>) Stream.of(type.getRawClass().getEnumConstants())
.map(SelectOption.class::cast)
.filter(enumConstant -> enumConstant.getId().equals(id))
.findFirst()
.orElse(null);
}
@Override
public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) {
return new SelectOptionDeserializer(ctxt.getContextualType() != null
? ctxt.getContextualType()
: property.getMember().getType());
}
}
Answer: As per the discussion in the comments, I decided to simply use Enum#name() instead of SelectOption#getId(). I'm already using a lot of other enums in my JSON responses even though those are simple "type" enums without any extra data like label here but nonetheless, I think I was wrong about screaming snake case (BLA_BLA) not fitting into APIs, they fit just fine.
Final solution:
public interface SelectOption {
/**
* refers to {@link Enum#name()}
*/
String name();
String getLabel();
}
The actual enum:
public enum AuthType implements SelectOption {
BASIC("Basic Auth"),
OAUTH("OAuth"),
TOKEN("Bearer Token");
private final String label;
private AuthType(String label) {
this.label = label;
}
@Override
public String getLabel() {
return this.label;
}
} | {
"domain": "codereview.stackexchange",
"id": 42802,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented, json, serialization",
"url": null
} |
java, object-oriented, json, serialization
@Override
public String getLabel() {
return this.label;
}
}
This way the default deserialization works as needed, so, no need for a deserializer class. | {
"domain": "codereview.stackexchange",
"id": 42802,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, object-oriented, json, serialization",
"url": null
} |
performance, c, chess, sdl
Title: Chess game for two human players
Question: I'm relatively new to programming, as in my second semester of college. To practice C, I started work on a chess game. I'm wondering if there are ways I could improve my code, make it look more professional, or reduce some blocks of inefficient code. I have more ideas on things to add to the game to make it more user-friendly and improve performance, but I want to make sure I'm going in the right direction so far.
This is my first big project that's more than a simple console program.
// Chess V1.0
// Kegan
// January 2022
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
typedef struct GraphicsComponents {
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Surface* surface;
SDL_Texture* texture;
SDL_Rect rect;
}gc;
void drawBoard(gc*, int);
void updatePieces(gc*, int[8][8], int, const char*[12]);
int findMousePosX(int[8][8], int, int, int, SDL_Event);
int findMousePosY(int[8][8], int, int, int, SDL_Event);
int main(int argc, char* args[]) {
const int originalTileSize = 32; // Original sprites are 32 * 32 pixels
const int scale = 3; // Scale to increase size of sprites on the screen
const int tileSize = originalTileSize * scale; // Each sqaure is 96 * 96 pixels
const int boardSize = tileSize * 8; // Width/length of the board based on the size of each sprite
// Keeping track of the board could be more optimized
int board[8][8] = {
8, 7, 9, 10, 11, 9, 7, 8,
6, 6, 6, 6, 6, 6, 6, 6,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
0, 0, 0, 0, 0, 0, 0, 0,
2, 1, 3, 4, 5, 3, 1, 2
};
int mouseX = 0;
int mouseY = 0;
bool madeSelection = false;
int selectedPiece = 0; | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
performance, c, chess, sdl
const char* spritePath[12] = {
"./sprites/chess_00.png", // light pawn
"./sprites/chess_01.png", // light knight
"./sprites/chess_02.png", // light rook
"./sprites/chess_03.png", // light bishop
"./sprites/chess_04.png", // light queen
"./sprites/chess_05.png", // light king
"./sprites/chess_06.png", // dark pawn
"./sprites/chess_07.png", // dark knight
"./sprites/chess_08.png", // dark rook
"./sprites/chess_09.png", // dark bishop
"./sprites/chess_10.png", // dark queen
"./sprites/chess_11.png" // dark king
};
gc graphics;
gc* graphicsPtr = &graphics;
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
SDL_Event event;
graphics.window = SDL_CreateWindow("Chess!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, boardSize, boardSize, 0);
graphics.renderer = SDL_CreateRenderer(graphics.window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
performance, c, chess, sdl
drawBoard(graphicsPtr, tileSize);
updatePieces(graphicsPtr, board, tileSize, spritePath);
// Change later to break loop
while (1) {
if (SDL_PollEvent(&event)) {
switch (event.type) {
case SDL_MOUSEMOTION:
mouseX = findMousePosX(board, mouseX, tileSize, boardSize, event); // Temporary solution. Update later. // Updated. Works better. Could be more optimized?
mouseY = findMousePosY(board, mouseY, tileSize, boardSize, event); // ^
break;
case SDL_MOUSEBUTTONDOWN:
if (madeSelection == false) {
selectedPiece = board[mouseY][mouseX];
board[mouseY][mouseX] = 12; // Sprite of moved piece is not rendered in original position
}
else if (madeSelection == true) {
board[mouseY][mouseX] = selectedPiece;
}
break;
case SDL_MOUSEBUTTONUP:
if (madeSelection == false) {
madeSelection = true;
}
else if (madeSelection == true) {
drawBoard(graphicsPtr, tileSize);
updatePieces(graphicsPtr, board, tileSize, spritePath);
madeSelection = false;
}
break;
}
}
}
SDL_DestroyTexture(graphics.texture);
SDL_DestroyRenderer(graphics.renderer);
SDL_DestroyWindow(graphics.window);
IMG_Quit();
SDL_Quit();
return 0;
}
void drawBoard(gc* graphics, int tileSize) {
// Load and render the sprites for the alternating tiles
// This could be more optimized / written better
char* path = { '\0' };
SDL_RenderClear(graphics->renderer); | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
performance, c, chess, sdl
for (int y = 0; y < 8; y++) {
for (int x = 0; x < 8; x++) {
if (y % 2 == 0) {
if (x % 2 == 0) {
path = "./sprites/chess_12.png";
}
else {
path = "./sprites/chess_13.png";
}
}
else if (y % 2 == 1) {
if (x % 2 == 0) {
path = "./sprites/chess_13.png";
}
else {
path = "./sprites/chess_12.png";
}
}
graphics->surface = IMG_Load(path);
graphics->texture = SDL_CreateTextureFromSurface(graphics->renderer, graphics->surface);
SDL_FreeSurface(graphics->surface);
graphics->rect.x = (x * tileSize);
graphics->rect.y = (y * tileSize);
graphics->rect.w = tileSize;
graphics->rect.h = tileSize;
SDL_RenderCopy(graphics->renderer, graphics->texture, NULL, &graphics->rect);
}
}
SDL_RenderPresent(graphics->renderer);
return;
} | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
performance, c, chess, sdl
return;
}
void updatePieces(gc* graphics, int board[8][8], int tileSize, const char* spritePath[12]) {
// Load and render the pieces according to their position in the board[][] array
// This could be more optimized by creating a separate function for moving a single piece
for (int x = 0; x < 8; x++) {
for (int y = 0; y < 8; y++) {
for (int i = 0; i < 12; i++) {
if (board[y][x] == i) {
if (board[y][x] < 12) {
graphics->surface = IMG_Load(spritePath[i]);
graphics->texture = SDL_CreateTextureFromSurface(graphics->renderer, graphics->surface);
SDL_FreeSurface(graphics->surface);
graphics->rect.x = (x * tileSize);
graphics->rect.y = (y * tileSize);
graphics->rect.w = tileSize;
graphics->rect.h = tileSize;
SDL_RenderCopy(graphics->renderer, graphics->texture, NULL, &graphics->rect);
}
}
}
}
}
SDL_RenderPresent(graphics->renderer);
return;
}
int findMousePosX(int board[8][8], int mouseX, int tileSize, int boardSize, SDL_Event event) {
// Convert the raw mouse position to the chess board square the cursor is inside of
int rawPosX = event.motion.x;
for (int i = 0; i < boardSize; i += tileSize) {
if ((rawPosX >= i) && (rawPosX < (i + tileSize))) {
mouseX = (i / tileSize);
}
}
printf("X %d, ", mouseX);
return mouseX;
}
// This function is technically redundant. Consider attempting to merge this with the above function
int findMousePosY(int board[8][8], int mouseY, int tileSize, int boardSize, SDL_Event event) {
// Convert the raw mouse position to the chess board square the cursor is inside of
int rawPosY = event.motion.y; | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
performance, c, chess, sdl
for (int i = 0; i < boardSize; i += tileSize) {
if ((rawPosY >= i) && (rawPosY <= (i + tileSize))) {
mouseY = (i / tileSize);
}
}
printf("Y %d\n\n", mouseY);
return mouseY;
}
Answer: Reducing maintenance burden:
void drawBoard(gc*, int);
void updatePieces(gc*, int[8][8], int, const char*[12]);
int findMousePosX(int[8][8], int, int, int, SDL_Event);
int findMousePosY(int[8][8], int, int, int, SDL_Event);
We could avoid having to maintain these declarations by moving the function definitions here instead.
Declare variables as locally as possible:
int mouseX = 0;
int mouseY = 0;
bool madeSelection = false;
int selectedPiece = 0;
...
gc graphics;
gc* graphicsPtr = &graphics;
...
SDL_Event event;
It's reasonable to put the constants at the top of main(), but we should declare most variables as close to the point of use as possible. All of the variables above could be declared at least a few lines lower down, closer to where they are used. event could be inside the main loop.
Taking the address of an object is a common thing in C so we don't need really the graphicsPtr variable; it's more typing and conveys less meaning:
drawBoard(&graphics, tileSize);
Use enums to give meaning to values:
int board[8][8] = {
8, 7, 9, 10, 11, 9, 7, 8,
6, 6, 6, 6, 6, 6, 6, 6,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
12, 12, 12, 12, 12, 12, 12, 12,
0, 0, 0, 0, 0, 0, 0, 0,
2, 1, 3, 4, 5, 3, 1, 2
};
We should use an enum to give each piece a name and make the meaning obvious. Using "magic numbers" like the above is more error-prone, and involves more work for the programmer looking up the values.
It might also be more convenient to separate the piece and color information into two separate variables in a Piece struct, something like:
enum PieceType { Pawn, Knight ... };
enum PieceColor { Light, Dark }; | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
performance, c, chess, sdl
struct Piece { enum PieceType type; enum PieceColor color; };
And then we could declare the board as an array of Pieces instead of ints.
Check for errors:
SDL_Init(SDL_INIT_EVERYTHING);
IMG_Init(IMG_INIT_PNG);
graphics.window = SDL_CreateWindow("Chess!", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, boardSize, boardSize, 0);
graphics.renderer = SDL_CreateRenderer(graphics.window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
These function calls can all fail. We need to check that and handle the error instead of just carrying on. Since we're in the main() function, the simplest thing to do would be to print an error message, and return EXIT_FAILURE;.
Simplify input handling:
switch (event.type) {
case SDL_MOUSEMOTION:
mouseX = findMousePosX(board, mouseX, tileSize, boardSize, event); // Temporary solution. Update later. // Updated. Works better. Could be more optimized?
mouseY = findMousePosY(board, mouseY, tileSize, boardSize, event); // ^
break;
case SDL_MOUSEBUTTONDOWN:
if (madeSelection == false) {
selectedPiece = board[mouseY][mouseX];
board[mouseY][mouseX] = 12; // Sprite of moved piece is not rendered in original position
}
else if (madeSelection == true) {
board[mouseY][mouseX] = selectedPiece;
}
break;
case SDL_MOUSEBUTTONUP:
if (madeSelection == false) {
madeSelection = true;
}
else if (madeSelection == true) {
drawBoard(graphicsPtr, tileSize);
updatePieces(graphicsPtr, board, tileSize, spritePath);
madeSelection = false;
}
break;
} | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
performance, c, chess, sdl
SDL_MOUSEBUTTONDOWN and SDL_MOUSEBUTTONUP also make the mouse position (and various other data) available in the event struct. So it might be neater to get the position when we get a mouse button event, rather than a mouse motion event.
When testing a boolean variable, we don't need to compare to true or false to produce a boolean value; it's already a boolean! Also, we don't need an else if to check the opposite condition:
if (!madeSelection) {
...
}
else {
...
}
I haven't run the program, but the code for selecting and moving a piece looks a bit suspicious. Is it supposed to be a "click and drag" style movement? Or a click once to select, and click again to move? Either way, I suggest grouping the selection variables (madeSelection, selectedPiece) into a single struct, and moving the logic of selecting a piece into a separate function.
So for a drag-to-move we'd get something like:
case SDL_MOUSEBUTTONDOWN:
if (!selection.active)
{
int mouseX = findMousePosX(...);
int mouseY = findMousePosY(...);
selectPiece(board, &selection, mouseX, mouseY);
}
case SDL_MOUSEBUTTONUP:
if (selection.active)
{
int mouseX = findMousePosX(...);
int mouseY = findMousePosY(...);
movePiece(board, &selection, mouseX, mouseY);
}
Note that we shouldn't be doing rendering inside the event / update logic. It should be done once per frame, at the end of the frame. While we could use a boolean flag to avoid "unnecessary" rendering when nothing has changed, it wouldn't really help us: we're still using a "busy" waiting loop while polling input from SDL.
Simplifying mouse position: | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
performance, c, chess, sdl
Simplifying mouse position:
int findMousePosX(int board[8][8], int mouseX, int tileSize, int boardSize, SDL_Event event) {
// Convert the raw mouse position to the chess board square the cursor is inside of
int rawPosX = event.motion.x;
for (int i = 0; i < boardSize; i += tileSize) {
if ((rawPosX >= i) && (rawPosX < (i + tileSize))) {
mouseX = (i / tileSize);
}
}
printf("X %d, ", mouseX);
return mouseX;
}
It doesn't look like we need to pass board or mouseX into this function.
It would be much better to pass the mouse pixel position in as an integer, rather than passing the entire SDL_Event struct. An SDL_MOUSEMOTION event might store the x position at event.motion.x, but SDL_MOUSEBUTTON_DOWN and SDL_MOUSEBUTTON_UP will store it at event.button.x. Passing the position as an integer would also avoid the need for two separate functions for x and y.
We can also calculate the position directly instead of looping:
int pixelToBoardPos(int tileSize, int pixelPos) {
return pixelPos / tileSize;
}
If we want to do bounds checking to ensure the mouse is over the board, we should probably do that before we pass the pixel position into this function.
Load once, render every frame:
void drawBoard(gc* graphics, int tileSize) { ... }
void updatePieces(gc* graphics, int board[8][8], int tileSize, const char* spritePath[12]) { ... } | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
performance, c, chess, sdl
Both of these functions are doing something they definitely shouldn't do: loading textures from disk every single time they're called! Reading from (or writing to) disk is very slow.
We have an array of paths for the pieces that we create once at the start: const char* spritePath[12] = { ... }. After initializing SDL, we can easily create another array of SDL_Texture*s to hold all our images, and pass it into the functions that need it. We can load the background images for the squares in a similar way.
Note that we should be calling SDL_RenderPresent() only once per frame. i.e.:
// main loop:
while (1) {
// input / update logic:
...
// rendering:
drawBoard(...);
drawPieces(...);
SDL_RenderPresent(graphics.renderer);
}
Don't reuse variables:
typedef struct GraphicsComponents {
SDL_Window* window;
SDL_Renderer* renderer;
SDL_Surface* surface;
SDL_Texture* texture;
SDL_Rect rect;
}gc;
Lastly, note that it's unnecessary (and misleading) to keep and reuse the surface, texture and rect variables here. They should all be local variables inside the functions that need them. | {
"domain": "codereview.stackexchange",
"id": 42803,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, chess, sdl",
"url": null
} |
beginner, c
Title: CS50 mario printing pyramids without using "CS50 library"
Question: I am new to programming and I've only learnt basics of C as far as functions.
I decided to solve this problem given in Harvard CS50 course. Please review my code.
We had to write a program which takes a height from the user and prints a pyramid of that height.
How the program might work if the user inputs 8 when prompted:
$ ./mario
Height: 8
# #
## ##
### ###
#### ####
##### #####
###### ######
####### #######
######## ########
My code:
#include <stdio.h>
void pattern(int n, int temp); // function prototype
int main()
{
int height, same_as; // same_as is just a temporary variable
printf("Enter the height \n");
while (1)
{
scanf("%d", &height);
if (height >= 1 && height <= 8) // if height is between 1 and 8
break;
else
printf("Height = %d\n", height);
}
same_as = height;
printf("Height = %d\n", height);
pattern(height, same_as);
return 0;
}
// definition of the function
void pattern(int n, int temp)
{
int i; // i is the counter
// printing the first line
if (n == 1)
{
for (i = 0; i != 2 * temp + 1; i++)
{
if (i == temp - 1 || i == temp + 1)
{
printf("#");
}
else if (i == temp)
{
printf(" ");
}
else if (i > temp + 1)
break;
else
printf(" ");
}
printf("\n");
return;
}
else
{
pattern(n - 1, temp);
// for loop to print each line
for (i = 0; i != 2 * temp + 1; i++)
{
// all the places where we print # in the same line
if (i >= temp - n && i <= temp + n && i != temp) // very important
{
printf("#");
} | {
"domain": "codereview.stackexchange",
"id": 42804,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c",
"url": null
} |
beginner, c
else if (i == temp)
{
printf(" ");
}
else if (i > temp + n)
break;
else
printf(" ");
}
printf("\n");
}
}
Answer: When you use scanf(), it's really important to inspect its return value before using any of the values you intended it to assign to.
For instance, try entering a non-number: it will loop continuously re-trying to parse the invalid input.
It's probably better to give up if input can't be parsed, certainly at this stage of your C career (really robust input handling is an advanced topic).
if (scanf("%d", &height) != 1) {
fputs("Sorry, I didn't understand you.\n", stderr);
return EXIT_FAILURE;
}
Note: we need to include <stdlib.h> to define the return value there.
The extra variable same_as is unnecessary:
pattern(height, height);
It's not clear what the temp parameter is for:
void pattern(int n, int temp)
It really needs a better name.
(partial review - I might get time to return to this) | {
"domain": "codereview.stackexchange",
"id": 42804,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
Title: Accessing multiple dynamic libraries with the same extern C methods
Question: I have multiple pre-compiled dynamic libraries that use the same extern "C" function names. The functions can behave differently for each dynamic library. Ultimately these methods will be accessed in a SystemVerilog simulation via DPI (Direct Program Interface).
When trying to link all the libraries to my simulator, I noticed that the visibility of the methods is dependent on link order. This blocks me from accessing the desired method of the same name if it is not the first library.
One solution would have been to require each extern "C" function to have a unique name. But this fails in my case for two reasons:
I do not own the source code of the dynamic libraries. I can make requests, but there is no guarantee whether or when they will be fulfilled.
It would add a lot of verbosity and static code to my SystemVerilog code as each component would need to figure out which DPI method it needs to access. It also doesn't scale well if a library is added or removed.
My solution is to create my own dynamic library that uses dlopen() and dlsym() (from dlfcn.h) to dynamically access methods from the pre-compiled dynamic libraries. Fortunately, all the pre-compiled library flavors use the same root class. They also contain a publicly accessible variable identifying the compiled flavor. I can use this identifier to decide which library to dynamically reference.
I cannot share the real code. Bellow is a runnable proof of concept. I am getting the desired output. It has been a few years since I have done this kind of coding with C++, so I'm hoping I not missing something.
my_model.h
#include <stdio.h>
#include <iostream>
#include <unordered_map>
#define CONCAT_(A, B) A ## B
#define CONCAT(A, B) CONCAT_(A, B)
#define EXPORTED __attribute__((visibility("default")))
#ifndef FLAVOR
#define FLAVOR PASSION
#endif | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
namespace my_ns{
enum Flavor { PASSION=0, ORANGE=1, GUAVA=2, POG=-1 };
class my_model {
public:
my_model(int cfg);
virtual ~my_model() { close(); }
virtual void close() { um.clear(); }
virtual int get_info(std::string key, int* value) { return -1; }
virtual int set_info(std::string key, int value) { return -1; }
virtual int del_info(std::string key) { return -1; }
const Flavor flavor = FLAVOR;
protected:
std::unordered_map<std::string,int> um;
};
#if FLAVOR>=0
class CONCAT(my_model_,FLAVOR) : public my_model {
public:
CONCAT(my_model_,FLAVOR)(int cfg) : my_model(cfg) {}
virtual int get_info(std::string key, int* value);
virtual int set_info(std::string key, int value);
virtual int del_info(std::string key);
};
#endif
extern "C" {
int EXPORTED create_model(void** model_h, int flavor, int cfg);
int EXPORTED delete_model(void** model_h);
int EXPORTED get_info(const void* model_h, const char* key, int* value);
int EXPORTED set_info(const void* model_h, const char* key, int value);
int EXPORTED del_info(const void* model_h, const char* key);
}
}
my_model.cpp
#include "my_model.h"
namespace my_ns {
my_model::my_model(int cfg) {
um["cfg"] = cfg;
um["flavor"] = static_cast<int>(FLAVOR);
printf("Info: cfg:%0d FLAVOR:%0d (%s:%s:%d)\n", um["cfg"],FLAVOR,__func__,__FILE__,__LINE__);
} | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
int CONCAT(my_model_,FLAVOR)::get_info(std::string key, int* value) {
printf("Info: %s(%s,%%d) : %s:%d\n", __func__,key.c_str(), __FILE__,__LINE__);
if (um.count(key)==0) return -1;
*value = um[key] + static_cast<int>(FLAVOR);
return 0;
}
int CONCAT(my_model_,FLAVOR)::set_info(std::string key, int value) {
printf("Info: %s(%s,%0d) : %s:%d\n", __func__,key.c_str(),value, __FILE__,__LINE__);
um[key] = value * um["cfg"] * um["cfg"];
return 0;
}
int CONCAT(my_model_,FLAVOR)::del_info(std::string key) {
printf("Info: %s(%s):%s:%d)\n", __func__,key.c_str(), __FILE__,__LINE__);
if (um.count(key)==0) return -1;
um.erase(key);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
int create_model(void** model_h, int flavor, int cfg) {
printf("Info: cfg:%0d FLAVOR:%d (%s:%s:%d)\n", cfg, FLAVOR, __func__,__FILE__,__LINE__);
*model_h = (void*) new CONCAT(my_model_,FLAVOR)(cfg);
return (!*model_h ? -1 : 0);
}
int delete_model(void** model_h) {
CONCAT(my_model_,FLAVOR)* _model = (CONCAT(my_model_,FLAVOR)*) *model_h;
if (!_model) { fprintf(stderr, "Error: NULL model_h"); return -1; }
delete _model;
*model_h = (void*) NULL;
return 0;
}
int get_info(const void* model_h, const char* key, int* value) {
CONCAT(my_model_,FLAVOR)* _model = (CONCAT(my_model_,FLAVOR)*) model_h;
if (!_model) { fprintf(stderr, "Error: NULL model_h"); return -1; }
return _model->get_info(std::string(key), value);
}
int set_info(const void* model_h, const char* key, int value) {
CONCAT(my_model_,FLAVOR)* _model = (CONCAT(my_model_,FLAVOR)*) model_h;
if (!_model) { fprintf(stderr, "Error: NULL model_h"); return -1; }
return _model->set_info(std::string(key), value);
}
int del_info(const void* model_h, const char* key) {
CONCAT(my_model_,FLAVOR)* _model = (CONCAT(my_model_,FLAVOR)*) model_h;
if (!_model) { fprintf(stderr, "Error: NULL model_h"); return -1; }
return _model->del_info(std::string(key));
}
}
my_top.cpp
#include "my_model.h"
#include <dlfcn.h>
namespace my_ns {
my_model::my_model(int cfg) {} | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
my_model::my_model(int cfg) {}
const char lib[3][16] = {"./libPassion.so","./libOrange.so","./libGuava.so"};
void *my_so[3];
int link_so(Flavor flavor) {
if (my_so[flavor] == NULL) {
printf("linking %s (%s:%s:%d)\n", lib[flavor], __func__,__FILE__,__LINE__);
my_so[flavor] = dlopen(lib[flavor], RTLD_NOW);
}
if (!my_so[flavor]) {
/* fail to load the library */
fprintf(stderr, "Error: %s\n", dlerror());
return -1;
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
int create_model(void** model_h, int flavor, int cfg) {
link_so(static_cast<Flavor>(flavor));
int (*dlsym_create_model)(void** model_h, int flavor, int cfg);
*(void**)(&dlsym_create_model) = dlsym(my_so[flavor], "create_model");
return dlsym_create_model(model_h, flavor, cfg);
}
int delete_model(void** model_h) {
my_model* _model = (my_model*) model_h;
link_so(_model->flavor);
int (*dlsym_delete_model)(void** model_h);
*(void**)(&dlsym_delete_model) = dlsym(my_so[_model->flavor], "delete_model");
return dlsym_delete_model(model_h);
}
int get_info(const void* model_h, const char* key, int* value) {
my_model* _model = (my_model*) model_h;
link_so(_model->flavor);
int (*dlsym_get_info)(const void* model_h, const char* key, int* value);
*(void**)(&dlsym_get_info) = dlsym(my_so[_model->flavor], "get_info");
return dlsym_get_info(model_h, key, value);
}
int set_info(const void* model_h, const char* key, int value) {
my_model* _model = (my_model*) model_h;
link_so(_model->flavor);
int (*dlsym_set_info)(const void* model_h, const char* key, int value);
*(void**)(&dlsym_set_info) = dlsym(my_so[_model->flavor], "set_info");
return dlsym_set_info(model_h, key, value);
}
int del_info(const void* model_h, const char* key) {
my_model* _model = (my_model*) model_h;
link_so(_model->flavor);
int (*dlsym_del_info)(const void* model_h, const char* key);
*(void**)(&dlsym_del_info) = dlsym(my_so[_model->flavor], "del_info");
return dlsym_del_info(model_h, key);
}
} | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
my_dpi.sv
package my_dpi_pkg;
import "DPI-C" function int create_model( output chandle handle, input int flavor, cfg );
import "DPI-C" function int delete_model( inout chandle handle );
import "DPI-C" function int get_info( input chandle handle, input string key, output int value );
import "DPI-C" function int set_info( input chandle handle, input string key, input int value );
import "DPI-C" function int del_info( input chandle handle, input string key );
endpackage : my_dpi_pkg
module tb;
import my_dpi_pkg::*;
initial begin
chandle passion_h,orange_h, guava_h;
string str;
int flavor,val;
$display("Create");
assert(create_model(passion_h, 0, 10)==0);
assert(create_model( orange_h, 1, 16)==0);
assert(create_model( guava_h, 2, 8)==0);
$display("\nInfo via set_info()");
assert(set_info(passion_h, "alpha", 'd13)==0);
assert(set_info( orange_h, "beta", 'h13)==0);
assert(set_info( guava_h, "gamma", 'o13)==0);
$display("\nInfo via get_info()");
assert(get_info(passion_h,"flavor", flavor)==0);
assert(get_info(passion_h,"alpha", val)==0);
$display("passion_h flavor:%0d, alpha:'d%0d",flavor,val);
assert(get_info(orange_h,"flavor", flavor)==0);
assert(get_info(orange_h,"beta", val)==0);
$display("orange_h flavor:%0d, beta:'h%0h",flavor,val);
assert(get_info(guava_h,"flavor", flavor)==0);
assert(get_info(guava_h,"gamma", val)==0);
$display("guava_h flavor:%0d, gamma:'o%0o",flavor,val);
assert(get_info(guava_h,"cfg", flavor)==0);
val = 0;
assert(get_info(guava_h,"alpha", val)==-1);
$display("guava_h cfg:%0d, alpha:'d%0d",flavor,val);
$display("Delete");
assert(delete_model(passion_h)==0);
assert(delete_model(orange_h)==0);
assert(delete_model(guava_h)==0);
$finish(0);
end
endmodule | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
$finish(0);
end
endmodule
Commands to build and run:
g++ -fvisibility=hidden -fvisibility-inlines-hidden -s -shared -fPIC -std=gnu++11 -DFLAVOR=PASSION -o libPassion.so my_model.h my_model.cpp -Wall -g || exit 1
g++ -fvisibility=hidden -fvisibility-inlines-hidden -s -shared -fPIC -std=gnu++11 -DFLAVOR=ORANGE -o libOrange.so my_model.h my_model.cpp -Wall -g || exit 1
g++ -fvisibility=hidden -fvisibility-inlines-hidden -s -shared -fPIC -std=gnu++11 -DFLAVOR=GUAVA -o libGuava.so my_model.h my_model.cpp -Wall -g || exit 1
g++ -fvisibility=hidden -fvisibility-inlines-hidden -s -shared -fPIC -std=gnu++11 -DFLAVOR=POG -o libPOG.so my_model.h my_top.cpp -Wall -g
<sv_simulator> -<dpi_keyword> libPOG.so my_dpi.sv
Output:
Create
linking ./libPassion.so (link_so:my_top.cpp:11)
Info: cfg:10 FLAVOR:0 (create_model:my_model.cpp:29)
Info: cfg:10 FLAVOR:0 (my_model:my_model.cpp:7)
linking ./libOrange.so (link_so:my_top.cpp:11)
Info: cfg:16 FLAVOR:1 (create_model:my_model.cpp:29)
Info: cfg:16 FLAVOR:1 (my_model:my_model.cpp:7)
linking ./libGuava.so (link_so:my_top.cpp:11)
Info: cfg:8 FLAVOR:2 (create_model:my_model.cpp:29)
Info: cfg:8 FLAVOR:2 (my_model:my_model.cpp:7)
Info via set_info()
Info: set_info(alpha,13) : my_model.cpp:17
Info: set_info(beta,19) : my_model.cpp:17
Info: set_info(gamma,11) : my_model.cpp:17
Info via get_info()
Info: get_info(flavor,%d) : my_model.cpp:11
Info: get_info(alpha,%d) : my_model.cpp:11
passion_h flavor:0, alpha:'d1300
Info: get_info(flavor,%d) : my_model.cpp:11
Info: get_info(beta,%d) : my_model.cpp:11
orange_h flavor:2, beta:'h1301
Info: get_info(flavor,%d) : my_model.cpp:11
Info: get_info(gamma,%d) : my_model.cpp:11
guava_h flavor:4, gamma:'o1302
Info: get_info(cfg,%d) : my_model.cpp:11
Info: get_info(alpha,%d) : my_model.cpp:11
guava_h cfg:10, alpha:'d0
Delete
./my_dpi.sv:42 $finish(0); | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
Answer: The code looks correct. It looks like a weird mix of C and C++ though.
Assumptions
There was a statement that they share the same base class, but I am not sure what it means if they all use C style interface (not only linkage, but dealing in void*). I will assume that the library only has the free standing functions and classes are free for modification.
The ABI looks quite safe with it using only C style built in types, so I will assume that ABI needs to be preserved.
Code Review
Dangers of dynamic loading. Dynamic loading has a lot of weird implicit behavior. If there are common dependency libraries and they have different versions, it is one way ticket to DLL hell. dlclose is also tricky because calling it can actually leave the library linked because it is a dependency to something else. There is also RPATH vs RUNPATH vs environment variables (LD_PRELOAD, LD_LIBRARY_PATH) vs system wide config ... Well, it is a pain to deal with dynamic loading.
Not using RTLD_LOCAL. If there is a common dependency symbol and one has it defined and the other does not, instead of failing it will silently link the wrong one.
Inefficiency. The code always dlsyms on a function call. It would be better to link class member functions once and reuse the retrieved function pointer.
Propagating C style interface. Is the code meant to be used on C++ side? If so, I believe it would be better to use C++ style error handling (there is expected library and std::optional with error code taken as reference, or straight up exceptions if they are supported). The reason I'm saying this is that the classes provide minimal abstraction even if it seems they could do more. | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
"Sticking out" symbols. I believe it would be better to not declare the functions to be linked from the loaded libraries. The last time I used dynamic loading I just declared a local function pointer variable and casted the result of dlsym. When the functions are declared, they might be accidentally linked and then cause some confusion. It is better to not expose symbols to be dynamically loaded to avoid accidental linkage.
No lifetime management. If libraries are loaded and unloaded, it is important to keep track of instances that use to-be-unloaded library. If the binary for the function to be called is unloaded then the program will terminate, probably with SIGSEGV as the page containing the binary does not belong to the process.
Better abstraction
I cannot believe I'm saying this, but GObject architecture looks good here. The idea is that the class needs to be loaded and linked exactly once, afterwards the function pointers will be reused. I did this outside of GObject where I had a factory function dlsymed and retrieve all of the information from there. After dlopening another one I would just ask for another factory function pointer. It just worked.
The idea is to deal in local pointers that the linker does not see, otherwise it will think we want to link it to something. The function definitions need to be in cpp file, I wrote them inline for brevity (overall it is untested sketch code to illustrate the proposed interface with some implementation guidelines). | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
class Model {
public:
virtual int get_info(std::string_view key, int* value) = 0;
virtual void set_info(std::string_view key, int value) = 0;
virtual bool del_info(std::string_view key) = 0;
virtual ~Model() {}
};
class ModelClass {
const Flavor flavour;
void* so_handle;
int (*create_model)(void**, int, int);
/* and the others */
public:
ModelClass(const ModelClass& other) = delete;
ModelClass& operator=(const ModelClass& other) = delete;
/* move operations are automatically deleted due to copy being deleted too*/
std::unique_ptr<Model> create_instance(/*args?*/) {
/*call the linked function and wrap it in something depending on the flavor,
cpp file will hide the definition of the class so the class is better defined there*/
}
Flavour get_flavour() const noexcept;
~ModelClass() {
/*unload the library, preferably track if no instances of this class are left out*/
}
private:
ModelClass(const char* lib_path) {
so_handle = dlopen(lib_path, RTLD_NOW | RTLD_LOCAL);
if (!so_handle) {
throw std::runtime_error(dlerror());
}
create_model = reinterpret_cast<int (*)(void**, int, int)>(dlsym(so_handle), "create_model");
if (!create_model) {
throw runtime_error(dlerror());
}
/*link the rest*/
}
};
There is also unncessary copying when passing std::string by value where it is clearly meant to be read only. As JDługosz mentioned, it should std::string_view.
After having all of the above, one could create a manager class and befirend them with ModelClass. The manager can be a singleton that will load everything needed at program start providing either static variables of ModelClass or a map if needed. The manager class could store the paths, constants for function names, etc. | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
c++, c++11, library, dynamic-loading, system-verilog
If Boost.DLL is an option, I would just use that. I do not have experience with it, but I believe it should contain the boilerplate I wrote above. | {
"domain": "codereview.stackexchange",
"id": 42805,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, library, dynamic-loading, system-verilog",
"url": null
} |
python, beginner, tic-tac-toe
Title: Variable Grid Size Tic Tac Toe
Question: Tic-Tac-Toe from scratch. Code Ugliness check before I implement the win-condition and maybe get set in to bad habits.
Questions:
As implemented:
Better to pass board between functions or set as a global variable?
OK to use same variable name within different functions?
OOP:
Would you recommend using Object Orientated Programming for this?
import sys
import copy
import random
#this function accepts a user input if it's contained in a list
def get_user_input(input_array,prompt):
valid_input = False
#the purpose of this is to convert a range() to list
acceptable_input_array = list(copy.copy(input_array))
for i,element in enumerate(acceptable_input_array):
#convert elements in array to string
acceptable_input_array[i] = str(element).upper()
while not valid_input:
print("Please enter choice of",
acceptable_input_array,
"for",
prompt,
", blank to cancel.")
user_input = input()
user_input = user_input.upper()
#if blank input
if user_input == '':
#exit program
print('Exiting program.')
sys.exit()
#if input is in acceptable input
if(user_input in acceptable_input_array):
valid_input = True
else:
print('Incorrect Input')
return user_input | {
"domain": "codereview.stackexchange",
"id": 42806,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, tic-tac-toe",
"url": null
} |
python, beginner, tic-tac-toe
#this function simply prints the board state
def print_board(board):
#0 is blank, 1 is X, 2 is O
token = ''
for i, element in enumerate(board):
if element == 1:
token = 'X'
elif element == 2:
token = 'O'
else:
token = ' '
position = i%BOARD_SIZE
#position = 0 is leftmost
if position == 0:
#print numberals at left of table
print(i//BOARD_SIZE,end='')
#.center to make an equidistant board
print(token.center(BOARD_SIZE), end='')
print('|',end='')
#position BOARD_SIZE - 1 is rightmost
if position == BOARD_SIZE - 1:
#print newline
print()
#each token has BOARD_SIZE + BOARD_SIZE^2 spacing
print('-' * (BOARD_SIZE + BOARD_SIZE**2))
print(' ',end='')
for j in range(BOARD_SIZE):
#print numerals at bottom of table
print(str(j).center(BOARD_SIZE+1),end='')
print()
#this function accepts co-ordinates from player then updates board
def player_turn(board):
valid_coords = False
while not valid_coords:
i = int(get_user_input(range(BOARD_SIZE),'i co-ordinate'))
j = int(get_user_input(range(BOARD_SIZE),'j co-ordinate'))
print('You selected position [', i, j, ']')
index = j*BOARD_SIZE + i
#if not already X or O in position
if(board[index] == 0):
valid_coords = True
else:
print('Spot already taken, please enter valid co-ordiantes.')
board[index] = 1
print_board(board) | {
"domain": "codereview.stackexchange",
"id": 42806,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, tic-tac-toe",
"url": null
} |
python, beginner, tic-tac-toe
board[index] = 1
print_board(board)
#this function chooses a random free space for a.i. turn
def cpu_turn(board):
print('cpu turn')
list_of_indices = []
for i, element in enumerate(board):
if(element == 0):
list_of_indices.append(i)
print(list_of_indices)
random_index = random.choice(list_of_indices)
print('random index: ', random_index)
board[random_index] = 2
print_board(board)
#variable board size, based on user input.
BOARD_SIZE = int(get_user_input([3,5,7],'board size'))
#create empty list board with length of BOARD_SIZE squared
#board represented by a 1D array
board = [0] * BOARD_SIZE**2
print_board(board)
print("You are playing as 'X'")
while True:
player_turn(board)
cpu_turn(board)
Answer: Answers to the explicit questions
Better to pass board between functions or set as a global variable?
I'd recommend against global variables, since accessing those will lead to side-effects within your functions. Either pass the object to pure functions or create an instance of the board as a property of some superordinate Game class.
OK to use same variable name within different functions?
This is perfectly fine.
Would you recommend using Object Orientated Programming for this?
Programming paradigms should be selected based on the problem to solve. Python is a multi-paradigm language. You can use functional or OO programming and mix those. You should use the paradigm that most fittingly solves your problem at hand. That being said, your functional approach is absolutely reasonable.
General review
PEP 8
Read and apply PEP8.
Your code especially can be improved by applying the recommended whitespace rules.
Do not translate values
You use 0, 1 and 2 for values on the board. Later you replace them with ' ', 'X'and 'O'. Why not use those values directly?
Even better, you can use an enum.Enum for those values:
from enum import Enum
class CellValue(Enum):
"""Cell values.""" | {
"domain": "codereview.stackexchange",
"id": 42806,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, tic-tac-toe",
"url": null
} |
python, beginner, tic-tac-toe
class CellValue(Enum):
"""Cell values."""
EMPTY = ' '
PLAYER = 'X'
CPU = 'O'
Suboptimal code
This:
...
#the purpose of this is to convert a range() to list
acceptable_input_array = list(copy.copy(input_array))
for i,element in enumerate(acceptable_input_array):
acceptable_input_array[i] = str(element).upper()
can be siplified to this:
acceptable_input = [str(element) for element in input_array]
And since you use it for a membership check, you can use a set instead of a list:
acceptable_input = {str(element) for element in input_array}
Since all elements of the range are ints anyway, calling str.upper() on their string representation is pretty useless.
Pro tip: If you want to compare strings case-insensitively, use str.casefold().
Use early return in loops
Instead of using a boolean loop variable, use an infinte loop with conditional return. I.e. instead of:
while not valid_input:
...
if(user_input in acceptable_input_array):
valid_input = True
else:
print('Incorrect Input')
Write:
while True:
...
if user_input in acceptable_input_array:
return user_input
print('Incorrect Input')
Know your functions
The built-in input() takes an optional prompt as string.
So instead of
print("Please enter choice of",
acceptable_input_array,
"for",
prompt,
", blank to cancel.")
user_input = input()
You can write
user_input = input(
"Please enter choice of "
f"{acceptable_input_array} for "
f"{prompt}, blank to cancel."
)
Naming
The parameter input_array of get_user_input() is not an array. In fact, there are no arrays at all in plain python. Since the parameter is a range, it should be called input_range.
Outsource common operations into functions
A common task is to filter the indices of free cells on the board. Write a function for that:
def get_free_indices(board):
"""Yields indices of free fields on the board.""" | {
"domain": "codereview.stackexchange",
"id": 42806,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, tic-tac-toe",
"url": null
} |
python, beginner, tic-tac-toe
for index, field in enumerate(board):
if field == 0: # or: if field is CellValue.EMPTY:
yield index
main() function and the __main__ guard
Consider putting your running code into a main() function, that you call under the infamous if __name__ == '__main__': guard:
def main():
"""Play the game."""
BOARD_SIZE = int(get_user_input([3,5,7],'board size'))
board = [0] * BOARD_SIZE**2
print_board(board)
print("You are playing as 'X'")
while True:
player_turn(board)
cpu_turn(board)
if __name__ == '__main__':
main()
Comments
Comment what needs clarification. Don't comment what the code does. Anybody can see this by reading the code itself. Comment why your code does things, if and only if it is not obvious. All of your comments can be removed.
Docstrings
Don't document your functions with comments before them. Use docstrings instead.
This:
#this function accepts a user input if it's contained in a list
def get_user_input(input_array,prompt):
valid_input = False
...
should be:
def get_user_input(input_range, prompt):
"""Read user input and validate it for free fields."""
valid_input = False
... | {
"domain": "codereview.stackexchange",
"id": 42806,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, tic-tac-toe",
"url": null
} |
json, web-scraping, xpath, xslt
Title: Using XSLT 3.0 to extract information from real-world HTML and produce JSON | {
"domain": "codereview.stackexchange",
"id": 42807,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "json, web-scraping, xpath, xslt",
"url": null
} |
json, web-scraping, xpath, xslt
Question: For work, I extract information from HTML and XML sources to save in databases. The objective is to generate JSON representing the source document's information and its relationships in order to 1) extract key information for database columns, like the title of a court case, and 2) to save the whole resulting JSON structure in a PostgreSQL JSONB column for possible later reference.
Normally this is done piecemeal using Xpaths with the lxml.etree or lxml.html libraries in Python, which our system is written in, but we wanted to try solutions using XSLT 3.0 and Xpath 3.1, which they do not support.
I'm mainly asking for feedback on the XSLT, but for context, this is what's happening:
The solution we hit on is to invoke the saxon-js processor for nodejs from within Python with check_output(), capture the output, and load it as JSON.
This is the input. It's a version of https://pubapps2.usitc.gov/337external/4921 run through Python's lxml.html.clean, parsed, and output again with html.tostring(root, method='xml') in order to make it parsable with XSLT. saxon-js is being run with the -ns:##html5 option to simplify the Xpath namespaces.
<html:div xmlns:html="http://www.w3.org/1999/xhtml">
<!--2.5-->
<html:meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
Investigation Detail
<html:meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<html:link rel="shortcut icon" href="/337external/static/images/favicon.ico" type="image/x-icon"/>
<html:link rel="apple-touch-icon" href="/337external/static/images/apple-touch-icon.png"/>
<html:link rel="apple-touch-icon" sizes="114x114" href="/337external/static/images/apple-touch-icon-retina.png"/>
<!-- <link rel="stylesheet" href="/337external/static/css/main.css" type="text/css">--> | {
"domain": "codereview.stackexchange",
"id": 42807,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "json, web-scraping, xpath, xslt",
"url": null
} |
json, web-scraping, xpath, xslt
<html:div id="page-wrap">
<html:div id="header">
<html:div id="agencytitle">
<html:h1>United States<html:br/>
International Trade Commission</html:h1>
</html:div>
<html:div id="agencytitle" style="width:inherit;">
<html:h1 style="font-size: xx-large;">337Info</html:h1>
</html:div>
<html:div id="topnav">
<html:ul>
<html:li><html:a href="/337external/">Home</html:a></html:li>
<html:li class="help"><html:a href="/337external/advanced">Advanced Search</html:a></html:li>
<html:li class="help"><html:a href="http://www.usitc.gov/documents/337Info_FAQ.pdf" target="_blank">FAQ</html:a></html:li>
<html:li class="help"><html:a href="/337external/help">Help</html:a></html:li>
<html:li class="help"><html:a href="http://www.usitc.gov/documents/337Info_tutorial.pptx" target="_blank">Tutorial</html:a></html:li>
<html:li class="help"><html:a href="mailto:337InfoHelp@usitc.gov?subject=337Info%20External%20help">Contact Us</html:a></html:li>
<html:li class="help"><html:a href="/337external/disclaimer">Disclaimer</html:a></html:li>
</html:ul>
</html:div>
</html:div>
<html:div id="inside">
<html:div id="detail-main-content">
<html:div id="main-filter-content"><html:h2> Summary Investigation Information</html:h2></html:div>
<html:div id="main-detail-window"> | {
"domain": "codereview.stackexchange",
"id": 42807,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "json, web-scraping, xpath, xslt",
"url": null
} |
json, web-scraping, xpath, xslt
<html:div id="main-detail-window">
<html:div style="float:right">
<html:p>
<html:span style="font-weight:bolder">Investigation Number:</html:span>
<html:span style="margin-left:.5em;">337-TA-1185</html:span>
</html:p>
<html:p>
<html:span style="font-weight:bolder">Investigation Type:</html:span>
<html:span style="margin-left:.5em;"> Violation</html:span>
</html:p>
<html:p>
<html:span style="font-weight:bolder">Docket Number:</html:span>
<html:span style="margin-left:.5em;"> 3418</html:span>
</html:p>
<html:p>
<html:span style="font-weight:bolder">Investigation Status:</html:span>
<html:span style="margin-left:.5em;"> Terminated</html:span>
</html:p>
</html:div>
<html:div id="titlecontainer">
<html:p><html:span style="font-weight:bolder">Title (In the Matter of Certain):</html:span></html:p>
<html:h2>Certain Smart Thermostats, Smart HVAC Systems, and Components Thereof; Inv. No. 337-TA-1185</html:h2>
</html:div>
</html:div>
<!--Start right-container -->
<html:div id="right-filter">
<html:div id="right-filter-content-detail2"><html:h2><html:img src="/337external/static/images/scheduled.png" width="24" height="20" alt="People Icon"/>Procedural History</html:h2></html:div>
<!-- START of Prcedural history -->
<html:div id="returned-detail-content"> | {
"domain": "codereview.stackexchange",
"id": 42807,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "json, web-scraping, xpath, xslt",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.