text
stringlengths
1
2.12k
source
dict
javascript, html, css document.getElementById('r3').innerHTML = typeof(t) == 'string' || typeof(g) == 'string' ? `Reinput and try again` : m == 100 ? `If you lose ${down} you will have a 90%` : Math.sign(up) == -1 ? `If you lose ${Math.abs(Math.round((t-g)*100)/100)} points you will have a 100%` : g == 0 ? `You have no points, I hope you get that up :D` : `${g == 69 && x == 'F' || g == 420 && x == 'F' ? `Nice i` : `I`}f you lose ${down === 0 ? 1 : down} points you'll ${x == 'F' ? `have a zero`:`go down to the next letter grade ${grade(m-10)}`}` //A lot of stuff used for user information for the amount of points you need to go down a letter grade.
{ "domain": "codereview.stackexchange", "id": 42600, "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": "javascript, html, css", "url": null }
javascript, html, css } document.getElementById("btn").onclick = function() { document.getElementById('m').style.display = "block" } document.getElementsByClassName("close")[0].onclick = function() { document.getElementById('m').style.display = "none"; } window.onclick = function(event) { if (event.target == document.getElementById('m')) { document.getElementById('m').style.display = "none"; } } body { background-color: #f0efda; } .inputs { display: flex; justify-content: center; } .footnote { font-size: 12px; user-select: none; color: slategray; position: fixed; bottom: 0; left: 5px; } p { display: flex; justify-content: center; } input { width: 100px; height: 20px; } .input { line-height: 50px; display: inline-block; } .grid { background: #333; display: grid; text-align: center; grid-template-columns: 75% 1fr; width: 95%; position: fixed; top: 5px; padding: 10px; } .grid b { text-align: left; user-select: none; border-right: 1px solid #bbb; font-size: 40px; color: white; } .grid a { display: flex; margin-left: 5%; padding-top: 12.5px; color: white; user-select: none; justify-content: center; align-content: center; } .grid a:hover { cursor: pointer; background-color: #111; } .modal { background-color: rgb(0, 0, 0); background-color: rgba(0, 0, 0, 0.4); display: none; position: fixed; z-index: 1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; } .modal-header { background: #333; display: grid; grid-template-columns: 90% 1fr; padding: 1px; } .modal-header span { display: flex; align-content: center;
{ "domain": "codereview.stackexchange", "id": 42600, "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": "javascript, html, css", "url": null }
javascript, html, css } .modal-header span { display: flex; align-content: center; justify-content: center; } .modal-content { background-color: #fefefe; margin: auto; user-select: none; padding: 20px; border: 1px solid #888; width: 80%; } .close { color: white; display: flex; margin-top: 7px; margin-right: 7px; font-size: 28px; font-weight: bold; } .close:hover, .close:focus { color: #000; text-decoration: none; cursor: pointer; } .button { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; transition-duration: 0.4s; } .button:hover { box-shadow: 0 12px 16px 0 rgba(0, 0, 0, 0.24), 0 17px 50px 0 rgba(0, 0, 0, 0.19); } .button2 { background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; transition-duration: 0.4s; } .info { color: white; border-right: 1px solid #bbb; margin: 5px; margin-left: 10px; text-align: left; font-size: 30px; } <body> <div class='inputs'> <div class='grid'> <b>Grade Calculator</b> <a id="btn">Info</a> </div> </div> <br><br><br><br> <div class='inputs'> <button class='button' onClick="Calc()" width="50px">Calculate</button> </div> <br> <div class='inputs'> <input class='align' type='text' id="g" autocomplete="off" maxlength="9" placeholder="Current Points"> /
{ "domain": "codereview.stackexchange", "id": 42600, "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": "javascript, html, css", "url": null }
javascript, html, css <input type='text' id="t" autocomplete="off" maxlength="9" placeholder="Total Points"> </div> <p id="r1"> This is your grade </p> <p id="r2"> If you gain this many points you'll go up to the next letter grade: </p> <p id="r3"> If you lose this many points you'll go down to the next letter grade: </p> <div id='m' class='modal'> <div class="modal-content"> <div class = 'modal-header'> <b class='info'b>Info</b> <span class="close">&times;</span> </div> <p class='input'>Put your current points in your class in the <input placeholder='Current Points' disabled='disabled'> box, and your class's total points in the <input placeholder='Total Points' disabled='disabled'> box. Then click <button class='button2' disabled='disabled'>Calculate</button> or enter. It will give you how many points you need to go up, or down a letter grade. </p> </div> </div> <div class='footnote'> <p> Hello I am Zain, I made this calculator for you! Full Release </p> </div> </body>
{ "domain": "codereview.stackexchange", "id": 42600, "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": "javascript, html, css", "url": null }
javascript, html, css Answer: General points Use number input for numbers. The DOM interface HTMLInputElement means you don't have to worry about vetting for anything but numbers Keep code out of the global scope. Wrap it in an IIFE (Immediately Invoked Function Expression) Run code in strict mode to avoid some dangerous problems your code has. Eg undeclared variables. Avoid repeating data. You have the data for conversion from percent to grade twice. This make the data highly prone to error. Design. Make the user experience as simple as possible. The less the user must do to get a result the better the experience. In the example the grade and percent is calculated automatically. There is no need for the user to click a calculate button. It will never display an error as it considers bad (unknown values) as an incomplete form and simply waits for the data to be completed rather than force more user interaction, Be careful with JavaScript numbers and don't report more or less precision than required. Don't allow inputs to hold values that do not make sense. Max Score can never be lower than score. Score can never be greater that max score or less than 0. Max score can never be lower than 1. Example A simple example show how one can achieve the same result as your code. Note that I did not bother styling the content. I have added a few comments to explain what you may be unfamiliar with. ;(()=> { // IIFE Function is isolate code from global scope. "use strict"; // Use strict mode const els = {scoreInEl: null, maxInEl: null, percentEl: null, gradeEl: null}; Object.keys(els).reduce((o, k) => (o[k] = document.querySelector("#"+k), o), els); // Required data once. const grades = [[0.9, "A"], [0.8, "B"], [0.7, "C"], [0.6, "D"], [0, "F"]]; els.scoreInEl.addEventListener("input", update); els.maxInEl.addEventListener("input", update); function calcGrade(score, maxPoints) { const frac = score / maxPoints;
{ "domain": "codereview.stackexchange", "id": 42600, "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": "javascript, html, css", "url": null }
javascript, html, css // Calculate number of digits to use when rounding the percentage const digits = (Math.max(2, Math.ceil(Math.log10(maxPoints))) - 2) | 0; const level = grades.find(g => frac >= g[0] || g[0] === 0)[1]; return {percent: (frac * 100).toFixed(digits) + "%", level }; } function update() { var score = els.scoreInEl.valueAsNumber, max = els.maxInEl.valueAsNumber; if (!(isNaN(score) || isNaN(max)) && max > 0) { if (score > max) { els.maxInEl.value = max = score } // Ensure max >= score const g = calcGrade(score, max); els.percentEl.textContent = g.percent; els.gradeEl.textContent = g.level; } } })(); input { width: 70px; } <label for="scoreInEl">Score........:</label> <input type="number" id="scoreInEl" min=0 maxLength=5 placeholder="Score"><br> <label for="maxInEl">Max Score:</label> <input type="number" id="maxInEl" min=1 width=5 placeholder="Max Score"> <div> Percent: <span id="percentEl"></span></div> <div> Grade..: <span id="gradeEl"></span></div> Second example same but uses ids to directly reference elements.
{ "domain": "codereview.stackexchange", "id": 42600, "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": "javascript, html, css", "url": null }
javascript, html, css Second example same but uses ids to directly reference elements. ;(()=> { "use strict"; const grades = [[0.9, "A"], [0.8, "B"], [0.7, "C"], [0.6, "D"], [0, "F"]]; scoreInEl.addEventListener("input", update); maxInEl.addEventListener("input", update); function calcGrade(score, maxPoints) { const frac = score / maxPoints; const digits = (Math.max(2, Math.ceil(Math.log10(maxPoints))) - 2) | 0; const level = grades.find(g => frac >= g[0] || g[0] === 0)[1]; return {percent: (frac * 100).toFixed(digits) + "%", level}; } function update() { var score = scoreInEl.valueAsNumber, max = maxInEl.valueAsNumber; if (!(isNaN(score) || isNaN(max)) && max > 0) { if (score > max) { maxInEl.value = max = score } // Ensure max >= score const g = calcGrade(score, max); percentEl.textContent = g.percent; gradeEl.textContent = g.level; } } })(); input { width: 70px; } <label for="scoreInEl">Score........:</label> <input type="number" id="scoreInEl" min=0 maxLength=5 placeholder="Score"><br> <label for="maxInEl">Max Score:</label> <input type="number" id="maxInEl" min=1 width=5 placeholder="Max Score"> <div> Percent: <span id="percentEl"></span></div> <div> Grade..: <span id="gradeEl"></span></div>
{ "domain": "codereview.stackexchange", "id": 42600, "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": "javascript, html, css", "url": null }
c++, object-oriented, template, finance, numerical-methods Title: C++ bond mathematics calculator Question: I have written a program in C++ that processes financial bond mathematics, making extensive use of the valarray class, so that mathematical functions and operations can be applied vectorially on whole arrays in just one expression, instead of having to resort to a loop over all elements. This is similar to how numeric data is processed in languages more focused on scientific computation like Fortran or Matlab. There are many function templates in my code that perform one-line operations as described above, which is ideal if the template parameter is instantiated as a scalar, say an int or double, or as a valarray<int or double>. I guess this is less ideal instead if the template parameter is taken to be an array or a vector. This perhaps might constitute a possible objection that can be levelled to the logic of my program, but I don't think it's practical to introduce loops just so one can accept vectors as data. The mathematics behind the program revolve around the equation for the bond value \$B\$: $$ B = \sum_{i=1}^{n-1} \frac{C}{2} P \cdot d(t_i) + \left( 1 + \frac{C}{2} \right) P \cdot d(t_n) \qquad\qquad\qquad\qquad\qquad\qquad (1) $$ where \$t_i\$ are the \$i = 1, 2 \dots n\$ coupon dates, \$C\$ is the bond coupon rate, \$P\$ is the bond principal (initial loan to be returned at maturity \$t_n\$), \$d(t_i)\$ are the discount factors for each coupon date. The formula to obtain \$d(t_i)\$ varies based on the type of interest rate \$r(t_i)\$ considered: Zero-rate: $$d(t_i) = e^{- r(t_i) \cdot t_i} \qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad (2)$$ where \$r(t_i)\$ is given either tabular or as a continuous function of \$t\$. Instantaneous rate: $$d(t_i) = e^{- \int_{0}^{t_i} r(\tau) d\tau} \qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad\qquad (3)$$ where \$r(t)\$ is a given continuous function. Other bond-related quantities the program computes are:
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods Other bond-related quantities the program computes are: the yield \$y\$, which is the constant interest rate that substituted in (1) attains a known \$B\$. That is given \$B\$, solve (1) implicitly to extract \$y\$ with a numerical method (I hardcoded Newton-Raphson). The par yield coupon rate is the value of \$C\$ that makes \$B = P\$ in (1). The bond duration \$D\$ is the opposite of the relative change of \$B\$ coming after a change of yield \$y\$: $$D = - \frac{1}{B} \frac{\partial B}{\partial y}$$ The bond convexity \$V\$ is the opposite of the relative change of duration with respect to yield: $$V = \frac{1}{B} \frac{\partial^2 B}{\partial y^2}$$ The program below creates a Bond class hierarchy with four derived classes: KnownRateBond takes zero-interest rate input in tabular form; ZeroRateBond takes zero-interest rate input as a continuous function of time; InstantRateBond takes instantaneous interest rate input, so it has to evaluate the integral in (3) with NewtonCotesFormulas classes of quadratures that I had written here; BondGivenYield takes the yield value as input instead of the interest rate to compute the other quantities. The code is below, please don't spare any critique or suggestion for possible enhancements: main.cpp: /** Computes the important quantities for a bond from input * All quantities are acquired as class data members, * useful to print all on file or on excel * TODO: - add parser to type interest time-law directly on input * - add xlw interface * - fix virtual computeDiscountFactors() function not overridden by InstantRateBond class */ #include <iostream> #include <initializer_list> #include <algorithm> #include <iterator> #include <cmath> #include <valarray> #include <functional> #include "Bond.h" using std::initializer_list; using std::valarray; using std::cout; using std::cin; using std::function; using std::copy; using std::begin; using std::unique_ptr;
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods // helps with input void flushCin() { cin.ignore(); cin.clear(); } // processes inputs void inputFromUser(valarray<double>& times, double& coupon, valarray<double>& inp_known_rates, function<valarray<double> (valarray<double>)>& inp_rate, double& inp_yield, InterestRates& type, Formula& quadrature, double& principal, double& tol) { cout << "Please input coupon dates as fraction (decimal number) of the year," << " and press Enter key when done: \n"; constexpr size_t MAX_SIZE = 1000; double input_times[MAX_SIZE]; int counter; while (cin.peek() != '\n') // while next input is not Enter key cin >> input_times[counter++]; flushCin(); times.resize(counter); copy(input_times, input_times+counter, begin(times)); // or briefly, while testing //times = {0.1667, 0.6667, 1.1667, 1.6667}; //times = {0.5, 1., 1.5, 2}; inp_known_rates.resize(times.size()); cout << "\nPlease enter the coupon rate in fraction of year (decimal): \n"; cin >> coupon;
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods cout << "\nPlease enter the coupon rate in fraction of year (decimal): \n"; cin >> coupon; cout << "\nPlease select (1, 2, 3 or 4) how the interest rate law above should be computed: \n" << "Known rates at given dates ---> (1)\n" << "Zero rate --------------------> (2)\n" << "Instantaneous rate -----------> (3)\n" << "Yield rate -------------------> (4)\n"; int input_type; do { cin >> input_type; switch (input_type) { case 1: type = InterestRates::known_rate; break; case 2: type = InterestRates::zero_rate; break; case 3: type = InterestRates::instantaneous; break; case 4: type = InterestRates::given_yield; break; default: cout << "Select 1, 2, 3 or 4 only\n"; flushCin(); break; } } while (input_type < 1 || input_type > 4); flushCin(); cout << "\nPlease digit a value for the principal, or press Enter to leave it at 100 : \n"; while (cin.peek() != '\n') cin >> principal; flushCin();
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods if (type == InterestRates::known_rate) { // inp_known_rates = {0.05, 0.0525, 0.0535, 0.055}; // debug cout << "Please input known interest rate at coupon dates, separated by space," << " and press Enter key when done: \n"; while (cin.peek() != '\n') { // while next input is not Enter key for (auto& rate : inp_known_rates) cin >> rate; } flushCin(); } else if (type == InterestRates::instantaneous) { cout << "Choose the numerical integration method for the interest rate law :\n" << "Midpoint numeric quadrature -----> (1)\n" << "Trapezoidal numeric quadrature --> (2)\n" << "Simpson's numeric quadrature ----> (3)\n\n"; int input_quadrature; do { cin >> input_quadrature; switch (input_quadrature) { case 1: quadrature = Formula::Midpoint; break; case 2: quadrature = Formula::Trapezoidal; break; case 3: quadrature = Formula::Simpsons; break; default: cout << "Select 1, 2 or 3 only\n"; flushCin(); break; } } while (input_quadrature < 1 || input_quadrature > 3); flushCin(); cout << "\nPlease enter the tolerance value sufficient for convergence of integration above,"; cout << " or press Enter to leave it at 1E-6 : \n"; while (cin.peek() != '\n') cin >> tol; flushCin(); } else if (type == InterestRates::given_yield) { cout << "Please input the bond yield and press Enter key when done: \n"; while (cin.peek() != '\n') { // while next input is not Enter key cin >> inp_yield; } } }
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods // functor for interest rate law if any // would be nice to input this directly through a parser template<typename T> function<T (T)> interestRateLaw() { return [](const T t)->T { //return 0.0525 + 1 / (100 * (1 + exp(- t * t))); return 0.0525 + log(1 + 2.*t) / 200; // another law }; } int main() { // declare variables valarray<double> times, inp_known_rates; double coupon, principal{100}, tol{1E-6}, inp_yield{0}; InterestRates bond_type; Formula quadrature; // acquire input function<valarray<double> (valarray<double>)> inp_rate = interestRateLaw<valarray<double> >(); inputFromUser(times, coupon, inp_known_rates, inp_rate, inp_yield, bond_type, quadrature, principal, tol); // calculates bond data and print it on output unique_ptr<Bond> my_bond = makeBond(bond_type, times, coupon, inp_known_rates, inp_rate, inp_yield, quadrature, principal, tol); my_bond->printData(cout, bond_type); return 0; } bond.h: #ifndef BOND_H_INCLUDED #define BOND_H_INCLUDED #include <iostream> #include <memory> #include <functional> #include <valarray> #include "NewtonCotesFormulas.h" // bond types enum class InterestRates { known_rate = 1, zero_rate, instantaneous, given_yield }; // BASE CLASS class Bond { public: Bond(std::valarray<double>, const double); virtual ~Bond() = default; void setConstants(size_t&, double&); virtual void computeDiscountFactors(){} // will be overridden by all derived classes except one void computeValues(const double, const double = 100, const double = 1E-6); std::valarray<double> getCashTimes() const; double getCouponRate() const; std::valarray<double> getDiscountFactors() const; double getValue() const; double getDuration() const; double getConvexity() const;
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods virtual double getGivenYield() const {return 0;} double getYield() const; double getParYieldCoupon() const; double NewtonMethodForYield(const double, const double, std::function<double (double)>&, std::function<double (double)>&); void printData(std::ostream&, const InterestRates&); protected: // acquired on input std::valarray<double> cash_times; double coupon_rate; // computed after initialization std::valarray<double> discount_factors; double bond_value; double duration; double convexity; double yield; double par_yield_coupon; }; // DERIVED CLASSES class KnownRateBond : public Bond { public: KnownRateBond(std::valarray<double>, const double, std::valarray<double>, double = 100); ~KnownRateBond() = default; void computeDiscountFactors() override; private: std::valarray<double> known_rates; }; template<typename T> class ZeroRateBond : public Bond { public: ZeroRateBond(std::valarray<double>, const double, std::function<T (T)>&, double = 100); ~ZeroRateBond() = default; void computeDiscountFactors() override; private: std::function<T (T)> interest_rate; }; template<typename T> class InstantRateBond : public Bond { public: InstantRateBond(std::valarray<double>, const double, std::function<T (T)>&, const Formula&, double, const double=1E-6); ~InstantRateBond() = default; void computeDiscountFactors(const Formula&, const double); // alas doesn't override virtual function private: std::function<T (T)> interest_rate; }; class BondGivenYield : public Bond { public: BondGivenYield(std::valarray<double>, const double, double, double); ~BondGivenYield() = default; void computeDiscountFactors() override; double getGivenYield() const override; private: double given_yield; };
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods // BOND FACTORY FUNCTION template<typename T> std::unique_ptr<Bond> makeBond(const InterestRates&, std::valarray<double>, const double, std::valarray<double>, std::function<T (T)>&, double, const Formula&, const double = 100, double = 1E-6); #include "Bond.cpp" #endif // BOND_H_INCLUDED bond.cpp: #include <iostream> #include <iomanip> #include <numeric> #include <cmath> #include <iterator> #include <memory> #include <algorithm> #include <stdexcept> #include "Bond.h" using std::valarray; using std::function; using std::begin; using std::end; using std::accumulate; using std::exp; using std::copy; using std::setprecision; using std::cout; using std::move; using std::ostream; using std::ostream_iterator; using std::make_unique; using std::runtime_error; using std::unique_ptr; using std::fixed; using std::scientific; // BASE CLASS Bond::Bond(valarray<double> inp_times, const double inp_coupon) : cash_times{inp_times}, coupon_rate{inp_coupon}, discount_factors(cash_times.size()), bond_value{0}, duration{0}, convexity{0}, yield{0}, par_yield_coupon{0} {} // sets auxiliary variables that are not included in the class as data void Bond::setConstants(size_t& index_maturity, double& coupon_frequency) { if (cash_times.size() == 1) { index_maturity = 0; coupon_frequency = 1 / cash_times[index_maturity]; } else { index_maturity = cash_times.size() - 1; coupon_frequency = 1 / (cash_times[index_maturity] - cash_times[index_maturity - 1]); } }
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods // compute main bond quantities void Bond::computeValues(const double coupon_frequency, const double principal, const double tol) { // coupon payment double coupon_spot_cash_flow = principal * coupon_rate / coupon_frequency; // all coupons discounted to present valarray<double> cash_flows = coupon_spot_cash_flow * discount_factors; // last cashflow at expiry includes return of principal *(end(cash_flows)-1) += principal * *(end(discount_factors)-1); // copy(begin(cash_flows), end(cash_flows), ostream_iterator<double>(cout, " ")); // debug // cout << '\n'; // main values bond_value = accumulate(begin(cash_flows), end(cash_flows), 0.0); valarray<double> cash_flows_t = cash_flows * cash_times; duration = accumulate(begin(cash_flows_t), end(cash_flows_t), 0.0) / bond_value; valarray<double> cash_flows_tt = cash_flows_t * cash_times; convexity = accumulate(begin(cash_flows_tt), end(cash_flows_tt), 0.0) / bond_value; // auxiliary variables will be used to compute the yield valarray<double> exp_cash_times = exp(- cash_times); function<double (double)> bond_implicit = [&](double rate_old) { valarray<double> exp_pow_rate = pow(exp_cash_times, rate_old); // *(end(cash_times)-1) below is time of maturity return bond_value - principal * exp(- rate_old * *(end(cash_times)-1)) - coupon_spot_cash_flow * accumulate(begin(exp_pow_rate), end(exp_pow_rate), 0.0); }; function<double (double)> deriv_bond = [&](double rate_old) { valarray<double> exp_pow_rate_times_t = cash_times * pow(exp_cash_times, rate_old); return principal * *(end(cash_times)-1) * exp(- rate_old * *(end(cash_times)-1)) + coupon_spot_cash_flow * accumulate(begin(exp_pow_rate_times_t), end(exp_pow_rate_times_t), 0.0); };
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods // compute yield and par-yield coupon yield = NewtonMethodForYield(tol, 0.1, bond_implicit, deriv_bond); par_yield_coupon = (1 - *(end(discount_factors)-1)) * coupon_frequency; par_yield_coupon /= accumulate(begin(discount_factors), end(discount_factors), 0.0); } // Newton-Raphson method to extract yield double Bond::NewtonMethodForYield(const double tol, const double rate_init, function<double (double)>& num, function<double (double)>& denum) { double rate_old = rate_init; double rate_new = rate_old - 1; while (abs(rate_new - rate_old) > tol) { rate_old = rate_new; rate_new = rate_old - num(rate_old) / denum(rate_old); } return rate_new; } // getters valarray<double> Bond::getCashTimes() const {return cash_times;} double Bond::getCouponRate() const {return coupon_rate;} valarray<double> Bond::getDiscountFactors() const {return discount_factors;} double Bond::getValue() const {return bond_value;} double Bond::getDuration() const {return duration;} double Bond::getConvexity() const {return convexity;} double Bond::getYield() const {return yield;} double Bond::getParYieldCoupon() const {return par_yield_coupon;} // print all bond data, e.g. on a.txt file void Bond::printData(ostream& os, const InterestRates& choice) { os << "Bond current state :" << setprecision(5) << fixed; valarray<double> print_times = getCashTimes(); os << "\nCoupon dates : "; copy(begin(print_times), end(print_times), ostream_iterator<double>(os, " ")); os << "(per year length)\n"; valarray<double> print_discounts = getDiscountFactors(); os << "Discount to present value for each date : "; copy(begin(print_discounts), end(print_discounts), ostream_iterator<double>(os, " "));
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods os << "\nCoupon rate : " << setprecision(2) << getCouponRate() * 100 << " % \n"; os << "Bond VALUE : " << setprecision(5) << getValue() << '\n'; os << "Bond duration : " << getDuration() << '\n'; os << "Bond convexity : " << getConvexity() << "\n\n"; if (choice == InterestRates::given_yield) os << "Yield given : " << getGivenYield() << '\n'; os << "Bond yield : " << getYield() << '\n'; os << "Par yield coupon : " << getParYieldCoupon() << "\n\n"; } // DERIVATE CLASSES KnownRateBond::KnownRateBond(valarray<double> inp_times, const double inp_coupon, valarray<double> inp_known_rates, double inp_principal) : Bond{inp_times, inp_coupon}, known_rates{inp_known_rates} { double principal{inp_principal}, coupon_frequency; // copy(begin(known_rates), end(known_rates), ostream_iterator<double>(cout, " ")); // debug // cout << '\n'; size_t index_maturity; setConstants(index_maturity, coupon_frequency); computeDiscountFactors(); computeValues(coupon_frequency, principal); } void KnownRateBond::computeDiscountFactors() { discount_factors = exp(- known_rates * cash_times); } template<typename T> ZeroRateBond<T>::ZeroRateBond(valarray<double> inp_times, const double inp_coupon, function<T (T)>& inp_rate, double inp_principal) : Bond(inp_times, inp_coupon), interest_rate(inp_rate) { double principal{inp_principal}, coupon_frequency; size_t index_maturity; setConstants(index_maturity, coupon_frequency); computeDiscountFactors(); computeValues(coupon_frequency, principal); } template<typename T> void ZeroRateBond<T>::computeDiscountFactors() { discount_factors = exp(- interest_rate(cash_times) * cash_times); }
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods template<typename T> InstantRateBond<T>::InstantRateBond(valarray<double> inp_times, const double inp_coupon, function<T (T)>& inp_rate, const Formula& quadrature, double inp_principal, const double inp_tol) : Bond(inp_times, inp_coupon), interest_rate(inp_rate) { double principal{inp_principal}, coupon_frequency, tol{inp_tol}; size_t index_maturity; setConstants(index_maturity, coupon_frequency); computeDiscountFactors(quadrature, tol); computeValues(coupon_frequency, principal, tol); } template<typename T> void InstantRateBond<T>::computeDiscountFactors(const Formula& quadrature, const double tol) { function<T (const T&, const T&, int, function<T (T)>)> my_method = createQuadrature<T>(quadrature); const size_t array_size = cash_times.size(); valarray<double> integrated_rate(array_size); valarray<double> tol_array(tol, array_size); tol_array[array_size-1] *= 1E-2; valarray<double> inp_inf(0.0, array_size); integrated_rate = convergeToTol(quadrature, inp_inf, cash_times, 4, tol_array, interest_rate, my_method); discount_factors = exp(- integrated_rate); } BondGivenYield::BondGivenYield(valarray<double> inp_times, const double inp_coupon, double inp_yield, double inp_principal) : Bond{inp_times, inp_coupon}, given_yield{inp_yield} { double principal{inp_principal}, coupon_frequency; size_t index_maturity; setConstants(index_maturity, coupon_frequency); computeDiscountFactors(); computeValues(coupon_frequency, principal); } void BondGivenYield::computeDiscountFactors() { discount_factors = exp(- given_yield * cash_times); }
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods double BondGivenYield::getGivenYield() const {return given_yield;} // bond factory function template<typename T> unique_ptr<Bond> makeBond(const InterestRates& choice, valarray<double> inp_times, const double inp_coupon, valarray<double> inp_known_rates, function<T (T)>& inp_rate_law, double inp_yield, const Formula& quadrature, const double principal, double tol) { if (choice == InterestRates::known_rate) return make_unique<KnownRateBond>(inp_times, inp_coupon, inp_known_rates, principal); else if (choice == InterestRates::zero_rate) return make_unique<ZeroRateBond<T> >(inp_times, inp_coupon, inp_rate_law, principal); else if (choice == InterestRates::instantaneous) return make_unique<InstantRateBond<T> >(inp_times, inp_coupon, inp_rate_law, quadrature, principal, tol); else if (choice == InterestRates::given_yield) return make_unique<BondGivenYield>(inp_times, inp_coupon, inp_yield, principal); else throw runtime_error("Pick either choice = 1, 2, 3 or 4"); return 0; // never gets here } NewtonCotesFormulas.h: #ifndef NEWTONCOTESFORMULAS_H_INCLUDED #define NEWTONCOTESFORMULAS_H_INCLUDED #include <iostream> #include <functional> enum class Formula { Midpoint = 1, Trapezoidal, Simpsons }; std::ostream& operator<< (std::ostream&, const Formula&); template<typename Quadrature, typename T> T convergeToTol(const Formula&, const T&, const T&, int, const T&, const std::function<T (T)>&, const Quadrature&); void printConvergenceValues(std::ostream&, const int, const Formula&, const int, const double, const double, double); template<typename T> T Midpoint(const T&, const T&, const int, const std::function<T (T)>&);
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods template<typename T> T Midpoint(const T&, const T&, const int, const std::function<T (T)>&); template<typename T> T Trapezoidal(const T&, const T&, const int, const std::function<T (T)>&); template<typename T> T Simpsons(const T&, const T&, const int, const std::function<T (T)>&); template<typename T> std::function<T (const T&, const T&, const int, const std::function<T (T)>&) > createQuadrature(const Formula&); #include "NewtonCotesFormulasTemplateImplementation.cpp" // provide definitions for template functions #endif // NEWTONCOTESFORMULAS_H_INCLUDED NewtonCotesFormulasTemplateImplementation.cpp: #include <iostream> #include <cmath> #include <functional> #include <stdexcept> #include "NewtonCotesFormulas.h" using std::cout; using std::abs; using std::function; using std::runtime_error; template<typename Quadrature, typename T> // also prints convergence table T convergeToTol(const Formula& choice, const T& inf, const T& sup, int intervals, const T& tol, const function<T (T)>& func, const Quadrature& my_method) { // set up variables T old_integral = my_method(inf, sup, intervals, func); auto array_size = tol.size(); printConvergenceValues(cout, 0, choice, intervals, tol[array_size-1], old_integral[array_size-1], old_integral[array_size-1]); intervals *= 2; T new_integral = my_method(inf, sup, intervals, func); T difference = abs(new_integral - old_integral); // iterate until convergence while((difference > tol).max()) { printConvergenceValues(cout, 1, choice, intervals, tol[array_size-1], new_integral[array_size-1], difference[array_size-1]); old_integral = new_integral; intervals *= 2; new_integral = my_method(inf, sup, intervals, func); difference = abs(new_integral - old_integral); }
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods printConvergenceValues(cout, 2, choice, intervals, tol[array_size-1], new_integral[array_size-1], difference[array_size-1]); return new_integral; } template <typename T> T Midpoint(const T& inf, const T& sup, const int intervals, const function<T (T) >& func) { T interval_width = (sup - inf) / intervals; T result(0., inf.size()); for (int i = 1; i <= intervals; ++i) result += func(inf + (i - 0.5) * interval_width); return result * interval_width; } template <typename T> T Trapezoidal(const T& inf, const T& sup, const int intervals, const function<T (T)>& func) { T interval_width = (sup - inf) / intervals; T result = (func(inf) + func(sup)) / 2.; for (auto i = 1.; i <= intervals - 1; ++i) result += func(inf + i * interval_width); return result * interval_width; } template <typename T> T Simpsons(const T& inf, const T& sup, const int intervals, const function<T (T)>& func) { T interval_width = (sup - inf) / intervals; T result = (func(inf) + func(sup)) / 6; for (auto i = 1.; i <= intervals - 1; ++i) result += func(inf + i * interval_width) / 3. + 2. * func(inf + (i - 0.5) * interval_width) / 3.; result += 2. * func(inf + (intervals - 0.5) * interval_width) / 3.; return result * interval_width; } // factory function integration methods template<typename T> function<T (const T&, const T&, const int, const function<T (T)>&) > createQuadrature(const Formula& choice) { if (choice == Formula::Midpoint) return Midpoint<T>; else if (choice == Formula::Trapezoidal) return Trapezoidal<T>; else if (choice == Formula::Simpsons) return Simpsons<T>; else throw runtime_error("Pick between choice = 1, 2, or 3"); return 0; // never gets here } NewtonCotesFormulas.cpp: #include <iostream> #include <iomanip> #include <string> #include "NewtonCotesFormulas.h"
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods using std::string; using std::cout; using std::setprecision; using std::fixed; using std::scientific; using std::ostream; using std::to_string; // this just prints the formula name on cout ostream& operator<< (ostream& os, const Formula& method) { if (method == Formula::Midpoint) os << "Midpoint"; else if (method == Formula::Trapezoidal) os << "Trapezoidal"; else if (method == Formula::Simpsons) os << "Simpsons"; return os; } void printConvergenceValues(ostream& os, const int flag, const Formula& choice, const int intervals, const double tol, const double integral, double difference) { string pad_to_size = string(9 - to_string(intervals).size(), ' '); switch(flag) { case 0: os << "Numerical integration, convergence table\n"; os << choice << " method, with tolerance " << setprecision(1) << tol << "\n"; os << "intervals" << string(5,' ') << "integral " << string(9,' ') << "tol\n"; os << setprecision(8) << fixed << pad_to_size << intervals << string(3,' ') << integral << string(3,' ') << scientific << difference << '\n'; break; case 1: //cout.setf(ios_base::scientific); //cout.precision(8); os << pad_to_size << intervals << string(3,' ') << fixed << integral << string(3,' ') << scientific << difference << '\n'; break; case 2: os << fixed << pad_to_size << intervals << string(3,' ') << integral << string(3,' ') << scientific << difference << "\n\n"; break; } }
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods Results for a semiannual coupon bond with principal \$P = 100\$, coupon rate \$C = 6 \% = 0.06\$, maturity \$t_n = 20\$ months and zero-rate interest law given by \$r(t) = 0.0525 + \frac{\log{(1 + 2 t)}}{200}\$: Please input coupon dates as fraction (decimal number) of the year, and press En ter key when done: 0.16667 0.66667 1.16667 1.66667 Please enter the coupon rate in fraction of year (decimal): 0.06 Please select (1, 2, 3 or 4) how the interest rate law above should be computed: Known rates at given dates ---> (1) Zero rate --------------------> (2) Instantaneous rate -----------> (3) Yield rate -------------------> (4) 2 Please digit a value for the principal, or press Enter to leave it at 100 : Bond current state : Coupon dates : 0.16667 0.66667 1.16667 1.66667 (per year length) Discount to present value for each date : 0.99105 0.96288 0.93401 0.90509 Coupon rate : 6.00 % Bond VALUE : 101.88819 Bond duration : 1.58080 Bond convexity : 2.59243 Bond yield : 0.05975 Par yield coupon : 0.05004 Process returned 0 (0x0) execution time : 45.476 s Press any key to continue. [Execution time is as large as 45.476 s because of the time needed to manually input starting data into the interactive prompt] Answer: Bond::Bond(valarray<double> inp_times, const double inp_coupon) : cash_times{inp_times}, coupon_rate{inp_coupon}, discount_factors(cash_times.size()), bond_value{0}, duration{0}, convexity{0}, yield{0}, par_yield_coupon{0} {}
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
c++, object-oriented, template, finance, numerical-methods Why are you passing imp_times by value? If you meant to use the "sink" constructor idiom, you forgot the std::move. If not, you forgot that C++ has value semantics? This constructor body should go inline in the header, inside the class definition, not in the CPP file. Use inline initializers for all the members that are not set by arguments. E.g. the class would define the member as: double bond_value = 0.0; inside the class. Then, don't list them all in the constructor init list. BTW, don't use double for money!!! inputFromUser, with a fist full of "out" parameters, is not very nice. It would be awkward to call too, having to first declare all those things and then pass them to the function, rather than initializing (and maybe making const). Use switch instead of a cascade of if/else when you want to do something based on the value of an enumeration variable. ~KnownRateBond() = default; There's no need to do that in the derived classes. You only needed =default in the base class in order to mark it as virtual. Declaring the destructor -- even as =default -- disables the auto-generated copy constructor and assignment operators. (BTW, I see a lot of good things too!)
{ "domain": "codereview.stackexchange", "id": 42601, "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++, object-oriented, template, finance, numerical-methods", "url": null }
java, recursion Title: method to check if number is ascending order by recursion Question: method name: public static boolean ascendingNum(int n) method need to be done by recursion and return if the given number is in ascending order from right to left public static boolean ascendingNum(int n) { ///123456 true // 987654 true // 123455 false if(n > 9 && n < 100) if(n / 10 < n % 10) return true; else if(n / 10 >= n % 10) return false; if(((n / 10) % 10) == (n % 10 )) return false; if ( ((n / 10) % 10) < (n % 10 )) return(ascendingNum(n/10)); return false; } from running the numbers like in the comments it worked fine,can i have your opinion? Answer: The erratic formatting makes this code exceedingly difficult to read. The line indents are all over the place, and the whitespace is inconsistent. The code should have a consistent indent depth, preferably 2 or 4 spaces. There should be whitespace after control flow operators (if () and none in between multiple parentheses. There should be no whitespace before a ). Curly braces are technically optional for single-line blocks, but they should always be used. They greatly increase the readability of the code, which is crucial for preventing errors and for future maintainability. Use blank lines to break up clauses in the code. Just making those changes: public static boolean ascendingNum2(int n) { if (n > 9 && n < 100) { if (n / 10 < n % 10) { return true; } else if (n / 10 >= n % 10) { return false; } } if (((n / 10) % 10) == (n % 10)) { return false; } if (((n / 10) % 10) < (n % 10)) { return (ascendingNum(n / 10)); } return false; }
{ "domain": "codereview.stackexchange", "id": 42602, "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, recursion", "url": null }
java, recursion Now it's possible to review. The first if block is mostly extraneous. Set your base case to be a single-digit number. Right now, single-digit numbers fall through to the second clause, and report false. I would expect that any single-digit number is vacuously true. If you do that, you can replace the whole first clause with a check if the number is less than 10. Your second and third clauses handle two-digit numbers correctly. Your second and third clauses are doing the same math twice. Extract those values to variables. Give them good names, because readability is quite possibly the single most important property of good code. Instead of checking == (false), then > (recurse), and defaulting to false for <, check for <= and return false, then default to recursing. The code does not handle negative numbers. I would assume they should be false. If the expected behavior isn't specified, ask. If the method name isn't set by the question, I think isAscendingNum(12345) is easier to read. If you made all these changes, your code might look more like: public static boolean isAscendingNum(int n) { if (n < 0) { return false; } if (n < 10) { return true; } int lastDigit = n % 10; int secondToLastDigit = (n / 10) % 10; if (lastDigit <= secondToLastDigit) { return false; } return isAscendingNum(n / 10); }
{ "domain": "codereview.stackexchange", "id": 42602, "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, recursion", "url": null }
c++, beginner, object-oriented, database Title: Console Library System in C++ Question: I'm a beginner and came up with this simple project in C++. Any feedback would be very much appreciated. GitHub Repo Note: I'm using a file called "db.txt" as a database. main.cpp #include "Library.h" #include <iostream> #include <vector> #include <algorithm> #include <fstream> int main() { Library::init(); //initiates program Library::run(); //run program return 0; } Book.h #pragma once #include <string> #ifndef BOOK_H #define BOOK_H class Book { std::string title; std::string author; std::string category; bool available; public: Book(std::string title_ = "", std::string author_ = "", std::string category_ = "", int avai = 1); void changeAvailability(); bool getAvailability(); std::string getTitle(); std::string getAuthor(); std::string getCategory(); friend std::ostream& operator << (std::ostream& os, const Book& book); friend std::istream& operator >> (std::istream& is, Book& book); friend bool operator == (const Book& b1, const Book& b2); }; #endif Book.cpp #include "Book.h" #include <iostream> #include <string> Book::Book(std::string title_, std::string author_, std::string category_, int avai) : title(title_), author(author_), category(category_), available(avai) {} void Book::changeAvailability() { available = !available; } std::string Book::getTitle() { return title; } std::string Book::getAuthor() { return author; } std::string Book::getCategory() { return category; } bool Book::getAvailability() { return available; } std::ostream& operator << (std::ostream& os, const Book& book) { std::string avai = (book.available) ? "(Available)" : "(Unavailable)"; os << book.title + " - " + book.author + " " + avai + "\nCategory: " + book.category << std::endl; return os; }
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database std::istream& operator >> (std::istream& is, Book& book) { std::cout << "Name of the book: " << std::endl; std::getline(is, book.title); std::cout << "Name of the author: " << std::endl; std::getline(is, book.author); std::cout << "Book's category: " << std::endl; std::getline(is, book.category); return is; } bool operator == (const Book& b1, const Book& b2) { if (b1.title == b2.title and b1.author == b2.author and b1.category == b2.category) { return true; } return false; } Library.h #include <vector> #include <string> #include "Book.h" #ifndef LIBRARY_H #define LIBRARY_H //namespace singleton design namespace Library { namespace Container { static std::vector<Book> db; } void printAllBooks(); void addBook(); void deleteBook(); void searchByCategory(); void borrowBook(); void returnBook(); void writeToCustomFile(); void init(); void readFromFile(std::string filename = "db.txt"); void writeToFile(std::string filename = "db.txt"); int takeInput(); void run(); } #endif Library.cpp #include "Library.h" #include "Book.h" #include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <string> using namespace Library::Container; //function print all books from library static void Library::printAllBooks() { if (db.size() == 0) { std::cout << "There are no existing book. Please start by adding new books!" << std::endl; return; } else { int order = 1; std::sort(db.begin(), db.end(), [](Book b1, Book b2) { return b1.getAvailability() > b2.getAvailability(); } ); for (auto& i : db) { std::cout << order++ << ". " << i << std::endl; } } }
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database } //function to add new book to library static void Library::addBook() { Book book; std::cin >> book; db.push_back(book); std::cout << "Book added successfully!" << std::endl; writeToFile(); } //function to delete book from library static void Library::deleteBook() { Book book; std::cin >> book; auto it = std::find(db.begin(), db.end(), book); if (it == db.end()) { std::cout << "Cannot find the book! Please try again!" << std::endl; return; } else { std::cout << (*it).getTitle() + " by " + (*it).getAuthor() + "has been deleted!" << std::endl; db.erase(it); } writeToFile(); } //function to search books by category static void Library::searchByCategory() { int order = 1; std::sort(db.begin(), db.end(), [](Book b1, Book b2) { return b1.getCategory() < b2.getCategory(); } ); std::string query; std::cout << "Which book category are you looking for?" << std::endl; std::getline(std::cin, query); if (query == "") { printAllBooks(); } std::string copy_query = query; copy_query[0] = std::toupper(query[0]); for (auto& i : db) { if (i.getCategory().find(query) != std::string::npos || i.getCategory() == copy_query) { std::cout << order++ << ". " << i << std::endl; } } if (order == 1) { std::cout << "There is no book with this category!" << std::endl; } } //function to borrow a book static void Library::borrowBook() { Book book; std::cin >> book; std::vector<Book>::iterator it = std::find(db.begin(), db.end(), book);
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database if (it == db.end()) { std::cout << "Cannot find book! Please try again!" << std::endl; return; } else if ((*it).getAvailability() == false) { std::cout << "Book is being borrowed! Sorry." << std::endl; } else { (*it).changeAvailability(); std::cout << "You are now borrowing " + (*it).getTitle() + " by " + (*it).getAuthor() + ". Enjoy the book :)" << std::endl; } writeToFile(); } //function to return book after borrowing static void Library::returnBook() { Book book; std::cin >> book; std::vector<Book>::iterator it = std::find(db.begin(), db.end(), book); if (it == db.end()) { std::cout << "Cannot find book! Please try again!" << std::endl; return; } else if ((*it).getAvailability() == true) { std::cout << "Book is not being borrowed!" << std::endl; } else { (*it).changeAvailability(); std::cout << (*it).getTitle() + " has been returned!" << std::endl; } writeToFile(); } //write to custom file void Library::writeToCustomFile() { std::string filename; std::cout << "What file do you want to write to?" << std::endl; std::getline(std::cin, filename); std::ofstream ofile(filename); if (!ofile.is_open()) { std::cout << "An error occured while opening file for writing. Please try again!" << std::endl; return; } for (auto i : db) { ofile << i << std::endl; } } //init function void Library::init() { db.clear(); Library::readFromFile(); }
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database //init function void Library::init() { db.clear(); Library::readFromFile(); } //function to read from a file. Can read from custom file (will be implemented later) static void Library::readFromFile(std::string filename) { std::vector<std::string> class_mem; std::ifstream ifile(filename); if (!ifile.is_open()) { std::cout << "An error occured while opening file for reading. Please try again!" << std::endl; return; } std::string tmp; while (std::getline(ifile, tmp, ',')) { class_mem.push_back(tmp); if (class_mem.size() == 4) { Book book(class_mem[0], class_mem[1], class_mem[2], std::stoi(class_mem[3])); db.push_back(book); class_mem.clear(); } } } //function to write to a file. Can write to custom file (will be implemented later) static void Library::writeToFile(std::string filename) { std::ofstream ofile(filename); if (!ofile.is_open()) { std::cout << "An error occured while opening file for writing. Please try again!" << std::endl; return; } if (filename == "db.txt") { for (auto i : db) { ofile << i.getTitle() + "," + i.getAuthor() + "," + i.getCategory() + "," + std::to_string(i.getAvailability()) + ","; } } else { for (auto i : db) { ofile << i << std::endl; } } } //function to take user's input int Library::takeInput() { int input(0); std::cout << "MENU:\n1: Print all books\n2: Add a new book to library\n"; std::cout << "3: Delete a book\n4: Search for books of a specific category\n5: Borrow a book\n6: Return a book\n"; std::cout << "7: Write to custom file\n8: Exit\n\nNOTE : ENTERING -1 WILL CAUSE THE PROGRAM TO STOP AUTOMATICALLY" << std::endl; std::cin >> input; if (!std::cin) { return -1; } int temp = std::getchar(); return input; }
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database //main program void Library::run() { bool userExit = false; while (!userExit) { switch (Library::takeInput()) { case -1: std::cout << "Program exited due to invalid input." << std::endl; userExit = true; break; case 1: Library::printAllBooks(); break; case 2: Library::addBook(); break; case 3: Library::deleteBook(); break; case 4: Library::searchByCategory(); break; case 5: Library::borrowBook(); break; case 6: Library::returnBook(); break; case 7: Library::writeToCustomFile(); break; case 8: //save changes to file Library::writeToFile(); userExit = true; break; default: std::cout << "Invalid input. Please input a number shown on the menu" << std::endl; break; } } }
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database Answer: Make variables and functions const where appropriate You used const references in a few places, but you missed a lot of opportunities to make other things const. Consider a Book for example. Ideally, once constructed, the title, author and category should not change. So you could make this explicit and mark these member variables as const. This allows the compiler to better optimize code, and prevents accidental mistakes in your code. The drawback is that you can then no longer have a friend operator>>() to read in a Book from a std::istream, although you could still make a function that just takes a std::istream reference, and have that function construct and return a Book. Apart from variables, you can also make functions const. This tells the compiler that this function will not change any of the member variables. You should do this for all getters like getAvailability(), getTitle() and so on, and in Library you would use this for things like printAllBooks(), writeToFile() and so on. You make a function const by adding const after the arguments but before the body, like so: class Book { ... std::string getTitle() const; ... }; std::string Book::getTitle() const { return title; } Consider returning const references from getters While it is fine for getAvailability() to just return a bool, consider that returning a std::string by value in functions like getTitle() will cause the string to be copied. However, you can make it return a const reference to the member variable title instead: const std::string &Book::getTitle() { return title; }
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database The caller can still use getTitle() like before without any modifications, but now no copy has to be made by getTitle(). Reduce responsibilities of classes and functions It is good practice to reduce the responsibilities each class and function has. This keeps the code simpler and more generic. Consider your class Book. Apart from storing its immutable properties that define a book, like title, author and category, it also keeps track of whether it is available, and it knows how to read and write to iostreams. However, the latter responsibilities introduce problems: The available flag is not something that should be in Book. It is not a property of a book whether it is "available" or not. Rather, it should be something the Libary keeps track of. Consider a program where you want to manage two libraries, each maybe having the same book in its catalog. Which library does the available flag refer to? The operator<<() formats the properties of a book in a human-readable way, and operator>>() seems to expect a human looking at the standard output. However, what if you later want to add functions to read and write Books in JSON format? What if you don't want to read from std::cin, why is operator>>() still printing to std::cout? Technically, the friend functions operator<<() and operator>>() that work on Books are not part of class Book, they are just global functions, so you can argue that they are not part of Books responsibility. But still, I would consider reducing the code in Book.h to be just this: struct Book { const std::string title; const std::string author; const std::string category; }; Make Library a class Your Library, while currently a namespace, already looks very much like a class: it has state (Container::db) and associated functions that act on that state. I would therefore make it a proper class: class Library { std::vector<Book> db; public: void addBook(const Book &book); void deleteBook(const Book &book); ... };
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database void Library::addBook(const Book &book) { db.push_back(book); } void Library::deleteBook(const Book &book) { std::erase(db, book); } ...
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database Again, consider what the basic properties of a library are: it has a catalog of books it has, you can add and remove books to the catalog, you can browse and search for books, and you can borrow and return books. Printing and file I/O is a responsibility that is better placed outside class Library, for the same reasons I mentioned above for class Book. Also, run() should not be a member function. You might keep this into a free-standing function, or perhaps create a class Librarian whose responsibility it is to run a Library. So how to ensure this still is a singleton? Well, if you just want one Library, just create one instance of it. This doesn't prevent you from creating more instances though, but did it need to be a singleton to begin with? Dealing with multiple copies of the same book Most real-world libraries have multiple copies of a given book in their catalog, especially for popular books for which it is likely that more than one person wants to borrow it at the same time. One problem with your code is that two books with the same title, author and category are indistinguishable from each other. This becomes a problem for your borrowBook() and returnBook() functions. A solution is to make sure that books get some unique ID, like a serial number. However, this will make searching for a book in the catalog a little bit harder; you can't just use the first result returned by std::find(), you might have to look for other possible copies as well if the first result is already borrowed for example. Related to this, searching for books in a std::vector is slow, as it has to check every element in sequence. If you ensure the elements of db are always sorted, you can do better, and use std::equal_range() to find books. There are also other containers you could consider using. Use \n instead of std::endl
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
c++, beginner, object-oriented, database Use \n instead of std::endl Prefer using \n instead of std::endl, the latter is equivalent to the former, but it also forces the output to be flushed, which is usually not necessary and might hurt performance. Many C++ tutorials attempt to use std::endl everywhere, but it not only hurts the performance, but using \n is for many programmers easier to read, especially for non-C++ programmers. For example in Java or C, there is only the \n escape sequence. Write it->foo instead of (*it).foo It is more idiomatic to write it->getAvailability() than (*it).getAvailability(). Missing error checking in I/O functions Errors can happen while reading from and writing to a file at any time, not just when opening the file. It is therefore not enough to just check that is_open() returns true. What you should do instead is check after doing all file I/O whether the stream object is in the expected state. When reading from a file, after reading the whole file ifile.eof() should be true. If it is not, you encountered an error before reading the end of the file. When writing to the file, after writing everything you wanted, call ofile.flush(), and then check if ofile.good() is still true, or do this in one go, like if (!ofile.flush()) { /* handle error */ }. Note that for std::ofstream (not std::ostream), you should also call close() and check its result.
{ "domain": "codereview.stackexchange", "id": 42603, "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++, beginner, object-oriented, database", "url": null }
python, object-oriented, game, chess Title: Chess game in Python - follow-up Question: Three weeks ago I wrote the first version of my chess game in Python and shared on Code Review. Thanks to your suggestions, I improved my code. I would like to know if I am going in good direction with all this stuff. __author__ = 'Goldsmitd' class Condition: def range(x,y): return x > 8 and y > 8 def if_figure(board,x,y): return board[x][y].sl == '.' def same_team(x1,y1,x2,y2,board): if board[x1][y1].team == board[x2][y2].team: return True else: return False def s_choice(board): while True: try: print('give x and y') x = int(input()) y = int(input()) except: print('Coordinates can only be integers') if Condition.range(x,y): print('Coordinates are out of range') elif Condition.if_figure(board,x,y): print('Square chosen by you is empty') else: return x,y break def d_choice(board): while True: try: print('give x and y') x=int(input()) y=int(input()) except: print('Coordinates can only be integers') if Condition.range(x,y): print('Coordinates are out of range') else: return x,y break def kill(x1,y1,x2,y2,board): if board[x1][y1].team == 'white' and board[x2][y2].team == 'black': return True elif board[x1][y1].team == 'black' and board[x2][y2].team == 'white': return True else: return False
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
python, object-oriented, game, chess def Pawnkill(x1,y1,x2,y2,board): if board[x1][y1].team == 'white' and board[x2][y2].team == 'black' and board[x1][y1].name == 'Pawn': return True elif board[x1][y1].team == 'black' and board[x2][y2].team == 'white'and board[x1][y1].name == 'Pawn': return True else: return False def solid(x1,y1,x2,y2,board): if board[x1][y1].name=='Rook': if x2>x1: for i in range(x1+1,x2): if board[i][y1].sl != '.': return False break elif x2<x1: for i in range(x2+1,x1): if board[i][y1].sl != '.': return False break elif y2>y1: for j in range(y1+1,y2): if board[x1][j].sl != '.': return False break elif y2<y1: for j in range(y2+1,y1): if board[x1][j].sl != '.': return False break else: return True
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
python, object-oriented, game, chess elif board[x1][y1].name=='Bishop': if x2>x1 and y2>y1: for i in range(x1+1,x2): for j in range(y1+1,y2): if board[i][j].sl != '.': return False break elif x2<x1 and y2<y1: for i in range(x2+1,x1): for j in range(y2+1,y1): if board[i][j].sl != '.': return False break elif x2<x1 and y2>y1: for i in range(x2+1,x1): for j in range(y1+1,y2): if board[i][j].sl != '.': return False break elif x2>x1 and y2<y1: for i in range(x1+1,x2): for j in range(y2+1,y1): if board[i][j].sl != '.': return False break else: return True
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
python, object-oriented, game, chess elif board[x1][y1].name=='Queen': if x2>x1 and y2>y1: for i in range(x1+1,x2): for j in range(y1+1,y2): if board[i][j].sl != '.': return False break elif x2<x1 and y2<y1: for i in range(x2+1,x1): for j in range(y2+1,y1): if board[i][j].sl != '.': return False break elif x2<x1 and y2>y1: for i in range(x2+1,x1): for j in range(y1+1,y2): if board[i][j].sl != '.': return False break elif x2>x1 and y2<y1: for i in range(x1+1,x2): for j in range(y2+1,y1): if board[i][j].sl != '.': return False break elif x2>x1: for i in range(x1+1,x2): if board[i][y1].sl != '.': return False break elif x2<x1: for i in range(x2+1,x1): if board[i][y1].sl != '.': return False break elif y2>y1: for j in range(y1+1,y2): if board[x1][j].sl != '.': return False break elif y2<y1: for j in range(y2+1,y1): if board[x1][j].sl != '.': return False break else: return True else: return True class Number: def __init__(self,sl): self.sl=sl
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
python, object-oriented, game, chess else: return True class Number: def __init__(self,sl): self.sl=sl class Empty: def __init__(self,x,y,sl,team): self.name = 'Empty' self.x = x self.y = y self.sl = sl self.team = team class Rook: def __init__(self,x,y,sl,team): self.name = 'Rook' self.x = x self.y = y self.sl = sl self.team = team def req(self,sx,sy,dx,dy,board): if ( dx==sx or dy==sy ) : return True else: return False class Knight: def __init__(self,x,y,sl,team): self.name = 'Knight' self.x = x self.y = y self.sl = sl self.team = team def req(self,sx,sy,dx,dy,board): if (abs(dx - sx)**2+abs(dy - sy)**2 == 5) : return True else: return False class Bishop: def __init__(self,x,y,sl,team): self.name = 'Bishop' self.x = x self.y = y self.sl = sl self.team = team def req(self,sx,sy,dx,dy,board): if (abs(dx - sx)==abs(dy - sy)) : return True else: return False class Queen: def __init__(self,x,y,sl,team): self.name = 'Queen' self.x = x self.y = y self.sl = sl self.team = team def req(self,sx,sy,dx,dy,board): if (dx == sx or dy == sy or (abs(dx - sx) == abs(dy - sy))) : return True else: return False class King: def __init__(self,x,y,sl,team): self.name = 'King' self.x = x self.y = y self.sl = sl self.team = team def req(self,sx,sy,dx,dy,board): if abs(dx-sx) < 2 and abs(dy-sy) < 2 : return True else: return False
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
python, object-oriented, game, chess class Pawn: def __init__(self,x,y,sl,team): self.name = 'Pawn' self.x = x self.y = y self.sl = sl self.team = team def req(self,sx,sy,dx,dy,board): if board[sx][sy].team == "white" and dx-sx == -1: return True elif board[sx][sy].team == 'black' and dx-sx == 1: return True else: return False
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
python, object-oriented, game, chess class Chess_Board: def __init__(self): self.board = [[Empty(x='',y='',sl='.',team='')]*9 for _ in range(9)] self.board[0][0] = Rook(x=0,y=0,sl='r',team='black') self.board[0][1] = Knight(x=0,y=1,sl='n',team='black') self.board[0][2] = Bishop(x=0,y=2,sl='b',team='black') self.board[0][3] = Queen(x=0,y=3,sl='q',team='black') self.board[0][4] = King(x=0,y=4,sl='k',team='black') self.board[0][5] = Bishop(x=0,y=5,sl='b',team='black') self.board[0][6] = Knight(x=0,y=6,sl='n',team='black') self.board[0][7] = Rook(x=0,y=7,sl='r',team='black') self.board[1][0] = Pawn(x=1,y=0,sl='p',team='black') self.board[1][1] = Pawn(x=1,y=1,sl='p',team='black') self.board[1][2] = Pawn(x=1,y=2,sl='p',team='black') self.board[1][3] = Pawn(x=1,y=3,sl='p',team='black') self.board[1][4] = Pawn(x=1,y=4,sl='p',team='black') self.board[1][5] = Pawn(x=1,y=5,sl='p',team='black') self.board[1][6] = Pawn(x=1,y=6,sl='p',team='black') self.board[1][7] = Pawn(x=1,y=7,sl='p',team='black') self.board[7][0] = Rook(x=7,y=0,sl='R',team='white') self.board[7][1] = Knight(x=7,y=1,sl='N',team='white') self.board[7][2] = Bishop(x=7,y=2,sl='B',team='white') self.board[7][3] = Queen(x=7,y=3,sl='Q',team='white') self.board[7][4] = King(x=7,y=4,sl='K',team='white') self.board[7][5] = Bishop(x=7,y=5,sl='B',team='white') self.board[7][6] = Knight(x=7,y=6,sl='N',team='white') self.board[7][7] = Rook(x=7,y=7,sl='R',team='white') self.board[2][0] = Pawn(x=3,y=0,sl='P',team='white') self.board[6][1] = Pawn(x=6,y=1,sl='P',team='white') self.board[6][2] = Pawn(x=6,y=2,sl='P',team='white') self.board[6][3] = Pawn(x=6,y=3,sl='P',team='white') self.board[6][4] = Pawn(x=6,y=4,sl='P',team='white') self.board[6][5] = Pawn(x=6,y=5,sl='P',team='white')
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
python, object-oriented, game, chess self.board[6][5] = Pawn(x=6,y=5,sl='P',team='white') self.board[6][6] = Pawn(x=6,y=6,sl='P',team='white') self.board[6][7] = Pawn(x=6,y=7,sl='P',team='white') for i in range(9): self.board[i][8 ]= Number(sl=i) for j in range(9): self.board[8][j] = Number(sl=j)
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
python, object-oriented, game, chess def display(self): for i in range(9): for j in range(9): print (self.board[i][j].sl, end=' ') print() def move(self): while True: print('Give a position of figure') sx,sy=Condition.s_choice(self.board) print(self.board[sx][sy].name) print('Now choose a destnation') dx,dy=Condition.d_choice(self.board) mark_same=Condition.same_team(sx,sy,dx,dy,self.board) mark_kill=Condition.kill(sx,sy,dx,dy,self.board) mark_Pawnkill=Condition.Pawnkill(sx,sy,dx,dy,self.board) mark_solid=Condition.solid(sx,sy,dx,dy,self.board) mark_move=self.board[sx][sy].req(sx,sy,dx,dy,self.board) if mark_solid==False: print('Figures are not ghosts') elif (mark_Pawnkill == True and abs(dx-sx) == abs(dy-sy) and mark_same == False): self.board[dx][dy] = self.board[sx][sy] self.board[dx][dy].x = dx self.board[dx][dy].y = dy self.board[sx][sy] = Empty(x='',y='',sl='.',team='') return self.board break elif (mark_move == True and mark_Pawnkill == False and (mark_kill == True or mark_same == False)): self.board[dx][dy] = self.board[sx][sy] self.board[dx][dy].x = dx self.board[dx][dy].y = dy self.board[sx][sy] = Empty(x='',y='',sl='.',team='') return self.board break else: print('Figure can not move here, try again') continue a=Chess_Board() a.display() #Early version of game engine while True: a.move() a.display()
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
python, object-oriented, game, chess a=Chess_Board() a.display() #Early version of game engine while True: a.move() a.display() Answer: Very nice game. Good effort! A few suggestions to make it better. The instruction to give x and y is a little confusing i tried entering 3, 6 then 3 and 6 ... it took me a while to figure out that I needed to enter one and then the other. making this small change could make it easier: try: print('give x and y') x = int(input("x:")) y = int(input("y:")) Not really a "code problem" per se, but rather a chess problem. The numbering on the board should start from the bottom left corner and move out. And it should count from 1, not from 0. r n b q k b n r 0 p p p p p p p p 1 P . . . . . . . 2 . . . . . . . . 3 . . . . . . . . 4 . . . . . . . . 5 . P P P P P P P 6 R N B Q K B N R 7 0 1 2 3 4 5 6 7 8 So that the white Rook on The Queen side is at coordinates (1,1) and the other white rook at coordinates (1,8) The system accepts negative values for x and y, as well as the number 8... all of these generate an error (since the grid currently starts counting at 0) At the start of the game, the left-most white pawn is sitting all the way across the board r n b q k b n r 0 p p p p p p p p 1 >P . . . . . . . 2 . . . . . . . . 3 . . . . . . . . 4 . . . . . . . . 5 . P P P P P P P 6 R N B Q K B N R 7 0 1 2 3 4 5 6 7 8 You could use unicode chess pieces, this would allow you to free the alphabet and use the traditional Letter-Number chess coordinates. This is the Wikipedia link. You can get them into python using chr() for i in range(12): chr(9812+i) output: '♔' '♕' '♖' '♗' '♘' '♙' '♚' '♛' '♜' '♝' '♞' '♟'
{ "domain": "codereview.stackexchange", "id": 42604, "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, object-oriented, game, chess", "url": null }
c++, c++17, template-meta-programming Title: Automatically registering a class using header-only templated classes Question: I'm trying to reduce the boilerplate of a lot of header-only classes I'm using. Each of these classes must go through a registration step. I want this step to be defined in the same file as the class definition. I came to the following solution (-std=c++17 required): #include <iostream> #include <typeinfo> template<typename T> bool __autoRegisteringFunction() { std::cout << "Registering: " << typeid(T).name() << std::endl; return true; } #define REGISTER_CLASS(TYPE) \ inline static const bool __registered = __autoRegisteringFunction<TYPE>(); class Foo { REGISTER_CLASS(Foo) }; class Bar { REGISTER_CLASS(Bar) }; int main() { return 0; } While doing some research, I realized it was even possible to skip the class name in the macro by being clever (inspired from this library): #include <iostream> #include <typeinfo> template<typename T> bool __autoRegisteringFunction() { std::cout << "Registering: " << typeid(T).name() << std::endl; return true; } template<typename T> struct __AutoRegisteringClass { inline static const bool __registered = __autoRegisteringFunction<T>(); }; #define REGISTER_CLASS() \ const void* __autoRegisteringMethod() const { \ return &__AutoRegisteringClass<decltype(*this)>::registered; \ } class Foo { REGISTER_CLASS() }; class Bar { REGISTER_CLASS() }; int main() { return 0; } Note that I simplified the example. The macro I plan to use needs more parameters, not requiring to pass the class name would both avoid possible typos and reduce repeatability. That's why I'm interested in the 2nd solution. From what I tested it works quite well. I still have a few questions:
{ "domain": "codereview.stackexchange", "id": 42605, "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++17, template-meta-programming", "url": null }
c++, c++17, template-meta-programming Is the first solution safe from the "static initialization order fiasco"? Is using a dummy method (never called) for instantiating a template thanks to decltype(*this) a common practice (or a known trick) in C++ meta-programming? Would you consider the given implementations well defined by standards and thus globally safe to use? Could the pattern I'm willing to use be somehow simplified? Answer: Questions: Is the first solution safe from the "static initialization order fiasco"? I hate that term. It is not relevant as there are no ordering issues in the code. The "static initialization order problem" happens when a static storage duration object depends on another static storage duration object that is in another compilation unit (and thus it is hard to guarantee the order of initialization without knowing things about the compiler and thus things are not portable easily). Note: There are is a simple solution to this problem once you know it exists. Is using a dummy method (never called) for instantiating a template thanks to decltype(*this) a common practice (or a known trick) in C++ meta-programming? Yes. Would you consider the given implementations well defined by standards and thus globally safe to use? Very close: The double underscore breaks some rules. But can be fixed. Not sure if the static inline const is guaranteed to not require declaration, I think that is an optimization. But can be fixed. Could the pattern I'm willing to use be somehow simplified? There is always somebody out there that will can come up with something better. Code Review: This function should be inline (it is obviously in a header file). template<typename T> bool __autoRegisteringFunction() { std::cout << "Registering: " << typeid(T).name() << std::endl; return true; }
{ "domain": "codereview.stackexchange", "id": 42605, "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++17, template-meta-programming", "url": null }
c++, c++17, template-meta-programming All identifiers with a double underscore are reserved. The rules for underscores at the beginning of identifiers are complex; prefer not to use them at the start (even if you know the rules as everybody else does not and will get it wrong). Again the double underscore. template<typename T> struct __AutoRegisteringClass { inline static const bool __registered = __autoRegisteringFunction<T>(); }; I am assuming the advantage here is that this does not take any space in the object while the original method does. Again the double underscore. #define REGISTER_CLASS() \ const void* __autoRegisteringMethod() const { \ return &__AutoRegisteringClass<decltype(*this)>::registered; \ } // ^^^ Forgot double underscore here. No need for return 0; in main. int main() { return 0; }
{ "domain": "codereview.stackexchange", "id": 42605, "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++17, template-meta-programming", "url": null }
python, multithreading Title: Replacement for starting threads from a for loop Question: I have the following code: def start_threads(self): thread_pool = [] for obj in self._objs_list: thread = threading.Thread(target=self._do_task, args=(obj,)) thread_pool.append(thread) thread.start() for thread in thread_pool: thread.join() self._do_final_task() _do_task is basically a method which process some I/O operations and I want to to execute it in parallel for each obj in self._objs_list I want self._do_final_task() to be executed only once all the threads finished their job. My code works, however it is very ugly and immature (it seems). Is there a more elegant way of doing so? Answer: At least for many situations, modern Python does not require so much hoop-jumping for multithreading or multiprocessing situations -- no need to worry about appending, starting, and joining. A schematic illustration is shown below. See the docs to decide which of the many flavors of map or imap to use for your situation. In this example, return values from self._do_task will arrive as result in the for-loop. from multiprocessing.pool import ThreadPool def start_threads(self): with ThreadPool() as pool: for result in pool.map(self._do_task, self._objs_list): ... self._do_final_task()
{ "domain": "codereview.stackexchange", "id": 42606, "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, multithreading", "url": null }
java, object-oriented, game, homework, javafx Title: Space Invaders clone for a college project Question: Edit: the project was submitted, and I got a good grade! :D I am finishing up a project for my computer science class. The project is a space invaders clone that uses the JavaFX library to provide graphics. The program itself is complete and functional, but I wanted to make sure that the code itself is readable and proper. The due date is tomorrow (December 12, 12 AM), so it would be great if I could get an answer before then, but if the date is passed I would still appreciate any advice on improving my code structure/practices (I'm a lurker, but I'm new to posting on codereview/StackExchange/StackOverflow, so please excuse me if this isn't proper form. I have no intention of being rude or demanding). I am specifically looking for criticism that covers: Modular design Documentation Efficiency Proper OOP Code Structure Anything else you notice that is poorly written/implemented I have listed my code below, separated by class. If you put all code segments into a file in the order in which they were presented, it would form the source code. MyProj class/imported references: package myproj; import java.util.ArrayList; import javafx.scene.shape.Polygon; import javafx.scene.shape.Polyline; import javafx.scene.layout.Pane; import javafx.scene.text.Text; import javafx.scene.text.TextAlignment; import javafx.scene.Scene; import javafx.scene.input.KeyCode; import javafx.scene.paint.Color; import javafx.event.ActionEvent; import javafx.scene.Node; import javafx.stage.Stage; import javafx.event.EventHandler; import javafx.animation.KeyFrame; import javafx.animation.Timeline; import javafx.util.Duration; import javafx.application.Application;
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx public class MyProj extends Application{ public void start(Stage mainStage){ GameManager gameManager = new GameManager(); Scene mainScene = new Scene(gameManager.gamePane, 500, 600); mainStage.setScene(mainScene); mainStage.setResizable(false); mainStage.show(); mainScene.setFill(Color.BLACK); //Set the game pane to the start screen gameManager.gamePane.requestFocus(); gameManager.startScreen("Space Invaders\n\nPress arrow keys to move\nPress space to shoot\nKill all of the aliens to win\n\nPress any key to start game"); } public static void main(String[] args) { Application.launch(args); } }
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx GameManager class: //GameManager serves as the manager of the pane that contains the game and //everything in it. It handles collisions, movement, controls, score, lives, setting up //the game, and starting the game. class GameManager{ Pane gamePane; Player player; AlienGridController alienGrid; Bullet activePlayerBullet; Text scoreText; Text lifeText; private int score; private int lives; //Increments in pixels that the player and alien grid move in private int playerMovementIncrement = 5; private int alienGridMovementIncrementX = 10; private int alienGridMovementIncrementY = 20; //Event handler that moves the player EventHandler<ActionEvent> playerMovement = e -> { //Checks to see if the player will be out of bounds if they move an //increment, and move them if they won't be if(player.getTranslateX() + player.getBoundsInLocal().getWidth() + playerMovementIncrement < gamePane.getWidth() && player.getTranslateX() + playerMovementIncrement > 0) player.setTranslateX(player.getTranslateX() + playerMovementIncrement); }; //Event handler that moves the alien grid EventHandler<ActionEvent> alienGridMovement = e -> { //Ensures that the column and row borders are calibrated in order for //getWidth() and getHeight() to be accurate alienGrid.calibrateColumnBorders(); alienGrid.calibrateRowBorders(); //Check if the alien grid will be out of bounds if it moves another //increment. If it will be, then it is moved down and the x movement //increment is inverted. If the alien grid won't be out of bounds, //then move it an x increment. //In the case that the alien grid manages to get to the level of the //player, then invoke startScreen()
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx //player, then invoke startScreen() if(alienGrid.getTranslateX() + alienGrid.getWidth() + alienGridMovementIncrementX > gamePane.getWidth() || alienGrid.getTranslateX() + alienGridMovementIncrementX < 0){ alienGrid.moveY(alienGridMovementIncrementY); alienGridMovementIncrementX = Math.negateExact(alienGridMovementIncrementX); if(alienGrid.getHeight() + alienGrid.getTranslateY() + alienGridMovementIncrementY > player.getTranslateY()) startScreen("Game Over\n\npress any key to restart"); } else alienGrid.moveX(alienGridMovementIncrementX); }; //Event handler that detects if bullets hit the player, aliens, or walls, //and acts accordingly EventHandler<ActionEvent> bulletCollisionDetection = e -> { //Gets the list of bullets currently in gamePane ArrayList<Node> bulletList = getBullets(); //Iterate through the bullets for(int i = 0; i < bulletList.size(); i++){ Bullet bullet = (Bullet)bulletList.get(i); //Check if bullet is out of bounds, and remove accordingly if(bullet.getTranslateY() > gamePane.getHeight() || bullet.getTranslateY() < 0){ gamePane.getChildren().remove(bullet); }
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx //Check if bullet has collided with the player. If the bullet tag is //Bullet.ALIEN, then remove the bullet and invoke playerDeath() else if(player.getBoundsInParent().intersects(bullet.getBoundsInParent()) && bullet.tag.equals(Bullet.ALIEN)){ gamePane.getChildren().remove(bullet); playerDeath(); } //Check if the bullet has collided with an alien. If it has, then //remove the bullet and alien, set the corresponding alien grid cell //to null, add 100 points to the score, and check if the grid is //empty. else{ for(int column = 0; column < alienGrid.getAlienList().length; column++){ for(int row = 0; row < alienGrid.getAlienList()[column].length; row++){ if(alienGrid.getAlienList()[column][row] != null){ if(alienGrid.getAlienList()[column][row].getBoundsInParent().intersects(bullet.getBoundsInParent())){ gamePane.getChildren().remove(bullet); gamePane.getChildren().remove(alienGrid.getAlienList()[column][row]); alienGrid.getAlienList()[column][row] = null; setScore(score + 100); if(alienGrid.isEmpty()) startScreen("You Won!\n\nPress any key to restart"); } } } } } } }; //Event handler that fires bullets from alien grid EventHandler<ActionEvent> alienFire = e -> { int randomColumn; Alien lowestAlien; while(true){ //Choose random column and check if it's empty. if so, then choose //another.
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx //another. randomColumn = (int)((alienGrid.getRightBorder() - alienGrid.getLeftBorder()) * Math.random()) + alienGrid.getLeftBorder(); if(alienGrid.getAlienList()[randomColumn] != null){ break; } } for(int row = alienGrid.getAlienList()[randomColumn].length - 1; row > 0; row--){ //Iterate through the rows for the column, starting from the lowest. //If the current row contains an alien, fire a bullet from that alien. if(alienGrid.getAlienList()[randomColumn][row] != null){ lowestAlien = alienGrid.getAlienList()[randomColumn][row]; gamePane.getChildren().add(new Bullet(lowestAlien.getTranslateX() + lowestAlien.getBoundsInLocal().getWidth() / 2, lowestAlien.getTranslateY() + lowestAlien.getBoundsInLocal().getHeight(), -3, Bullet.ALIEN)); break; } } }; //Timelines for the four previous event handlers Timeline playerMovementTimeline = new Timeline(new KeyFrame(Duration.millis(20), playerMovement)); Timeline alienGridMovementTimeline = new Timeline(new KeyFrame(Duration.millis(500), alienGridMovement)); Timeline bulletCollisionDetectionTimeline = new Timeline(new KeyFrame(Duration.millis(50), bulletCollisionDetection)); Timeline alienFireTimeline = new Timeline(new KeyFrame(Duration.seconds(1), alienFire)); //Create new pane, score text, and life text objects, and set cycle counts //for the Timeline objects to indefinite. GameManager(){ gamePane = new Pane(); scoreText = new Text(); lifeText = new Text(); playerMovementTimeline.setCycleCount(Timeline.INDEFINITE); alienGridMovementTimeline.setCycleCount(Timeline.INDEFINITE); bulletCollisionDetectionTimeline.setCycleCount(Timeline.INDEFINITE); alienFireTimeline.setCycleCount(Timeline.INDEFINITE); }
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx alienFireTimeline.setCycleCount(Timeline.INDEFINITE); } //Set up gamePane and its children void setUpGame(){ //Clear the game pane of all nodes gamePane.getChildren().clear(); this.player = new Player(); this.alienGrid = new AlienGridController(5, 8); //Set the score to 0 and position/color the score text setScore(0); scoreText.setTranslateX(10); scoreText.setTranslateY(10); scoreText.setStroke(Color.WHITE); //Set the lives to 3 and position/color the life text setLives(3); lifeText.setTranslateX(gamePane.getWidth() - lifeText.getBoundsInLocal().getWidth() - 10); lifeText.setTranslateY(10); lifeText.setStroke(Color.WHITE); //Position the alien grid alienGrid.setTranslateX((gamePane.getWidth() / 2) - (alienGrid.getWidth() / 2)); alienGrid.setTranslateY(50); //Position the player player.setTranslateX((gamePane.getWidth() / 2) - (player.getBoundsInLocal().getWidth() / 2)); player.setTranslateY(gamePane.getHeight() - 50); //Add all of the aliens in the alien grid to the gamePane gamePane.getChildren().addAll(player, scoreText, lifeText); for(int column = 0; column < alienGrid.getAlienList().length; column++) for(int row = 0; row < alienGrid.getAlienList()[column].length; row++) gamePane.getChildren().add(alienGrid.getAlienList()[column][row]); } //Start the alien movement, bullet collision, and alien firing timelines, //and enable controls. void startGame(){ alienGridMovementTimeline.play(); bulletCollisionDetectionTimeline.play(); alienFireTimeline.play(); enableControls(); } //Arranges the player's death, and ends game if necessary void playerDeath(){ //Event handler that is played after the deathTimeline
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx void playerDeath(){ //Event handler that is played after the deathTimeline EventHandler<ActionEvent> deathTimelineFinished = e -> { //If no more lives remain, invoke startScreen if(lives <= 0) startScreen("Game Over\n\npress any key to restart"); else{ //Remove a life setLives(lives - 1); //Start necessary timelines alienGridMovementTimeline.play(); alienFireTimeline.play(); enableControls(); //Center player player.setTranslateX(gamePane.getWidth() / 2 - (player.getBoundsInLocal().getWidth() / 2)); player.setTranslateY(gamePane.getHeight() - 50); //In case of a freak one-off error on the timeline's part, //ensure that player is visible player.setVisible(true); } }; //Timeline that flashes player to show damage Timeline deathTimeline = new Timeline(new KeyFrame(Duration.millis(300), e -> player.setVisible(!player.isVisible()))); deathTimeline.setOnFinished(deathTimelineFinished); deathTimeline.setCycleCount(4); //Pause necessary timelines alienGridMovementTimeline.pause(); alienFireTimeline.pause(); playerMovementTimeline.pause(); disableControls(); //Remove all bullets gamePane.getChildren().removeAll(getBullets()); deathTimeline.play(); } //Displays simple start screen that starts the game when any key is pressed void startScreen(String message){ //Clear the game pane of all nodes gamePane.getChildren().clear(); Text startScreenText = new Text(message);
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx Text startScreenText = new Text(message); //Move, style, and add the start screen text to the game pane startScreenText.setTextAlignment(TextAlignment.CENTER); startScreenText.setTranslateX((gamePane.getWidth() / 2) - (startScreenText.getBoundsInLocal().getWidth() / 2)); startScreenText.setTranslateY((gamePane.getHeight() / 2) - (startScreenText.getBoundsInLocal().getHeight() / 2)); startScreenText.setStroke(Color.WHITE); gamePane.getChildren().add(startScreenText); //Bind any key press to set up and start game gamePane.setOnKeyPressed(e -> { setUpGame(); startGame(); }); } //Bind the player controls void enableControls(){ gamePane.setOnKeyPressed(e -> { //Starts player movement to the left when left key is pressed if(e.getCode().equals(KeyCode.LEFT)){ playerMovementTimeline.play(); playerMovementIncrement = -2; } //Starts player movement to the right when right key is pressed if(e.getCode().equals(KeyCode.RIGHT)){ playerMovementTimeline.play(); playerMovementIncrement = 2; } //If there is not already a bullet launched by the player in the //game pane, then launch one when space is pressed if(e.getCode().equals(KeyCode.SPACE)){ if(!gamePane.getChildren().contains(activePlayerBullet)){ activePlayerBullet = new Bullet(player.getTranslateX() + player.getBoundsInLocal().getWidth() / 2, player.getTranslateY() - 20, 3, Bullet.PLAYER); gamePane.getChildren().add(activePlayerBullet); } } }); gamePane.setOnKeyReleased(e -> { //Stop player movement if a player movement key is released
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx //Stop player movement if a player movement key is released if(e.getCode().equals(KeyCode.LEFT) || e.getCode().equals(KeyCode.RIGHT)){ playerMovementTimeline.pause(); } }); } //Disables the player controls void disableControls(){ //Bind key presses to null, disabling controls gamePane.setOnKeyPressed(null); gamePane.setOnKeyReleased(null); } //Gets all bullets currently in the game pane ArrayList<Node> getBullets(){ ArrayList<Node> bulletList = new ArrayList<Node>(); //Iterates through the nodes in game pane. If the current node is an //instance of Bullet, then add it to the bullet list; for(int node = 0; node < gamePane.getChildren().size(); node++) if(gamePane.getChildren().get(node) instanceof Bullet) bulletList.add(gamePane.getChildren().get(node)); return bulletList; } //Set score and scoreText void setScore(int score){ this.score = score; scoreText.setText("Score: " + score); } //Set lives and lifeText void setLives(int lives){ this.lives = lives; lifeText.setText("Lives: " + lives); } }
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx AlienGridController Class: //AlienGridController arranges alien objects in a grid pattern, moves and //positions them in unision, and performs calculations to determine its borders, //width, and height for the convenience of gameManager. I originally planned to //use gridPane, but a combination of factors(collision detection, alien placement, etc) //led to me making my own class. class AlienGridController{ private Alien[][] alienList; private Alien outerAlienLeft; private Alien outerAlienRight; private Alien outerAlienTop; private Alien outerAlienBottom; private int leftBorder = 0; private int rightBorder = 0; private int topBorder = 0; private int bottomBorder = 0; private double cellMargin = 10; AlienGridController(int rows, int columns){ //Initializes the alien list to hold the specified rows and columns alienList = new Alien[columns][rows]; //Iterate through the alien list, setting each value to a new alien //object and positioning it according to previous entries and the cell //margin for(int column = 0; column < columns; column++){ for(int row = 0; row < rows; row++){ alienList[column][row] = new Alien(); alienList[column][row].setTranslateX(row * (cellMargin + alienList[column][row].getBoundsInLocal().getWidth())); alienList[column][row].setTranslateY(row * (cellMargin + alienList[column][row].getBoundsInLocal().getHeight())); } } //Initially calibrate the column and row borders and set the translate //values to 0 calibrateColumnBorders(); calibrateRowBorders(); setTranslateX(0); setTranslateY(0); } //Finds the far left and far right column index and alien objects in the alien //grid void calibrateColumnBorders(){ boolean leftBorderSet = false; boolean rightBorderSet = false;
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx boolean leftBorderSet = false; boolean rightBorderSet = false; //Iterate through the alien list, starting from the left. Once a alien //object is found, the left border is set as that iteration's column, //and the alien object that is furthest left is set as that iteration's //alien. for(int column = 0; column < alienList.length; column++){ for(int row = 0; row < alienList[column].length; row++){ if(alienList[column][row] != null){ leftBorder = column; outerAlienLeft = alienList[column][row]; leftBorderSet = true; break; } } if(leftBorderSet) break; } //Iterate through the alien list, starting from the right. Once a alien //object is found, the right border is set as that iteration's column, //and the alien object that is furthest right is set as that iteration's //alien. for(int column = alienList.length - 1; column >= 0; column--){ for(int row = alienList[column].length - 1; row >= 0; row--){ if(alienList[column][row] != null){ rightBorder = column; outerAlienRight = alienList[column][row]; rightBorderSet = true; break; } } if(rightBorderSet) break; } } //Finds the top and bottom row index and alien objects in the alien grid void calibrateRowBorders(){ boolean topBorderSet = false; boolean bottomBorderSet = false; //Iterate through the alien list, starting from the top. Once a alien //object is found, the top border is set as that iteration's row, //and the alien object that is furthest up is set as that iteration's //alien.
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx //and the alien object that is furthest up is set as that iteration's //alien. for(int row = 0; row < alienList[0].length; row++){ for(int column = 0; column < alienList.length; column++){ if(alienList[column][row] != null){ topBorder = row; outerAlienTop = alienList[column][row]; topBorderSet = true; break; } } if(topBorderSet) break; } //Iterate through the alien list, starting from the bottom. Once a alien //object is found, the bottom border is set as that iteration's row, //and the alien object that is furthest down is set as that iteration's //alien. for(int row = alienList[0].length - 1; row >= 0; row--){ for(int column = alienList.length - 1; column >= 0; column--){ if(alienList[column][row] != null){ bottomBorder = row; outerAlienBottom = alienList[column][row]; bottomBorderSet = true; break; } } if(bottomBorderSet) break; } } //Get the list of aliens in the alien grid public Alien[][] getAlienList(){ return alienList; } //Check if the grid is empty public boolean isEmpty(){ //Iterate through the alien grid. If an alien is found, return false for(int column = 0; column < alienList.length; column++) for(int row = 0; row < alienList[column].length; row++) if(alienList[column][row] != null) return false; return true; } //Set the X transform of the aliens inside the grid void setTranslateX(double position){ //Iterate through the alien grid. If an alien is found, than transform it
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx //Iterate through the alien grid. If an alien is found, than transform it //while accounting for the cell margin and aliens to the lefr for(int column = 0; column < alienList.length; column++) for(int row = 0; row < alienList[column].length; row++) if(alienList[column][row] != null) alienList[column][row].setTranslateX(position + (column * (cellMargin + alienList[column][row].getBoundsInLocal().getWidth()))); } //Set the Y transform of the aliens inside the grid void setTranslateY(double position){ //Iterate through the alien grid. If an alien is found, than transform it //while accounting for the cell margin and aliens above for(int column = 0; column < alienList.length; column++) for(int row = 0; row < alienList[column].length; row++) if(alienList[column][row] != null) alienList[column][row].setTranslateY(position + (row * (cellMargin + alienList[column][row].getBoundsInLocal().getHeight()))); } //Get the x position of the outer left alien, which represents the alien grid's //x position double getTranslateX(){ return outerAlienLeft.getTranslateX(); } //Get the y position of the outer top alien, which represents the alien grid's //y position double getTranslateY(){ return outerAlienTop.getTranslateY(); } //Increments the alien grid on the x axis void moveX(double increment){ setTranslateX(getTranslateX() + increment); } //Increments the alien grid on the y axis void moveY(double increment){ setTranslateY(getTranslateY() + increment); } //Get the width of the alien grid double getWidth(){ return outerAlienRight.getTranslateX() + outerAlienRight.getBoundsInLocal().getWidth() - outerAlienLeft.getTranslateX(); } //Get the height of the alien grid
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx } //Get the height of the alien grid double getHeight(){ return outerAlienBottom.getTranslateY() + outerAlienBottom.getBoundsInLocal().getHeight() - outerAlienTop.getTranslateY(); } //Get the index of the right border int getRightBorder(){ return rightBorder; } //Get the index of the left border int getLeftBorder(){ return leftBorder; } //set the cell margin void setCellMargin(double cellMargin){ this.cellMargin = cellMargin; } double getCellMargin(){ return cellMargin; } }
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx Alien class: //The Alien class constructs a Polygon node that can be manipulated class Alien extends Polygon{ Alien(){ super(0.0, 4.0, 0.0, 12.0, 4.0, 16.0, 8.0, 16.0, 6.0, 24.0, 10.0, 24.0, 12.0, 16.0, 16.0, 16.0, 18.0, 24.0, 22.0, 24.0, 20.0, 16.0, 24.0, 16.0, 28.0, 12.0, 28.0, 4.0, 24.0, 0.0, 4.0, 0.0); setStrokeWidth(2); setStroke(Color.WHITE); } } Bullet class: class Bullet extends Polyline{ //Tag constants to identify if the bullet is from the alien or player public final static String ALIEN = "ALIEN"; public final static String PLAYER = "PLAYER"; double increment; String tag; //Event handler that moves the bullet EventHandler<ActionEvent> bulletMovement = e -> this.setTranslateY(this.getTranslateY() - increment); Timeline bulletTimeline = new Timeline(new KeyFrame(Duration.millis(10), bulletMovement)); //Set bullet position, the movement increment, the tag, and style Bullet(double positionX, double positionY, double increment, String tag){ super(0.0, 0.0, 0.0, 10.0); setTranslateX(positionX); setTranslateY(positionY); this.increment = increment; this.tag = tag; setStroke(Color.WHITE); bulletTimeline.setCycleCount(Timeline.INDEFINITE); bulletTimeline.play(); } }
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
java, object-oriented, game, homework, javafx Answer: Thanks for sharing your code. Just a few things coming to my mind when skimming over it: Inappropriate inheritance In OOP we create subclasses to extend the behavior of a parent class. Your classes Bullet and Alien do not extend the behavior of their parent classes but only configure them. violation of information hiding / encapsulation Your class GameManager has a property gamePane that is directly accessed from your class MyProj. Since you instantiate GameManager immediately before this access in MyProj you could instead instantiate the Panel object in MyProj and pass it as constructor parameter to GameManager. Inline comments Most of your inline comments are just useless because they repeat what the code itself already expresses (or could express with more careful naming). But some of them are lies: //Set bullet position, the movement increment, the tag, and style Bullet(double positionX, double positionY, double increment, String tag){ No! This is not a setter method, its the Constructor of that class that might (but shouldn't) set something as a side effect. Work in constructors Constructors should not have any logic. They should just assign their parameters to (final) member variables. That's it. Any calculation should be done outside the constructor and only results should be passed in. Disclaimer This is just my personal opinion and may be completely wrong.
{ "domain": "codereview.stackexchange", "id": 42607, "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, game, homework, javafx", "url": null }
python, python-3.x, interpreter Title: Interpreter for NLRNIS programming language, written in Python
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter Question: Code: # read file of first agrument import sys, os try: data = open(sys.argv[1]).read() except: data = open("File.txt").read() sys.argv.append("File.txt") dct = {"@": data, "E": "0"} iteration = 0 RESET = False define = False printf = False replace = False inp = False join = False Reverse = False getascii = False getfirstchar = False removeallexceptcertainchar = False readfile = False comment = False multilinecomment = False takeagrument = False definebutvar = False getfilesandfolders = False haltifeof = False ################################################################################ variable = "" variable2 = "" variable3 = "" variable4 = "" variable5 = "" variable6 = "" string = "" escape = False isready = False isset = False isgo = False def erroring(errtype, errreason, tb): print(errreason, end="", file=sys.stderr) sys.excepthook = erroring def dctremoveallexceptcertain(string, variable): # removes all except certain characters # string = string to be modified # variable = characters to be kept # returns modified string global newstring newstring = "" for i in string: if i in variable: newstring += i return newstring while True: # Note you should use try and except to catch errors, not if x in y: for i in data: if printf: # print the variable of dct variable if i in dct: print(dct[i], end = "") printf = False else: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) break elif define: if isready: if escape: # check if i is quote or backslash add to string else add backslash and i if i == "\"" or i == "\\": string += i escape = False else: string += "\\" + i
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter else: string += "\\" + i escape = False elif i == "\"": dct[variable] = string string = "" isready = False define = False # check if the variable is "@" change the data if variable == "@": RESET = True break elif i == "\\": escape = True continue else: string += i else: variable = i isready = True elif replace: # get 3 variables if isgo: try: dct[variable] = dct[variable2].replace(variable3, i) except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) break replace = isset = isready = isgo = False # check if the variable is "@" change the data if variable == "@": RESET = True break elif isset: variable3 = i isgo = True elif isready: variable2 = i isset = True else: variable = i isready = True elif inp: try: dct[i] = input() dct["E"] = "0" except EOFError: dct["E"] = "1" inp = False if i == "@": RESET = True break elif join: if isset: try: dct[variable] = dct[variable2] + dct[i] except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration)
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter break join = isset = isready = isgo = False # check if the variable is "@" change the data if variable == "@": RESET = True break elif isready: variable2 = i isset = True else: variable = i isready = True elif Reverse: # this is equivalent to pseudocode var = var2.reverse() if isready: try: dct[variable] = dct[i][::-1] except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) break isready = False Revert = False if variable == "@": RESET = True break else: variable = i isready = True elif getfirstchar: # gets the first character of the variable if isready: try: dct[variable] = dct[i][0] except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) isready = False getfirstchar = False if variable == "@": RESET = True break else: variable = i isready = True elif getascii: # gets ascii value of the variable if isready: try: dct[i] try: dct[variable] = ord(dct[i]) except: raise Exception("ERROR IN FILE", sys.argv[1], "INVALID NUMBER IN ITERATION", iteration) except:
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) getascii = False isready = False if variable == "@": RESET = True break else: variable = i isready = True elif removeallexceptcertainchar: # removes all except certain character if isready: try: dct[variable] = dctremoveallexceptcertain(dct[variable], dct[i]) except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) isready = False removeallexceptcertainchar = False if variable == "@": RESET = True break else: variable = i isready = True elif readfile: if isready: try: dct[i] except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) try: dct[variable] = open(dct[i], "r").read() dct["E"] = "0" except: dct["E"] = "1" isready = False readfile = False if variable == "@": RESET = True break else: variable = i isready = True elif comment: # ignore until a newline is found if i == "\n": comment = False elif multilinecomment: if i == "}": multilinecomment = False elif takeagrument: # checks if the variable is defined and the variable is a number if isready:
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter # checks if the variable is defined and the variable is a number if isready: try: dct[i] try: int(dct[i]) try: dct[variable] = sys.argv[int(dct[i])] dct["E"] = "0" except: dct["E"] = "1" except: raise Exception("ERROR IN FILE", sys.argv[1], "INVALID NUMBER", iteration) except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) isready = False takeagrument = False if variable == "@": RESET = True else: variable = i isready = True elif definebutvar: # like > but it defines the variable if isready: try: dct[variable] = dct[i] except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) isready = False definebutvar = False if variable == "@": RESET = True break else: variable = i isready = True elif getfilesandfolders: # gets all files and folders in a variable if folder not found the variable "E" is equal to "1" else "0" if isready: # check if variable is defined try: dct[i] except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) try: files = os.listdir(dct[i]) dct[variable] = files dct["E"] = "0" except:
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter dct[variable] = files dct["E"] = "0" except: dct["E"] = "1" isready = False getfilesandfolders = False if variable == "@": RESET = True break else: variable = i isready = True elif haltifeof: if dct["E"] == "1":break haltifeof = False elif i == "@": ############################################################################################################# RESET = True break elif i == "H": break elif i == ">": define = True elif i == "*": printf = True elif i == "$": replace = True elif i == "&": inp = True elif i == "+": join = True elif i == "/": Reverse = True elif i == "?": getfirstchar = True elif i == ".": getascii = True elif i == "!": removeallexceptcertainchar = True elif i == ";": readfile = True elif i == ":": comment = True elif i == "{": multilinecomment = True elif i == "|": takeagrument = True elif i == "=": definebutvar = True elif i == "%": getfilesandfolders = True elif i == "_": haltifeof = True # its not necessary to raise error invalid command # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # iteration += 1 # check if string still contains something put it in dct if string != "": dct[variable] = string string = "" define = False isready = False
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter dct[variable] = string string = "" define = False isready = False isset = False isgo = False printf = False replace = False inp = False join, Reverse = False, False getfirstchar = False getascii = False removeallexceptcertainchar = False readfile = False comment = False multilinecomment = False takeagrument = False definebutvar = False getfilesandfolders = False # check if dct is "@" change the data if variable == "@": RESET = True if RESET: RESET = False data = dct["@"] iteration = 0 continue break try: print(dct["#"], end = "") except: pass
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter This is a programming language interpreter. I will show wiki. Commands: (a, b, c, d means variables next command) "@" goto first char "H" halt (must be uppercase, not lowercase) ">" define var Syntax: >~Hello" Escape is backslash (the quote is optional) "*" print the next char variable "$" a = b.replace(c, d) "&" Input the next char variable ("E" var is 1 if EOF) "+" a = b.join(c) "/" a = b.reverse() "?" a = b.getfirstchar() "." a = chr(b) "!" a = a but non-b chars removed ";" a = readfile(b) ("E" = 1 if the file doesn't exist) ":" comment "{" start multiline comment "}" end multiline comment "|" a = takearg(int(b)) "=" a = b "%" a = str(getfilesandfolders(b)) "_" halt if EOF Variables: "@" if the variable is edited, the program changes "#" print when program ends. "E" EOF Var Examples: >#Hello, World! Hello, World! @ Infinite loop &#*# read a line and output without newline twice >HHello, World!" NOP >H\""*H print double quotes Can you find bugs? Answer: To build a language with good quality code requires understanding the various approaches to building operators, evaluators and tokenizers. Lets go through the concepts from simplest to complicated, to build a calculator. Operators Operators is concerned with evaluating each operator. Normally an operator function can be passed arguments and return the result, like add(1, 2). Inline Operators The simplest approach is to define all the operators inline in a 'switch'. Since Python doesn't have a dedicated switch statement (until 3.10), we can instead use if elif else statements. if op == "+": result = lhs + rhs elif op == "-": result = lhs - rhs elif op == "*": result = lhs * rhs elif op == "/": result = lhs / rhs
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter Dictionary Operators We can store the operators in an object. Giving us the ability to pass Operators to the Evaluator and/or the Tokenizer. Since the operators are strings we can build a dictionary mapping operator strings to the corresponding operator function. When building the dictionary we can use lambda functions as we can define the operator inside the dictionary. However, lambda functions can only contain one expression in Python. If we need more than one expression then we will have to use 'full-fat' functions. I have made addition a 'full-fat' function, so we have an example of both approaches. def add(lhs, rhs): return lhs + rhs operators = { "+": add, "-": lambda lhs, rhs: lhs - rhs, "*": lambda lhs, rhs: lhs * rhs, "/": lambda lhs, rhs: lhs / rhs, } Class Operators Rather than defining the operators in a dictionary we can define the operators on a class. We can then build the operators dictionary somewhat automatically from the class. We do however have to use valid Python names for the operators. class CalculatorOperators: @staticmethod def add(lhs, rhs): return lhs + rhs @staticmethod def sub(lhs, rhs): return lhs - rhs @staticmethod def mul(lhs, rhs): return lhs * rhs @staticmethod def div(lhs, rhs): return lhs / rhs We can then iterate through the class by iterating through __dict__. To only get our functions we can filter out any dunder values. def get_operators(obj): return { name: getattr(obj, name) for name in obj.__dict__ if not (name.startswith("__") and name.endswith("__")) } print(get_operators(CalculatorOperators)) {'add': <function CalculatorOperators.add at 0x7ff171f61f30>, ...}
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter {'add': <function CalculatorOperators.add at 0x7ff171f61f30>, ...} Metaclass Operators We can automatically call get_operators by having a base class with an __init_subclass__ method or a custom metaclass. Either can run when the class is defined and transparently build operators. class Operators: def __init_subclass__(cls, /, **kwargs): cls.OPERATORS = get_operators(cls) class CalculatorOperators(Operators): @staticmethod def add(lhs, rhs): return lhs + rhs ... print(CalculatorOperators.OPERATORS) {'add': <function CalculatorOperators.add at 0x7ff171f623b0>, ...} Decorated Class Operators We can customize the key to use by defining a decorator function (somewhat comprehensive guide by me). The decorator function can assign the desired name to an attribute on the function. We'd need to make a little change to how we build operators. We'd need to use the function's attribute value if available. def with_name(name=None): def inner(fn): fn.name = name return fn return inner class CalculatorEvaluator: @with_name("+") @staticmethod def add(lhs, rhs): return lhs + rhs ... operators = { getattr(fn, "name", name): fn for name, fn in CalculatorEvaluator.__dict__.items() if not (name.startswith("__") and name.endswith("__")) } print(operators) {'+': <staticmethod(<function CalculatorEvaluator.add at 0x7ff171f62560>)>, ...} Comparison Inline Operators The simplest approach. However with larger operator sets or complicated logic for the operators the code quickly becomes unmaintainable. The approach is good when building a very simple evaluator for BrainFuck.
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter Dictionary Operators A very common approach. Googling "Python switch" is bound to result in results saying to use a dictionary. The approach has a complexity improvement over Inline Operators, going from \$O(n)\$ to \$O(1)\$ operator lookup. I, however, don't find the approach to be the much more maintainable to Inline Operators. As the approach is prone to code fragmentation and the function in operators getting out of sync. The approach is good when; all the operators can be defined as lambdas and documenting the operators isn't needed. Or, the operators must be fragmented and can't be contained within a single class/namespace. For example a menu screen, as the user can enter the same view from two different ways. Class Operators The most advanced approach of the three, requiring an understanding of __dict__ (and potentially __slots__). After learning the little bit of metaprogramming required to understand the approach I find the approach to be the simplest. We can throw all our operators in one class, document the class like any other class and have the approach best for our use case. Whilst we currently need to use Decorated Class Operators, we can normally use the simpler Class Operators approach when using the best approach to defining our own language. The approach seems to be the standard approach ranging from single operator evaluators like cmd to parser libraries like TatSu. For the rest of the answer operators is the following: operators = { "+": lambda lhs, rhs: lhs + rhs, "-": lambda lhs, rhs: lhs - rhs, "*": lambda lhs, rhs: lhs * rhs, "/": lambda lhs, rhs: lhs / rhs, } Evaluator Now we've decided gone through the operators we can move onto the evaluators. The evaluators are generally pretty simple, like the operators. Single Operator Evaluator We need to evaluate an operator and some values. To do so we just get the operator from operators and just pass the values. print(operators["+"](1, 2)) 3
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter 3 Stream Evaluator Stream evaluators typically use a stack, and so work best on postfix input. In Python the stack can just be a list. Then, whenever we have a non-operator token; we add the token to the stack. Whenever we have a operator token; we pop the operands from the stack, and pass the operands to the function. We then add the result of the operator to the stack. After processing all tokens we pop the top value of the stack. def evaluate__stream(tokens, operators): stack = [] for token in tokens: if token in operators: b = stack.pop() a = stack.pop() token = operators[token](a, b) stack.append(token) return stack.pop() evaluate__stream([1, 2, 3, "*", "+"], operators) 7 Tree Evaluator Tree evaluators interact with a tree. To have a tree the input must be nodes of some sort. We can build a simple Node class to store the operator and children. class Node: def __init__(self, operator, *children): self.operator = operator self.children = children def __repr__(self): values = [self.operator, *self.children] return f"Node({', '.join(map(repr, values))})" def __str__(self): # Only supports binary operators op = self.operator lhs = self.children[0] rhs = self.children[1] return f"({lhs} {op} {rhs})" ast = Node("+", 1, Node("*", 2, 3)) print(repr(ast)) print(ast) Node('+', 1, Node('*', 2, 3)) (1 + (2 * 3)) We then perform a depth first walk of the tree. Otherwise we will perform the following operation 1 + Node("*", 2, 3), resulting in an error. We can build a simple tree evaluator using recursion. def evaluate__tree(node, operators): if not isinstance(node, Node): return node children = [ evaluate__tree(child, operators) for child in node.children ] return operators[node.operator](*children) print(evaluate__tree(ast, operators)) 7 Comparison
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter print(evaluate__tree(ast, operators)) 7 Comparison Single Operator Evaluator Very simple and allows simple control flow. The approach is good for menus or terminal commands, like with cmd. Stream Evaluator Good at implementing postfix evaluators. However, most human languages aren't postfix only; binary operators typically are infix. And, functions are typically prefix. The approach is good for postfix languages, or languages easily converted to postfix. Tree Evaluator Trees are typically easier to understand then a postfix stream. As such languages typically build and evaluate an Abstract Syntax Tree (AST). An AST is also easier to mutate as we don't need to partially evaluate the stream to find the children. The approach is good for most languages. The Evaluator to pick is largely dictated by how the tokens are made. Using a Tree Evaluator with the Single Operator Tokenizer doesn't make sense. As the Evaluator is completely overkill for the Tokenizer. Additionally the Single Operator Evaluator can only work with the Single Operator Tokenizer. Tokenizer Now we've got the easy stuff out of the way. Lets focus on the hard part, converting a string into a bunch of tokens. Single Operator Tokenizer The simplest approach is to get the user to provide the individual tokens. We can do so by just calling input a bunch, effectively sidestepping building a tokenizer. lhs = int(input("lhs> ")) op = input("op > ") rhs = int(input("rhs> ")) print(operators[op](lhs, rhs)) lhs> 1 op > + rhs> 2 3 Simple Tokenizer (postfix) The section is based of another one of my answers. Tokenizers can be pretty complicated to build correctly as a beginner. In the past I've gotten caught up trying to implement something, but I forget I need to make the tokenizer do everything. So my code became complicated as I missed the forrest for the trees. Lets use TDD to build the tokenizer:
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter We'll handle only numbers. However only one character, and we'll convert to an int. def tokenize__simple(text): for char in text: if char in "0123456789": yield int(char) >>> list(tokenize__simple("123")) [1, 2, 3] We'll handle one number of any size. We'll build up a 'token' stack. We'll use a list to ensure \$O(1)\$ time when adding new characters. As Python's strings guarantee a minimum \$O(n)\$ time when adding. def tokenize__simple(text): token = [] for char in text: if char in "0123456789": token.append(char) if token: yield int("".join(token)) >>> list(tokenize__simple("1 2 3")) [123] >>> list(tokenize__simple("")) [] We'll handle spaces. We just need to copy the if token code. And reset token after yielding one. def tokenize__simple(text): token = [] for char in text: if char in "0123456789": token.append(char) elif char in " ": if token: yield int("".join(token)) token = [] if token: yield int("".join(token)) >>> list(tokenize__simple("1 2 3")) [1, 2, 3] We'll handle operators. Basically the same as spaces but we also yield the operator. def tokenize__simple(text): token = [] for char in text: if char in "0123456789": token.append(char) elif char in " +-*/": if token: yield int("".join(token)) token = [] if char != " ": yield char if token: yield int("".join(token)) >>> list(tokenize__simple("1+ 2*3")) [1, "+", 2, "*", 3] From here we can tokenize numbers in postfix notation and pass the values to the Stream Evaluator we wrote earlier. evaluate__stream(tokenize__simple("1 2 3 * +"), operators) 7
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter 7 Simple Tokenizer + Transformation (Infix Stream) Performing transformations on the tokens afterwards is fairly common. For example, we can use Dijkstra's Shunting-Yard algorithm to convert from infix to postfix. We can then pass the tokens to the Stream Evaluator for evaluation. def to_postfix(tokens, precedences): operators = list() for token in tokens: if isinstance(token, int): yield token else: try: precedence = precedences[token] while precedence <= precedences[operators[-1]]: yield operators.pop() except LookupError: pass operators.append(token) yield from operators[::-1] precedences = {"+": 0, "-": 0, "*": 1, "/": 1} print(evaluate__stream(to_postfix(tokenize__simple("1 + 2 * 3"), precedences), operators)) 7 Multiple Tokenizers (Infix Graph) To build an infix graph we can build specialized parsers for each part of the grammar. The approach allows us to build more complex grammars. Whilst completely overkill for a calculator with 4 operators the idea is transferable to more complex systems. First we'll get whitespace working. We don't actually have a need for the whitespace, so we'll throw any runs away. The for loop will advance stream leading to the consecutive whitespace being removed. WHITESPACE = " " def whitespace(char, stream): if char in WHITESPACE: for char in stream: if char not in WHITESPACE: break return char, None >>> it = iter(" 12") >>> whitespace(next(it), it) ('1', None) >>> next(it) '2' Next we want to get the numbers as integers. The solution is a lot like whitespace. However we'll store the integer characters in chars. And we'll return chars as an integer. NUMBERS = "0123456789"
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter def number(char, stream): chars = [] if char in NUMBERS: chars.append(char) for char in stream: if char not in NUMBERS: break chars.append(char) return char, int("".join(chars)) Next we'll say numbers can be surrounded by whitespace. We'll discard whatever the whitespace is. Since a number must be either side of an operator, we'll be able to put whitespace anywhere. def spaced_number(char, stream): char, _ = whitespace(char, stream) char, num = number(char, stream) char, _ = whitespace(char, stream) return char, num Next we'll handle multiplication and division. By handling multiplication and division 'closer' to number allows us to implement BODMAS. To get the code to work we get a spaced_number then we build a tree (more like a linked list) whilst we encounter multiplication or division. def mul_div(char, stream): char, number = spaced_number(char, stream) node = number while char in "*/": op = char char, number = spaced_number(next(stream, None), stream) node = Node(op, node, number) return char, node Then we do the same we did for mul and div to add and sub. However we call mul_div rather than spaced_number. def add_sub(char, stream): char, number = mul_div(char, stream) node = number while char in "+-": op = char char, number = mul_div(next(stream, None), stream) node = Node(op, node, number) return char, node Finally we hide the char and stream implementation details away by making the tokenize__tree function. def tokenize__tree(text): it = iter(text) _, value = add_sub(next(it, None), it) return value print(evaluate__tree(tokenize__tree("1 + 2 * 3"), operators)) 7 Comparison Single Operator Tokenizer Very simple and allows simple control flow without needing a complicated tokenizer. The approach is good for menus or terminal commands, like with cmd.
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter Simple Tokenizer Good at implementing postfix evaluators and simple grammars. The approach can also work with infix or prefix grammars. If you can think up an algorithm like Shunting-Yard for your use-case. The approach is good for simple grammars where using *BNF is not an option. Multiple Tokenizers The approach is very powerful, but also very verbose. The approach is good for complex grammars where using *BNF is not an option. Like writing a library to parse *BNF. If a tokenizer isn't needed then use the Single Operator Tokenizer. Otherwise using *BNF is the best approach. If *BNF isn't an option then use Multiple Tokenizers. Most grammars seem simple as a beginner, so picking the option for complex grammars will allow the code room to grow if the grammar is more complex then anticipated. *BNF BNF BNF is a very simple language for parsing strings. We can write the complex Multiple Tokenizers in a couple lines of BNF. Whilst BNF is a standard structure, many libraries use a bespoke flavour of the language. First lets define the two constants. To define NUMBERS we need to allow any of the number characters, so we'll use | to say either the character on the left hand side or right hand side. <WHITESPACE> ::= " " <NUMBER> ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" Next lets define whitespace. We'll need to use the and operator; "a" "b" matches ab. Then we'll need to use recursion to allow any amount of whitespace. <whitespace> ::= <WHITESPACE> <whitespace> | "" number is defined almost exactly the same way as whitespace. The difference is the minimum match (the right hand side) must be <NUMBER> not "" to match at least one number. <number> ::= <NUMBER> <number> | <NUMBER> From here the rest is effectively the same. <spaced_number> ::= <whitespace> <number> <whitespace> <mul_div> ::= <spaced_number> ("*" | "/") <mul_div> | <spaced_number> <add_sub> ::= <mul_div> ("+" | "-") <add_sub> | <mul_div>
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter BNF, the notoriously ugly and verbose flavour, is far easier to read then the Multiple Tokenizers code we wrote. Use a Parser Library I've used TatSu once or twice before and found the library to be easy to use. We can write the equivalent of the entire Tokenizer, Evaluator and Operators in not much code. Lets convert the BNF to TatSu's flavour. TatSu supports regex, so we can define spaced_number in one line. spaced_number = / *\d+ */; TatSu also seems to ignore whitespace so both / */ are not needed. number = /\d+/; From here the rest can be effectively the same. mul_div = number ("*" | "/") mul_div | number; add_sub = mul_div ("+" | "-") add_sub | mul_div; TatSu also provides a regex like {}* syntax, like regex's *, so we can avoid the recursive definition. mul_div = number {("*" | "/") number}*; add_sub = mul_div {("+" | "-") mul_div}*; However, rather than focusing on brevity we should focus on defining clear tokens we can interact with, with the Operators class we'll provide to TatSu. So we need to make addition, subtraction, multiplication and division stand alone rules. mul = number "*" mul_div; div = number "/" mul_div; add = mul_div "+" add_sub; sub = mul_div "-" add_sub; We can then bind the values to names by using name:exp syntax. mul = lhs:number "*" rhs:mul_div; div = lhs:number "/" rhs:mul_div; add = lhs:mul_div "+" rhs:add_sub; sub = lhs:mul_div "-" rhs:add_sub; Now we can write the entire calculator in a very small amount of code. import tatsu GRAMMAR = """ root = add_sub $; number = /\d+/; mul_div = mul | div | number; mul = lhs:number "*" rhs:mul_div; div = lhs:number "/" rhs:mul_div; add_sub = add | sub | mul_div; add = lhs:mul_div "+" rhs:add_sub; sub = lhs:mul_div "-" rhs:add_sub; """
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter class CalculatorOperators: def number(self, ast): return int(ast) def mul(self, ast): return ast.lhs * ast.rhs def div(self, ast): return ast.lhs / ast.rhs def add(self, ast): return ast.lhs + ast.rhs def sub(self, ast): return ast.lhs - ast.rhs def evaluate(text): parser = tatsu.compile(GRAMMAR) return parser.parse(text, semantics=CalculatorOperators()) print(evaluate("1 + 2 * 3")) 7
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter The code is now ridiculously maintainable. We've got the power of Multiple Tokenizers by writing a Class Operators and a very simple grammar. We saw how much code and effort went into writing even the Simple Tokenizer. With fairly complex code and algorithms to get infix working. Vanilla Python isn't the right tool for writing a language. A library with a *BNF parser will normally be far better. We can also easily change the code to support brackets/parenthesis. The change would be to add a stage between number and mul_div. We wouldn't even need to add a new operator. Op's Code Design You've made the same mistake I have in the past. By making a Simple Tokenizer you seem to have missed the forrest for the trees. We can see you've gone "how can I get x to work" but you've not looked back over the entire code and gone; "Oh, the code is the same!" Look here: elif join: if isset: try: dct[variable] = dct[variable2] + dct[i] except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) break join = isset = isready = isgo = False # check if the variable is "@" change the data if variable == "@": RESET = True break elif isready: variable2 = i isset = True else: variable = i isready = True elif Reverse: # this is equivalent to pseudocode var = var2.reverse() if isready: try: dct[variable] = dct[i][::-1] except: raise Exception("ERROR IN FILE", sys.argv[1], "VARIABLE NOT FOUND IN ITERATION", iteration) break isready = False Revert = False if variable == "@":
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter isready = False Revert = False if variable == "@": RESET = True break else: variable = i isready = True # ... elif i == "+": join = True elif i == "/": Reverse = True
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
python, python-3.x, interpreter You've written effectively the same code twice. If we split the Tokenizer away from the Evaluator and Operators then we could drastically simplify the code. Whilst we can probably get away with a Stream Evaluator we'd be duplicating code in the Tokenizer and the Evaluator. Since your language is a prefix language to tokenize correctly we'd have to know the amount of operands to consume from the input. Then to evaluate correctly we'd need to know the correct amount of operands to consume from the input. Where instead using the Tree Evaluator would remove the duplication by storing the operands in the children variable. I'm using an iterator, like in Multiple Tokenizers, to make the code to get the variables simpler. By advancing the iterator _text we don't need any complicate join, Reverse, isset or isready variables. import itertools ARGS = { "+": 3, "/": 2, } def tokenize(text): _text = iter(text) nodes = [] for char in _text: if char in ARGS: nodes.append(Node(char, list(itertools.islice(_text, ARGS[char])))) # handle other tokens return Node("root", nodes) However I'd still strongly recommend using *BNF if at all possible. Even if you can't, using TatSu to make a mostly working version of your language would probably help you figure out how to build Multiple Tokenizers. I really think you need to start over with TatSu. Post another question and then see where to go from there. Correctness Can you find bugs? Honestly your code needs a rewrite. Looking for bugs at the moment would be a waste of time. Additionally languages are incredibly fragile code bases. Asking us to hunt bugs when you have a very lackluster coverage is also a waste. You may fix the bug, but without testing infrastructure in place when you fix another bug you may just reintroduce the bug. You need tests to prevent regressions. I'd recommend installing PyTest and using TDD to rebuild your code.
{ "domain": "codereview.stackexchange", "id": 42608, "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, python-3.x, interpreter", "url": null }
c, windows, networking, child-process Title: Network utility tool Question: I wrote a little program in C based on some requirements: Ping every IP from a file and check the result Show, by network adapter, ONLY the IP, subnet, default gateway and DNS Check the speed between two pings. #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_LEN 256 void readAndPing(char* path) { /* Lee el contenido del fichero indicado por path y lanza pings a cada una de las direcciones ip del fichero. Printa si el ping ha sido efectivo o no. */ printf("Reading file %s...\n", path); FILE* fp = fopen(path, "r"); if (fp == NULL) { printf("File not found!\n"); } else { char buffer[MAX_LEN]; while (fgets(buffer, MAX_LEN, fp)) { buffer[strcspn(buffer, "\n")] = 0; char comando[MAX_LEN]; snprintf(comando, sizeof(comando), "ping -n 1 %s > NUL", buffer); printf("Executing command %s\n", comando); int ping_res = system(comando); if (ping_res) printf("Ping failed!\n"); else printf("Pinged!\n"); } fclose(fp); } } void showConfigNetAdpt(char* adptName) { /* Muestra por pantalla la configuración de red del adaptador adptNAme creando un archivo netAdpt.txt y mostrando sus resultados. */ char comando[MAX_LEN]; snprintf(comando, sizeof(comando), "netsh interface ip show config %s > netAdpt.txt", adptName); printf("Executing command %s\n", comando); int res = system(comando); if (res) { printf("Command failed!\n"); } else { //Lectura del fichero creado FILE* fp = fopen("netAdpt.txt", "r"); if (fp == NULL) { printf("File not found\n"); } else { char buffer[MAX_LEN]; while (fgets(buffer, MAX_LEN, fp)) { //Elimina el newline buffer[strcspn(buffer, "\n")] = 0; char* line;
{ "domain": "codereview.stackexchange", "id": 42609, "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, windows, networking, child-process", "url": null }
c, windows, networking, child-process //Cosas de no tener utf-8... line = strstr(buffer, "Direcci¢n IP:"); if (line) printf("%s\n", line); line = strstr(buffer, "Prefijo de subred:"); if (line) printf("%s\n", line); line = strstr(buffer, "Puerta de enlace predeterminada:"); if (line) printf("%s\n", line); line = strstr(buffer, "Servidores DNS configurados a trav‚s de DHCP:"); if (line) { printf("%s\n", line); fgets(buffer, MAX_LEN, fp); line = strstr(buffer, "Registrar con el sufijo:"); while (line == NULL) { printf("\t%s\n", buffer); fgets(buffer, MAX_LEN, fp); line = strstr(buffer, "Registrar con el sufijo:"); } } } fclose(fp); } } } void printResultsPingMean(char* path, char* ip) { FILE* fp = fopen(path, "r"); printf("Results from %s\n", ip); char buffer[MAX_LEN]; char* line; if (fp == NULL) { printf("File not foudn\n"); } else { while (fgets(buffer, MAX_LEN, fp)) { //Elimina el newline buffer[strcspn(buffer, "\n")] = 0; line = strstr(buffer, "Media "); if (line != NULL) { printf("\t%s\n", line); } } fclose(fp); } } void fastestDNS(char* ip1, char* ip2) { char comando[MAX_LEN]; snprintf(comando, sizeof(comando), "ping -n 5 %s > pingResDNS1.txt", ip1); printf("Executing command %s...\n", comando); int e_c1 = system(comando); if (e_c1) { printf("Error executing command! Is %s a valid IP? !\n", ip1); } snprintf(comando, sizeof(comando), "ping -n 5 %s > pingResDNS2.txt", ip2); printf("Executing command %s...\n", comando);
{ "domain": "codereview.stackexchange", "id": 42609, "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, windows, networking, child-process", "url": null }
c, windows, networking, child-process int e_c2 = system(comando); if (e_c2) { printf("Error executing command! Is %s a valid IP? !\n", ip2); } printResultsPingMean("pingResDNS1.txt", ip1); printResultsPingMean("pingResDNS2.txt", ip2); } void showMenu() { printf("-------------------------------------------------------\n"); printf("Net Utilities\n"); printf("1: Ping every IP from a file\n"); printf("2: Check net config by adapter\n"); printf("3: Compare ping speed of two IP's\n"); printf("4: Exit\n"); printf("-------------------------------------------------------\n"); } int readOption() { showMenu(); int opcion = -1; scanf("%d", &opcion); while (opcion < 1 || opcion > 4) { printf("Invalid option!\n"); showMenu(); scanf("%d", &opcion); } return opcion; } int main() { int opcion = -1; char buffer[MAX_LEN], buffer2[MAX_LEN]; while (opcion != 4) { opcion = readOption(); printf("Option %d\n", opcion); if (opcion == 1) { printf("\n-------------------------------------------------------\n"); printf("Ping every IP from a file\n"); printf("-------------------------------------------------------\n"); printf("Filename: "); scanf("%s", buffer); readAndPing(buffer); } if (opcion == 2) { printf("\n-------------------------------------------------------\n"); printf("Check net config by adapter\n"); printf("-------------------------------------------------------\n"); printf("Adapter name: "); scanf("%s", buffer); showConfigNetAdpt(buffer); }
{ "domain": "codereview.stackexchange", "id": 42609, "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, windows, networking, child-process", "url": null }
c, windows, networking, child-process if (opcion == 3) { printf("\n-------------------------------------------------------\n"); printf("Compare ping speed of two IP's\n"); printf("-------------------------------------------------------\n"); printf("First IP: "); scanf("%s", buffer); printf("Second IP: "); scanf("%s", buffer2); fastestDNS(buffer, buffer2); } printf("\n\n"); } } I'm using windows and my default language is spanish, so that's why the strstr calls are strange... However, I would like some feedback. This is the first time I used windows commands inside C. Answer: Nicely formatted comando[] deserves a greater size char buffer[MAX_LEN]; ... //char comando[MAX_LEN]; //snprintf(comando, sizeof(comando), "ping -n 1 %s > NUL", buffer); #define FMT_PING "ping -n 1 %s > NUL" char comando[MAX_LEN + sizeof(FMT_PING)]; snprintf(comando, sizeof(comando), FMT_PING, buffer); Line size 256 is not so generous for a command line size. Consider BUFSIZ from <stdio.h> "size of the buffer used by the setbuf function" // #define MAX_LEN 256 #define MAX_LEN BUFSIZ // or .... #define MAX_LEN 4096 // If you want a fixed size Beware of variant text file line endings Sometimes a system will read a text file that is foreign to the local OS with "\n" and "\r\n" expected - or visa-versa. Consider lopping off line ends, be they "\n", "\r\n","\r". // buffer[strcspn(buffer, "\n")] = 0; buffer[strcspn(buffer, "\n\r")] = 0; Check return values Check return values for errors, especially input functions. // scanf("%d", &opcion); if (scanf("%d", &opcion) != 1) { TBD_CODE_Handle_Error(); }
{ "domain": "codereview.stackexchange", "id": 42609, "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, windows, networking, child-process", "url": null }
c, windows, networking, child-process scanf("%s", ... is worse than gets() Use a width limit. Better yet, use fgets(). Better output With the below, the end of the command is unclear. Consider sentinels like below. Issue in multiple places throughout code. // printf("Executing command %s...\n", comando); printf("Executing command \"%s\"...\n", comando); Check spelling //"File not foudn\n" "File not found\n" Overall error handling In various places, code detects an error and must promptly stop, yet main() only returns 0. Consider returning EXIT_FAILURE from main() in those cases. Rather then print errors to stdout, consider stderr. // printf("File not found\n"); fprintf(stderr, "File not found\n"); Language Code uses hard coded strings like "Direcci¢n IP:", unlikely to work in many locales. Consider internationalization.
{ "domain": "codereview.stackexchange", "id": 42609, "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, windows, networking, child-process", "url": null }
c++, object-oriented, console Title: Simple console application to practice OOP and file layout Question: I am not used to work with OOP so I decided to make a simple console "walk" game to focus on the OOP and the general game design process. I tried to make it as robust as possible but I feel like I could have build the hierarchy of the classes and functions in a more systematic way. Please think of this as a much larger project. I would appreciate if you could criticize and offer a more reliable way of ordering the objects and of course other mistakes and performance issues. Coordinate.hpp #ifndef COORD_H #define COORD_H struct Coordinate{ int x; int y; }; #endif Game.hpp //Clear the console for different operating systems #ifdef _WIN32 #define CLEAR "cls" #else #define CLEAR "clear" #endif #ifndef GAME_H #define GAME_H #include "Player.hpp" #include "Map.hpp" class Game{ public: Game(); private: void setup(); void loop(Player p, Map m); char processInput(Player p); void update(Player &p, char movement, Map m); void draw(Player p, Map m); void clear(); }; #endif Map.hpp #ifndef MAP_H #define MAP_H #include <string> #include <vector> #include <iostream> class Map{ public: Map(int h, int w); int getWidth(); int getHeight(); std::vector<std::string> getLevel(); private: std::vector<std::string> level; int width; int height; void initMap(int h, int w); }; #endif Player.hpp #ifndef PLAYER_H #define PLAYER_H #include <iostream> #include "Coordinate.hpp" #include "Map.hpp" class Player{ public: Player(); void movePlayer(int x, int y, Map m); Coordinate getCoord(); private: Coordinate coord; }; #endif Game.cpp #include "Game.hpp" #include "Player.hpp" #include "Map.hpp"
{ "domain": "codereview.stackexchange", "id": 42610, "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++, object-oriented, console", "url": null }
c++, object-oriented, console Game.cpp #include "Game.hpp" #include "Player.hpp" #include "Map.hpp" Game::Game(){ setup(); } void Game::setup(){ Player p; Map m(5, 5); Game::loop(p, m); } //Main Game Loop /* Clear the screen Draw the map Take input Update the Map */ void Game::loop(Player p, Map m){ while(true){ Game::clear(); Game::draw(p, m); char movement = Game::processInput(p); Game::update(p, movement, m); } } char Game::processInput(Player p){ char movement; std::cin>>movement; tolower(movement); return movement; } void Game::update(Player &p, char movement, Map m){ switch (movement) { case 'w'://up p.movePlayer(0,-1,m); break; case 'a'://left p.movePlayer(-1,0,m); break; case 's'://down p.movePlayer(0,1,m); break; case 'd'://right p.movePlayer(1,0,m); break; default: break; } } void Game::draw(Player p, Map m){ Map map = m;//Copy the layer without the player without changing the main level std::vector<std::string> level = map.getLevel(); level[p.getCoord().y].replace(p.getCoord().x, 1, "P");//replace the # with P for(int i=0; i<map.getHeight(); i++){ for(int j=0; j<map.getWidth(); j++){ std::cout<<level[i][j]; } std::cout<<std::endl; } } void Game::clear(){ system(CLEAR);//works for Windows and Linux } Map.cpp #include "Map.hpp" Map::Map(int h, int w){ initMap(h, w); } int Map::getWidth(){ return width; } int Map::getHeight(){ return height; } std::vector<std::string> Map::getLevel(){ return level; } void Map::initMap(int h, int w){ height = h; width = w; for(int i=0; i<height; i++){ std::string str; level.push_back(str); for(int j=0;j<width;j++){ level[i].append("."); } } } Player.cpp #include "Player.hpp" #include "Map.hpp"
{ "domain": "codereview.stackexchange", "id": 42610, "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++, object-oriented, console", "url": null }
c++, object-oriented, console Player.cpp #include "Player.hpp" #include "Map.hpp" Player::Player(){ coord.x=0; coord.y=0; } void Player::movePlayer(int x, int y, Map m){ if(!(coord.x + x >= m.getWidth() || coord.x + x < 0)){//If not at the map limit, move coord.x += x; } if(!(coord.y + y >= m.getHeight() || coord.y + y < 0)){ coord.y += y; } } Coordinate Player::getCoord(){ return coord; } main.cpp /*ASCII Walk Simulator P: Player .: Walkable Path Enter w,a,s,d to walk */ #include "Game.hpp" int main(){ Game game; } In terminal: g++ *.cpp -o out Answer: Here are some things that may help you improve your code. Don't use system("cls") There are two reasons not to use system("cls") or system("pause"). The first is that it is not portable to other operating systems which you have attempted to address. The second is that it's a security hole. Specifically, if some program is defined and named cls or pause, your program will execute that program instead of what you intend, and that other program could be anything. First, isolate these into a seperate functions cls() and pause() and then modify your code to call those functions instead of system. Then rewrite the contents of those functions to do what you want using C++. For example, if your terminal supports ANSI Escape sequences, you could use this: void cls() { std::cout << "\x1b[2J"; } Use const where practical I would not expect the getWidth or getHeight member functions of Map to alter the underlying map on which they operate, and indeed they do not. You should make this expectation explicit by using the const keyword: int Map::getWidth() const { return width; }
{ "domain": "codereview.stackexchange", "id": 42610, "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++, object-oriented, console", "url": null }