text stringlengths 1 2.12k | source dict |
|---|---|
python-3.x, excel, xml
"{3F43AC39-6132-4397-B236-7D45F9E43019}": "Jahresurlaub"
}
approvalStatusDict = {
'0': "Nicht einger.",
'1': "GelΓΆscht (veraltet)",
'2': "Beantragt",
'3': "In Bearbeitung",
'4': "Abgelehnt",
'5': "Gebucht",
'6': "GelΓΆscht"
}
hidden_column = ("E", "G", "M", "N")
loglevel = logging.DEBUG
wantedMonth = None
wantedYear = None | {
"domain": "codereview.stackexchange",
"id": 45258,
"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-3.x, excel, xml",
"url": null
} |
python-3.x, excel, xml
# configure_logging(loglevel)
check_doubles()
wantedYear, wantedMonth = set_month()
allVacations = xml_to_list()
write_excel(allVacations) | {
"domain": "codereview.stackexchange",
"id": 45258,
"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-3.x, excel, xml",
"url": null
} |
python-3.x, excel, xml
and the XML file
<VacationRequestsList xmlns="urn:orkan-software.de:schema:ORKAN">
<VacationRequests>
<DateAdd>2023-01-22</DateAdd>
<RequestorMaMatch>ALPHA</RequestorMaMatch>
<ApprovalStatus>5</ApprovalStatus>
<FilingDateDate>2023-02-22</FilingDateDate>
<RequestedHalfDays>30</RequestedHalfDays>
<Approval1RcptTyp>0</Approval1RcptTyp>
<Approval1RcptMatch>LAMBDA</Approval1RcptMatch>
<Approval1ApprovalStatus>5</Approval1ApprovalStatus>
<Approval1TimeStampPutDate>2023-02-23</Approval1TimeStampPutDate>
<Approval1MaMatch>LAMBDA</Approval1MaMatch>
<Approval2ApprovalStatus>5</Approval2ApprovalStatus>
<Approval2TimeStampPutDate>2023-02-23</Approval2TimeStampPutDate>
<Approval2MaMatch>KAPPA</Approval2MaMatch>
<RequestorFullName>Christian Alpha</RequestorFullName>
<Approval1MaFullName>Daniel Lambda</Approval1MaFullName>
<Approval2MaFullName>Karsten Kappa</Approval2MaFullName>
<AbsenceList>
<Absence>
<DateAdd>2023-01-22</DateAdd>
<MaMatch>ALPHA</MaMatch>
<AbsenceType>1</AbsenceType>
<AbsenceAccountChange>10</AbsenceAccountChange>
<Origin>0</Origin>
<Beginning>2023-07-17T00:00:00.00+02:00</Beginning>
<BeginningDate>2023-07-17</BeginningDate>
<Ending>2023-07-21T23:59:59.99+02:00</Ending>
<EndingDate>07:231:07.21</EndingDate>
<ApprovalStatus>5</ApprovalStatus>
</Absence>
<Absence>
<DateAdd>2023-01-22</DateAdd>
<MaMatch>ALPHA</MaMatch>
<AbsenceType>1</AbsenceType>
<AbsenceAccountChange>10</AbsenceAccountChange>
<Origin>0</Origin>
<Beginning>2023-07-24T00:00:00.00+02:00</Beginning>
<BeginningDate>2023-07-24</BeginningDate>
<Ending>2023-07-28T23:59:59.99+02:00</Ending>
<EndingDate>07:231:07.28</EndingDate>
<ApprovalStatus>5</ApprovalStatus>
</Absence>
<Absence>
<DateAdd>2023-01-22</DateAdd>
<MaMatch>ALPHA</MaMatch>
<AbsenceType>1</AbsenceType>
<AbsenceAccountChange>10</AbsenceAccountChange> | {
"domain": "codereview.stackexchange",
"id": 45258,
"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-3.x, excel, xml",
"url": null
} |
python-3.x, excel, xml
<AbsenceType>1</AbsenceType>
<AbsenceAccountChange>10</AbsenceAccountChange>
<Origin>0</Origin>
<Beginning>2023-07-31T00:00:00.00+02:00</Beginning>
<BeginningDate>2023-07-31</BeginningDate>
<Ending>2023-08-04T23:59:59.99+02:00</Ending>
<EndingDate>07:231:08.04</EndingDate>
<ApprovalStatus>5</ApprovalStatus>
</Absence>
</AbsenceList>
</VacationRequests>
</VacationRequestsList> | {
"domain": "codereview.stackexchange",
"id": 45258,
"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-3.x, excel, xml",
"url": null
} |
python-3.x, excel, xml
```
Answer: Consider following tips:
Class: Encapsulate your related def methods for parsing XML and preparing Excel within a Class object to be imported in an end use script that runs full program. This facilitates readability and maintainability even portability. In fact, unit testing becomes easier.
class VacationXMLParser(...)
...
def init(self, ...):
...
def xml_to_list(self):
...
class VacationExcelBuilder(...)
...
def init(self, ...):
...
def write_excel(self):
...
Then calling processes will be better handled:
p = VacationXMLParser(xml_file)
allVacations = p.xml_to_list()
e = VacationExcelBuilder(allVacations)
e.write_excel()
Parameters: Parameterize values such as filenames and namespaces within defined method or above proposed class. Do not have underlying methods rely on object declared in global environment. For example, upon first reading ns was an unknown object. Consider passing it in as an argument:
def get_full_tag(ns, tag):
'''
Adds the namespace to an single xml tag.
param 1: string
returns: string
'''
return "".join((ns, tag))
If Logic: Avoid the if ... continue logic. Use the counterfactual condition as needed. As example, replace below logic with further below logic:
if request_is_relevant(request) is False:
continue
else:
# if request is relevant call function to grab all needed data.
relevant += 1
if request_is_relevant(request):
# if request is relevant call function to grab all needed data.
relevant += 1
Exit Calls: Avoid explicitly exiting program based on conditions of program execution. Refractor code to cleanly return nothing, raise exceptions, or other robust code flow. With above proposed imported classes you can separate XML and Excel processing and avoid exiting program prematurely.
try:
tree = ET.parse(xmlfile)
logging.debug("Reading xml-file {} successful".format(xmlfile))
root = tree.getroot() | {
"domain": "codereview.stackexchange",
"id": 45258,
"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-3.x, excel, xml",
"url": null
} |
python-3.x, excel, xml
except Exception as error:
logging.error("Failed to get xml-tree root.")
logging.error(error)
raise
Try/Except: Related to above, properly release or uninitialize potentially large objects to avoid holding in memory. Use finally block to clear large objects and it will execute before re-raising error (see docs).
try:
workbook.save(fileName)
logging.info("Excel file successful written")
except Exception as error:
logging.critical("Failed to write excel file")
raise
finally:
workbook = None
Debug Logging: After solid solution in place, avoid the many logging.debug with counter variables in production code which can slow processing and affect performance. Use unit tests on many examples XML files to robustly debug code at each step of process:
def test_always_passes():
p = VacationXMLParser(xml_file)
...
assert p.request_is_relevant(request) == True
def test_always_fails():
p = VacationXMLParser(xml_file)
...
assert p.request_is_relevant(request) == False
Pythonic Code: Consider pythonic methods like list/dict comprehensions or conditional expressions:
Specifically, below if/else can be replaced with one line conditional expressions:
if node is None:
value = None
else:
value = node.text
value = None if node is None else node.text
Also, building lists can avoid bookkeeping with comprehension:
allVacations = [
process_request(request)
for request in root.findall(get_full_tag("VacationRequests"))
if request_is_relevant(request)
]
...
def get_path(part_list):
...
return "/".join(get_full_tag(tag) for tag in part_list)
Even use the latest F-strings for string formatting (introduced in Python 3.6) without the many str.join or long .format calls:
return f"{character.strip()}{str(number).strip()}"
...
fileName = os.path.join("material", f"urlaub-{year}-{month}.xls")
sheetName = f"urlaub {year} {month}"
...
logging.info(f"{len(allVacations)} relevant requests found") | {
"domain": "codereview.stackexchange",
"id": 45258,
"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-3.x, excel, xml",
"url": null
} |
python-3.x, excel, xml
Even replace many if/elif for dictionary:
# any values needs to convert into an readable format
values_dict = {
"Art": lambda v: absenceKindDict[v],
"Tage": lambda v: int(int(v) / 2),
"Freigabe1": lambda v: approvalStatusDict[v],
"Freigabe2": lambda v: approvalStatusDict[v],
"Freigabe": lambda v: approvalStatusDict[v],
"Start": lambda v: dt.date.fromisoformat(v.split("T")[0]),
"Ende": lambda v: dt.date.fromisoformat(v.split("T")[0]),
"Eingetr.": lambda v: dt.date.fromisoformat(v.split("T")[0])
}
value = values_dict[key](value)
Maybe you can rewrite above method with conditional expressions returning tuples:
def set_month():
year, month = time.localtime()[0:1]
return (year-1, 12) if month == 1 else (year, month-1) | {
"domain": "codereview.stackexchange",
"id": 45258,
"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-3.x, excel, xml",
"url": null
} |
python, python-3.x, hash-map
Title: Dictionary additional function implementations
Question: I've written a utility class BetterDict to help me on some of my other projects. I've implemented the &, +, and - operators. It extends from the base class dict so I can use all the builtin functions without having to rewrite them all. I would like some feedback on my implementation, best practices, more pythonic way of doing this, etc.
from typing import NewType
BetterDict = NewType('BetterDict', object)
class BetterDict(dict):
def __and__(self, other: BetterDict) -> BetterDict:
"""
Returns a dictionary containing only the keys that are
present in both dicts.
"""
result = BetterDict()
for (sk, _), (ok, ov) in zip(self.items(), other.items()):
if sk == ok:
result[sk] = ov
return result
def __add__(self, other: BetterDict) -> BetterDict:
"""
Combines two dictionaries, replacing same keys with "other" values.
"""
result = BetterDict()
for k, v in self.items():
result[k] = v
for k, v in other.items():
result[k] = v
return result
def __sub__(self, other: BetterDict) -> BetterDict:
"""
Returns a dictionary containing only the keys that are not
present in both dicts.
"""
result = BetterDict()
keys = list(set(self.keys()).symmetric_difference(other.keys()))
for key in keys:
if key in self.keys():
result[key] = self[key]
if key in other.keys():
result[key] = other[key]
return result
Example Code
from better_dict import BetterDict
a = BetterDict({'a': 1})
b = BetterDict({'a': 3, 'b': 2})
print(a & b)
print(a + b)
print(a - b) | {
"domain": "codereview.stackexchange",
"id": 45259,
"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, hash-map",
"url": null
} |
python, python-3.x, hash-map
a = BetterDict({'a': 1})
b = BetterDict({'a': 3, 'b': 2})
print(a & b)
print(a + b)
print(a - b)
Answer: As @FMc already commented, your method __add__() assumes that both dicts have the same keys at the same positions, which is a very bold assumption.
Furthermore, the documentation of __add__() does not indicate, that values of other will override values of self, which may be surprising to the user (and users generally don't like to be surprised).
Some further nitpicks:
You restrict other to BetterDict, though it would also work with a plain old dict.
I don't like for (sk, _), (ok, ov) in zip(self.items(), other.items()): since you throw away the value of the first item anyway. It should read for sk, (ok, ov) in zip(self.keys(), other.items()): imho. But since this assumes, that both dicts have the same keys in the same places, this should be rewritten entirely anyways.
Instead of the NewType you should use typing.Self when referring to BetterDict within its methods. | {
"domain": "codereview.stackexchange",
"id": 45259,
"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, hash-map",
"url": null
} |
c++, performance, search, simulation
Title: Spatial radius search in Boid simulation
Question: I am working on a Boid simulation with 10,000 boids. I've successfully utilized geometry shaders and an array<GLfloat[3], MAX_BOIDS> for vertices to enhance display performance. Currently, I can display 500,000 boids moving randomly at 60 FPS.
However, the neighbor search is a bottleneck. With a naive search, I'm dealing with O(nΒ²) complexity, which is prohibitively slow. Before experimenting with QuadTrees or RTrees, I wanted to benchmark a simple lattice structure. Unfortunately, this approach is already too slow; I can only manage to display 1,000 boids at 60 FPS.
Here the simulator. I can freely move the mouse to highlight seen nearby boids:
How can I optimize this code to improve its efficiency? Perhaps my data structure is not optimal.
Here is the code:
/**
* For a boid simulation, I am testing a bin lattice structure to speed up
* the neighbor search. The idea is to divide the screen into a grid of bins
* and store the boids in the corresponding bin. When querying for neighbors,
* only the bins in a 3x3 square around the boid need to be checked.
*
* Goal is to have a 60 FPS simulation with 10000 boids.
*/
#include <SFML/Graphics.hpp>
#include <cmath>
#include <array>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <span>
#define SHOW_GRID
#define WINDOW_WIDTH 1000
#define WINDOW_HEIGHT 1000
#define NUMBER_BINS 20 // Number of bins should be proportional to sight radius
#define MAX_BOIDS_PER_BIN 100 // Limit number of boids per bin to avoid large queries
#define BOIDS 1000 // To be increased to 10000
#define RADIUS 100 // Radius of the circle around the mouse to query for neighbors
struct Boid {
sf::Vector2f position;
}; | {
"domain": "codereview.stackexchange",
"id": 45260,
"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++, performance, search, simulation",
"url": null
} |
c++, performance, search, simulation
struct Boid {
sf::Vector2f position;
};
/**
* In this implementation I am using a fixed size array for the boids in each bin.
* std::vector is not used because it is slower. I am seeking to optimize the
* neighbor search, so I am not concerned with the memory overhead of a fixed size
* array.
*/
template<size_t WIDTH, size_t HEIGHT, size_t BINS, size_t BIN_SIZE>
class BinLattice {
public:
static constexpr size_t MaxQuerySize = BIN_SIZE * 9;
using Bin = std::pair<std::array<Boid*, BIN_SIZE>, size_t>;
using Lattice = std::array<std::array<Bin, BINS>, BINS>;
using BoidArray = std::array<Boid*, MaxQuerySize>;
using QueryResult = std::pair<BoidArray, size_t>; // Pair of array and count
BinLattice() {
for (auto &row : lattice) {
for (auto &bin : row) {
bin.first.fill(nullptr);
bin.second = 0;
}
}
}
void addBoid(Boid* boid) {
size_t xIndex = static_cast<size_t>(boid->position.x / (WIDTH / BINS));
size_t yIndex = static_cast<size_t>(boid->position.y / (HEIGHT / BINS));
auto& bin = lattice[xIndex][yIndex];
bin.first[bin.second++] = boid;
}
void clear() {
for (auto &row : lattice) {
for (auto &bin : row) {
bin.second = 0;
}
}
}
void query(sf::Vector2f &position, QueryResult& result, float radius) {
size_t count = 0;
size_t xIndex = static_cast<size_t>(position.x / (WIDTH / BINS));
size_t yIndex = static_cast<size_t>(position.y / (HEIGHT / BINS)); | {
"domain": "codereview.stackexchange",
"id": 45260,
"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++, performance, search, simulation",
"url": null
} |
c++, performance, search, simulation
// Query all bins in a 3x3 square around the boid
for (int dx = -1; dx <= 1; ++dx) {
for (int dy = -1; dy <= 1; ++dy) {
size_t newX = std::clamp(xIndex + dx, 0ul, BINS - 1);
size_t newY = std::clamp(yIndex + dy, 0ul, BINS - 1);
auto& bin = lattice[newX][newY];
for (size_t i = 0; i < bin.second; ++i) {
// Check if boid is within radius
if (std::hypot(bin.first[i]->position.x - position.x,
bin.first[i]->position.y - position.y) < radius) {
result.first[count++] = bin.first[i];
}
}
}
}
result.second = count;
}
Lattice lattice;
};
int main() {
std::vector<Boid> boids;
using Lattice = BinLattice<WINDOW_WIDTH, WINDOW_HEIGHT, NUMBER_BINS, MAX_BOIDS_PER_BIN>;
for (int i = 0; i < BOIDS; ++i) {
boids.push_back({{
static_cast<float>(rand() % WINDOW_WIDTH),
static_cast<float>(rand() % WINDOW_HEIGHT)}});
}
Lattice binLattice;
Lattice::QueryResult result;
sf::RenderWindow window(sf::VideoMode(1000, 1000), "Boids");
// Load a font
sf::Font font;
if (!font.loadFromFile("collegiate.ttf")) std::cout << "Error loading font" << std::endl;
// Setup text
sf::Text text;
text.setFont(font);
text.setCharacterSize(24);
text.setFillColor(sf::Color::White);
text.setPosition(10.f, 10.f);
// Grid lines
sf::RectangleShape hline(sf::Vector2f(WINDOW_WIDTH / NUMBER_BINS, 1.f));
sf::RectangleShape vline(sf::Vector2f(1.f, WINDOW_HEIGHT / NUMBER_BINS));
hline.setFillColor(sf::Color(255, 255, 255, 35));
vline.setFillColor(sf::Color(255, 255, 255, 35));
// Mouse circle
sf::CircleShape spotlight(1.f);
spotlight.setFillColor(sf::Color(255, 255, 255, 35));
spotlight.setRadius(RADIUS); | {
"domain": "codereview.stackexchange",
"id": 45260,
"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++, performance, search, simulation",
"url": null
} |
c++, performance, search, simulation
// Boid circle
sf::CircleShape boidShape(1.f);
boidShape.setFillColor(sf::Color::Cyan);
// Highlight circle
sf::CircleShape boidSeen(2.f);
boidSeen.setFillColor(sf::Color::Yellow);
sf::Clock frameClock; // Clock to measure frame time
sf::Clock updateClock; // Clock to measure update intervals
float fps = 0.0f;
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); }
binLattice.clear();
for (auto& boid : boids) binLattice.addBoid(&boid);
window.clear();
// Display lattice grid with clear gray lines
#ifdef SHOW_GRID
for (size_t i = 0; i < NUMBER_BINS; ++i) {
for (size_t j = 0; j < NUMBER_BINS; ++j) {
hline.setPosition(i * WINDOW_WIDTH / NUMBER_BINS, j * WINDOW_HEIGHT / NUMBER_BINS);
window.draw(hline);
vline.setPosition(i * WINDOW_WIDTH / NUMBER_BINS, j * WINDOW_HEIGHT / NUMBER_BINS);
window.draw(vline);
}
}
#endif
// Get Mouse Position
sf::Vector2i mousePosition = sf::Mouse::getPosition(window);
sf::Vector2f mousePositionFloat = sf::Vector2f(mousePosition.x, mousePosition.y);
// Draw clear alpha circle around mouse
spotlight.setPosition(mousePositionFloat.x - RADIUS, mousePositionFloat.y - RADIUS);
window.draw(spotlight);
for (auto& boid : boids) {
boidShape.setPosition(boid.position);
window.draw(boidShape);
}
binLattice.clear();
for (auto& boid : boids) binLattice.addBoid(&boid); | {
"domain": "codereview.stackexchange",
"id": 45260,
"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++, performance, search, simulation",
"url": null
} |
c++, performance, search, simulation
binLattice.clear();
for (auto& boid : boids) binLattice.addBoid(&boid);
#if 1 // For each boid (real usecase), very slow < 10 FPS
// *********** SLOW ***********
for (auto& boid : boids) {
binLattice.query(mousePositionFloat, result, RADIUS);
for (size_t i = 0; i < result.second; ++i) {
boidSeen.setPosition(result.first[i]->position);
window.draw(boidSeen);
}
}
// *********** /SLOW ***********
#else // Only for mouse position (for profiling): very fast > 120 FPS
binLattice.query(mousePositionFloat, result, RADIUS);
for (size_t i = 0; i < result.second; ++i) {
boidSeen.setPosition(result.first[i]->position);
window.draw(boidSeen);
}
#endif
sf::Time frameTime = frameClock.restart();
if (updateClock.getElapsedTime().asSeconds() >= 0.5) {
// Update FPS every 0.5 seconds
fps = 1.0f / frameTime.asSeconds();
updateClock.restart();
}
// Update text
std::stringstream ss;
ss << std::fixed << std::setprecision(2) << fps << " FPS";
text.setString(ss.str());
window.draw(text);
window.display();
}
}
Built on Ubuntu with:
g++ -Os -pg main.cpp -o myapp -lsfml-graphics -lsfml-window -lsfml-system
Curiously gprof doesn't show the bottleneck query method:
granularity: each sample hit covers 4 byte(s) for 25.00% of 0.04 seconds | {
"domain": "codereview.stackexchange",
"id": 45260,
"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++, performance, search, simulation",
"url": null
} |
c++, performance, search, simulation
index % time self children called name
<spontaneous>
[1] 100.0 0.04 0.00 main [1]
0.00 0.00 230000/230000 BinLattice<1000ul, 1000ul, 20ul, 100ul>::addBoid(Boid*) [8]
0.00 0.00 230/230 BinLattice<1000ul, 1000ul, 20ul, 100ul>::clear() [9]
0.00 0.00 116/117 std::__cxx11::basic_string<unsigned int, std::char_traits<unsigned int>, std::allocator<unsigned int> >::_M_dispose() [10]
0.00 0.00 11/11 void std::vector<Boid, std::allocator<Boid> >::_M_realloc_insert<Boid>(__gnu_cxx::__normal_iterator<Boid*, std::vector<Boid, std::allocator<Boid> > >, Boid&&) [11]
0.00 0.00 3/3 sf::CircleShape::~CircleShape() [12]
0.00 0.00 2/2 sf::RectangleShape::~RectangleShape() [14]
0.00 0.00 1/1 sf::Text::~Text() [15]
0.00 0.00 1/1 std::_Vector_base<Boid, std::allocator<Boid> >::~_Vector_base() [16]
-----------------------------------------------
0.00 0.00 230000/230000 main [1]
[8] 0.0 0.00 0.00 230000 BinLattice<1000ul, 1000ul, 20ul, 100ul>::addBoid(Boid*) [8]
-----------------------------------------------
0.00 0.00 230/230 main [1]
[9] 0.0 0.00 0.00 230 BinLattice<1000ul, 1000ul, 20ul, 100ul>::clear() [9] | {
"domain": "codereview.stackexchange",
"id": 45260,
"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++, performance, search, simulation",
"url": null
} |
c++, performance, search, simulation
Answer: Nice problem!
I gotta tell ya, QuadTrees is definitely the appropriate datastructure.
And it's just not that hard.
Let coord be the bit interleaving of x and y coords.
That is, the top two bits are MSB of x and MSB of y.
For the next two bits, keep shifting.
Last two bits are LSB of x and y.
I'm assuming htonl() network order.
Now sort in the usual way, and locate a boid at index i.
All the boids that are spatially near will also have nearby indexes.
Thank you for the nice manifest constants, they are very clear.
comments where appropriate
bin.first[bin.second++] = boid;
It wouldn't hurt to mention to the Gentle reader that .first is a boid
and .second is count of boids within a bin.
(Similar to the QueryCount comment.)
I see why it isn't necessary,
but I'm still a little sad that clear() leaves
all the .first pointers untouched.
edge effect
size_t newX = std::clamp(xIndex + dx, 0ul, BINS - 1);
size_t newY = std::clamp(yIndex + dy, 0ul, BINS - 1);
Hmmm, interesting.
No "index out of bounds" errors.
But bins at edge of screen shall be double counted,
which seems undesirable.
That is, if Percival the pigeon is flying near the center left edge,
then result records a pair of pointers to Percival.
And if he is flying near one of the corners, the effect is even worse.
squared vs square root
We pass in delta_x and delta_y:
if (std::hypot(bin.first[i]->position.x - position.x,
bin.first[i]->position.y - position.y) < radius) {
Finding length of hypoteneuse involves a slow sqrt().
But it would suffice to compare sum of squared deltas against radiusΒ².
And then a good optimizing compiler would hoist it out of the loop,
or you could help it out by assigning a radius_squared = radius * radius temp var.
no velocity
struct Boid {
sf::Vector2f position;
}; | {
"domain": "codereview.stackexchange",
"id": 45260,
"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++, performance, search, simulation",
"url": null
} |
c++, performance, search, simulation
no velocity
struct Boid {
sf::Vector2f position;
};
What, no motion vector, no (dx, dy) speed?
Ok, I guess it's early days in this prototype, we'll get there before too long.
Here's the query:
for (auto& boid : boids) {
binLattice.query(mousePositionFloat, result, RADIUS);
for (size_t i = 0; i < result.second; ++i) {
boidSeen.setPosition(result.first[i]->position);
window.draw(boidSeen);
}
}
So we're just identifying and highlighting static birds within radius,
preparatory to velocity updates, OK.
And at that point we can "head toward neighbor" when too far away,
and "avoid collision" when too near.
When you are ready for velocity updates, you might consider having
each boid maintain pointers to a few nearby boids at several distances,
perhaps roughly doubling distances. For many update cycles the identity
of a moving boid would be stable, and every so often you would have
to pick a new neighbor at an appropriate distance.
You could even manage a budget of only picking three such neighbor updates
per displayed frame.
I don't understand the nesting there.
For each boid, we visit all the spotlight boids?
That seems unnecessary, and slow.
aggregate weights
I was kind of expecting to see "the N-body problem" in the update loop,
where we sum up gravitational attraction of our neighbors,
or compute some similar potential function.
Distant boids make a negligible contribution, so you can approximate
by ignoring them beyond some cutoff threshold.
Aggregating their statistics to a bin, and mostly having those
numbers influence velocity is an approach worth pursuing.
(Maybe avoid aggregation for just the current bin a boid is in.)
It might motivate using more than a 3 Γ 3 bin window.
square bins
I note in passing that bins have the same aspect ratio
as your display window.
So you might want e.g. 20 Γ 15 bins for certain display sizes,
if you're applying an isotropic potential function. | {
"domain": "codereview.stackexchange",
"id": 45260,
"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++, performance, search, simulation",
"url": null
} |
c++, performance, search, simulation
This code achieves a subset of its design goals.
It is written in a very clear style.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45260,
"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++, performance, search, simulation",
"url": null
} |
c++, visitor-pattern
Title: Implementing an Object type in C++
Question: I'm currently working through the "Crafting Interpreters" book by Robert Nystrom. He uses Java to implement the visitor pattern in which the visitor functions return the Object type. C++ doesn't support an Object type so my solution was to create a polymorphic type in c++ using virtual functions and inheritance
I'm just curious about the drawbacks of my implementation and how it could be implemented better:
#include <iostream>
#include <string>
class Object {
public:
virtual std::string getType() const = 0;
};
class String : public Object {
private:
std::string value;
public:
String(const std::string& val) : value(val) {}
std::string getType() const override {
return "string";
}
std::string getValue() const {
return value;
}
};
class Double : public Object {
private:
double value;
public:
Double(double val) : value(val) {}
std::string getType() const override {
return "double";
}
double getValue() const {
return value;
}
};
Answer: Use std::variant instead
With your code you have to write a visitor like this:
Object* object = new Double(3.1415);
if (object->getType() == "string") {
std::cout << static_cast<String*>(object)->getValue();
} else if (object->getType() == "double") {
std::cout << static_cast<Double*>(object)->getValue();
}
Which is very tedious (especially as you add more types), inefficient, and doesn't have type safety, as you can accidentally static_cast<>() to the wrong type and the compiler won't notice. You also need to work with pointers a lot, which means you have to be careful to delete them where appropriate, or use the right smart pointers.
C++17 introduced std::variant to solve this in a type safe way, and allows for an easier way to visit it. For example, you can write:
using Object = std::variant<std::string, double>;
β¦
Object object = 3.1415; | {
"domain": "codereview.stackexchange",
"id": 45261,
"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++, visitor-pattern",
"url": null
} |
c++, visitor-pattern
std::visit([](auto& value) {
std::cout << value;
}, object); | {
"domain": "codereview.stackexchange",
"id": 45261,
"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++, visitor-pattern",
"url": null
} |
c, hash-map
Title: Simple hash table written in C with REPL
Question: This is a simple hash table I've written in C. It is a closed-addressing hash table with TABLE_SIZE number of buckets. The hash function is extremely simple and only sum up the characters of the key string. I've also implemented a REPL for it to be able to test it.
I appreciate any type of suggestion to improve this code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TABLE_SIZE 1024
typedef unsigned int HashResult;
typedef struct _node {
char *key;
void *value;
struct _node* next;
} Node;
typedef struct _hashtable {
Node* cells[TABLE_SIZE];
} HashTable;
HashTable* new_hashtable() {
return (HashTable*)calloc(1, sizeof(HashTable));
}
HashResult hash(char* string) {
HashResult result = 0;
while(*string != '\0')
result += *(string++);
return result % TABLE_SIZE;
}
void set(HashTable* ht, char *key, void *value) {
HashResult hash_result = hash(key);
Node* node = (Node*)malloc(sizeof(Node));
node->key = key;
node->value = value;
node->next = NULL;
if (ht->cells[hash_result] == NULL) {
ht->cells[hash_result] = node;
} else {
Node* root = ht->cells[hash_result];
while (root->next != NULL)
root = root->next;
root->next = node;
}
}
void* get(HashTable* ht, char* key) {
HashResult hash_result = hash(key);
if (ht->cells[hash_result] == NULL)
return NULL;
Node* node = ht->cells[hash_result];
if (!strcmp(key, node->key))
return node->value;
do {
if (!strcmp(key, node->key))
return node->value;
node = node->next;
}
while (node != NULL);
return NULL;
} | {
"domain": "codereview.stackexchange",
"id": 45262,
"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, hash-map",
"url": null
} |
c, hash-map
return NULL;
}
void delete(HashTable* ht, char* key) {
void *i = get(ht, key);
if (i == NULL)
return;
HashResult hash_result = hash(key);
Node *current, *prev, *temp;
current = ht->cells[hash_result];
if (!strcmp(current->key, key)) {
free(current);
current = NULL;
ht->cells[hash_result] = NULL;
return;
}
while (current->next != NULL) {
temp = current;
current = current->next;
prev = temp;
if (!strcmp(current->key, key)) {
free(current);
current = NULL;
prev->next = NULL;
return;
}
}
}
int
main(int argc, char* argv[]) {
HashTable* ht = new_hashtable();
while (!feof(stdin)) {
fprintf(stdout, ">>> ");
char input[256];
fgets(input, 256, stdin);
char *command;
command = strtok(input, " ");
if (!strcmp(command, "SET")) {
char *sub = &input[(int)strlen(command) + 1];
char *key = strtok(sub, " ");
sub = &input[(int)strlen(command) + (int)strlen(key) + 2];
char *value = strtok(sub, "\n");
key = strncpy(malloc(strlen(key)), key, strlen(key));
value = strncpy(malloc(strlen(value)), value, strlen(value));
set(ht, key, (void*)value);
} else if (!strcmp(command, "GET")) {
char *sub = &input[(int)strlen(command) + 1];
char *key = strtok(sub, "\n");
char *value = get(ht, key);
fprintf(stdout, "%s\n", (char*)value);
} else if (!strcmp(command, "DEL") || !strcmp(command, "DELETE")) {
char *sub = &input[(int)strlen(command) + 1];
char *key = strtok(sub, "\n");
delete(ht, key);
} else if (input[0] != '\n') {
puts("Invalid command!");
}
}
free(ht);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45262,
"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, hash-map",
"url": null
} |
c, hash-map
return 0;
}
Answer: Unnecessary casts
You cast a lot of value unnecessarily, sometimes even to the type they already have! Casting should only be done if really necessary. Some things that don't need casting:
return (HashTable*)calloc(1, sizeof(HashTable));
Since the function's return type is already HashTable*, the cast here is not necessary. C allows implicit casts from void* to another pointer type. The same goes for casts of the return value of malloc().
set(ht, key, (void*)value);
Similarly, you don't need to explicitly cast from another pointer type to void*.
sub = &input[(int)strlen(command) + (int)strlen(key) + 2];
There is no need to cast from the size_t to an int here, and in fact this can lead to incorrect truncation of the length if you would have really large strings.
fprintf(stdout, "%s\n", (char*)value);
Why the cast at all? value is already a char*.
Use strdup()
Use strdup() to copy strings. While officially it has only been part of C since C23, most compilers have supported this function for decades.
Missing error checking everywhere
There are many things that can fail in your code. For example:
If you run out of memory, calloc() and malloc() will return NULL. If you don't check for that, your program will crash with a segmentation fault.
There could also be an issue reading from stdin, for example if the user redirected a file to stdin, and there is an error reading that file somehwere halfway. Checking for feof() is not enough.
There could also be error writing to stdout. Again, this might be important to check for if that is redirected to another file.
Your input might not be a valid command. Consider what happens if strtok() cannot find the separator.
An input line might be longer than 256 characters. What happens with the result from fgets()? What happens with the next call to fgets()? | {
"domain": "codereview.stackexchange",
"id": 45262,
"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, hash-map",
"url": null
} |
c, hash-map
If an error happens, you ideally print an error message to stderr (you can use helper functions like perror() or the nicer but less standard err()), and then exit the program with EXIT_FAILURE. The error message informs a potential human looking at the output, and the error code will ensure that scripts calling your program can detect that something went wrong.
Error handling is one of the less fun things to do when programming, and you have to do a lot of that if you write in C, but it is important; it ensures your program will not have unexpected behavior when things go wrong.
Hardcoded number of buckets
You have hardcoded the number of buckets to use for the hash table. What if you only need to store a few entries? Then you have wasted memory. What if you need to store a million entires? Then your hash table becomes very slow as it just scanning linked lists all the time.
Only if you know up front how many items you will store in the hash table can you make a good decision about the number of buckets to use. Consider making the number of buckets configurable at runtime, and/or make it so the hash table will dynamically grow to avoid too many items being stored in the same bucket.
Your hash function is of very poor quality
Just summing the ASCII values of the characters in a string is a very bad hash function. Consider that this will put a lot of things in the same bucket. Consider: abc, cba, aad. Using modulo a power of two is also not great.
A real hash table implementation would use a more sophisticated hash function that doesn't suffer from these problems.
Deleting a hash table
At the end of your main(), you call free(ht). However, that only deletes the HashTable object, but it doesn't free any of the Nodes that were created. You should implement a free_hashtable() function that ensures all the nodes are deleted before deleting the HashTable object. | {
"domain": "codereview.stackexchange",
"id": 45262,
"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, hash-map",
"url": null
} |
beginner, c, file-system
Title: Simple text file encryption and decryption
Question: Short introduction; recently I've completed a basic course on C but other than that I have no programming experience and I am a total beginner.
As a practice project and to practice reading from and writing to files I've created this simple text encryption program in C.
It basically asks the user for a text file to open (but no file extension check on that yet) and gives the user the choice to either encrypt or decrypt the file based on if it already has been encrypted before by checking if the signature is present at the last line of the file or not.
Would love some general feedback on anything I could improve on (program structure, style, error handling, security, use of functions, whatever else comes to mind) but also what things I should keep on doing if there are any!
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LINES 1024
#define MAX_LENGTH 1024
#define FILENAME_LENGTH 100
#define WRITE_MODE "w"
#define READ_MODE "r"
void addSignature(char file_content[][MAX_LENGTH], int lines_read);
int checkSignature(char file_content[][MAX_LENGTH], int lines_read);
void closeFile(FILE * file_ptr);
void encryptData(char file_content[][MAX_LENGTH], int lines_read);
void decryptData(char file_content[][MAX_LENGTH], int lines_read);
void getFilename(char* file_name);
FILE* openFile(char* file_name, char* file_mode);
int readFile(char file_content[][MAX_LENGTH], FILE * file_ptr);
void removeSignature(char file_content[][MAX_LENGTH], int lines_read);
void showMenu(int has_signature, char file_content[][MAX_LENGTH], int lines_read, FILE * file_ptr, char* file_name);
void writeFile(char file_content[][MAX_LENGTH], FILE * file_ptr, int lines_read); | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
beginner, c, file-system
int main(void)
{
FILE *file_ptr = NULL;
char file_name[FILENAME_LENGTH] = {'\0'};
char file_content[MAX_LINES][MAX_LENGTH] = {'\0'};
int lines_read = 0;
int has_signature = 0;
printf("*** SIMPLE ENCRYPT 1.0 by RESLASHD ***\n");
getFilename(file_name);
printf("\nAttempting to open file %s ...\n", file_name);
if (( file_ptr = openFile(file_name, READ_MODE)) != NULL){
printf("\n*** FILE OPENED ***\n");
// Read file and store in array
lines_read = readFile(file_content, file_ptr);
closeFile(file_ptr);
// Set signature flag for showMenu
has_signature = checkSignature(file_content, lines_read);
showMenu(has_signature, file_content, lines_read, file_ptr, file_name);
}
printf("\n*** EXITING PROGRAM ***\n");
return 0;
}
void addSignature(char file_content[][MAX_LENGTH], int lines_read){
strcpy(file_content[lines_read], "S_ENCRYPT23");
}
int checkSignature(char file_content[][MAX_LENGTH], int lines_read){
if(strcmp(file_content[lines_read-1],"S_ENCRYPT23") == 0){
// File is encrypted
return 1;
} else{
// File is not encrypted
return 0;
}
}
void closeFile(FILE * file_ptr)
{
// NULL means no file is open so nothing to close
if ( file_ptr != NULL ){
fclose(file_ptr);
}
} | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
beginner, c, file-system
void encryptData(char file_content[][MAX_LENGTH], int lines_read){
int row = 0; // line number (0 is the first line)
int column = 0; // character number (0 is the first character on a line)
for(row = 0 ; row < lines_read ; row++){
column = 0;
while(file_content[row][column] != '\0'){
if(file_content[row][column] != '\n'){
file_content[row][column] = file_content[row][column]+1;
column++;
} else{
column++;
}
}
}
addSignature(file_content, lines_read);
}
void decryptData(char file_content[][MAX_LENGTH], int lines_read){
int row = 0; // line number (0 is the first line)
int column = 0; // character number (0 is the first character on a line)
lines_read = lines_read - 1;
for(row = 0 ; row <= lines_read ; row++){
column = 0;
while(file_content[row][column] != '\0'){
if(file_content[row][column] != '\n'){
file_content[row][column] = file_content[row][column]-1;
column++;
} else{
column++;
}
}
}
lines_read = lines_read + 1;
removeSignature(file_content, lines_read);
}
void getFilename(char* file_name){
printf("\nPlease enter the name of the file you want encrypt/decrypt > ");
fgets(file_name, 100, stdin);
file_name[strcspn(file_name, "\n")] = 0;
}
FILE* openFile(char* file_name, char* file_mode)
{
FILE *file_ptr = NULL;
if (( file_ptr = fopen(file_name, file_mode )) == NULL ){
printf("\n*** ERROR OPENING FILE ***\n");
}
return file_ptr;
} | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
beginner, c, file-system
int readFile(char file_content[][MAX_LENGTH], FILE * file_ptr){
int lines_read = 0;
// While the end of the file is not reached yet AND there are no errors reading the file
while (!feof(file_ptr) && !ferror(file_ptr)){
if (fgets(file_content[lines_read], MAX_LENGTH, file_ptr) != NULL){
lines_read++;
}
}
return lines_read;
}
void removeSignature(char file_content[][MAX_LENGTH], int lines_read){
strcpy(file_content[lines_read-1], "\0");
}
void showMenu(int has_signature, char file_content[][MAX_LENGTH], int lines_read, FILE * file_ptr, char* file_name){
char choice = '\0';
printf("\n********* MENU *********\n");
if( has_signature == 0) {
printf("1 = Encrypt File \n");
}else{
printf("1 = Decrypt File \n");
}
printf("2 = Close file and exit\n\n");
printf("************************\n");
choice = getchar();
if( has_signature == 0 && choice == '1'){
printf("\nEncrypting file...\n");
//Open file for writing (erasing all contents!)
openFile(file_name, WRITE_MODE);
encryptData(file_content, lines_read);
writeFile(file_content, file_ptr, lines_read);
closeFile(file_ptr);
printf("\n*** FILE ENCRYPTED ***\n");
} else if(has_signature == 1 && choice == '1'){
printf("\nDecrypting file...\n");
//Open file for writing (erasing all contents!)
openFile(file_name, WRITE_MODE);
decryptData(file_content, lines_read);
writeFile(file_content, file_ptr, lines_read);
closeFile(file_ptr);
printf("\n*** FILE DECRYPTED ***\n");
}
else{
printf("\n*** NO CHANGES MADE TO FILE ***\n");
}
} | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
beginner, c, file-system
void writeFile(char file_content[][MAX_LENGTH], FILE * file_ptr, int lines_read){
int row = 0; // line number (0 is the first line)
int column = 0; // character number (0 is the first character on a line)
lines_read = lines_read + 1;
for(row = 0 ; row < lines_read ; row++){
column = 0;
while(file_content[row][column] != '\0'){
fprintf(file_ptr, "%c", file_content[row][column]);
column++;
}
}
}
Answer:
Enable more compiler warnings. | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
beginner, c, file-system
$ gcc -std=c17 -fPIC -gdwarf-4 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Wstrict-prototypes -fanalyzer encrypt.c -o enc
encrypt.c: In function 'main':
encrypt.c:9:19: warning: passing argument 2 of 'openFile' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
9 | #define READ_MODE "r"
| ^~~
encrypt.c:36:42: note: in expansion of macro 'READ_MODE'
36 | if (( file_ptr = openFile(file_name, READ_MODE)) != NULL){
| ^~~~~~~~~
encrypt.c:17:39: note: expected 'char *' but argument is of type 'const char *'
17 | FILE* openFile(char* file_name, char* file_mode);
| ~~~~~~^~~~~~~~~
encrypt.c: In function 'showMenu':
encrypt.c:155:14: warning: conversion from 'int' to 'char' may change value [-Wconversion]
155 | choice = getchar();
| ^~~~~~~
encrypt.c:8:20: warning: passing argument 2 of 'openFile' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
8 | #define WRITE_MODE "w"
| ^~~
encrypt.c:160:29: note: in expansion of macro 'WRITE_MODE'
160 | openFile(file_name, WRITE_MODE);
| ^~~~~~~~~~
encrypt.c:119:39: note: expected 'char *' but argument is of type 'const char *'
119 | FILE* openFile(char* file_name, char* file_mode)
| ~~~~~~^~~~~~~~~
encrypt.c:8:20: warning: passing argument 2 of 'openFile' discards 'const' qualifier from pointer target type [-Wdiscarded-qualifiers]
8 | #define WRITE_MODE "w"
| ^~~
encrypt.c:168:29: note: in expansion of macro 'WRITE_MODE'
168 | openFile(file_name, WRITE_MODE);
| ^~~~~~~~~~
encrypt.c:119:39: note: expected 'char *' but argument is of type 'const char *'
119 | FILE* openFile(char* file_name, char* file_mode) | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
beginner, c, file-system
119 | FILE* openFile(char* file_name, char* file_mode)
| ~~~~~~^~~~~~~~~
encrypt.c: In function 'openFile':
encrypt.c:125:12: warning: leak of FILE 'file_ptr' [CWE-775] [-Wanalyzer-file-leak]
125 | return file_ptr;
| ^~~~~~~~
'showMenu': events 1-4
|
| 144 | void showMenu(int has_signature, char file_content[][MAX_LENGTH], int lines_read, FILE * file_ptr, char* file_name){
| | ^~~~~~~~
| | |
| | (1) entry to 'showMenu'
|......
| 157 | if( has_signature == 0 && choice == '1'){
| | ~
| | |
| | (2) following 'true' branch...
| 158 | printf("\nEncrypting file...\n");
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (3) ...to here
| 159 | //Open file for writing (erasing all contents!)
| 160 | openFile(file_name, WRITE_MODE);
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (4) calling 'openFile' from 'showMenu'
|
+--> 'openFile': events 5-10
|
| 119 | FILE* openFile(char* file_name, char* file_mode)
| | ^~~~~~~~
| | |
| | (5) entry to 'openFile'
|......
| 122 | if (( file_ptr = fopen(file_name, file_mode )) == NULL ){
| | ~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | | |
| | | (6) opened here
| | (7) assuming 'file_ptr' is non-NULL
| | (8) following 'false' branch (when 'file_ptr' is non-NULL)...
|......
| 125 | return file_ptr;
| | ~~~~~~~~
| | |
| | (9) ...to here | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
beginner, c, file-system
| | |
| | (9) ...to here
| | (10) 'file_ptr' leaks here; was opened at (6)
| | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
beginner, c, file-system
WRITE_MODE and READ_MODE are unnecessary. "w" and "r" are clear as they are.
You won't require the forward declarations if you simply define move the definition of main() to the end of the program.
Use puts()/fputs() when the formatting capabilities of printf()/fprintf() are not required.
Reduce scope of variables. In main(), lines_read and has_signature need not be visible outside of the (only) if statement.
Use bool from stdbool.h to denote a binary state instead of 0 and 1. has_signature should be a bool.
Use size_t for sizes, cardinalities, and ordinal numbers. lines_read need not be signed.
Use EXIT_SUCCESS and EXIT_FAILURE from stdlib.h as the exit status codes instead of magic values.
openFile() simply returns NULL if fopen() fails. I don't see a point of writing a wrapper around fopen() here, especially when you ignore the return value of that wrapper.
closeFile() won't be required if you check the return value of fopen(), or the wrapper around it.
readFile() doesn't check whether there are more than MAX_LINES in the file and would continue to write past the buffer in case it does, which would result in undefined behavior. But why is there a limit to the number and length of lines? What if someone wants to encrypt a file that has more than MAX_LINES lines, or lines exceeding MAX_LENGTH characters? Dynamic memory allocation would be more apt here.
addSignature() doesn't check whether lines_read < MAX_LINES before copying the signature. Same for checkSignature() and removeSignature().
checkSignature() can be simplified:
int checkSignature(char file_content[][MAX_LENGTH], int lines_read) {
#if 0
if(strcmp(file_content[lines_read-1],"S_ENCRYPT23") == 0){
// File is encrypted
return 1;
} else{
// File is not encrypted
return 0;
}
#else
return strcmp(file_content[lines_read - 1], "S_ENCRYPT23") == 0;
#endif
}
In getFileName(), the return value of fgets() is ignored. | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
beginner, c, file-system
In getFileName(), the return value of fgets() is ignored.
lines_read = lines_read + 1; can be written as: lines_read += 1, or ++lines_read/lines_read++. Though, I don't see why you decremented lines_read by 1 before looping through the lines only to choose i <= lines_read as the loop condition, and then incrementing it back to the previous value.
encryptData() and decryptData() are basically the same function. Consider:
void crypt(char file_content[][MAX_LENGTH], int lines_read, int op) {
int row = 0; // line number (0 is the first line)
int column = 0; // character number (0 is the first character on a line)
for (row = 0; row < lines_read; row++) {
column = 0;
while (file_content[row][column] != '\0') {
if (file_content[row][column] != '\n') {
file_content[row][column] = (op == 1) ? file_content[row][column] + 1 : file_content[row][column] - 1;
column++;
} else {
column++;
}
}
}
}
void encryptData(char file_content[][MAX_LENGTH], int lines_read) {
crypt(file_content, lines_read, 1);
addSignature(file_content, lines_read);
}
void decryptData(char file_content[][MAX_LENGTH], int lines_read) {
crypt(file_content, lines_read, 0);
removeSignature(file_content, lines_read);
}
It would have been better if the program accepted the file name and the operation to be performed as command-line arguments. | {
"domain": "codereview.stackexchange",
"id": 45263,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, file-system",
"url": null
} |
java, recursion
Title: Double each occurrence of a char recursively
Question: The exercise is to write a recursive method that takes a String and a char parameter and returns a String with each occurrence of the char doubled. Additionally, the number of doubling operations should be added at the end of the string. No "extern" variables outside the method are allowed to use. The String parameter can contain any valid char, including numbers.
My code works up to 1000 doubling operations, but not correctly for 1001. My question is whether this is just a rounding error or whether this task is theoretical unsolvable.
public class Doubly {
public static String doubly(final String s, final char c) {
if (s.length() > 0) {
if (c == s.charAt(0)) {
int len1 = s.length();
String s1 = "" + c + c + doubly(s.substring(1), c);
int len2 = s1.length();
int lenDiff = len2 - len1;
int log = (int) Math.log10(lenDiff - Math.log(lenDiff + 1) + 1) + 1;
if (log > 0) {
int n = Integer.parseInt(s1.substring(s1.length() - log));
return s1.substring(0, s1.length() - log) + (n + 1);
}
return s1;
}
return "" + s.charAt(0) + doubly(s.substring(1), c);
}
return "0";
}
public static void main(final String[] args) {
String s = "ccc";
for (int i = 0; i < 1500; i++) {
s += "a";
String s2 = doubly(s, 'a');
System.out.println("Expected: " + (i + 1) + ", actual: " + s2.substring(s2.length() - (int) Math.log10(i + 1) - 1));
if (!String.valueOf(i + 1)
.equals(s2.substring(s2.length() - (int) Math.log10(i + 1) - 1))) {
System.out.println("ERROR");
return;
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45264,
"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
Answer: typo
Wow, you really like that
log10
expression. I see several occurrences of it.
Might be worth packaging up in a helper function.
Which you could unit test.
I don't understand this expression at all:
int log = (int) Math.log10(lenDiff - Math.log(lenDiff + 1) + 1) + 1;
You say the code works correctly,
but how is natural log relevant?
Or is that just a typo bug?
Recall that examining length of Integer.toString(n) is another way
to learn its base-ten logarithm.
(My initial theory was the bug was due to FP rounding issues,
until I saw natural log working its way into the mix.
Or perhaps a string length OBOB related to 99 -> 100 or 999 -> 1000.)
recursive function that iterates
You embrace recursion fully with this test:
if (c == s.charAt(0)) { | {
"domain": "codereview.stackexchange",
"id": 45264,
"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
So the (non-empty) base case is a test for: "Starts with c?"
Another approach would have been to examine
s.indexOf(c),
which iterates until hitting either a match or end-of-string.
A -1 says there's no more recursing to do.
Else we turn a "FRONT c BACK" string into "FRONT cc BACK".
data format
You're passing around "ccccNN", along with an integer, the string length.
And you're finding it a bit of a challenge both to get that format right,
and to debug it when things go south.
Recommend you adopt a simpler format.
At the outset you might try sample delimiters, such as SPACE or β or ζ°,
till you find one that is not present in s.
Pass it around as a parameter during recursive calls.
Then your format is "cccc NN", and s.reverseIndexOf(' ')
lets you split apart string from the serialized count.
Hmmm, actually you can always use SPACE, even if it occurred in s,
just ensure the first call tacks on a " 0" suffix to get things started,
and maybe strip it at the end if necessary.
Alternatively, rather than a single String you might choose to pass around a
Map.Entry(s, n)
pair, which is how standard java offers Pair.of(s, n) from Apache Commons.
Take care to nicely format the string at the end when recursion is done.
This codebase is buggy and does not achieve its design goals.
Given the peculiar representation of an integer, and the lack of a test suite,
I would not be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45264,
"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++, library, template-meta-programming
Title: C++ printing library with templates
Question: I was mad C++ did not have support for printing containers. I also could not find a header only library for printing containers so I decided to make my own. My goals were: 1) practicing templates 2) learn how to make a small library. I would also be very happy if some people found this useful and used it.
What does this library offer:
Header only, so should be really easy to setup this library (just put the .h file in your project)
Has support for printing the most common types
Easy to use ( has only one function print )
With my goals in mind can you please critique this code. And maybe some general advice?
#include <iostream>
#include <tuple>
#include <utility>
namespace p {
template<typename T> // forward dec
void print(const T& t, const std::string& sep = ", ", const std::string& end = "\n");
namespace {
// Requires T to have ::iterator and ::const_iterator, which should
// guarantee that the type is iterable as far as the STL is concerned
template<typename T>
concept Iterable = requires(T a) {
typename T::iterator;
typename T::const_iterator;
};
// Forward declarations
template<typename T>
void print_iterable(const T& t, const std::string& sep);
void print_iterable(const std::string& str, const std::string& sep);
void print_iterable(const bool b, const std::string& sep);
template<typename TupType, size_t... I>
void print_iterable(const TupType& tup, std::index_sequence<I...>, const std::string& sep);
template<typename... T>
void print_iterable(const std::tuple<T...>& tup, const std::string& sep);
template<class T1, class T2>
void print_iterable(const std::pair<T1, T2>& pair, const std::string& sep);
template<Iterable T>
void print_iterable(const T& t, const std::string& sep);
// ----------------- End of forward declartions | {
"domain": "codereview.stackexchange",
"id": 45265,
"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++, library, template-meta-programming",
"url": null
} |
c++, library, template-meta-programming
// ----------------- End of forward declartions
// Print a non-iterable type
template<typename T>
void print_iterable(const T& t, const std::string& sep)
{
std::cout << t;
}
// Specialization for std::string (should be treated like non-iterable)
void print_iterable(const std::string& str, const std::string& sep)
{
std::cout << str;
}
// Print bools
void print_iterable(const bool b, const std::string& sep) {
std::cout << std::boolalpha << b;
}
// Helper to put sep string between print statements inside fold expression
template<typename T>
void print_with_delim(const T& t, size_t I, size_t index_length, const std::string& sep)
{
print_iterable(t, sep);
if (I != index_length - 1) {
std::cout << sep;
}
}
// Print a tuple
template<typename TupType, size_t... I>
void print_iterable(const TupType& tup, std::index_sequence<I...> index_s, const std::string& sep)
{
std::cout << "(";
(..., print_with_delim(std::get<I>(tup), I, index_s.size(), sep)); // Fold expression: get<0>, get<1>, ...
std::cout << ")";
}
// Wrapper for printing a tuple
template<typename... T>
void print_iterable(const std::tuple<T...>& tup, const std::string& sep)
{
print_iterable(tup, std::make_index_sequence<sizeof...(T)>(), sep); // make_index_sequence -> 0, 1, 2, ..., N-1
}
// Print a pair
template<class T1, class T2>
void print_iterable(const std::pair<T1, T2>& pair, const std::string& sep)
{
std::cout << "(";
print_iterable(pair.first, sep);
std::cout << " : ";
print_iterable(pair.second, sep);
std::cout << ")";
} | {
"domain": "codereview.stackexchange",
"id": 45265,
"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++, library, template-meta-programming",
"url": null
} |
c++, library, template-meta-programming
// Print an iterable (can be deeply nested)
template<Iterable T>
void print_iterable(const T& t, const std::string& sep)
{
int indx = 0;
std::cout << '[';
for (auto it = t.begin(); it != t.end(); ++it) {
print_iterable(*it, sep); // <---- Recursive call to go one level deeper
if (indx++ != t.size() - 1) {
std::cout << sep;
}
}
std::cout << ']';
}
} // -> end of private namespace
// Wrapper
template<typename T>
void print(const T& t, const std::string& sep, const std::string& end)
{
print_iterable(t, sep);
std::cout << end;
}
} // -> end on print namespace
```
Answer: C++23 and the {fmt} library can print ranges
I was mad C++ did not have support for printing containers.
C++23 will have the ability to print the contents of containers, and even better of any range. There are some notable differences between how std::print() will format ranges and how your function works. In particular, std::print() will allow you to specify how to format the individual elements of a range using a format string. Customizing the start, end and separator characters might be possible by implementing your own formatter for the types you want to print.
I also could not find a header only library for printing containers so I decided to make my own.
std::format() and std::print() are based on the {fmt} library. According to the documentation, you can configure it to be a header-only library.
Consider writing a custom formatter for standard library functions instead
The problem with your function is that it doesn't work like existing formatting functions in the standard library. However, you can write your own formatters that integrate with those. For example, you can write an operator<<(std::ostream&, β¦) overload for ranges so you can write:
std::vector<int> foo{1, 2, 3};
std::cout << foo << '\n'; | {
"domain": "codereview.stackexchange",
"id": 45265,
"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++, library, template-meta-programming",
"url": null
} |
c++, library, template-meta-programming
Similarly, since C++20 you can specialize std::formatter to do something similar for std::format() and friends, so you could write:
std::cout << std::format("{}\n", foo);
You can still make your custom formatter a header-only library, you can still use templates so it will be able to print most common types, and it's even easier because users don't have to learn how to use a new printing function.
One benefit of a custom formatter over a print() function is that you can print to things other than std::cout, for example to a file or to a stringstream.
Another benefit is that it now works in exactly the same way as formatting standard types. That means you can write a generic function:
template<typename T>
print_key_value(const std::string& key, const T& value) {
std::cout << std::format("{}: {}\n", key, value);
}
And it will be able to print both containers and simple types, without needing to treat T being a container as a special case. | {
"domain": "codereview.stackexchange",
"id": 45265,
"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++, library, template-meta-programming",
"url": null
} |
programming-challenge, bash
Title: Advent of code 2023 day 1: count trebuchet calibration numbers - mostly in Bash
Question: It's that time of the year again!
Although there's no more Winter Bash, we can still have all the Bash we want in winter ;-)
Part 1
To paraphrase the description:
For each line in the input:
Find the first digit.
Find the last digit.
Form a 2-digit number by concatenating the first and the last digits.
Compute the sum.
For example, given the input:
1abc2
pqr3stu8vwx
a1b2c3d4e5f
treb7uchet
The numbers are 12, 38, 15, and 77, and the sum is 142.
Finding the digits is simple enough using sed and regex replacements, and computing the sum is easy using awk.
{ sed -e 's/^[^0-9]\+//' -e 's/[^0-9]\+$//' -e 's/^\(.\).*\(.\)$/\1\2/' -e 's/^\(.\)$/\1\1/' | awk '{ sum += $1 } END { print sum }'; } < path/to/input.txt
Part 2
Part 2 throws a wrench in the gears by changing the specifications: English spelling of digits must also be considered as digits.
For example from two1nine we should parse 29 instead of 11.
My first idea was to replace the English words with their corresponding digits, and then simply reuse the implementation for part 1. There, instead of spelling out all the s/// commands for sed manually, I used a loop to produce the commands like any lazy programmer would:
digits=(dummy one two three four five six seven eight nine)
replace_digits=()
for ((i = 1; i < ${#digits[@]}; ++i)); do
replace_digits+=(-e "s/${digits[i]}/$i/g")
done
{ sed "${replace_digits[@]}" -e 's/^[^0-9]\+//' -e 's/[^0-9]\+$//' -e 's/^\(.\).*\(.\)$/\1\2/' -e 's/^\(.\)$/\1\1/' | awk '{ sum += $1 } END { print sum }'; } < path/to/input.txt
Keen readers and advent of code veterans probably have already spotted how this approach falls apart on inputs such as:
eightwo1
2oneight
(Spoiler alert ahead.)
Incorrectly parses eightwo1 as 21 instead of 81.
Incorrectly parses 2oneight as 21 instead of 28. | {
"domain": "codereview.stackexchange",
"id": 45266,
"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": "programming-challenge, bash",
"url": null
} |
programming-challenge, bash
Incorrectly parses eightwo1 as 21 instead of 81.
Incorrectly parses 2oneight as 21 instead of 28.
I considered adding additional replacement rules to work around this, such as s/oneight/18/g and so on, but it seems there would be quite a lot of those to write, and starting to look harder to do then to simply implement the algorithm straight as instructed by the description.
And so it was time to open a text editor and write something more than a one-liner:
#!/usr/bin/env bash
#
# Solver for https://adventofcode.com/2023/day/1 part 2
# Redirect the input file to this script, for example day1part2.sh < path/to/input.txt
#
set -euo pipefail
# Prints the digit in $line at $index if exists, without a trailing newline, or fail.
printf_digit_in_line_at() {
local line index
line=$1
index=$2
case ${line:index} in
[0-9]*) printf "%s" "${line:index:1}" ;;
one*) printf 1 ;;
two*) printf 2 ;;
three*) printf 3 ;;
four*) printf 4 ;;
five*) printf 5 ;;
six*) printf 6 ;;
seven*) printf 7 ;;
eight*) printf 8 ;;
nine*) printf 9 ;;
*) return 1
esac
}
# Prints the first digit found in $line, without trailing newline.
printf_first_digit() {
local line index
line=$1
for ((index = 0; index < ${#line}; ++index)); do
printf_digit_in_line_at "$line" "$index" && return || true
done
}
# Prints the last digit found in $line, without trailing newline.
printf_last_digit() {
local line index
line=$1
for ((index = ${#line} - 1; index >= 0; index--)); do
printf_digit_in_line_at "$line" "$index" && return || true
done
}
# Solve part2 of the puzzle and print the output.
solve_part2() {
while read line; do
printf_first_digit "$line"
printf_last_digit "$line"
echo
done | awk '{ sum += $1 } END { print sum }'
}
solve_part2 | {
"domain": "codereview.stackexchange",
"id": 45266,
"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": "programming-challenge, bash",
"url": null
} |
programming-challenge, bash
solve_part2
Review request
I do realize this is a bit whimsical, and Bash is not a great choice to solve algorithmic puzzles.
Do you some patterns here that you would replace with better patterns?
Do you see a simpler way to solve any part of the puzzle with Bash and common shell tools?
Anything else to do better?
Answer: For me, bash solution would rather be something like this:
Part 1
#!/bin/bash
set -eu
shopt -s extglob
sum=0
while read line ; do
line=${line##+([^0-9])}
line=${line%%+([^0-9])}
left=${line:0:1}
right=${line: -1}
add=$left$right
(( sum += add ))
done
echo $sum
Part 2
#!/bin/bash
set -eu
shopt -s extglob
declare -A english_digits=([one]=1 [two]=2 [three]=3 [four]=4 [five]=5
[six]=6 [seven]=7 [eight]=8 [nine]=9)
digits=({1..9})
digits_pattern=$(IFS='|' ; echo "${!english_digits[*]}|${digits[*]}")
sum=0
while read line ; do
if [[ $line =~ ($digits_pattern) ]] ; then
left=${BASH_REMATCH[1]}
fi
if [[ $line =~ .*($digits_pattern) ]] ; then
right=${BASH_REMATCH[1]}
fi
if [[ ${english_digits[$left]:-} ]] ; then
left=${english_digits[$left]}
fi
if [[ ${english_digits[$right]:-} ]] ; then
right=${english_digits[$right]}
fi
add=$left$right
(( sum += add ))
done
echo $sum
I.e. using bash and only bash instead of external tools like sed and awk. | {
"domain": "codereview.stackexchange",
"id": 45266,
"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": "programming-challenge, bash",
"url": null
} |
c++, game
Title: Re: C++ 4X Game
Question: This post is regarding the revamp of this post/project I did about 8 months ago. I took a lot of the advice from the suggestions provided (thank you by the way), and fixed the project up, so I'm reposting it. @Ajinkya Kamat wanted to see the revisions I made, so here they are:
(From https://replit.com/@Selisine/CBPR?v=1)
main.cpp
#include <iostream>
#include "game_logic.cpp"
int main(){
game_logic game_logic;
bool repeater = false;
game_logic.assign_stats();
game_logic.name_entry();
//Begin game loop
while (game_logic.victor_status() == "continue"){
game_logic.check_non_zeroes();
game_logic.stat_rundown();
game_logic.passive_income();
do {
switch (game_logic.turn_choice()){
case 1:
game_logic.expand_territory();
repeater = false;
break;
case 2:
game_logic.upgrade_technology();
repeater = false;
break;
case 3:
game_logic.recruit_army();
repeater = false;
break;
case 4:
game_logic.battle_initiation();
repeater = false;
break;
default:
std::cout << "Invalid input! Try again...";
repeater = true;
break;
}
} while (repeater);
game_logic.turn_counter_update();
}
}
player_stats.hpp
#ifndef CBPR_PLAYER_STATS_HPP
#define CBPR_PLAYER_STATS_HPP
#include <iostream>
class player_stats {
public:
player_stats(); //Setter
int stat_table[2][5];
int return_values(int, int);
void assign_values();
private:
int territory_count;
int army_count;
int money; | {
"domain": "codereview.stackexchange",
"id": 45267,
"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++, game",
"url": null
} |
c++, game
private:
int territory_count;
int army_count;
int money;
//Tech Levels
int army_skill_level;
int passive_income_level;
};
void player_stats::assign_values(){
int base_stat_table[5] = {territory_count, army_count, money, army_skill_level, passive_income_level};
for (int x = 0; x < 2; x++){
for (int y = 0; y < 5; y++){
stat_table[x][y] = base_stat_table[y];
}
}
}
//Setter
player_stats::player_stats(){
territory_count = 2;
army_count = 5;
money = 50'000;
army_skill_level = 0;
passive_income_level = 0;
assign_values();
}
//Getter
int player_stats::return_values(int turn_counter, int stat_type){
return stat_table[turn_counter][stat_type];
}
#endif //CBPR_PLAYER_STATS_HPP
game_logic.cpp
#ifndef CBPR_GAME_LOGIC_CPP
#define CBPR_GAME_LOGIC_CPP
#include <iostream>
#include <random>
#include "player_stats.hpp"
class game_logic {
public:
//Misc
void assign_stats();
void name_entry();
void stat_rundown();
//Choices
int turn_choice();
void expand_territory();
void upgrade_technology();
void recruit_army();
void battle_initiation();
//Passives
void passive_income();
int turn_counter = 0;
void turn_counter_update();
std::string victor_status();
void check_non_zeroes();
private:
std::string names[2];
int player_stats_malleable[2][5];
};
/*
-----PREPROCESSED-----
*/
void game_logic::assign_stats(){
player_stats player_stats;
for (int x = 0; x < 2; x++){
for (int y = 0; y < 5; y++){
player_stats_malleable[x][y] = player_stats.return_values(x, y);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45267,
"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++, game",
"url": null
} |
c++, game
/*
-----MISC-----
*/
//Gets all player names
void game_logic::name_entry() {
std::cout << "Player 1, enter your name: ";
std::getline(std::cin, names[0]);
std::cout << "Player 2, enter your name: ";
std::getline(std::cin, names[1]);
}
//Lists all stats
void game_logic::stat_rundown(){
std::string stat_type[5] = {"Territories: ", "Armies: ", "Money: $", "Army Skill Level: ", "Passive Income Level: "};
for (int x = 0; x < 2; x++){
std::cout << "[" << names[x] << "'s stats]\n";
for (int y = 0; y < 5; y++){
std::cout << stat_type[y];
std::cout << player_stats_malleable[x][y] << "\n";
}
std::cout << "\n";
}
}
//Dice Roll
int will_of_tyche(){
static std::default_random_engine rng(std::random_device{}());
static std::uniform_int_distribution<> dist{};
return dist(rng, decltype(dist)::param_type{1, 100});
}
//Checks if the player's choice can be bought
bool can_be_bought(int player_money, int price){
if (player_money - price < 0){
return false;
}
return true;
}
/*
-----CHOICES-----
*/
//Lists each choice
void choice_list(){
game_logic game_logic;
std::string choice_list[5] = {"Expand Territory [$10,000]", "Upgrade Technology", "Recruit Army [$8,000]", "Battle"};
for (int x = 0; x < 4; x++){
std::cout << "[" << x + 1 << "] ";
std::cout << choice_list[x] << "\n";
}
}
//Gets and returns the player's choice
int game_logic::turn_choice(){
int player_choice;
std::cout << "It is your turn " << names[turn_counter] << ". Here are your options:\n";
choice_list();
std::cout << "Choice: ";
std::cin >> player_choice;
return player_choice;
} | {
"domain": "codereview.stackexchange",
"id": 45267,
"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++, game",
"url": null
} |
c++, game
std::cout << "Choice: ";
std::cin >> player_choice;
return player_choice;
}
//+1 Territories if can_be_bought() returns true
void game_logic::expand_territory(){
int price = 10'000;
if (!can_be_bought(player_stats_malleable[turn_counter][2], price)){
std::cout << "Not enough money!\n";
}
else {
std::cout << names[turn_counter] << " expands their territory! [-10,000]\n";
player_stats_malleable[turn_counter][0] += 1;
player_stats_malleable[turn_counter][2] -= 10'000;
}
}
/*
---TECHNOLOGY---
*/
//List of technologies to choose from
void tech_list(){
std::string tech_list[2] = {"Army Skill [$8,000]", "Passive Income Level [$8,000]"};
for (int x = 0; x < 2; x++){
std::cout << "[" << x + 1 << "] ";
std::cout << tech_list[x] << "\n";
}
}
//+1 of chosen technology
void game_logic::upgrade_technology(){
int technology_index;
int price = 8'000;
std::cout << names[turn_counter] << ", what technology would you like to upgrade?\n";
tech_list();
std::cin >> technology_index;
if (!can_be_bought(player_stats_malleable[turn_counter][2], price)){
std::cout << "Not enough money!\n";
}
else {
player_stats_malleable[turn_counter][technology_index + 2] += 1;
player_stats_malleable[turn_counter][2] -= price;
}
}
//+1 army
void game_logic::recruit_army(){
int price = 8000;
if (player_stats_malleable[turn_counter][1] == player_stats_malleable[turn_counter][0]){
std::cout << names[turn_counter] << " recruits another army! [-8,000]\n";
player_stats_malleable[turn_counter][1] += 1;
player_stats_malleable[turn_counter][2] -= 8'000;
}
else if (!can_be_bought(player_stats_malleable[turn_counter][2], price)){
std::cout << "Not enough money!\n";
}
else {
std::cout << "Territories must be as much or higher than armies!\n";
}
} | {
"domain": "codereview.stackexchange",
"id": 45267,
"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++, game",
"url": null
} |
c++, game
void game_logic::battle_initiation(){
int player_one_boosts = .3 * player_stats_malleable[0][1] * player_stats_malleable[0][3];
int player_two_boosts = .3 * player_stats_malleable[1][1] * player_stats_malleable[1][3];
srand( time(NULL) );
int player_one_roll;
int player_two_roll;
std::cout << "A skirmish commences!\n\n";
player_one_roll = will_of_tyche() + player_one_boosts;
player_two_roll = will_of_tyche() + player_two_boosts;
if (std::max(player_one_roll, player_two_roll) == player_one_roll){
std::cout << player_one_roll << " > " << player_two_roll << "\n";
std::cout << names[0] << " wins!\n";
player_stats_malleable[0][2] += 1'000;
player_stats_malleable[1][2] -= 1'000;
}
else if (std::max(player_one_roll, player_two_roll) == player_two_roll){
std::cout << player_one_roll << " < " << player_two_roll << "\n";
std::cout << names[1] << " wins!\n";
player_stats_malleable[0][2] -= 1'000;
player_stats_malleable[1][2] += 1'000;
}
else {
std::cout << "Tie!\n";
}
}
/*
-----PASSIVES-----
*/
void game_logic::passive_income(){
int upgrade_addition = 1'000 * (.1 * player_stats_malleable[turn_counter][4]);
player_stats_malleable[turn_counter][2] += 1'000 + upgrade_addition;
}
std::string game_logic::victor_status(){
if (player_stats_malleable[0][0] <= 0 || player_stats_malleable[0][2] <= 0){
std::cout << names[1] << " has won the war! Congratulations!\n";
return "player_two_win";
}
else if (player_stats_malleable[1][0] <= 0 || player_stats_malleable[1][2] <= 0){
std::cout << names[1] << " has won the war! Congratulations!\n";
return "player_one_win";
}
else {
return "continue";
}
} | {
"domain": "codereview.stackexchange",
"id": 45267,
"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++, game",
"url": null
} |
c++, game
void game_logic::turn_counter_update(){
if (turn_counter + 1 == 1){
turn_counter++;
}
else if (turn_counter + 1 == 2){
turn_counter--;
}
else {
std::cout << "Something is wrong.\n";
}
}
//Checks if armies is below zero (potential to lose one during battle)
void game_logic::check_non_zeroes(){
if (player_stats_malleable[turn_counter][1] < 0){
player_stats_malleable[turn_counter][1] = 0;
}
}
#endif //CBPR_GAME_LOGIC_CPP
Answer: Just seperating the game_logic from input processing has made a huge difference in terms of code clarity. In this review, I will start with nitpicks with the current code and then suggest a new architecture to make the code easier to extend. I can easily see this project as a good jumping off point into good software architecture.
In this review, I will first go through the code and review it. Since you are a new coder, I will suggest a better architecture, so as to introduce to this key aspect of software engineering.
Review
I have forked your repl and made changes. You can see them here. | {
"domain": "codereview.stackexchange",
"id": 45267,
"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++, game",
"url": null
} |
c++, game
Never #include a cpp file. Always seperate declarations and definition into hpp and cpp files. This answer goes into details. This means you will have to use a build system. I have used CMake in my reviewed code. I had to modify the hidden .replit and replit.nix files to make this work.
Always use your own namespace for your code.
Prefer constructors over delayed initialization. You dont need a seperate assign_logic() and name_entry() functions in game_logic class.
Prefer <verb>_<noun> pattern for naming functions. name_entry() can be input_names().
Use m_ prefix to identify class member variables. So game_logic::names becomes game_logic::m_names
Prefer enum classes over std::string to return status. This reduces errors as the status can only take values listed in the enum. This also makes the code more readable because the reader does not have to look at the implementation. game_logic::victory_status() should return enums.
Since, you are already doing input processing in game_logic. The switch statement after turn_choice can be moved inside game_logic.
turn_counter_update can be implemented using modulus operator instead of if statements. Similarly can_be_bought can be implement by using not operator.
Prefer structs over arrays for storing named parameters like player_stats.
In will_of_tyche you dont need to have decltype incantation. You can just initialize std::uniform_distribution with the right parameters aka 1, 100. C and C++ random number generators are not the same, you don't have to call srand before using C++ random number generators | {
"domain": "codereview.stackexchange",
"id": 45267,
"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++, game",
"url": null
} |
c++, game
New Architecture
The repl for this can be found here.
Your code is written in procedural style. There is nothing wrong with procedural style. But your problem statement will benefit if we introduce object oriented paradigm here. In this iteration, I will focus on encapsulating player choice. I will call player choices Actions from now on. My goal here is to make every action a standalone item. Each Player has a list of Actions that they can perform. At the start of their turn, they are presented with this list. The player chooses and action which our code executes. Upon execution, the player stats change. I will also keep these actions dynamic. This can allow for complex behavior such as the cost of a tech upgrade might increase as the tech levels up. Keeping the player dynamic actions and storing them in a list means that a concept of civilizations similar to Age of Empires can easily be added in the future.
Also, making Game an interface we can easily add features to save and replay games. This will make it super easy to balance the game. | {
"domain": "codereview.stackexchange",
"id": 45267,
"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++, game",
"url": null
} |
python, beginner, game, tic-tac-toe
Title: Simple Tic-tac-toe in Python
Question: I am a beginner programmer who coded a simple Tic-tac-toe in Python for practice. Any feedback, especially regarding best practices and tidying up the code, is appreciated.
import random
board = {"a1": ".", "b1": ".", "c1": ".",
"a2": ".", "b2": ".", "c2": ".",
"a3": ".", "b3": ".", "c3": "."}
#randomly assigns user to either x or o
userIcon = random.choice(["x", "o"])
if userIcon == "x":
computerIcon = "o"
else:
computerIcon = "x"
def main():
print("\n\nWelcome to Tic-tac-toe!\n")
print("The columns and rows are labelled with letters and numbers respectively")
print("Choose your desired spot by typing in the letter followed by the number and pressing Enter")
print("For example: b2[Enter]\n")
print(f"You {userIcon} will be playing against the computer ({computerIcon})")
#the turn variable keeps track of whose turn it is (even number is user's turn, odd number is computer's turn)
if userIcon == "x":
print("Your turn is first")
turn = 0
else:
print("Your turn is second")
turn = 1
input("\nPress Enter to start!\n")
printBoard()
#moves are made until the game is finished
while True:
if turn % 2 == 0:
try:
user()
turn += 1
printBoard()
result = arbiter()
if result != 0:
break
except:
print("Invalid")
continue
else:
computer()
turn += 1
printBoard()
result = arbiter()
if result != 0:
break
if result == 1:
print("User wins")
elif result == 2:
print("Computer wins")
else:
print("Draw") | {
"domain": "codereview.stackexchange",
"id": 45268,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game, tic-tac-toe",
"url": null
} |
python, beginner, game, tic-tac-toe
def printBoard():
print("\n a b c")
for i in [1, 2, 3]:
print(i, board[f"a{i}"], board[f"b{i}"], board[f"c{i}"], sep=" ")
print("____________________________________")
#lets user make their move
def user():
while True:
selection = input("\nChoose your spot: ")
if board[selection] != ".":
print("Spot taken")
continue
else:
board[selection] = userIcon
break
#picks random available spot for computer
def computer():
while True:
row = random.choice(["1", "2", "3"])
column = random.choice(["a", "b", "c"])
if board[column + row] == ".":
board[column + row] = computerIcon
break
#returns 1 if user wins, 2 if computer wins, 3 if draw
def arbiter():
if winner(userIcon) == True:
return 1
if winner(computerIcon) == True:
return 2
#checks for draw
for i in board:
if board[i] == ".":
return 0
return 3
#returns True if specified player has won, False if they have not won
def winner(icon):
#check rows
for i in [1, 2, 3]:
line = 0
for j in ["a", "b", "c"]:
if board[f"{j}{i}"] == icon:
line += 1
if line == 3:
return True
#check columns
for i in ["a", "b", "c"]:
line = 0
for j in [1, 2, 3]:
if board[f"{i}{j}"] == icon:
line += 1
if line == 3:
return True
#check major diagonal
line = 0
for i in ["a1", "b2", "c3"]:
if board[f"{i}"] == icon:
line += 1
if line == 3:
return True
#check minor diagonal
line = 0
for i in ["c1", "b2", "a3"]:
if board[f"{i}"] == icon:
line += 1
if line == 3:
return True
return False
main()
Answer: You could represent the board as list of nine items, initialized as
board = ["."] * 9 | {
"domain": "codereview.stackexchange",
"id": 45268,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game, tic-tac-toe",
"url": null
} |
python, beginner, game, tic-tac-toe
Answer: You could represent the board as list of nine items, initialized as
board = ["."] * 9
Where, if row and col are zero-based coordinates, the respective index into board can be calculated as row * 3 + col. The indices of the board items are then placed like
0 1 2
3 4 5
6 7 8
This may need some rewrite but allows to define a function
def check_winner_seq(icon, start, step):
for i in range(start, start + step * 3, step):
if board[i] != icon:
return False
return True
To check a whole row, column or diagonal at once.
Then you can rewrite winner like
def winner(icon):
# Check rows
for i in range(0, 9, 3):
if check_winner_seq(icon, i, 1):
return True
# Check cols
for i in range(0, 3, 1):
if check_winner_seq(icon, i, 3):
return True
# Check major diagonal
if check_winner_seq(icon, 0, 4):
return True
# Check minor diagonal
if check_winner_seq(icon, 2, 2):
return True
return False
With some advanced features like list comprehensions and the all and any functions, this can be written even more concise. | {
"domain": "codereview.stackexchange",
"id": 45268,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, game, tic-tac-toe",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Title: A recursive_minmax Template Function Implementation in C++
Question: This is a follow-up question for A Maximum Function For Various Type Arbitrary Nested Iterable Implementation in C++. Besides the function for finding maximum, I am trying to implement recursive_minmax template function which returns both minimum and maximum values.
The experimental implementation
recursive_minmax template function implementation
template<class T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
requires(!(std::ranges::input_range<T>)) // non-range overloading
constexpr auto recursive_minmax(const T& input, Comp comp = {}, Proj proj = {})
{
return input;
}
template<std::ranges::input_range T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
constexpr auto recursive_minmax(const T& numbers, Comp comp = {}, Proj proj = {})
{
return std::make_pair(
recursive_min(numbers, comp, proj),
recursive_max(numbers, comp, proj)
);
}
recursive_min template function implementation
template<class T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
requires(!std::ranges::input_range<T>) // non-range overloading
static inline T recursive_min(T inputNumber, Comp comp = {}, Proj proj = {})
{
return std::invoke(proj, inputNumber);
} | {
"domain": "codereview.stackexchange",
"id": 45269,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<std::ranges::input_range T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
static inline auto recursive_min(const T& numbers, Comp comp = {}, Proj proj = {})
{
auto output = recursive_min(numbers.at(0), comp, proj);
for (auto& element : numbers)
{
output = std::ranges::min(
output,
recursive_min(element, comp, proj),
comp,
proj);
}
return output;
}
recursive_max template function implementation
template<class T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
requires(!std::ranges::input_range<T>) // non-range overloading
static inline T recursive_max(T inputNumber, Comp comp = {}, Proj proj = {})
{
return std::invoke(proj, inputNumber);
}
template<std::ranges::input_range T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
static inline auto recursive_max(const T& numbers, Comp comp = {}, Proj proj = {})
{
auto output = recursive_max(numbers.at(0), comp, proj);
for (auto& element : numbers)
{
output = std::ranges::max(
output,
recursive_max(element, comp, proj),
comp,
proj);
}
return output;
}
Full Testing Code
The full testing code:
// A `recursive_minmax` Template Function Implementation in C++
#include <algorithm>
#include <array>
#include <chrono>
#include <concepts>
#include <execution>
#include <iostream>
#include <ranges>
#include <vector> | {
"domain": "codereview.stackexchange",
"id": 45269,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class T>
requires (std::ranges::input_range<T>)
constexpr auto recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << "\n";
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << "\n";
return x;
}
);
return output;
}
template<class T>
requires (std::ranges::input_range<T> &&
std::ranges::input_range<std::ranges::range_value_t<T>>)
constexpr T recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << "\n";
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
bool comp(int a, int b){
return a > b;
}
template<class T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
requires(!std::ranges::input_range<T>) // non-range overloading
static inline T recursive_min(T inputNumber, Comp comp = {}, Proj proj = {})
{
return std::invoke(proj, inputNumber);
}
template<std::ranges::input_range T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
static inline auto recursive_min(const T& numbers, Comp comp = {}, Proj proj = {})
{
auto output = recursive_min(numbers.at(0), comp, proj);
for (auto& element : numbers)
{
output = std::ranges::min(
output,
recursive_min(std::invoke(proj, element), comp, proj),
comp,
proj);
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 45269,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
template<class T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
requires(!std::ranges::input_range<T>) // non-range overloading
static inline T recursive_max(T inputNumber, Comp comp = {}, Proj proj = {})
{
return std::invoke(proj, inputNumber);
}
template<std::ranges::input_range T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
static inline auto recursive_max(const T& numbers, Comp comp = {}, Proj proj = {})
{
auto output = recursive_max(numbers.at(0), comp, proj);
for (auto& element : numbers)
{
output = std::ranges::max(
output,
recursive_max(std::invoke(proj, element), comp, proj),
comp,
proj);
}
return output;
}
template<class T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
requires(!(std::ranges::input_range<T>)) // non-range overloading
constexpr auto recursive_minmax(const T& input, Comp comp = {}, Proj proj = {})
{
return std::invoke(proj, input);
}
template<std::ranges::input_range T, class Proj = std::identity,
std::indirect_strict_weak_order<
std::projected<const T*, Proj>> Comp = std::ranges::less>
constexpr auto recursive_minmax(const T& numbers, Comp comp = {}, Proj proj = {})
{
return std::make_pair(
recursive_min(numbers, comp, proj),
recursive_max(numbers, comp, proj)
);
} | {
"domain": "codereview.stackexchange",
"id": 45269,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
void recursive_minmax_test()
{
std::array test_array1{3, 1, 4, 1, 5, 15, 2, 6, 5};
std::array test_array2{3, 1, 4, -1, 5, 9, 2, 6, 5};
std::vector<decltype(test_array1)> v = {test_array1, test_array2};
auto [min, max] = recursive_minmax(v);
std::cout << "Min value is " << min << "\n";
std::cout << "Max value is " << max << "\n";
}
int main()
{
auto start = std::chrono::system_clock::now();
recursive_minmax_test();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n';
return 0;
}
The output of the test code above:
Min value is -1
Max value is 15
Computation finished at Sun Dec 3 08:04:27 2023
elapsed time: 3.4378e-05
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A Maximum Function For Various Type Arbitrary Nested Iterable Implementation in C++
What changes has been made in the code since last question?
I am trying to implement recursive_minmax template function in this post.
Why a new review is being asked for?
Please review recursive_minmax template function implementation and all suggestions are welcome.
Answer: Separate concerns
You are not following the principle of separation of concerns. Whenever you write a recursive_foo() function, you should separate the concern of recursively iterating over a container from applying foo() to each element.
Since the minmax operation is a reduction operation, ideally you'd want to write something like:
void recursive_minmax_test()
{
β¦
std::vector<decltype(test_array1)> v = {test_array1, test_array2};
auto [min, max] = recursive_reduce(v, minmax);
β¦
} | {
"domain": "codereview.stackexchange",
"id": 45269,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Where minmax() would be a generic function that takes a value and an existing min/max pair, and returns a new pair that is updated based on the given value.
The benefit should be obvious. Instead of having to write many recursive_something() functions, you only have to write one. If you want a recursive sum: recursive_reduce(v, std::plus{}), if you want a recursive minimum: recursive_reduce(v, std::min), and so on.
Allow for passing an initial value
Many standard library algorithms allow (or sometimes require) you to pass an initial value. This is very useful for several reasons:
It avoids having to treat the first element as a special case. This is also avoids the issue you have if the container you pass in is empty.
It allows chaining multiple reduction operations, by simply passing the result of the first reduction as an initial value for the second reduction.
There might be cases where the initial value of the reduction operation cannot be one of the values of the container, for example when the reduced value has a different type... like with the min/max reduction!
recursive_minmax() is inefficient
Your recursive_minmax() just calls recursive_min() and recursive_max(). That means it will iterate twice over the containers. But you only need one pass to get both the minimum and maximum. | {
"domain": "codereview.stackexchange",
"id": 45269,
"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++, recursion, template, c++20, constrained-templates",
"url": null
} |
python, beginner, database
Title: DB Layer of a project management CLI
Question: I am (re)writing a project management CLI and want to put it on a solid foundation concerning the database connections and testing. My focus was to build a DB class which is easy to test and could be reused for any tables I would maybe add at some point. However I am not sure if the duplicate creation of the engine is an issue.
This is my first project which also includes a database, and also my first time trying a TDD approach. So if you would use a wildly different approach to set up the DB connections, I would be also thankful for those alternative ways. Please also feel free to review the testing part, since that's something I am not that familiar with yet too.
db.py consists of two models (they inherit from SQLModel, which is specific to sqlmodel), Project and Account, which define the tables. The class DB is meant as a wrapper around the sqlmodel ORM-functionality, where I reduce the interaction needed for each CRUD-operation to one method.
The tests in test_db.py test all CRUD-operations of the class for both tables, and test one case were both instances of the class are used in the same test. All tests pass (with deprecation warnings from sqlalchemy which are caused by the implementation used by sqlmodel).
For executing the code in your own environment you might need to replace from projects.db import ... with from db import ... in test_db.py (I used a src-layout with an editable pip install for running pytest).
db.py
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Account(SQLModel, table=True):
"""Model for the accounts table. Accounts belong to a project."""
id: Optional[int] | None = Field(default=None, primary_key=True)
account_number: str
description: Optional[str] = None
project_id: Optional[int] = Field(default=None, foreign_key="project.id")
class Project(SQLModel, table=True):
"""Model for the projects table.""" | {
"domain": "codereview.stackexchange",
"id": 45270,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, database",
"url": null
} |
python, beginner, database
class Project(SQLModel, table=True):
"""Model for the projects table."""
id: Optional[int] | None = Field(default=None, primary_key=True)
name: str
project_number: str
class DB:
"""Database wrapper specific to the supplied database table.
url: URL of the database file.
table: Model of the table to which the operations should refer.
Must be a Subclass of SQLModel.
"""
def __init__(self, url: str, table: SQLModel, *, echo=False):
self.url = url
self.table = table
self.engine = create_engine(url, echo=echo)
def create_metadata(self):
"""Creates metadata, call only once per database connection."""
SQLModel.metadata.create_all(self.engine)
def read_all(self):
"""Returns all rows of the table."""
with Session(self.engine) as session:
projects = session.exec(select(self.table)).all()
return projects
def read(self, _id):
"""Returns a row of the table."""
with Session(self.engine) as session:
project = session.get(self.table, _id)
return project
def add(self, **fields):
"""Adds a row to the table. Fields must map to the table definition."""
with Session(self.engine) as session:
entry = self.table(**fields)
session.add(entry)
session.commit()
def update(self, _id, **updates):
"""Updates a row of the table. Updates must map to the table definition."""
with Session(self.engine) as session:
entry = self.read(_id)
for key, val in updates.items():
setattr(entry, key, val)
session.add(entry)
session.commit()
def delete(self, _id):
"""Delete a row of the table."""
with Session(self.engine) as session:
entry = self.read(_id)
session.delete(entry)
session.commit()
test_db.py
import sqlite3
import pytest | {
"domain": "codereview.stackexchange",
"id": 45270,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, database",
"url": null
} |
python, beginner, database
test_db.py
import sqlite3
import pytest
from projects.db import DB, Account, Project
@pytest.fixture
def account_db(tmp_path):
db = DB(url=f"sqlite:///{tmp_path}/database_account.db", table=Account, echo=True)
db.create_metadata()
conn = sqlite3.Connection(f"{tmp_path}/database_account.db")
cur = conn.cursor()
cur.execute(
"""
INSERT INTO "project" ("name", "project_number") VALUES
("Project", "00-001"),
("Project2", "01-174"),
("Project3", "20-005")
"""
)
cur.execute(
"""
INSERT INTO "account" ("account_number", "description", "project_id") VALUES
("10-0450-001", "Primary account for this project.", 1),
("10-0450-002", "Account specific for department XY", 1)
"""
)
conn.commit()
return db
@pytest.fixture
def project_db(tmp_path):
db = DB(url=f"sqlite:///{tmp_path}/database_project.db", table=Project, echo=True)
db.create_metadata()
conn = sqlite3.Connection(f"{tmp_path}/database_project.db")
cur = conn.cursor()
cur.execute(
"""
INSERT INTO "project" ("name", "project_number") VALUES
("Project", "00-001"),
("Project2", "01-174"),
("Project3", "20-005")
"""
)
conn.commit()
return db
def test_db_read_all(project_db):
results = project_db.read_all()
assert results == [
{"id": 1, "name": "Project", "project_number": "00-001"},
{"id": 2, "name": "Project2", "project_number": "01-174"},
{"id": 3, "name": "Project3", "project_number": "20-005"},
]
def test_db_read_one(project_db):
result = project_db.read(_id=1)
assert result == {"id": 1, "name": "Project", "project_number": "00-001"} | {
"domain": "codereview.stackexchange",
"id": 45270,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, database",
"url": null
} |
python, beginner, database
def test_db_add(project_db):
project_db.add(name="NewProject", project_number="27-asdf-23487")
entries = project_db.read_all()
assert entries[-1].dict()["name"] == "NewProject"
assert entries[-1].dict()["project_number"] == "27-asdf-23487"
def test_db_update(project_db):
project_db.update(1, name="ModifiedProject")
entry = project_db.read(1)
assert entry == {"id": 1, "name": "ModifiedProject", "project_number": "00-001"}
def test_db_delete(project_db):
project_db.delete(1)
deleted_item = project_db.read(1)
assert deleted_item is None
def test_account_read_all(account_db):
results = account_db.read_all()
assert results == [
{
"id": 1,
"account_number": "10-0450-001",
"description": "Primary account for this project.",
"project_id": 1,
},
{
"id": 2,
"account_number": "10-0450-002",
"description": "Account specific for department XY",
"project_id": 1,
},
]
def test_account_read(account_db):
result = account_db.read(_id=1)
assert result == {
"id": 1,
"account_number": "10-0450-001",
"description": "Primary account for this project.",
"project_id": 1,
}
def test_account_add(account_db):
account_db.add(account_number="20-5000.1-20", project_id=2)
entries = account_db.read_all()
assert entries[-1].dict()["account_number"] == "20-5000.1-20"
assert entries[-1].dict()["project_id"] == 2
def test_account_update(account_db):
account_db.update(1, account_number="20-000", description="")
entry = account_db.read(1)
assert entry == {"id": 1, "account_number": "20-000", "description": "", "project_id": 1}
def test_account_delete(account_db):
account_db.delete(1)
deleted_item = account_db.read(1)
assert deleted_item is None | {
"domain": "codereview.stackexchange",
"id": 45270,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, database",
"url": null
} |
python, beginner, database
def test_read_from_both(account_db, tmp_path):
"""Test if the duplicate engine connecting to the db makes issues."""
project_db = DB(url=f"sqlite:///{tmp_path}/database_account.db", table=Project, echo=True)
project_result = project_db.read(_id=1)
account_result = account_db.read(_id=1)
assert project_result == {"id": 1, "name": "Project", "project_number": "00-001"}
assert account_result == {
"id": 1,
"account_number": "10-0450-001",
"description": "Primary account for this project.",
"project_id": 1,
}
Dependencies are pytest and sqlmodel.
Answer: Optional means None
class Account(SQLModel, table=True):
...
id: Optional[int] | None = ...
Tell us that id is Optional[int] (old way),
or preferably that it is int | None (new way),
but not both.
Also, the notion of a
PK
allowing a NULL value seems pretty weird.
Maybe we can just insist that it is always an int?
Similarly for Project.
class docstring
In DB, move that docstring down so it's describing
the __init__ ctor rather than the whole class.
Feel free to write a new docstring for the class if you like.
I like the "Must be a subclass of SQLModel" advice.
But we're already saying that with the optional type annotation.
Consider decorating the class with
@beartype
for runtime type checking enforcement.
Now you can delete that sentence,
since caller will get a helpful diagnostic message
if he ignores the rules.
... , *, echo=False):
Nice signature, I like it!
Now caller can't offer an ambiguous ... , False),
he is required to describe what it means. | {
"domain": "codereview.stackexchange",
"id": 45270,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, database",
"url": null
} |
python, beginner, database
predictable order
My only caveat about the read_all method is it lacks an explicit ORDER BY.
Unit tests love predictable row order.
Now I guess this is predictable if we require all tables to have a PK.
(I don't let a new table definition sneak past PR code review if it lacks a PK,
but I have seen some codebases that are a bit more lax.)
The natural order might plausibly be in PK order,
though I'm not sure the DB vendor guarantees that behavior across versions.
Consider requiring that the table shall have an ID column,
and then you could explicitly ORDER BY that.
Choosing the identifier projects seems a bit odd,
given that this method works for all tables.
(BTW in {add, update, delete} I like the explicit .commit().)
execute()
In the account_db fixture, I am a little bit sad that DB
doesn't offer an .execute() method for these ad hoc INSERTs.
Or at least a method to get a .cursor().
A hardcoded echo=True in the fixtures seems undesirable,
now that debugging is done.
multiple databases
not sure if the duplicate creation of the engine is an issue.
When I first read your remark, I thought you had asked sqlmodel
twice for engine objects that point at the same underlying database,
perhaps due to some calling detail where existing engine was
not visible to another layer that needed it.
What we see instead is "one table per database", which is worse.
def account_db(tmp_path):
db = DB(url=f"sqlite:///{tmp_path}/database_account.db", table=Account, ...)
...
def project_db(tmp_path):
db = DB(url=f"sqlite:///{tmp_path}/database_project.db", table=Project, ...) | {
"domain": "codereview.stackexchange",
"id": 45270,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, database",
"url": null
} |
python, beginner, database
Sometimes we need to put tables in separate databases on separate servers.
But to the greatest extent possible, strive to keep tables
together within a single RDBMS instance.
Why?
So we can JOIN them.
It's unclear to me how the Account project_id
FK
reference to project.id even works.
Are you maybe using a non-sql92 vendor specific command like
ATTACH?
Your code is built atop some very nice DB layers.
You happen to be using sqlite now, but this code should
work just the same if a connect string is changed
to mention a MariaDB or Postgres database.
And we would want FKs and JOINs to still work across tables,
which won't be feasible if tables are in e.g. a pair
of different postgres databases.
This code substantially achieves its design goals,
and is accompanied by a very nice test suite.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45270,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, database",
"url": null
} |
c++, c++17, networking
Title: Asynchronous OOP-based networking using the Epic EOS SDK
Question: There is also a limitation from the Epic EOS SDK in the absence of thread safety, all "C" calls can only be made from one thread. And from the thread where the SDK was initialized.
Based on the answer @G. Sliepen in my previous deferred-networking-eos.
This is not an answer to its own question, because everything is new: the architecture, the code, and the meaning.
Trivial synchronization used. No catch in main for simplicity. Channel is 0 for simplicity.
The main.cpp code provided simply sends and receives a text strings twice.
Async/Environs.h
#pragma once
namespace Async {
namespace detail_ {
struct Environs {
const EOS_HPlatform m_platformHandle;
EOS_ProductUserId const m_localUserId, m_friendLocalUserId;
};
} // namespace detail_
typedef std::future< Networking::messageData_t > future_t;
} // namespace Async
namespace Async::Transport {
using Environs = detail_::Environs;
} // namespace Async::Transport
Async/Selector/IMultiplex.h
#pragma once
namespace Async::detail_::Selector {
typedef std::function<bool()> task_arg_t;
typedef std::packaged_task< Networking::messageData_t(task_arg_t const&) > task_t;
enum class Direction { Outgoing, Incoming };
struct IMux {
virtual void outgoing(task_t &&) = 0;
virtual void incoming(task_t &&) = 0;
virtual ~IMux() {}
};
typedef std::shared_ptr< IMux > multiplex_t;
struct IDemux {
virtual ~IDemux() {}
virtual bool pop(task_t*, Direction *) = 0;
};
typedef std::shared_ptr< IDemux > demultiplex_t;
} // namespace Async::detail_::Selector
namespace Async::Transport {
using multiplex_t = detail_::Selector::multiplex_t;
using task_t = detail_::Selector::task_t;
using task_arg_t = detail_::Selector::task_arg_t;
} // namespace Async::Transport | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
Async/Selector/Multiplexer.h
#pragma once
namespace Async::detail_::Selector {
class Multiplexer : public IMux, public IDemux {
typedef std::pair< task_t, Direction > queue_elem_t;
std::queue< queue_elem_t > m_fifo;
std::mutex m_mu;
bool pop(task_t *p, Direction *direction) override {
if ( m_fifo.empty( ) )
return false;
queue_elem_t x;
{ std::lock_guard lock( m_mu );
x = std::move( m_fifo.front( ) );
m_fifo.pop( );
}
*p = std::move( x.first );
*direction = x.second;
return true;
}
public:
void outgoing(task_t &&task) override {
std::lock_guard lock( m_mu );
m_fifo.push( { std::move( task ), Direction::Outgoing } );
}
void incoming(task_t &&task) override {
std::lock_guard lock( m_mu );
m_fifo.push( { std::move( task ), Direction::Incoming } );
}
virtual ~Multiplexer() {}
};
} // namespace Async::detail_::Selector | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
Async/GradualExecutor.h
#pragma once
namespace Async::detail_ {
class GradualExecutor {
Selector::demultiplex_t m_demultiplexer;
const EOS_HPlatform m_platformHandle;
static constexpr auto c_commandTO{ std::chrono::seconds{ 20 } };
static constexpr auto now = std::chrono::system_clock::now;
public:
GradualExecutor(Selector::demultiplex_t const& demultiplexer, Environs const& ctx) :
m_demultiplexer( demultiplexer )
, m_platformHandle( ctx.m_platformHandle )
{}
void all() {
using namespace std::literals::chrono_literals;
Selector::task_t task;
Selector::Direction direction;
while ( m_demultiplexer ->pop( &task, &direction ) ) {
if ( Selector::Direction::Outgoing == direction ) {
task( { } );
::EOS_Platform_Tick( m_platformHandle );
}
const auto timeout = now( ) + c_commandTO;
if ( Selector::Direction::Incoming == direction ) {
Selector::task_arg_t function( [this, &timeout] {
::EOS_Platform_Tick( m_platformHandle );
std::this_thread::sleep_for( 300ms );
return ( now( ) < timeout );
} );
task( function );
}
}
}
}; } // namespace Async::detail_
Async/Transport/Send.h
#pragma once
namespace Async::Transport {
class Send {
multiplex_t m_multiplexer; // shared_ptr to avoid dangling
const EOS_HP2P m_p2PHandle;
EOS_P2P_SendPacketOptions m_options{ EOS_P2P_SENDPACKET_API_LATEST };
EOS_P2P_SocketId m_sendSocketId{ EOS_P2P_SOCKETID_API_LATEST };
detail_::Acceptor m_acceptor;
typedef Networking::messageData_t messageData_t; | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
template<typename T>
future_t send_(T const& container) const {
task_t task =
std::packaged_task( [this, container](task_arg_t const&) ->messageData_t
{
const size_t maxDataLengthBytes = Networking::c_MaxDataSizeBytes;
auto it = container.begin( );
while ( it != container.end( ) ) {
const size_t distance = std::distance( it, container.end( ) );
const size_t dataLengthBytes = std::min( maxDataLengthBytes, distance );
EOS_P2P_SendPacketOptions options = m_options;
options.DataLengthBytes = static_cast< uint32_t >( dataLengthBytes );
options.Data = std::addressof( *it );
EOS_EResult result = ::EOS_P2P_SendPacket( m_p2PHandle, &options );
if ( EOS_EResult::EOS_Success != result )
throw std::runtime_error( "error EOS_P2P_SendPacket" );
it += dataLengthBytes;
}
return { };
} );
auto future = task.get_future( );
m_multiplexer ->outgoing( std::move( task ) );
return future;
} | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
public:
Send(Environs const& ctx, std::string const& socketName, multiplex_t const& mux) :
m_multiplexer( mux )
, m_p2PHandle( ::EOS_Platform_GetP2PInterface( ctx.m_platformHandle ) )
, m_acceptor( ctx, socketName )
{
strcpy_s( m_sendSocketId.SocketName , socketName.c_str( ) );
m_options.LocalUserId = ctx.m_localUserId;
m_options.RemoteUserId = ctx.m_friendLocalUserId;
m_options.SocketId = &m_sendSocketId;
m_options.bAllowDelayedDelivery = EOS_TRUE;
m_options.Channel = 0; // zero for simplicity
m_options.Reliability = EOS_EPacketReliability::EOS_PR_ReliableOrdered;
m_options.bDisableAutoAcceptConnection = EOS_FALSE;
}
auto text(std::string const& text) const {
return send_( text );
}
auto vector(messageData_t const& vector) const {
return send_( vector );
}
};
} // namespace Async::Transport
Async/Transport/Recv.h
#pragma once
namespace Async::Transport {
class Recv {
multiplex_t m_multiplexer; // shared_ptr to avoid dangling
const uint8_t m_channel;
const EOS_HP2P m_p2PHandle;
const uint8_t* m_requestedChannel = &m_channel;
EOS_P2P_ReceivePacketOptions m_options{ EOS_P2P_RECEIVEPACKET_API_LATEST };
detail_::Acceptor m_acceptor;
typedef Networking::messageData_t messageData_t; | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
public:
Recv(Environs const& ctx, std::string const& socketName, multiplex_t const& mux) :
m_multiplexer( mux )
, m_channel( 0 ) // zero for simplicity
, m_p2PHandle( ::EOS_Platform_GetP2PInterface( ctx.m_platformHandle ) )
, m_acceptor( ctx, socketName )
{
m_options.LocalUserId = ctx.m_localUserId;
m_options.MaxDataSizeBytes = Networking::c_MaxDataSizeBytes;
m_options.RequestedChannel = m_requestedChannel;
}
[[nodiscard]] auto byLength(size_t len) const {
task_t task =
std::packaged_task( [this, len](task_arg_t const& tick) ->messageData_t
{
EOS_ProductUserId unused_;
EOS_P2P_SocketId socketId;
uint8_t channel = 0;
messageData_t container( len );
uint32_t bytesWritten = 0;
auto it = container.begin( );
while ( it != container.end( ) ) {
EOS_EResult result = ::EOS_P2P_ReceivePacket( m_p2PHandle, &m_options
, &unused_, &socketId, &channel, std::addressof( *it ), &bytesWritten );
if ( EOS_EResult::EOS_Success == result ) {
it += bytesWritten;
continue;
}
if ( EOS_EResult::EOS_NotFound != result )
throw std::runtime_error( "error EOS_P2P_ReceivePacket" );
if ( !tick( ) )
return { };
}
return container;
} );
auto future = task.get_future( );
m_multiplexer ->incoming( std::move( task ) );
return future;
}
};
} // namespace Async::Transport | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
Async/TickerCore.h
#pragma once
namespace Async::detail_ {
struct TickerCore {
std::shared_ptr< Selector::Multiplexer > m_mux;
Selector::multiplex_t m_multiplexer;
Selector::demultiplex_t m_demultiplexer;
Environs m_ctx;
GradualExecutor m_executor;
typedef std::unique_ptr< TickerCore > uptr_t;
TickerCore(PrepareEos::prepared_t const& oes) :
m_mux( std::make_shared< Selector::Multiplexer >( ) )
, m_multiplexer( m_mux )
, m_demultiplexer( m_mux )
, m_ctx{ oes ->m_platformHandle, oes ->m_auth ->getLocalUserId( ), oes ->m_mapping ->getFriendLocalUserId( ) }
, m_executor( m_demultiplexer, m_ctx )
{}
};
} // namespace Async::detail_
Async/Thread/GameThread.h
#pragma once
namespace Async::Thread::detail_ {
class GameThread {
const bool m_isServer;
using TickerCore = Async::detail_::TickerCore;
TickerCore::uptr_t m_core;
protected:
std::atomic_bool m_bPrepared = false, m_bStop = false;
void run_() {
auto oes = Async::detail_::PrepareEos::ordinary( m_isServer );
if ( !oes )
return;
m_core = TickerCore::uptr_t( new TickerCore( oes ) );
// ugly, but need only this thread for init and working
m_bPrepared = true;
while ( !m_bStop ) {
std::this_thread::sleep_for( std::chrono::microseconds{ 300 } );
m_core ->m_executor.all( );
::EOS_Platform_Tick( m_core ->m_ctx.m_platformHandle );
}
}
explicit GameThread(bool isServer) :
m_isServer( isServer )
{}
public:
virtual ~GameThread() {}
Transport::Send createSender(std::string const& m_socketName) const {
return Transport::Send( m_core ->m_ctx, m_socketName, m_core ->m_multiplexer );
}
Transport::Recv createReceiver(std::string const& m_socketName) const {
return Transport::Recv( m_core ->m_ctx, m_socketName, m_core ->m_multiplexer );
}
};
} // namespace Async::Thread::detail_ | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
Async/Thread/JThread.h
#pragma once
namespace Async::Thread { struct FactoryInfiniteWait; } // forward decl
namespace Async::Thread::detail_ {
class JThread final : public GameThread {
std::future<void> m_future;
public:
JThread(bool isServer) :
GameThread( isServer )
{
// convenient, but leakage may occur if the process is quickly exited
m_future = std::async( &JThread::run_, this );
}
~JThread() {
if ( m_future.valid( ) )
GameThread::m_bStop = true, m_future.wait( );
}
bool isValid() const {
return GameThread::m_bPrepared;
}
auto &getFuture() {
return m_future;
}
};
} // namespace Async::Thread::detail_
Async/Thread/Factory.h
#pragma once
namespace Async::Thread {
struct FactoryInfiniteWait {
typedef std::unique_ptr< detail_::GameThread > gameThread_t;
static gameThread_t gameThread(bool isServer) {
using namespace std::literals::chrono_literals;
const auto timeout = std::future_status::timeout;
// hide JThread from user
auto *p = new detail_::JThread( isServer );
auto &future = p ->getFuture( );
auto gameThread = gameThread_t( p );
std::future_status stat = std::future_status::ready;
while ( true
&& !p ->isValid( )
&& ( timeout == ( stat = future.wait_for( 300ms ) ) )
) (void)0;
if ( timeout == stat )
return gameThread;
// void or rethrow exception
future.get( );
return { };
}
};
} // namespace Async::Thread | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
demo main.cpp
#include "pch.h"
#include "Async/Environs.h"
#include "Async/Selector/IMultiplex.h"
#include "Async/Selector/Multiplexer.h"
#include "Async/GradualExecutor.h"
#include "Async/Transport/Send.h"
#include "Async/Transport/Recv.h"
#include "Async/TickerCore.h"
#include "Async/Thread/GameThread.h"
#include "Async/Thread/JThread.h"
#include "Async/Thread/Factory.h"
int main(int argc, char *argv[]) {
bool isServer = ( argc > 1 );
auto oes = Async::Thread::FactoryInfiniteWait::gameThread( isServer );
if ( !oes )
return ECONNRESET;
auto socketNameChat = "CHAT";
std::string text0 = "Hello Asy", text1 = "nc World!";
if ( isServer ) {
Async::Transport::Recv recvChat = oes ->createReceiver( socketNameChat );
Async::future_t command0 = recvChat.byLength( text0.length( ) );
Async::future_t command1 = recvChat.byLength( text1.length( ) );
Networking::messageData_t incoming0 = command0.get( );
Networking::messageData_t incoming1 = command1.get( );
assert( text0 == std::string( incoming0.begin( ), incoming0.end( ) ) );
assert( text1 == std::string( incoming1.begin( ), incoming1.end( ) ) );
} else {
Async::Transport::Send sendChat = oes ->createSender( socketNameChat );
sendChat.text( text0 ).wait( );
sendChat.text( text1 ).wait( );
}
return printf( "press [Enter] to exit\n" ), getchar( ), 0;
}
Omitted detail_::Acceptor because it is not significantly involved in the work.
Async::detail_::PrepareEos is skipped because there is a lot of monotonous and flat code.
Full code on GitHub repo | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
Answer: Naming things
There are several things that are named confusingly. Names should be precise and concise; they should convey quite clearly what they stand for in one or a few words. Prefer to use commonly used words. Also be consistent in how you name things. Don't abbreviate unnecessarily though. Prefer to use nouns for variables and types, and verbs for functions. Use the plural for containers that potentially hold multiple values.
Here is a list of things I think can be improved: | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
Environs: this is an uncommon synonym of environment. It is usually used to describe the set of environment variables passed to programs. Here it used rather as a context, which is made clear by the variable m_ctx. Also, it is specifically holding the context used by the EOS SDK, so I would call this EOS_Context.
future_t: this is specifically a future holding Networking::messageData_t. Maybe rename it to messageData_future_t. Consider that you might add other things besides network functionality to namespace Async. What if you need futures holding other data types? This also brings me to:
Avoid using the _t suffix for type aliases. Just use the same naming scheme you use for other types: start with a capital. Consider that at some point you might change a type alias to become its own class. Would you want to rename it everywhere then?
Consider not creating a type alias for everything. Sure, it might save some typing in some places, but it avoids hiding information about the type.
task_arg_t: yes, it's used as the argument for the constructor of task_t, but on its own it is just the function you want the task to execute. So perhaps task_function_t?
multiplex_t: prefer nouns for types, so multiplexer_t. Also, it again hides that this is a shared pointer.
queue_elem_t: avoid abbreviations. I suggest using queue_element_t or queue_item_t instead.
m_fifo: that describes what kind of container it is, but I think it's more important to know what it holds. I would use m_tasks here (more about that later).
m_mu: don't abbreviate, write m_mutex.
x: one-letter variables are sometimes OK to use, but only if their name and meaning match how they are commonly used, like i for a loop index, or x if it is an x-coordinate. Here it represents a single task from the queue, so task?
p: similar, but more about that later.
Send: use nouns for types: Sender is much better. However, given that it wraps an EOS channel, I would name it TransmitChannel or TxChannel. | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
text(): use verbs for functions: send_text(). The same goes for vector(). Note that you can also just create two member functions named send() with different argument types.
outgoing(), incoming(): again, make them verbs: push_outgoing(), push_incoming().
GameThread: despite its name, it doesn't do anything with threads. Sure, someone might call run_() inside a thread, but they don't have to. It's misnamed for sure, but that's not the only problem of this class, so I'll discuss this more below.
JThread: sounds like std::jthread, does something similar, but is also quite different. This is actually running run_() in a thread, so maybe this should be called GameThread?
FactoryInfiniteWait: a factory that waits forever? What does it create and what does it wait for? It only contains a static member function, so this should not be a struct at all. Rather, its constructor should be a free function named createGameThread or something similar. | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
Make the task type hold the direction
You made things more complicated than necessary by making task_t only hold the packaged task, and let the direction be stored in queue_elem_t. I think it would be much better to store the direction inside a class representing tasks:
struct Task {
std::packaged_task<Networking::messageData_t(task_arg_t const&)> task;
Direction direction;
};
This will simplify Multiplexer a lot, especially if you also:
Use std::optional
Use std::optional to return optional values. Consider this:
class Multiplexer: β¦ {
std::queue<Task> m_tasks;
std::mutex m_mutex;
std::optional<Task> pop() override {
if (m_fifo.empty())
return std::nullopt;
Task task;
{
std::lock_guard lock(m_mutex);
task = std::move(m_tasks.front());
m_tasks.pop();
}
return task;
}
void push(Task task) override {
std::lock_guard lock(m_mutex);
m_fifo.push(std::move(task));
}
};
The code using this can then pop like so:
while (auto task = m_demultiplexer->pop()) {
if (Selector::Direction::Outgoing == task.direction) {
task.task({});
β¦
And push like so:
auto task = [](task_arg_t const&)->mesageData_t{β¦};
β¦
m_multiplexer->push({task, Selector::Direction::Outgoing});
Don't overcomplicate things
FactoryInfiniteWait is a terribly overcomplicated way to start a thread. I would get rid of it entirely, and then merge JThread into GameThread, so you have once object that when created runs a thread that handles game ticks, and when destructed stops that thread. Instead of having the thread create a TickerCore object, let the caller do that, and then pass a reference to it to the constructor.
class GameThread {
std::atomic_bool m_stop = false; | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
c++, c++17, networking
void run_(TickerCore& core) {
while (!m_stop) {
std::this_thread::sleep_for(std::chrono::microseconds{300});
m_core->m_executor.all( );
::EOS_Platform_Tick(m_core->m_ctx.m_platformHandle);
}
};
std::thread m_thread;
public:
GameThread(TickerCore& core):
m_thread(&GameThread::run_, this, core) {}
~GameThread() {
m_stop = true;
m_thread.join();
}
}
Since C++20 you can use std::jthread instead, so you just need a free run_() function that takes a stop object as a parameter.
Then in main() you write something like:
int main(int argc, char *argv[]) {
β¦
auto oes = Async::detail_::PrepareEos::ordinary(isServer);
auto tickerCore = TickerCore(oes);
auto gameThread = GameThread(tickerCore);
β¦
} | {
"domain": "codereview.stackexchange",
"id": 45271,
"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, networking",
"url": null
} |
python
Title: Advent of Code Day 2 in Python
Question: problem for day 2
Part 1
You're launched high into the atmosphere! The apex of your trajectory just barely reaches the surface of a large island floating in the sky. You gently land in a fluffy pile of leaves. It's quite cold, but you don't see much snow. An Elf runs over to greet you.
The Elf explains that you've arrived at Snow Island and apologizes for the lack of snow. He'll be happy to explain the situation, but it's a bit of a walk, so you have some time. They don't get many visitors up here; would you like to play a game in the meantime?
As you walk, the Elf shows you a small bag and some cubes which are either red, green, or blue. Each time you play this game, he will hide a secret number of cubes of each color in the bag, and your goal is to figure out information about the number of cubes.
To get information, once a bag has been loaded with cubes, the Elf will reach into the bag, grab a handful of random cubes, show them to you, and then put them back in the bag. He'll do this a few times per game.
You play several games and record the information from each game (your puzzle input). Each game is listed with its ID number (like the 11 in Game 11: ...) followed by a semicolon-separated list of subsets of cubes that were revealed from the bag (like 3 red, 5 green, 4 blue).
For example, the record of a few games might look like this:
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green | {
"domain": "codereview.stackexchange",
"id": 45272,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
In game 1, three sets of cubes are revealed from the bag (and then put back again). The first set is 3 blue cubes and 4 red cubes; the second set is 1 red cube, 2 green cubes, and 6 blue cubes; the third set is only 2 green cubes.
The Elf would first like to know which games would have been possible if the bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes?
In the example above, games 1, 2, and 5 would have been possible if the bag had been loaded with that configuration. However, game 3 would have been impossible because at one point the Elf showed you 20 red cubes at once; similarly, game 4 would also have been impossible because the Elf showed you 15 blue cubes at once. If you add up the IDs of the games that would have been possible, you get 8.
Determine which games would have been possible if the bag had been loaded with only 12 red cubes, 13 green cubes, and 14 blue cubes. What is the sum of the IDs of those games?
Part 2
The Elf says they've stopped producing snow because they aren't getting any water! He isn't sure why the water stopped; however, he can show you how to get to the water source to check it out for yourself. It's just up ahead!
As you continue your walk, the Elf poses a second question: in each game you played, what is the fewest number of cubes of each color that could have been in the bag to make the game possible?
Again consider the example games from earlier:
Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green
Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue
Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red
Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red
Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green | {
"domain": "codereview.stackexchange",
"id": 45272,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
In game 1, the game could have been played with as few as 4 red, 2 green, and 6 blue cubes. If any color had even one fewer cube, the game would have been impossible.
Game 2 could have been played with a minimum of 1 red, 3 green, and 4 blue cubes.
Game 3 must have been played with at least 20 red, 13 green, and 6 blue cubes.
Game 4 required at least 14 red, 3 green, and 15 blue cubes.
Game 5 needed no fewer than 6 red, 3 green, and 2 blue cubes in the bag.
The power of a set of cubes is equal to the numbers of red, green, and blue cubes multiplied together. The power of the minimum set of cubes in game 1 is 48. In games 2-5 it was 12, 1560, 630, and 36, respectively. Adding up these five powers produces the sum 2286.
For each game, find the minimum set of cubes that must have been present. What is the sum of the power of these sets?
import re
def part_1():
max_red = 12
max_green = 13
max_blue = 14
passed_game_sum = 0
def process_game(rs):
for r in rs:
for c in r.strip().split(','):
pick = re.findall(r'^([0-9]+) ([a-z]+)', c.strip())
if pick[0][1] == 'red' and int(pick[0][0]) > max_red:
return 'failed', parsed_line[0][0]
elif pick[0][1] == 'green' and int(pick[0][0]) > max_green:
return 'failed', parsed_line[0][0]
elif pick[0][1] == 'blue' and int(pick[0][0]) > max_blue:
return 'failed', parsed_line[0][0]
return 'passed', parsed_line[0][0]
with open('input.txt', 'r') as file:
for line in file.read().splitlines():
parsed_line = re.findall(r'^Game ([0-9]+): (.+)$', line)
rounds = parsed_line[0][1].split(';')
if (game := process_game(rounds))[0] == 'passed':
passed_game_sum += int(game[1])
print(passed_game_sum)
def part_2():
set_power = 0 | {
"domain": "codereview.stackexchange",
"id": 45272,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
print(passed_game_sum)
def part_2():
set_power = 0
def process_game(rs):
fewest_red = 0
fewest_green = 0
fewest_blue = 0
for r in rs:
for c in r.strip().split(','):
pick = re.findall(r'^([0-9]+) ([a-z]+)', c.strip())[0]
quantity = int(pick[0])
color = pick[1]
if color == 'red' and quantity > fewest_red:
fewest_red = quantity
elif color == 'green' and quantity > fewest_green:
fewest_green = quantity
elif color == 'blue' and quantity > fewest_blue:
fewest_blue = quantity
return fewest_red * fewest_green * fewest_blue
with open('input.txt', 'r') as file:
for line in file.read().splitlines():
parsed_line = re.findall(r'^Game ([0-9]+): (.+)$', line)
rounds = parsed_line[0][1].split(';')
set_power += process_game(rounds)
print(set_power)
if __name__ == '__main__':
part_1()
part_2()
```
Answer: Use functions instead of repeating yourself. The solutions for part 1 and
part 2 contain similar code for file reading, text parsing, and so forth.
Repeated code can become a real hassle: every bug fix or improvement requires
editing in multiple sites.
A function to read input. This is perhaps the simplest and most obvious
place to start. If you do continue with AoC, you might find yourself enhancing
a function like this to be able to read from a file, STDIN, or even the
clipboard.
def read_input(path):
with open(path) as fh:
return [line.strip() for line in fh] | {
"domain": "codereview.stackexchange",
"id": 45272,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Don't use findall() if you know the regex will return only one thing.
All of your regexes will only return one match. Using re.findall() in
a situation like that mis-communicates the intent of your code.
Some parsing advice. Give meaningful names to constants like separators,
markers, etc. And when feasible, prefer basic techniques like strip and split
over regex.
GID_SEP = ': '
DRAW_SEP = '; '
PICK_SEP = ', '
Keep separate tasks separate. Your current solutions have two levels of
operation: (1) line processing, where you do some parsing and some top-level
calculations; and (2) game processing, where you again combine parsing with
calculation. It usually results in more flexible, maintainable, and readable
code to separate the tasks in a sharper way. For example: read input; parse input into meaningful data; make calculations; communicate results.
When feasible, make data declarative rather than cryptic. For example, you
parse each pick into a two-element tuple and your code has to make repeated use
of things like pick[0][1]. That demands a lot of mental overload for a reader
of your code (meaning yourself). Much better is to unpack that data into more
readable parts, which can be done with something as simple as n, color = pick.
Modeling the data. This problem seems well suited to a couple of
dataclasses: one to represent a game, and one to represent a draw of cubes.
Simple dataclasses like these not only push your code in the direction of
meaningful, declarative data; they also create natural homes for related tasks,
such as the following: the ability to create a Game instance from an input
line of text; the ability to create a Draw instance from some text; and the ability to compare Draw instances to see
whether one is less than another, which is the
essence of part 1, and a behavior we get for free from dataclass(order = True).
from dataclasses import dataclass
@dataclass(order = True)
class Draw:
red: int = 0
green: int = 0
blue: int = 0 | {
"domain": "codereview.stackexchange",
"id": 45272,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
@dataclass(order = True)
class Draw:
red: int = 0
green: int = 0
blue: int = 0
@classmethod
def from_text(cls, text):
# Example: "3 green, 4 blue, 1 red".
draw = cls()
for pick in text.split(PICK_SEP):
n, col = pick.split()
setattr(draw, col, int(n))
return draw
@dataclass
class Game:
gid: int
draws: list[Draw]
@classmethod
def from_text(cls, text):
# Example: "Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red".
gid_text, draws_text = text.split(GID_SEP)
return cls(
gid = int(gid_text.split()[1]),
draws = [
Draw.from_text(dt)
for dt in draws_text.split(DRAW_SEP)
],
)
When feasible, don't hardcode file paths. When working on a program, it's
often helpful to experiment with different inputs. If you hardcode input file
paths, experimentation becomes a bit of a hassle. Much better to parameterize
the file path so you can pass it as a command-line argument. Here's one way to
write the orchestration code.
import sys
def main(args):
path = args[0]
games = [
Game.from_text(line)
for line in read_input(path)
]
print(part_1(games))
if __name__ == '__main__':
main(sys.argv[1:])
With effective data and clear separation of tasks, the solution code often
becomes simple. For part 1, we take some Game instances and return the sum
of the game IDs that have all draws less than or equal to the cube inventory
(which we can also represent as a "draw").
def part_1(games):
inventory = Draw(red = 12, green = 13, blue = 14)
return sum(
g.gid
for g in games
if all(d <= inventory for d in g.draws)
)
Part 2: a few ideas to consider. Here's a sketch of how I might
solve this part. Good luck!
class Draw:
...
@property
def power(self):
return self.red * self.green * self.blue | {
"domain": "codereview.stackexchange",
"id": 45272,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
@property
def power(self):
return self.red * self.green * self.blue
def satisfy(self, other):
# Take another Draw.
# Increase self to satisfy needs of other.
...
@dataclass
class Game:
...
@property
def minimum_draw(self):
# Return the minimum Draw to satisfy the game's draws.
inventory = Draw()
...
def part_2(games):
return sum(
g.minimum_draw.power
for g in games
) | {
"domain": "codereview.stackexchange",
"id": 45272,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
c++, file-system
Title: Binary file reader and writer
Question: I want to write a simple binary file reader and writer class. The class below can read or write file. main.cpp read 500 bytes from tmp.bin and copy at the end of the tmp_copy.bin file. How can I improve my code?
binaryfile.h
#ifndef BINARYFILE_H
#define BINARYFILE_H
#include <fstream>
#include <string>
using uchar = unsigned char;
enum FILE_TYPE {READ, WRITE, NONE};
class BinaryFile
{
public:
BinaryFile();
bool open(const std::string& file_path, FILE_TYPE file_type);
bool read(uchar* buffer, size_t num_of_bytes);
bool write(uchar* buffer, size_t num_of_bytes);
size_t get_file_size() const;
bool close();
private:
std::fstream _fstream;
std::string _file_path;
FILE_TYPE _file_type;
size_t _file_size;
size_t _file_read_pos;
};
#endif // BINARYFILE_H
binaryfile.cpp
#include "binaryfile.h"
#include <filesystem>
#include <iostream>
BinaryFile::BinaryFile() :
_file_type{NONE},
_file_size{0},
_file_read_pos{0}
{
}
bool BinaryFile::open(const std::string& file_path, FILE_TYPE file_type)
{
if(_fstream.is_open())
{
std::cout << "You have to close the opened file\n";
return false;
}
if(file_type == READ)
{
_file_type = READ;
_fstream.open(file_path, std::ios::binary | std::ios::in);
}
else if(file_type == WRITE)
{
_file_type = WRITE;
_fstream.open(file_path, std::ios::binary | std::ios::out | std::ios::app);
}
if(!_fstream)
{
std::cout << "Error in file open\n";
_file_type = NONE;
return false;
}
if(file_type == READ)
{
const std::filesystem::path path(file_path);
_file_size = std::filesystem::file_size(path);
}
_file_path = file_path;
return true;
} | {
"domain": "codereview.stackexchange",
"id": 45273,
"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++, file-system",
"url": null
} |
c++, file-system
_file_path = file_path;
return true;
}
bool BinaryFile::read(uchar *buffer, size_t num_of_bytes)
{
if(_file_read_pos + num_of_bytes > _file_size)
{
std::cout << "You are trying to read more byte than file has\n";
return false;
}
if(_fstream.is_open() && _file_type == READ)
{
_fstream.read((char*)buffer, num_of_bytes);
_file_read_pos += num_of_bytes;
return true;
}
return false;
}
bool BinaryFile::write(uchar *buffer, size_t num_of_bytes)
{
if(_fstream.is_open() && _file_type == WRITE)
{
_fstream.write((char*)buffer, num_of_bytes);
return true;
}
return false;
}
size_t BinaryFile::get_file_size() const
{
return _file_size;
}
bool BinaryFile::close()
{
if(!_fstream.is_open())
{
std::cout << "File is not opened\n";
return false;
}
_fstream.close();
_fstream.clear();
_file_path.clear();
_file_read_pos = 0;
_file_size = 0;
_file_type = NONE;
return true;
}
main.cpp
#include <memory>
#include "binaryfile.h"
constexpr size_t BUFFER_SIZE{1000};
int main()
{
BinaryFile tmp_file;
const std::unique_ptr<uchar[]> buffer(new uchar[BUFFER_SIZE]);
if(tmp_file.open("tmp.bin", FILE_TYPE::READ))
{
tmp_file.read(buffer.get(), 500);
tmp_file.close();
}
if(tmp_file.open("tmp_copy.bin", FILE_TYPE::WRITE))
{
tmp_file.write(buffer.get(), 500);
tmp_file.close();
}
return 0;
}
Answer: Here are some things that may help you improve your code.
Avoid redundant code
The BinaryFile class adds very little other than some error messages. I'd suggest instead that the code is much shorter and simpler without it:
#include <fstream> | {
"domain": "codereview.stackexchange",
"id": 45273,
"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++, file-system",
"url": null
} |
c++, file-system
int main()
{
constexpr std::size_t buffsize{500};
char buffer[buffsize];
std::ifstream in{"tmp.bin", std::ios::binary};
in.read(buffer, buffsize);
if (in) {
std::ofstream out{"alt.bin", std::ios::app};
out.write(buffer, buffsize);
}
}
Code you don't write, you don't need to debug or maintain. This kind of simplification is very useful in practice. See also ES.3 for details.
Don't use ALL_CAPS names
Your FILE_TYPE enum and the BUFFER_SIZE variable are not macros and shouldn't be macros. Don't use such names in C++. See ES.9 for more info.
Don't define variables with a leading underscore
In the global namespace, identifiers with a leading underscore are reserved names. Your class variables are not in the global namespace, but why confuse your reader? A common idiom is to use a trailing underscore, which has no such potential conflict, or to simply name things rationally without underscores -- this is the approach I take for my own code. It tends to make this easier to read in my view.
Prefer in-class initializers to constructor
There's no need to define the current default constructor for BinaryFile. There are two issues. First, once a BinaryFile is constructed this way, the only rational thing one can do with it is to call open. I'd suggest instead, that a better approach would be to define a constructor that takes a file name and mode so things can be done in a single step. Second, the constructor can be omitted entirely in favor of default data member initializers. See C.45
Fix the bug
The BinaryFile::read() function contains an error. If the enclosed std::fstream.read() function encounters eof or some other error, setting _file_read_pos += num_of_bytes is simply incorrect. Your code should check the state of the stream after the attempted read and increment by gcount() instead. Similarly, the BinaryFile::write() function fails to check the actual status of the stream after the attempted write. | {
"domain": "codereview.stackexchange",
"id": 45273,
"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++, file-system",
"url": null
} |
performance, sql, postgresql
Title: Find and conditionally sort all venues matching a filter provided by an API client in PostgreSQL
Question: I have an API where users can retrieve a list of "venues".
Every venue is a profile, but not every profile is a venue
Venues can be "parents" of other venues (think hotel - floor - room)
When a latitude and longitude is given, the list should be sorted by distance
When a latitude and longitude is not given, the list should be sorted alphabetically, by venue name (located in the profiles.profiles table)
Clients use key-based pagination (i.e. a fixed number of results is returned per page. to get the next page, the client should include the first id of the next page - hence LIMIT env.RESULT_PAGE_SIZE + 1). | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
I have constructed a query, utilizing multiple CTEs and "short circuits" (false AND condition). However, I'm still quite new to CTEs and would appreciate some feedback on the performance of my query. I have also attached the query plan and would appreciate a step-by-step explanation of how to read it and what conclusions to draw.
Context
dansdata=# \d profiles.profiles
Table "profiles.profiles"
Column | Type | Collation | Nullable | Default
-----------------+--------------------------+-----------+----------+---------
id | text | | not null |
type | profiles.profile_type | | not null |
name | text | | not null |
description | text | | not null |
created_at | timestamp with time zone | | not null | now()
cover_image_id | text | | |
poster_image_id | text | | |
square_image_id | text | | |
Indexes:
"profiles_pkey" PRIMARY KEY, btree (id)
"profiles_cover_image_id_idx" btree (cover_image_id)
"profiles_name_idx" gin (name gin_trgm_ops)
"profiles_poster_image_id_idx" btree (poster_image_id)
"profiles_square_image_id_idx" btree (square_image_id)
Foreign-key constraints:
"profiles_cover_image_id_fkey" FOREIGN KEY (cover_image_id) REFERENCES storage.images(id) ON UPDATE CASCADE ON DELETE SET NULL
"profiles_poster_image_id_fkey" FOREIGN KEY (poster_image_id) REFERENCES storage.images(id) ON UPDATE CASCADE ON DELETE SET NULL
"profiles_square_image_id_fkey" FOREIGN KEY (square_image_id) REFERENCES storage.images(id) ON UPDATE CASCADE ON DELETE SET NULL
Referenced by: | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
Referenced by:
TABLE "events.event_slot_participants" CONSTRAINT "event_slot_participants_profile_id_fkey" FOREIGN KEY (profile_id) REFERENCES profiles.profiles(id) ON UPDATE CASCADE ON DELETE RESTRICT
TABLE "profiles.individuals" CONSTRAINT "individuals_profile_id_fkey" FOREIGN KEY (profile_id) REFERENCES profiles.profiles(id) ON UPDATE CASCADE ON DELETE CASCADE
TABLE "profiles.organizations" CONSTRAINT "organizations_profile_id_fkey" FOREIGN KEY (profile_id) REFERENCES profiles.profiles(id) ON UPDATE CASCADE ON DELETE CASCADE
TABLE "profiles.profile_links" CONSTRAINT "profile_links_profile_id_fkey" FOREIGN KEY (profile_id) REFERENCES profiles.profiles(id) ON UPDATE CASCADE ON DELETE CASCADE
TABLE "profiles.venues" CONSTRAINT "venues_profile_id_fkey" FOREIGN KEY (profile_id) REFERENCES profiles.profiles(id) ON UPDATE CASCADE ON DELETE CASCADE | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
dansdata=# \d profiles.venues
Table "profiles.venues"
Column | Type | Collation | Nullable | Default
--------------------+-----------------------+-----------+----------+---------
profile_id | text | | not null |
parent_id | text | | |
coords | geography(Point,4326) | | not null |
permanently_closed | boolean | | not null | false
Indexes:
"venues_pkey" PRIMARY KEY, btree (profile_id)
"venues_coords_idx" gist (coords)
Foreign-key constraints:
"venues_parent_id_fkey" FOREIGN KEY (parent_id) REFERENCES profiles.venues(profile_id) ON UPDATE CASCADE ON DELETE SET NULL
"venues_profile_id_fkey" FOREIGN KEY (profile_id) REFERENCES profiles.profiles(id) ON UPDATE CASCADE ON DELETE CASCADE
Referenced by:
TABLE "events.event_slots" CONSTRAINT "event_slots_venue_id_fkey" FOREIGN KEY (venue_id) REFERENCES profiles.venues(profile_id) ON UPDATE CASCADE ON DELETE RESTRICT
TABLE "profiles.venues" CONSTRAINT "venues_parent_id_fkey" FOREIGN KEY (parent_id) REFERENCES profiles.venues(profile_id) ON UPDATE CASCADE ON DELETE SET NULL
Triggers:
enforce_non_circular_hierarchy_insert BEFORE INSERT ON profiles.venues FOR EACH ROW WHEN (new.parent_id IS NOT NULL) EXECUTE FUNCTION profiles.trigger_func_venue_enforce_non_circular_hierarchy()
enforce_non_circular_hierarchy_update BEFORE UPDATE ON profiles.venues FOR EACH ROW WHEN (new.parent_id IS NOT NULL AND (old.parent_id IS DISTINCT FROM new.parent_id OR new.profile_id IS DISTINCT FROM old.profile_id)) EXECUTE FUNCTION profiles.trigger_func_venue_enforce_non_circular_hierarchy()
refresh_venue_parents AFTER INSERT OR DELETE OR UPDATE OF parent_id OR TRUNCATE ON profiles.venues FOR EACH STATEMENT EXECUTE FUNCTION profiles.trigger_func_refresh_venue_parents() | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
dansdata=# \d profiles.venue_parents
Materialized view "profiles.venue_parents"
Column | Type | Collation | Nullable | Default
-----------+---------+-----------+----------+---------
child_id | text | | |
parent_id | text | | |
distance | integer | | |
Indexes:
"venue_distance_idx" btree (distance)
"venue_parents_child_idx" btree (child_id)
"venue_parents_child_parent_idx" UNIQUE, btree (child_id, parent_id)
"venue_parents_parent_idx" btree (parent_id)
CREATE MATERIALIZED VIEW "profiles"."venue_parents"(child_id, parent_id, distance) AS (
WITH RECURSIVE parent_query AS (
SELECT
profile_id AS child_id,
parent_id,
1 AS distance
FROM profiles.venues
WHERE parent_id IS NOT NULL
UNION ALL
SELECT
parent_query.child_id AS child_id,
profiles.venues.parent_id AS parent_id,
parent_query.distance + 1 AS distance
FROM parent_query, profiles.venues
WHERE profiles.venues.parent_id IS NOT NULL
AND profiles.venues.profile_id = parent_query.parent_id
)
SELECT child_id, parent_id, distance
FROM parent_query
);
CREATE UNIQUE INDEX "venue_parents_child_parent_idx" ON "profiles"."venue_parents"(child_id, parent_id);
CREATE INDEX "venue_parents_child_idx" ON "profiles"."venue_parents"(child_id);
CREATE INDEX "venue_parents_parent_idx" ON "profiles"."venue_parents"(parent_id);
CREATE INDEX "venue_distance_idx" ON "profiles"."venue_parents"(distance); | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
Query Under Review
WITH
root_nodes(profile_id) AS (
SELECT profile_id
FROM profiles.venues
WHERE profile_id NOT IN (
SELECT child_id
FROM profiles.venue_parents
)
),
leaf_nodes(profile_id) AS (
SELECT profile_id
FROM profiles.venues
WHERE profile_id NOT IN (
SELECT parent_id
FROM profiles.venue_parents
)
),
joined AS (
SELECT
p.*,
t.*
FROM (
(
SELECT
*,
-1 AS distance
FROM profiles.venues
WHERE ${filterModel.near && 1}::int IS NULL
)
UNION ALL
(
SELECT
*,
ST_DistanceSphere(
coords::geometry,
ST_MakePoint(${filterModel.near?.lng ?? 0}, ${filterModel.near?.lat ?? 0})
) AS distance
FROM profiles.venues
WHERE ${filterModel.near && 1}::int IS NOT NULL
)
) AS t
INNER JOIN profiles.profiles p
ON p.id = t.profile_id
),
sorted AS (
SELECT
*
FROM joined
ORDER BY
distance ASC,
name ASC,
id ASC
),
enumerated AS (
SELECT
*,
ROW_NUMBER() OVER () AS index
FROM sorted
)
SELECT id AS "profileId"
FROM enumerated
WHERE (
${filterModel.includePermanentlyClosed}
OR permanently_closed = FALSE
) AND (
${filterModel.level === "any"}
OR (
${filterModel.level === "root"}
AND profile_id IN (SELECT * FROM root_nodes)
)
OR (
${filterModel.level === "leaf"}
AND profile_id IN (SELECT * FROM leaf_nodes)
)
) AND (
index >= COALESCE(
(
SELECT index
FROM enumerated
WHERE id = ${filterModel.pageKey}
),
0
)
)
ORDER BY index
LIMIT ${env.RESULT_PAGE_SIZE + 1} | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
Example with actual values
ββββββββββββββββββββββββββββ¬ββββββββββββββββββββ¬βββββββββββββββββββββ¬βββββββββ
β (index) β lat β lng β Values β
ββββββββββββββββββββββββββββΌββββββββββββββββββββΌβββββββββββββββββββββΌβββββββββ€
β env.RESULT_PAGE_SIZE. β β β 30 β
β level β β β 'any' β
β includePermanentlyClosed β β β true β
β near β 58.41616195587502 β 15.625933242341707 β β
ββββββββββββββββββββββββββββ΄ββββββββββββββββββββ΄βββββββββββββββββββββ΄βββββββββ | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
performance, sql, postgresql
WITH
root_nodes(profile_id) AS (
SELECT profile_id
FROM profiles.venues
WHERE profile_id NOT IN (
SELECT child_id
FROM profiles.venue_parents
)
),
leaf_nodes(profile_id) AS (
SELECT profile_id
FROM profiles.venues
WHERE profile_id NOT IN (
SELECT parent_id
FROM profiles.venue_parents
)
),
joined AS (
SELECT
p.*,
t.*
FROM (
(
SELECT
*,
-1 AS distance
FROM profiles.venues
WHERE 1::int IS NULL
)
UNION ALL
(
SELECT
*,
ST_DistanceSphere(
coords::geometry,
ST_MakePoint(15.625933242341707, 58.41616195587502)
) AS distance
FROM profiles.venues
WHERE 1::int IS NOT NULL
)
) AS t
INNER JOIN profiles.profiles p
ON p.id = t.profile_id
),
sorted AS (
SELECT
*
FROM joined
ORDER BY
distance ASC,
name ASC,
id ASC
),
enumerated AS (
SELECT
*,
ROW_NUMBER() OVER () AS index
FROM sorted
)
SELECT id AS "profileId"
FROM enumerated
WHERE (
true
OR permanently_closed = FALSE
) AND (
true
OR (
false
AND profile_id IN (SELECT * FROM root_nodes)
)
OR (
false
AND profile_id IN (SELECT * FROM leaf_nodes)
)
) AND (
index >= COALESCE(
(
SELECT index
FROM enumerated
WHERE id = null
),
0
)
)
ORDER BY index
LIMIT 31 | {
"domain": "codereview.stackexchange",
"id": 45274,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, sql, postgresql",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.