text stringlengths 1 2.12k | source dict |
|---|---|
python, python-3.x
Title: Middle-outwards alternating iterator
Question: I have a use-case where I want to iterate from the middle of an array outwards, so I generate a list of indices as follows:
import itertools
def array_indices_from_middle(array_len: int, num_indices: int = 16) -> list[int]:
"""
Create indices for an array starting from the middle and then appending indices alternating the left and right.
If more indices are needed than the array length, start again from the middle.
"""
midpoint = (array_len - 1) // 2
sel_inds = []
left = range(midpoint - 1, -1, -1)
right = range(midpoint + 1, array_len, 1)
# right before left, because of how mid is chosen for even array lengths
alt = [i for i in itertools.chain.from_iterable(itertools.zip_longest(right, left)) if i is not None]
i = 0
while len(sel_inds) < num_indices:
if len(sel_inds) % array_len == 0:
sel_inds.append(midpoint)
else:
sel_inds.append(alt[i % len(alt)])
i += 1
return sel_inds
It passes the following unit tests:
assert array_indices_from_middle(array_len=5, num_indices=5) == [2, 3, 1, 4, 0]
assert array_indices_from_middle(array_len=5, num_indices=4) == [2, 3, 1, 4]
assert array_indices_from_middle(array_len=5, num_indices=8) == [2, 3, 1, 4, 0, 2, 3, 1]
assert array_indices_from_middle(array_len=6, num_indices=6) == [2, 3, 1, 4, 0, 5]
assert array_indices_from_middle(array_len=6, num_indices=5) == [2, 3, 1, 4, 0]
assert array_indices_from_middle(array_len=6, num_indices=9) == [2, 3, 1, 4, 0, 5, 2, 3, 1]
My combination of iterators feels a bit hacky. Is there a simpler way of approaching this problem? I'm not worried about corner cases. | {
"domain": "codereview.stackexchange",
"id": 44971,
"lm_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",
"url": null
} |
python, python-3.x
Answer: Your code is way too complicated, and not very efficient.
We can use an infinite iterator to repeatedly yield numbers back and forth.
We supply the infinite iterator with n, we yield n before the loop. We can then use an infinite loop, and yield n - 1 and n + 1 in the first iteration. We then yield n - 2 and n + 2 in the second iteration. In general, in ith iteration we yield n - i and n + i (one-based indexing).
This will eventually yield all integers in both directions.
We can then just use itertools.islice to ask for the first length elements, length is the number of elements of the array. We can just create the iterator with length // 2 as its argument. length // 2 is the index of the middle element.
So your code becomes:
from itertools import count, islice
from typing import Generator, Iterable
def alternate(n: int = 0) -> Generator[int, None, None]:
yield n
for i in count(1):
yield n - i
yield n + i
def zigzag(arr: Iterable) -> list:
l = len(arr)
return [arr[i] for i in islice(alternate(l // 2), l)]
Here is another version, it is a bit more complicated, and therefore somewhat slower, but it doesn't utilize infinite iterators.
To achieve what you want, at iteration 0, the index change needs to be 0, then at iteration 1, the index should decrease by 1, at the second iteration the index needs to increase by 2 from the last index, and at iteration 3 the index needs to decrease by 3 from the last index...
The series of index changes is therefore 0, -1, 2, -3, 4, -5... It is like the series of natural numbers, but each odd number is negated.
So, here is the code:
def alternate_finite(n: int) -> Generator[int, None, None]:
m = n // 2
sign = 1
for i in range(n):
yield (m := m + i * sign)
sign *= -1
def zigzag_finite(arr: Iterable) -> list:
return [arr[i] for i in alternate_finite(len(arr))] | {
"domain": "codereview.stackexchange",
"id": 44971,
"lm_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",
"url": null
} |
python, python-3.x
def zigzag_finite(arr: Iterable) -> list:
return [arr[i] for i in alternate_finite(len(arr))]
This version is considerably less efficient, but is cleverer and does more actual work unlike the lazy version.
In [395]: %timeit zigzag(range(4096))
846 µs ± 9.26 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
In [396]: %timeit zigzag_finite(range(4096))
1.14 ms ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each) | {
"domain": "codereview.stackexchange",
"id": 44971,
"lm_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",
"url": null
} |
python, pygame
Title: Pygame (First time trying to implement OOP)
Question: Recently I've been trying to learn more advanced things such as using classes and creating methods and such to implement OOP into my coding. This is the first time I've tried and I want opinion on what I could do to make this better or more efficient, or maybe what I'm doing wrong
Optional Read
For context, I watched a beginner tutorial on YouTube on how to create a game, and then after I finished the tutorial, I decided to try and implement classes and objects. Essentially the game is just a spaceship (red rectangle) at the bottom of the screen that moves left and right to try and avoid the stars (white rectangles) that fall from the top of your screen to the bottom
Main Class:
import pygame
import random
import time
from Player import Player
from Star import Star
pygame.init()
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 700
FONT = pygame.font.SysFont("comicsans", 30)
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Space Avoiders")
background = pygame.transform.scale(pygame.image.load("background1.jpg"), (SCREEN_WIDTH, SCREEN_HEIGHT + 15))
player = Player(SCREEN_WIDTH/2 - 20, SCREEN_HEIGHT - 60, 20, 60)
start_time = time.time()
elapsed_time = 0
star_spawn_rate = 2000
star_spawn = 1000
star_spawn_rate_decrease = 50
stars_to_spawn = 3
stars = []
hit = False
def starSpawner():
for _ in range(3):
randx = random.randint(0, 980)
stars.append(Star(randx, -40, 20, 40))
def redrawGameWindow():
screen.blit(background, (0, 0))
time_text = FONT.render(f'Time: {round(elapsed_time)}s', 1, "white")
screen.blit(time_text, (10, 10))
player.draw(screen)
for star in stars:
star.draw(screen)
star.fall()
pygame.display.update()
run = True
clock = pygame.time.Clock()
while run:
star_spawn += clock.tick(60)
elapsed_time = time.time() - start_time | {
"domain": "codereview.stackexchange",
"id": 44972,
"lm_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, pygame",
"url": null
} |
python, pygame
playerRect = pygame.Rect(player.x, player.y, player.width, player.height)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
break
if star_spawn >= max(200, star_spawn_rate):
star_spawn_rate -= star_spawn_rate_decrease
star_spawn = 0
starSpawner()
for star in stars[:]:
starRect = pygame.Rect(star.x, star.y, star.width, star.height)
if star.y >= SCREEN_HEIGHT:
stars.remove(star)
elif star.y + star.height >= player.y and starRect.colliderect(playerRect):
stars.remove(star)
hit = True
break
if hit:
lose_text = FONT.render("You Lost!", 1, "white")
screen.blit(lose_text, (SCREEN_WIDTH/2 - lose_text.get_width()/2, SCREEN_HEIGHT/2 - lose_text.get_height()/2))
pygame.display.update()
pygame.time.delay(4000)
break
player.move()
redrawGameWindow()
pygame.quit()
Player Class:
import pygame
class Player:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 3
def draw(self, screen):
pygame.draw.rect(screen, "red", (self.x, self.y, self.width, self.height))
def move(self):
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
self.x -= self.vel
elif keys[pygame.K_RIGHT]:
self.x += self.vel
Star Class:
import pygame
class Star:
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 5
def draw(self, screen):
pygame.draw.rect(screen, "white", (self.x, self.y, self.width, self.height))
def fall(self):
self.y += self.vel
Answer: Star and Player look lovely.
pygame.init()
...
screen = ...
while run: | {
"domain": "codereview.stackexchange",
"id": 44972,
"lm_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, pygame",
"url": null
} |
python, pygame
Answer: Star and Player look lovely.
pygame.init()
...
screen = ...
while run:
Ok, all that stuff needs to be packaged up
within def main(): or something similar.
Why?
Imagine that you, or someone else, wanted to write a
unit test
for starSpawner.
That module would need to import the current module.
Which should happen without side effects,
beyond the occasional function being defined.
Avoid such side effects.
Every module should be safe to import from elsewhere.
Include a
if __name__ == `__main__`:
main()
guard at the end, so the main() function
is only invoked via $ python main.py,
and not by import main.
Also, one could probably invent a more
informative module name than "main".
def starSpawner():
...
def redrawGameWindow():
Pep-8
asks that you choose names like star_spawner
and redraw_game_window.
for star in stars[:]:
Iterating over stars.copy() so we can delete entries
as we go is slightly tricky, and merits a # comment explaining it.
This code appears to achieve its design goals.
I would be willing to delegate or accept maintenance
tasks on this codebase. | {
"domain": "codereview.stackexchange",
"id": 44972,
"lm_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, pygame",
"url": null
} |
c++, performance, c++14, logging
Title: Custom single-header C++ logging library
Question: I started learning C++ recently for game development, and decided to write my own little library for debugging.
Here is the library (snoop.hpp)
#ifndef SNOOP_HPP
#define SNOOP_HPP
#include <chrono>
#include <fstream>
#include <iostream>
#include <memory>
#include <string>
#include <mutex>
#include <sstream>
#include <functional>
// Enumeration for different log levels
enum class LogLevel {
FATAL,
ERROR,
WARN,
INFO,
DEBUG,
VERB
};
// Forward declaration of Snoop class
class Snoop;
// Type definition for custom error handler function
using ErrorHandler = void (*)(const std::string&);
// Type definition for custom log message formatter function
using LogFormatter = std::function<std::string(LogLevel, const char*, int, const std::string&)>;
class Snoop {
public:
// Constructor
Snoop(LogLevel level = LogLevel::INFO, std::string filePath = "", bool log_to_console = true);
// Destructor
~Snoop();
// Copy Constructor (deleted)
Snoop(const Snoop&) = delete;
// Copy Assignment Operator (deleted)
Snoop& operator=(const Snoop&) = delete;
// Move Constructor
Snoop(Snoop&& other);
// Move Assignment Operator
Snoop& operator=(Snoop&& other);
// Method to set a custom error handler
void SetErrorHandler(ErrorHandler error_handler);
// Method to set a custom log formatter
void SetLogFormatter(LogFormatter formatter);
// Public log methods for different log levels
void Fatal(const char* file, int line, const std::string& message);
void Error(const char* file, int line, const std::string& message);
void Warn(const char* file, int line, const std::string& message);
void Info(const char* file, int line, const std::string& message);
void Debug(const char* file, int line, const std::string& message);
void Verb(const char* file, int line, const std::string& message); | {
"domain": "codereview.stackexchange",
"id": 44973,
"lm_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, c++14, logging",
"url": null
} |
c++, performance, c++14, logging
// Methods to configure logging behavior
void LogToFile(std::string filePath);
void LogToConsole(bool log_to_console);
void SetLevel(LogLevel level);
private:
LogLevel level = LogLevel::INFO;
bool log_to_file = false;
bool log_to_console = false;
std::mutex mutex;
std::unique_ptr<std::ofstream> file;
ErrorHandler error_handler = nullptr;
LogFormatter log_formatter = nullptr;
// Helper function for resource transfer
void swap(Snoop& other) noexcept;
// Helper function for default message formatting
std::string formatMessage(LogLevel level, const char* file, int line, const std::string& message);
// Internal log function used by public log functions
void log(LogLevel level, const char* file, int line, const std::string& message);
};
// Macros for simplified logging usage
#define LOG_FATAL(instance, msg) instance.Fatal(__FILE__, __LINE__, msg)
#define LOG_ERROR(instance, msg) instance.Error(__FILE__, __LINE__, msg)
#define LOG_WARN(instance, msg) instance.Warn(__FILE__, __LINE__, msg)
#define LOG_INFO(instance, msg) instance.Info(__FILE__, __LINE__, msg)
#define LOG_DEBUG(instance, msg) instance.Debug(__FILE__, __LINE__, msg)
#define LOG_VERB(instance, msg) instance.Verb(__FILE__, __LINE__, msg)
// Constructor
Snoop::Snoop(LogLevel level, std::string filePath, bool log_to_console) {
try {
LogToFile(filePath);
LogToConsole(log_to_console);
SetLevel(level);
}
catch (const std::exception& e) {
// Handle initialization exception
if (this->error_handler) {
this->error_handler("Exception during Snoop initialization: " + std::string(e.what()));
}
else {
std::cerr << "Exception during Snoop initialization: " << e.what() << std::endl;
}
}
}
// Destructor
Snoop::~Snoop() {
// unique_ptr will automatically close the file when it goes out of scope
} | {
"domain": "codereview.stackexchange",
"id": 44973,
"lm_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, c++14, logging",
"url": null
} |
c++, performance, c++14, logging
// Move Constructor
Snoop::Snoop(Snoop&& other) {
// Transfer ownership of resources
swap(other);
}
// Move Assignment Operator
Snoop& Snoop::operator=(Snoop&& other) {
// Self-assignment check
if (this != &other) {
// Release current resources
if (log_to_file) {
file.reset(); // Close file by resetting unique_ptr
}
// Transfer ownership of resources from 'other' to 'this'
swap(other);
}
return *this;
}
// Helper function to swap resources
void Snoop::swap(Snoop& other) noexcept {
using std::swap;
// Ensure thread safety by locking both mutexes
std::lock_guard<std::mutex> lock(mutex);
std::lock_guard<std::mutex> otherLock(other.mutex);
// Transfer resources between 'this' and 'other'
swap(level, other.level);
swap(log_to_file, other.log_to_file);
swap(log_to_console, other.log_to_console);
swap(file, other.file);
}
// Method to set a custom error handler
void Snoop::SetErrorHandler(ErrorHandler error_handler) {
this->error_handler = error_handler;
}
// Method to set a custom log formatter
void Snoop::SetLogFormatter(LogFormatter formatter) {
this->log_formatter = formatter;
}
// Method to set the log level
void Snoop::SetLevel(LogLevel level) {
this->level = level;
}
// Method to configure logging to console
void Snoop::LogToConsole(bool log_to_console) {
this->log_to_console = log_to_console;
}
// Method to configure logging to file
void Snoop::LogToFile(std::string filePath) {
this->file.reset(); // Release previous file handle | {
"domain": "codereview.stackexchange",
"id": 44973,
"lm_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, c++14, logging",
"url": null
} |
c++, performance, c++14, logging
if (!filePath.empty()) {
try {
// Attempt to open the specified file for logging
this->file = std::make_unique<std::ofstream>(filePath, std::ios_base::app);
if (!(*this->file)) {
// Error opening file
if (this->error_handler) {
this->error_handler("Failed to open file for logging: " + filePath);
}
else {
std::cerr << "Error while opening log file: " << filePath << std::endl;
}
this->log_to_file = false;
}
else {
// Successfully opened file
this->log_to_file = true;
}
}
catch (const std::exception& e) {
// Handle exception while opening the log file
if (this->error_handler) {
this->error_handler("Exception while opening log file: " + std::string(e.what()));
}
else {
std::cerr << "Exception while opening log file: " << e.what() << std::endl;
}
this->log_to_file = false;
}
}
else {
// Logging to file is disabled
this->log_to_file = false;
}
}
// Default message formatting function
std::string Snoop::formatMessage(LogLevel level, const char* file, int line, const std::string& message) {
std::ostringstream outstream;
// Generate timestamp
using clock = std::chrono::system_clock;
auto now = clock::now();
auto seconds = std::chrono::time_point_cast<std::chrono::seconds>(now);
auto fraction = now - seconds;
std::time_t clock_now = clock::to_time_t(now);
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(fraction);
char time_str[20];
std::strftime(time_str, sizeof(time_str), "%H:%M:%S", std::localtime(&clock_now));
outstream << time_str; | {
"domain": "codereview.stackexchange",
"id": 44973,
"lm_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, c++14, logging",
"url": null
} |
c++, performance, c++14, logging
outstream << time_str;
// Add log level
switch(level) {
case LogLevel::FATAL: outstream << " [FTL] "; break;
case LogLevel::ERROR: outstream << " [ERR] "; break;
case LogLevel::WARN: outstream << " [WRN] "; break;
case LogLevel::INFO: outstream << " [INF] "; break;
case LogLevel::DEBUG: outstream << " [DBG] "; break;
case LogLevel::VERB: outstream << " [VRB] "; break;
}
outstream << "[" << file << ":" << line << "] ";
outstream << message;
return outstream.str();
}
// Internal log function
void Snoop::log(LogLevel level, const char* file, int line, const std::string& message) {
// Skip logging if the level is above the set logging level
if (level > this->level) {
return;
}
std::string outstring;
// Format the log message using a custom formatter if provided
if (this->log_formatter) {
outstring = this->log_formatter(level, file, line, message);
}
else {
// Use the default message formatting function
outstring = formatMessage(level, file, line, message);
}
// Log to console
if (this->log_to_console) {
// Lock the mutex for thread safety while logging to console
this->mutex.lock();
if (level == LogLevel::FATAL || level == LogLevel::ERROR) {
std::clog << outstring << std::endl;
}
else {
std::clog << outstring << "\n";
}
this->mutex.unlock();
}
// Log to file
if (this->log_to_file) {
// Lock the mutex for thread safety while logging to file
this->mutex.lock();
if (level == LogLevel::FATAL || level == LogLevel::ERROR) {
(*this->file) << outstring << std::endl;
}
else {
(*this->file) << outstring << "\n";
}
this->mutex.unlock();
}
} | {
"domain": "codereview.stackexchange",
"id": 44973,
"lm_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, c++14, logging",
"url": null
} |
c++, performance, c++14, logging
// Public log functions that call the internal log function
void Snoop::Fatal(const char* file, int line, const std::string& message) {
log(LogLevel::FATAL, file, line, message);
}
void Snoop::Error(const char* file, int line, const std::string& message) {
log(LogLevel::ERROR, file, line, message);
}
void Snoop::Warn(const char* file, int line, const std::string& message) {
log(LogLevel::WARN, file, line, message);
}
void Snoop::Info(const char* file, int line, const std::string& message) {
log(LogLevel::INFO, file, line, message);
}
void Snoop::Debug(const char* file, int line, const std::string& message) {
log(LogLevel::DEBUG, file, line, message);
}
void Snoop::Verb(const char* file, int line, const std::string& message) {
log(LogLevel::VERB, file, line, message);
}
#endif
And here I have a file that showcases how to use it (example.cpp):
#include "snoop.hpp"
int main() {
// Create a Snoop logger instance with INFO level
Snoop logger(LogLevel::INFO);
// Set a custom error handler
logger.SetErrorHandler([](const std::string& error) {
std::cerr << "Custom Error Handler: " << error << std::endl;
});
// Log messages at different levels with the default formatter
LOG_FATAL(logger, "This is a fatal message.");
LOG_ERROR(logger, "This is an error message.");
LOG_WARN(logger, "This is a warning message.");
LOG_INFO(logger, "This is an info message.");
LOG_DEBUG(logger, "This is a debug message."); // Gets skipped
LOG_VERB(logger, "This is a verbose message."); // Gets skipped | {
"domain": "codereview.stackexchange",
"id": 44973,
"lm_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, c++14, logging",
"url": null
} |
c++, performance, c++14, logging
// Set a custom log formatter
logger.SetLogFormatter([](LogLevel level, const char* file, int line, const std::string& message) -> std::string {
std::ostringstream formatted;
formatted << "<" << file << "::" << line << "> ";
switch (level) {
case LogLevel::FATAL: formatted << "[FATAL] "; break;
case LogLevel::ERROR: formatted << "[ERROR] "; break;
case LogLevel::WARN: formatted << "[WARN] "; break;
case LogLevel::INFO: formatted << "[INFO] "; break;
case LogLevel::DEBUG: formatted << "[DEBUG] "; break;
case LogLevel::VERB: formatted << "[VERB] "; break;
}
formatted << message;
return formatted.str();
});
// Change LogLevel to verbose
logger.SetLevel(LogLevel::VERB);
// Configure logger to log to a file
logger.LogToFile("./log/file.log"); // Throws error (directory doesn't exist)
// Log messages at different levels with the custom formatter
LOG_FATAL(logger, "This is a fatal message.");
LOG_ERROR(logger, "This is an error message.");
LOG_WARN(logger, "This is a warning message.");
LOG_INFO(logger, "This is an info message.");
LOG_DEBUG(logger, "This is a debug message.");
LOG_VERB(logger, "This is a verbose message.");
// Configure logger to log to a file ONLY
logger.LogToFile("./example.log");
logger.LogToConsole(false);
// Log additional messages after configuring file logging
LOG_FATAL(logger, "This is a fatal message (logged to file).");
LOG_ERROR(logger, "This is an error message (logged to file).");
LOG_WARN(logger, "This is a warning message (logged to file).");
LOG_INFO(logger, "This is an info message (logged to file).");
LOG_DEBUG(logger, "This is a debug message (logged to file).");
LOG_VERB(logger, "This is a verbose message (logged to file).");
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44973,
"lm_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, c++14, logging",
"url": null
} |
c++, performance, c++14, logging
return 0;
}
Anything I could change or add to make my code more safe and/or performant? General C++ advice is welcome too! Thanks :)
Edit: I applied the excellent advice given by G. Sliepen; you can see the updated version here: https://github.com/makeyen/snoop
Answer: Unnecessary things
You don't need to forward declare class Snoop, nothing uses it before you actually define the class.
this-> is almost never necessary in C++. The only issue is with level in Snoop::log(); this can be solved by renaming either the function parameter or the member variable named level. I suggest renaming the latter to maximum_level.
The destructor is empty, you can omit its definition entirely.
Catching errors in the constructor: error_handler is never set in the constructor, so it's useless to check for it. It's also better to just let the exception propagate than to print an error message and then to ignore the error.
There is no need to delete the copy constructor and assignment operator explicitly; since the member variable mutex is non-copyable, the whole class will be non-copyable by default as well.
Using a std::unique_ptr to hold the std::ofstream: you can default-construct a std::ofstream that is not associated with any file, and you can std::move() and std::swap() std::ofstreams just like you can with std::mutex.
Simplify the code
There is quite some complexity in log() because it can choose between custom formatters or a default one, and can log to a file and/or the console. I would also move the early checks for the log level into the class definition so it can be inlined. And together with the use of std::lock_guard and some helper functions, it can be rewritten like so:
class Snoop {
public:
…
void log(LogLevel level, …) {
if (level <= maximum_level)
log_internal(level, …);
} | {
"domain": "codereview.stackexchange",
"id": 44973,
"lm_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, c++14, logging",
"url": null
} |
c++, performance, c++14, logging
void Fatal(…) { log(LogLevel::FATAL, …); }
…
private:
…
std::ofstream file;
void log_internal(LogLevel level, const char* file, int line, const std::string& message);
};
static void log_formatted(bool enabled, std::ofstream& file, LogLevel level, const std::string& formatted_message) {
if (enabled) {
file << formatted_message << '\n';
if (LogLevel::FATAL || level == LogLevel::ERROR) {
file.flush();
}
}
}
void Snoop::log_internal(LogLevel level, const char* file, int line, const std::string& message) {
std::string outstring = formatMessage(level, file, line, message);
std::lock_guard lock(mutex);
log_formatted(log_to_console, clog, level, outstring);
log_formatted(log_to_file, file, level, outstring);
}
std::string Snoop::formatMessage(LogLevel level, const char* file, int line, const std::string& message) {
if (log_formatter) {
return log_formatter(level, file, line, message);
}
…
}
The macros can be avoided in C++20
C++20 added std::source_location, which gives you the filename and line number in a way that avoids having to use macros. | {
"domain": "codereview.stackexchange",
"id": 44973,
"lm_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, c++14, logging",
"url": null
} |
performance, scheme, racket
Title: Brute-force algorithm to solve allocation/assignment in Racket
Question: The situation: A certain number of kids come to a library and each of them wants to borrow a book. Since there is only one copy of each book in the library, each child must say which book they would like to read the most, which book they like the second most, etc. We assign the books to the kids based on their preferences by trying to minimize the overall "mismatch" score (0 points for kids that get the book they like the most, 1 point for each kid that gets their second most liked book, etc.).
Here is a python script that computes the best way to assign the books to the kids by basically trying all possible combinations with backtracking. It's a very stupid algorithm (the only smart thing it does is to stop searching when it sees that the score for the currently investigated solution cannot become better than the currently known best solution):
# Example with 27 kids.
# Each kid gives a list of 4 books (starting with the most liked book)
preferences=[
[1,2,3,4], [5,6,7,8], [4,9,10,11],
[12,13,14,15], [16,17,18,19], [20,21,22,23],
[24,17,4,18], [21,25,26,20], [18,16,17,27],
[5,13,24,28], [28,3,19,9], [6,17,9,29],
[30,2,31,14], [27,32,33,25], [17,34,35,5],
[18,24,17,16], [18,17,35,36], [16,37,38,36],
[27,9,19,28], [3,39,33,40], [41,38,42,6],
[17,35,3,30], [43,16,44,23], [38,8,42,5],
[18,16,3,17], [28,45,46,47], [48,46,17,49]]
# The currently known best solution
bestassignment = []
bestscore = 10000000 | {
"domain": "codereview.stackexchange",
"id": 44974,
"lm_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, scheme, racket",
"url": null
} |
performance, scheme, racket
# The currently known best solution
bestassignment = []
bestscore = 10000000
# i: the kid we are currently processing
# assignment: the books assigned so far to the kids 0 to i-1
# score: the score calculated so far for the assignment
def search(i, assignment, score):
global bestassignment, bestscore
if i==len(preferences): # Preferences of all kids processed?
if score<bestscore: # Let's check whether we have found a new best solution.
bestscore = score
bestassignment = assignment
else:
choices = preferences[i] # Go through the books chosen by kid #i
for rank in range(len(choices)):
choice = choices[rank]
if choice not in assignment: # Book not already assigned to another kid?
newscore = score + rank # Only continue if the score is not
if newscore<=bestscore: # already worse than the best known score.
newassignment = assignment + [choice] # Add the book to the list of assigned books.
search(i+1, newassignment, newscore) # Continue with kid i+1.
search(0,[],0)
print(f"Score {bestscore} Assignment {bestassignment}")
The script works and finds the best solution for the given example in a few seconds. I know there are better algorithms but that's not why I am here. I have tried to write an equivalent Racket program:
#lang racket
(define preferences
'[
[1 2 3 4] [5 6 7 8] [4 9 10 11]
[12 13 14 15] [16 17 18 19] [20 21 22 23]
[24 17 4 18] [21 25 26 20] [18 16 17 27]
[5 13 24 28] [28 3 19 9] [6 17 9 29]
[30 2 31 14] [27 32 33 25] [17 34 35 5]
[18 24 17 16] [18 17 35 36] [16 37 38 36]
[27 9 19 28] [3 39 33 40] [41 38 42 6]
[17 35 3 30] [43 16 44 23] [38 8 42 5]
[18 16 3 17] [28 45 46 47] [48 46 17 49]])
(struct solution (score assignment)) | {
"domain": "codereview.stackexchange",
"id": 44974,
"lm_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, scheme, racket",
"url": null
} |
performance, scheme, racket
(struct solution (score assignment))
(define (search-choices choices preferences score assignment best-solution)
(for/fold ((new-best-solution best-solution))
((choice choices)
(rank (in-naturals)))
(cond
((member choice assignment)
new-best-solution)
(else
(define newscore (+ score rank))
(if (<= newscore (solution-score new-best-solution))
(search preferences newscore (cons choice assignment) new-best-solution)
new-best-solution)))))
(define (search preferences score assignment best-solution)
(match preferences
((cons choices remaining-preferences)
(search-choices choices remaining-preferences score assignment best-solution))
(null
(if (< score (solution-score best-solution))
(solution score assignment)
best-solution))))
(define best-solution (search preferences 0 null (solution 10000000 null)))
(printf "Score ~a Assignment ~a~n"
(solution-score best-solution)
(reverse (solution-assignment best-solution)))
To my big disappointment, the Racket program is slightly slower than the python script when debugging is activated and just a little bit faster without debugging and stack preservation, even though the python script creates a new list in each iteration.
Am I doing something particularly unidiomatic in the Racket code? Do you have any suggestions for improving its performance? (apart from changing the high-level algorithm, which is the same in both implementations, otherwise it wouldn't be fair to compare them)
Answer: Here's my re-implementation of the Python code:
#lang racket/base | {
"domain": "codereview.stackexchange",
"id": 44974,
"lm_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, scheme, racket",
"url": null
} |
performance, scheme, racket
Answer: Here's my re-implementation of the Python code:
#lang racket/base
(define preferences
'[
[1 2 3 4] [5 6 7 8] [4 9 10 11]
[12 13 14 15] [16 17 18 19] [20 21 22 23]
[24 17 4 18] [21 25 26 20] [18 16 17 27]
[5 13 24 28] [28 3 19 9] [6 17 9 29]
[30 2 31 14] [27 32 33 25] [17 34 35 5]
[18 24 17 16] [18 17 35 36] [16 37 38 36]
[27 9 19 28] [3 39 33 40] [41 38 42 6]
[17 35 3 30] [43 16 44 23] [38 8 42 5]
[18 16 3 17] [28 45 46 47] [48 46 17 49]])
(define (search preferences)
(define (do-search preferences score assignment best-score best-assignment)
(if (null? preferences)
(if (< score best-score)
(values score assignment)
(values best-score best-assignment))
(for/fold ([best-score best-score]
[best-assignment best-assignment])
([choice (in-list (car preferences))]
[rank (in-naturals)]
#:do [(define new-score (+ score rank))]
#:when (and (<= new-score best-score)
(not (memv choice assignment))))
(do-search (cdr preferences)
new-score (cons choice assignment)
best-score best-assignment))))
(define-values (score assignment)
(do-search preferences 0 '() 10000000 '()))
(values score (reverse assignment)))
(time
(define-values (score assignment) (search preferences))
(printf "Score ~S Assignment ~S~%" score assignment)) | {
"domain": "codereview.stackexchange",
"id": 44974,
"lm_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, scheme, racket",
"url": null
} |
performance, scheme, racket
Compared to yours, it keeps the search logic all in one function, uses multiple values instead of a struct to return a best score and assignment values, doesn't use pattern matching, and a few other minor structural differences.
Timings:
$ racket yours.rkt
Score 14 Assignment (1 5 4 12 16 20 24 21 18 13 28 6 30 27 34 17 36 37 9 39 41 35 43 38 3 45 48)
cpu time: 8500 real time: 8500 gc time: 55
$ racket mine.rkt
Score 14 Assignment (1 5 4 12 16 20 24 21 18 13 28 6 30 27 34 17 36 37 9 39 41 35 43 38 3 45 48)
cpu time: 477 real time: 477 gc time: 15
Times are in millseconds. The original python one takes 6.150945925000087 seconds according to timeit.timeit().
I didn't think there were enough differences between yours and mine to account for such a large different in run time, but with some playing around I discovered one huge reason: Your code calls member, mine uses memv for seeing if a number is present in a list. When I changed that in your version, I got:
$ racket yours.rkt
Score 14 Assignment (1 5 4 12 16 20 24 21 18 13 28 6 30 27 34 17 36 37 9 39 41 35 43 38 3 45 48)
cpu time: 1016 real time: 1016 gc time: 23
Still slower, but much much closer, and lots faster than the Python one. member uses equal? for comparing values, memv uses eqv?, which is a simpler function that works fine for comparing numbers and obviously runs a lot faster. member does take an optional third argument to use for comparisons, but giving it = for explicit numeric equality is, while faster than using equal?, still slower than eqv?.
Another noticeable speedup comes from using in-list in the for/fold instead of relying on it to pick the right sequence function at runtime based on the type of choices: (choice (in-list choices)) instead of (choice choices) in your search-choices function. | {
"domain": "codereview.stackexchange",
"id": 44974,
"lm_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, scheme, racket",
"url": null
} |
c++, performance, beginner, algorithm, sieve-of-eratosthenes
Title: Sieve of Eratosthenes in C++ with wheel factorization
Question: I have written a completely working C++ program for the first time, and I have managed to compile it. I have decided to learn C++ and I have written a C++ program to familiarize myself with C++, this is my first ever C++ program and I wrote it all by myself, having only started learning a few hours prior. (And I haven't written a "Hello, World." program.)
The purpose is to practice my C++ skills and put what I have learned into use, to test if I really know the concepts I used in the script.
My idea is simple, the program accepts two command-line arguments (no std::cin and std::cout, I dislike interactivity), the first argument is the limit up to which primality of numbers should be checked, the second is the file path to which the prime numbers should be saved to.
The program should find all prime numbers up to the given limit using Sieve of Eratosthenes with Wheel Factorization optimization and write the prime numbers to the file line by line.
Here is the code:
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <stdexcept>
#include <vector>
const int wheel[8] = { 4, 2, 4, 2, 4, 6, 2, 6 };
const int triple[3][2] = { {4, 2}, {9, 6}, {25, 10} }; | {
"domain": "codereview.stackexchange",
"id": 44975,
"lm_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, beginner, algorithm, sieve-of-eratosthenes",
"url": null
} |
c++, performance, beginner, algorithm, sieve-of-eratosthenes
std::vector<uint64_t> wheel_sieve(uint64_t limit)
{
limit++;
std::vector<bool>is_prime(limit, true);
is_prime[0] = is_prime[1] = false;
for (auto& pair : triple)
{
int square = pair[0];
int multiple = pair[1];
for (uint64_t i = square; i < limit; i += multiple)
{
is_prime[i] = false;
}
}
uint64_t k = 7;
int i = 0;
while (true)
{
uint64_t square = k * k;
if (square > limit)
{
break;
}
if (is_prime[k])
{
uint64_t twice = 2 * k;
for (uint64_t i = square; i < limit; i += twice)
{
is_prime[i] = false;
}
}
k += wheel[i];
if (++i == 8)
{
i = 0;
}
}
std::vector<uint64_t> primes;
for (uint64_t i = 0; i < limit; i++)
{
if (is_prime[i])
{
primes.push_back(i);
}
}
return primes;
}
int main(int argc, char* argv[])
{
if (argc != 3)
{
throw std::invalid_argument("number of arguments must be 2");
}
uint64_t limit = atoi(argv[1]);
std::vector<uint64_t> primes = wheel_sieve(limit);
std::ofstream file;
file.open(argv[2]);
for (uint64_t& prime : primes)
{
file << prime << std::endl;
}
file.close();
return 0;
}
I have managed to compile it and run it, and I have confirmed its correctness. I compiled it using Visual Studio 2022 in x64 Release mode.
I guess it can be faster?:
PS C:\Users\Xeni> measure-command {C:\Users\Xeni\source\repos\Wheel_Sieve\x64\Release\Wheel_Sieve.exe 1048576 D:\primes-under-1048576.txt} | {
"domain": "codereview.stackexchange",
"id": 44975,
"lm_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, beginner, algorithm, sieve-of-eratosthenes",
"url": null
} |
c++, performance, beginner, algorithm, sieve-of-eratosthenes
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 295
Ticks : 2950071
TotalDays : 3.41443402777778E-06
TotalHours : 8.19464166666667E-05
TotalMinutes : 0.004916785
TotalSeconds : 0.2950071
TotalMilliseconds : 295.0071
How can I make it more efficient? | {
"domain": "codereview.stackexchange",
"id": 44975,
"lm_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, beginner, algorithm, sieve-of-eratosthenes",
"url": null
} |
c++, performance, beginner, algorithm, sieve-of-eratosthenes
How can I make it more efficient?
Answer: Stop using std::endl
Use '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed. This is often unnecessary, and hurts performance.
Reserve space for vectors
If you use std::vector's reserve() member function, it can allocate all the memory it will need in one go. If you don't do it, it will have to reallocate several times while you push_back() items to it.
Of course, you don't know exactly how many primes there are up to limit without actually calculating the primes, but there are prime counting functions that can give you an estimate. It doesn't hurt to reserve a bit more memory than you'll need.
You don't need the vector primes
You actually don't need to create a std::vector<uint64_t> for holding the prime numbers, all the information is already in is_prime. Instead of creating the vector primes, just loop over is_prime and immediately print the numbers to file.
Missing error checking
Writing to a file can fail for various reasons; either it cannot be opened (maybe you don't have write permissions), or something happens while writing to an already opened file (maybe the disk got full, or it's a USB stick and you removed it before your program completed, and so on). You want to avoid your program pretending that everything is fine in that case.
While you could check every single I/O operation, you can just do the error checking at the end. After calling file.close(), check if file.good() == true; if not then something happened previously. Make sure you then write an error message to std::cerr, and return EXIT_FAILURE. Or throw an exception like you did for argc != 3; this will have a similar effect. | {
"domain": "codereview.stackexchange",
"id": 44975,
"lm_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, beginner, algorithm, sieve-of-eratosthenes",
"url": null
} |
c++, performance, beginner, converting, c++20
Title: C++ arbitrary base convertor | {
"domain": "codereview.stackexchange",
"id": 44976,
"lm_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, beginner, converting, c++20",
"url": null
} |
c++, performance, beginner, converting, c++20
Question: This is my second C++ program. Again, I wrote it all by myself. I only started learning C++ yesterday.
The concept of the program is simple; it should read input from std::cin and print the output to std::cout.
There are two functions that implement the bulk of the logic: a function to interpret numerals from a given base to its numerical value, and a function to represent a given number in a given base.
The base must be between 2 and 36. The reason is simple: I represent the number as strings, and I follow the convention of hexadecimal. Hexadecimal uses Arabic digits 0-9 and Basic Latin Alphabet a-f. There are 26 letters in the alphabet; if I use all of them I can represent base-36 numerals. For higher bases more symbols would be needed, but there aren't any good extensions to this.
My script only processes integers; it supports negative numbers and does some input validation. I use the ASCII character code to get the numerical value directly by decreasing the character code according to its value, and the case of the input can be mixed.
I stop the execution of the script if any character is not in the base-36 character set, or it has the same or higher numerical value than the base. I didn't do overflow and underflow checking though; those are currently beyond me.
The logic to interpret numerals from base is simple: initialize a variable n to 0, for each digit in string, multiply n by base, add the numerical value of digit to n and assign the result back to n, done.
The logic to represent numbers is its direct opposite: keep doing integer division with number as numerator and base as denominator, get the remainder as digit, collect the string representation in reverse order, and assign the quotient to number. Stop the loop when the number is 0. | {
"domain": "codereview.stackexchange",
"id": 44976,
"lm_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, beginner, converting, c++20",
"url": null
} |
c++, performance, beginner, converting, c++20
The program should keep asking for commands and print the execution result to console, until the input equals 'q'. The commands should be a space delimited string consisting of 3 fields: the first field is the number/numeral to process, which can be in any supported base; the third is the base to convert from/to, which must be in decimal; The second is the keyword, it must be either "to" or "from".
The keyword determines which function should be called, if it is "to", the command means converting the number represented in decimal to the target base, else if it is "from", the command means to interpret the numeral in the given base.
I also wrote the function to split the string entirely by myself. | {
"domain": "codereview.stackexchange",
"id": 44976,
"lm_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, beginner, converting, c++20",
"url": null
} |
c++, performance, beginner, converting, c++20
Code
#include <format>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
std::vector<std::string> split_string(std::string str, std::string delim) {
std::vector<std::string> fields;
int length = delim.length();
int pos = 0;
std::string field = "";
std::string buffer = "";
for (char& c : str) {
if (c == delim[pos]) {
buffer += c;
pos++;
}
else {
field += buffer + c;
buffer = "";
pos = 0;
}
if (pos == length) {
fields.push_back(field);
field = "";
buffer = "";
pos = 0;
}
}
if (field != "") {
fields.push_back(field);
}
return fields;
}
uint64_t interpret_base(std::string str, int base = 10) {
if (base < 2 or base > 36) {
throw std::invalid_argument(std::format("base {} is not between 2 and 36", base));
}
uint64_t number = 0;
for (char& c : str) {
int digit = c;
if (digit < 58) {
digit -= 48;
}
else if (digit < 91)
{
digit -= 55;
}
else {
digit -= 87;
}
if (digit < 0 or digit >= base) {
throw std::invalid_argument(std::format("input string is not a valid integer in base {}", base));
}
number = number * base + digit;
}
return number;
}
std::string base_repr(uint64_t number, int base) {
if (base < 2 or base > 36) {
throw std::invalid_argument(std::format("input base {} is between 2 to 36", base));
}
std::string repr = "";
int digit;
while (number) {
uint64_t quotient = number / base;
digit = number - quotient * base;
number = quotient;
if (digit < 10) {
digit += 48;
}
else {
digit += 87;
}
repr = char(digit) + repr;
}
return repr;
} | {
"domain": "codereview.stackexchange",
"id": 44976,
"lm_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, beginner, converting, c++20",
"url": null
} |
c++, performance, beginner, converting, c++20
std::string execute_command(std::string command) {
std::vector<std::string> fields = split_string(command, " ");
int size = fields.size();
if (size != 3) {
throw std::invalid_argument("command must have three fields");
}
std::string option = fields[1];
int base = interpret_base(fields[2]);
std::string sign = "";
std::string numeral = fields[0];
char first = numeral[0];
if (first == '-' or first == '+') {
if (first == '-') {
sign = "-";
}
numeral = numeral.substr(1, numeral.size() - 1);
}
if (option == "from") {
return sign + std::to_string(interpret_base(numeral, base));
}
else if (option == "to") {
uint64_t number = interpret_base(numeral);
return sign + base_repr(number, base);
}
else {
throw std::invalid_argument("option is not supported");
}
}
int main() {
std::string input;
std::cout << "input a numeral, operation and base (use space as delimiter)\n";
while (true) {
std::cout << ">>> ";
std::getline(std::cin, input);
if (input == "q") {
break;
}
std::cout << execute_command(input) + '\n';
}
return 0;
}
Test
PS C:\Users\Xeni> C:\Users\Xeni\source\repos\number_converter\x64\Release\number_converter.exe
input a numeral, operation and base (use space as delimiter)
>>> -123456789 to 36
-21i3v9
>>> -21i3v9 from 36
-123456789
>>> stirlingite from 36
105370617716134466
>>> 105370617716134466 to 36
stirlingite
>>> 242516 to 36
574k
>>> 574k from 36
242516
>>> 75bcd15 from 16
123456789
>>> 123456789 to 16
75bcd15
>>> q
PS C:\Users\Xeni>
How can it be improved?
I now use unsigned 64-bit integer for maximum representable integer range, I just add the sign as a string. And this is as far as I can go. | {
"domain": "codereview.stackexchange",
"id": 44976,
"lm_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, beginner, converting, c++20",
"url": null
} |
c++, performance, beginner, converting, c++20
Answer: Interface
The limit of base to maximum 36 is quite reasonable, as is the requirement that it be provided in decimal.
I find it strange that we only convert from and to decimal (i.e. one of input and output must be base-10). For an arbitrary converter, I would expect to be able to specify input radix and output radix, and not need to use decimal as an intermediate. It might also be useful to specify the input and output radices as command-line arguments, thus allowing the user to stream a whole series of values for conversion.
Instead of having to enter q as the last input, we should also stop processing when we reach end-of-file on input. Again, this makes it easier to use if we're streaming a series of numbers from some other process.
Implementation
A 64-bit integer is not necessarily the "maximum representable integer range" - <cstdint> provides std::intmax_t for that purpose.
Restricting to systems that use ASCII as character encoding isn't necessary (and even if it were, then using character constants such as '0' is much clearer to readers than bare numbers (48).
We can convert independently of character coding:
#include <cctype>
#include <string_view>
static const std::string_view all_digits{"0123456789abcdefghijklmnopqrstuvwxyz"};
auto n = all_digits.find(std::tolower(static_cast<unsigned char>(c)));
if (n == std::string_view::npos or n >= base) {
throw std::invalid_argument{std::format("{} is not a valid digit in base {}",
c, base)};
}
number = number * base + n; | {
"domain": "codereview.stackexchange",
"id": 44976,
"lm_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, beginner, converting, c++20",
"url": null
} |
c++, performance, beginner, converting, c++20
(There are faster methods - e.g. using an unsigned char sized lookup table, but this serves to demonstrate the point, and speed isn't a big concern at this stage).
We throw exceptions from various places, but never catch any. That leads to a poor user experience; depending on platform that might include a selection of diagnostics, perhaps also a stack trace, as well as exiting with a failure status. Consider handling recoverable errors and proceeding to the next line of input where possible, and exit only when we can't recover (such as a stream error or EOF of the input). | {
"domain": "codereview.stackexchange",
"id": 44976,
"lm_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, beginner, converting, c++20",
"url": null
} |
c++
Title: Parallel Accumulate
Question: template<typename It>
template<typename It>
std::iter_value_t<It> parallelAccumulate(It begin, It end) {
static const size_t MIN_COUNT_PER_THREAD = 10;
const auto size = distance(begin, end);
std::iter_value_t<It> init{};
if (size < MIN_COUNT_PER_THREAD) {
for (; begin != end; begin++) {
init = init + *begin;
}
return init;
}
auto const midIt = next(begin, size/2);
std::future firstIntervalAcc = std::async(parallelAccumulate<It>, begin, midIt);
std::future secondIntervalAcc = std::async(parallelAccumulate<It>, midIt,end);
return firstIntervalAcc.get() + secondIntervalAcc.get();
}
Trivial accumulate function just wanted to confirm I am not missing something as new to the language.
Answer: The standard library already has parallel algorithms
Trivial accumulate function just wanted to confirm I am not missing something as new to the language.
Since C++17 you can use std::reduce() to accumulate parallely:
template<typename It>
auto parallelAccumulate(It begin, It end) {
return std::reduce(std::execution::par, begin, end);
} | {
"domain": "codereview.stackexchange",
"id": 44977,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
How many threads to use?
The number of threads your function is going to use depends on the size of the input. However, the ideal number of threads to use is actually the number of CPU cores your computer has. Thus, for very large inputs, you could use much more threads than can actually run simultaneously, and then the overhead of context switching might actually slow your algorithm down. Maybe std::async() will defer new threads if it detects all cores are already in use, but you cannot rely on that, and even without running them all concurrently, there still is overhead from creating all the futures. Consider limiting the number of threads somehow to std::thread::hardware_concurrency().
Another issue is that there is some overhead in starting threads, so if you do too little work in a thread, the time your algorithm takes is dominated by creating and destroying threads. Adding 10 numbers is something that is very fast for a CPU to do, so I would definitely increase that. You might want to benchmark your algorithm with various values of MIN_COUNT_PER_THREAD to see what the best tradeoff is.
For some value types, it could be that adding some values is more expensive than adding others. Consider that the value type could be std::string, and you have a vector with very long and very short strings. Then some of the async calls might take much longer than others to complete, and this might result in CPU cores being utilized unevenly. A typical solution for this is to have a limited number of threads that continue to pick work to do until there is nothing left to do.
It can be made more generic
While making the iterator type a template parameter makes your algorithm already somewhat generic, there are lots of cases where it still will not work. Consider: | {
"domain": "codereview.stackexchange",
"id": 44977,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
c++
The value type not having a default constructor. This is why std::accumulate() has an init parameter.
The sum of two values might have a different type than the values themselves, and/or you want to store the result in a different type. Consider wanting to sum lots of 8-bit numbers into a 64-bit variable. This is also solved with an init parameter.
You might want to accumulate with a custom addition operation. The standard library algorithms often have overloads for custom operators. | {
"domain": "codereview.stackexchange",
"id": 44977,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++",
"url": null
} |
python, apache-spark
Title: Find the youngest athlete to win a Gold medal
Question: I have a dataframe loaded from CSV file which contains data from Olympics games. Goal is find out the athletes with minimum age who won Gold medal. I have managed to come up with following code. Is this the most optimal way of doing this?
from pyspark.sql.functions import min,col
gold_medal_df = athlete_events_df.filter(athlete_events_df.Medal == 'Gold')
min_age = gold_medal_df.select(min(athlete_events_df.Age)).collect()[0][0]
gold_medal_df.filter(col('Age') == min_age).display()
I am new to Python and Spark and I feel there must be some more optimised way of doing things.
Answer: pyspark.sql.functions import
It's more common to use
from pyspark.sql import functions as F
since there are functions like F.min that shadow python builtins (min, max, etc).
collect
It's not usually great to collect a result for filtering like this. Here, I would use an aggregate that I could join on:
from pyspark.sql import functions as F
df = athlete_events_df.filter(athlete_events_df.Medal == 'Gold')
min_age = df.agg(F.min('Age').alias('Age'))
# do the join here
joined = df.join(min_age, 'Age')
You really could swap the initial filter into a join as well using F.lit in the aggregate select statement:
min_age = (
athlete_events_df
.agg(F.min('Age').alias('Age'))
.select(
F.col('Age'),
F.lit('Gold').alias('Medal')
)
)
df = athlete_events_df.join(min_age, ['Age', 'Medal'])
Also note the use of parentheses to break up multiple lines. This is much preferred over the \ character to denote a multi-line operation | {
"domain": "codereview.stackexchange",
"id": 44978,
"lm_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, apache-spark",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
Title: A recursive_fold_left_all Template Function Implementation in C++
Question: This is a follow-up question for A recursive_sum Template Function Implementation with Unwrap Level in C++. I am trying to implement a recursive version fold_left template function in this post.
The experimental implementation
recursive_fold_left_all Template Function:
/* recursive_fold_left_all template function performs fold left operation on input container exhaustively
*/
template<typename T>
constexpr auto recursive_fold_left_all(const T& input)
{
return input;
}
template<std::ranges::input_range T, class I,
class F>
constexpr auto recursive_fold_left_all(const T inputRange, I init, F f)
{
return std::ranges::fold_left(inputRange, init, f);
}
template<std::ranges::input_range T, class I,
class F>
requires(std::ranges::input_range<std::ranges::range_value_t<T>>)
constexpr auto recursive_fold_left_all(const T inputRange, I init, F f)
{
return std::invoke(f, init, recursive_fold_left_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
inputRange,
[&](auto&& element){ return recursive_fold_left_all(element, I{}, f); }),
I{}, f
));
}
Full Testing Code
The full testing code:
// A recursive_fold_left_all Template Function Implementation in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <queue>
#include <ranges>
#include <stack>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
// is_reservable concept
template<class T>
concept is_reservable = requires(T input)
{
input.reserve(1);
}; | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
// is_sized concept, https://codereview.stackexchange.com/a/283581/231235
template<class T>
concept is_sized = requires(T x)
{
std::size(x);
};
template<typename T>
concept is_summable = requires(T x) { x + x; };
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1};
}
// recursive_invoke_result_t implementation
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::regular_invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::regular_invocable<F, Container<Ts...>>&& // F cannot be invoked to Container<Ts...> directly
std::ranges::input_range<Container<Ts...>>&&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<
typename recursive_invoke_result<
F,
std::ranges::range_value_t<Container<Ts...>>
>::type
>;
};
template<template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
std::regular_invocable<Container<T, N>> F>
struct recursive_invoke_result<F, Container<T, N>>
{
using type = std::invoke_result_t<F, Container<T, N>>;
}; | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
template<template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
typename F>
requires (
!std::regular_invocable<F, Container<T, N>>&& // F cannot be invoked to Container<Ts...> directly
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<T, N>>>::type; })
struct recursive_invoke_result<F, Container<T, N>>
{
using type = Container<
typename recursive_invoke_result<
F,
std::ranges::range_value_t<Container<T, N>>
>::type
, N>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
}; | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
};
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
// https://codereview.stackexchange.com/a/253039/231235
template<template<class...> class Container = std::vector, std::size_t dim, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times));
}
}
namespace UL // unwrap_level
{
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto make_view(const Container& input, const F& f) noexcept
{
return std::ranges::transform_view(
input,
[&f](const auto&& element) constexpr { return recursive_transform(element, f ); } );
} | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
/* Override make_view to catch dangling references. A borrowed range is
* safe from dangling..
*/
template <std::ranges::input_range T>
requires (!std::ranges::borrowed_range<T>)
constexpr std::ranges::dangling make_view(T&&) noexcept
{
return std::ranges::dangling();
} | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
// clone_empty_container template function implementation
template< std::size_t unwrap_level = 1,
std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto clone_empty_container(const Container& input, const F& f) noexcept
{
const auto view = make_view(input, f);
recursive_variadic_invoke_result<unwrap_level, F, Container> output(std::span{input});
return output;
}
// recursive_transform template function implementation (the version with unwrap_level template parameter)
template< std::size_t unwrap_level = 1,
class T,
std::copy_constructible F>
requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
std::ranges::view<T>&&
std::is_object_v<F>)
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
auto output = clone_empty_container(input, f);
if constexpr (is_reservable<decltype(output)>&&
is_sized<decltype(input)>)
{
output.reserve(input.size());
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
}
else
{
std::ranges::transform(
input,
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
);
}
return output;
}
else if constexpr(std::regular_invocable<F, T>)
{
return std::invoke(f, input);
}
else
{
static_assert(!std::regular_invocable<F, T>, "Uninvocable?");
}
} | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
/* This overload of recursive_transform is to support std::array
*/
template< std::size_t unwrap_level = 1,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
typename F >
requires (std::ranges::input_range<Container<T, N>>)
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
Container<recursive_variadic_invoke_result_t<unwrap_level, F, T>, N> output;
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
// recursive_transform function implementation (the version with unwrap_level, without using view)
template<std::size_t unwrap_level = 1, class T, class F>
requires (!std::ranges::view<T>)
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
static_assert(unwrap_level <= recursive_depth<T>(),
"unwrap level higher than recursion depth of input"); // trying to handle incorrect unwrap levels more gracefully
recursive_variadic_invoke_result_t<unwrap_level, F, T> output{};
std::ranges::transform(
input, // passing a range to std::ranges::transform()
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return std::invoke(f, input); // use std::invoke()
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
namespace NonUL
{
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::input_range<Container>&&
std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto make_view(const Container& input, const F& f) noexcept
{
return std::ranges::transform_view(
input,
[&f](const auto&& element) constexpr { return recursive_transform(element, f ); } );
}
/* Override make_view to catch dangling references. A borrowed range is
* safe from dangling..
*/
template <std::ranges::input_range T>
requires (!std::ranges::borrowed_range<T>)
constexpr std::ranges::dangling make_view(T&&) noexcept
{
return std::ranges::dangling();
}
/* Base case of NonUL::recursive_transform template function
https://codereview.stackexchange.com/a/283581/231235
*/
template< typename T,
std::regular_invocable<T> F>
requires (std::copy_constructible<F>)
constexpr auto recursive_transform( const T& input, const F& f )
{
return std::invoke( f, input );
}
/* The recursive case of NonUL::recursive_transform template function
https://codereview.stackexchange.com/a/283581/231235
*/
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::input_range<Container>&&
std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto recursive_transform(const Container& input, const F& f)
{
const auto view = make_view(input, f);
recursive_invoke_result_t<F, Container> output( std::ranges::begin(view), std::ranges::end(view) );
// One last sanity check.
if constexpr( is_sized<Container> && is_sized<recursive_invoke_result_t<F, Container>> )
{
assert( output.size() == input.size() );
} | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
return output;
}
/* The recursive case of NonUL::recursive_transform template function for std::array
https://codereview.stackexchange.com/a/283581/231235
*/
template< template<typename, std::size_t> typename Container,
typename T,
std::size_t N,
std::copy_constructible F>
requires std::ranges::input_range<Container<T, N>>
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
Container<recursive_invoke_result_t<F, T>, N> output;
std::ranges::transform( // Use std::ranges::transform() for std::arrays
input,
std::ranges::begin(output),
[&f](auto&& element){ return recursive_transform(element, f); }
);
// One last sanity check.
if constexpr( is_sized<Container<T, N>> && is_sized<recursive_invoke_result_t<F, Container<T, N>>> )
{
assert( output.size() == input.size() );
}
return output;
}
}
/* recursive_fold_left_all template function performs fold left operation on input container exhaustively
*/
template<typename T>
constexpr auto recursive_fold_left_all(const T& input)
{
return input;
}
template<std::ranges::input_range T, class I,
class F>
constexpr auto recursive_fold_left_all(const T inputRange, I init, F f)
{
return std::ranges::fold_left(inputRange, init, f);
}
template<std::ranges::input_range T, class I,
class F>
requires(std::ranges::input_range<std::ranges::range_value_t<T>>)
constexpr auto recursive_fold_left_all(const T inputRange, I init, F f)
{
return std::invoke(f, init, recursive_fold_left_all(
UL::recursive_transform<recursive_depth<T>() - 1>(
inputRange,
[&](auto&& element){ return recursive_fold_left_all(element, I{}, f); }),
I{}, f
));
} | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
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 << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
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 << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
void recursive_fold_left_all_tests()
{
auto test_vectors = n_dim_container_generator<std::vector, 4, int>(1, 3);
std::cout << "Play with test_vectors:\n\n";
std::cout << "recursive_fold_left_all function test with vectors / std::plus<>(): \n";
auto recursive_fold_left_all_result1 = recursive_fold_left_all(test_vectors, static_cast<int>(1), std::plus<>());
std::cout << recursive_fold_left_all_result1 << "\n\n";
std::cout << "recursive_fold_left_all function test with vectors / std::multiplies<>(): \n";
auto recursive_fold_left_all_result2 = recursive_fold_left_all(test_vectors, static_cast<int>(2), std::multiplies<>());
std::cout << recursive_fold_left_all_result2 << "\n\n"; | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
// From: https://en.cppreference.com/w/cpp/algorithm/ranges/fold_left
std::vector<std::pair<char, float>> data {{'A', 2.f}, {'B', 3.f}, {'C', 3.5f}};
auto recursive_fold_left_all_result3 = recursive_fold_left_all
(
data | std::ranges::views::values, 2.0f, std::multiplies<>()
);
std::cout << "recursive_fold_left_all_result3: " << recursive_fold_left_all_result3 << '\n';
std::array<int, 8> arr {1, 2, 3, 4, 5, 6, 7, 8};
// use a program defined function object (lambda-expression):
auto recursive_fold_left_all_result4 = recursive_fold_left_all
(
arr, "A", [](std::string s, int x) { return s + ':' + std::to_string(x); }
);
std::cout << "recursive_fold_left_all_result4: " << recursive_fold_left_all_result4 << '\n';
return;
}
int main()
{
recursive_fold_left_all_tests();
return 0;
}
The output of the test code above:
Play with test_vectors:
recursive_fold_left_all function test with vectors / std::plus<>():
82
recursive_fold_left_all function test with vectors / std::multiplies<>():
0
recursive_fold_left_all_result3: 42
recursive_fold_left_all_result4: A:1:2:3:4:5:6:7:8
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_sum Template Function Implementation with Unwrap Level in C++.
What changes has been made in the code since last question?
I am trying to implement a recursive version fold_left template function in this post.
Why a new review is being asked for?
Please review recursive_fold_left_all and all suggestions are welcome.
Answer: This makes lots of unnecessary copies. It already starts with the function declaration:
constexpr auto recursive_fold_left_all(const T inputRange, I init, F f) | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
c++, recursion, template, constrained-templates, c++23
Because inputRange is passed by value, a copy is made before the function even starts. And since this is called recursively, copies are made at every recursion level. But it gets worse:
UL::recursive_transform<recursive_depth<T>() - 1>(…)
Your recursive_transform() function produces a new container as its output. This is a temporary copy that will hold values until a regular std::ranges::fold_left() will fold the items in it.
I see how you got here: you wanted to do the folding itself recursively. However, consider instead just recursively visiting each value in the input, and then applying the fold operation to each value. If you have a recursive_foreach(), then you can just write:
template<class T, class I, class F>
constexpr auto recursive_fold_left_all(const T& inputRange, I init, F f)
{
recursive_foreach(inputRange, [&](auto& value) {
init = std::invoke(f, init, value);
});
return init;
}
However, you can make a recursive version from scratch like so:
template<class T, class I, class F>
constexpr auto recursive_fold_left_all(const T& value, I init, F f) {
return std::invoke(f, init, value);
}
template<std::ranges::input_range T, class I, class F>
constexpr auto recursive_fold_left_all(const T& inputRange, I init, F f)
{
return std::ranges::fold_left(range, init, [&](auto& value) {
return recursive_fold_left_all(value, I{}, f);
});
}
Also note that in general, you should only need two overloads for recursive functions: the generic recursive case, and the terminal case. You should not need a third one. | {
"domain": "codereview.stackexchange",
"id": 44979,
"lm_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, constrained-templates, c++23",
"url": null
} |
python, reinventing-the-wheel, hash-map
Title: Implemented a basic dictionary in python using lists as linked list and murmur hash as a hash function
Question: import mmh3
from random_things import string_generator
class HashMap:
def __init__(self, num_of_buckets=4, load_factor=0.75):
assert (num_of_buckets >= 1)
self.num_of_buckets = num_of_buckets
self.mp = [[] for i in range(num_of_buckets)]
self.LOAD_FACTOR = load_factor
self.num_of_elements_in_ht = 0
self.longest_chain = [-1, -1]
def bucket(self, key, num_of_buckets):
k = mmh3.hash(key)
return k % num_of_buckets
# return HashMap.my_own_hash_function(key) % 3
def _does_it_need_resizing(self):
return self.num_of_elements_in_ht / self.num_of_buckets >= self.LOAD_FACTOR
def resize(self):
if self._does_it_need_resizing():
new_hash_table_size = self.num_of_buckets * 2
new_hash_table = [[] for i in range(new_hash_table_size)]
for linkedlist in self.mp:
for element in linkedlist:
bucket_index = self.bucket(element[0], new_hash_table_size)
new_hash_table[bucket_index].append(element)
if len(new_hash_table[bucket_index]) > self.longest_chain[0]:
self.longest_chain = [len(new_hash_table[bucket_index]), new_hash_table[bucket_index]]
self.num_of_buckets = new_hash_table_size
self.mp = new_hash_table | {
"domain": "codereview.stackexchange",
"id": 44980,
"lm_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, reinventing-the-wheel, hash-map",
"url": null
} |
python, reinventing-the-wheel, hash-map
def set(self, key, value):
bucket_index = self.bucket(key, self.num_of_buckets)
element = self._get(self.mp[bucket_index], key)
if element:
element[1] = value
return element
self.mp[bucket_index].append([key, value])
if len(self.mp[bucket_index]) > self.longest_chain[0]:
self.longest_chain = [len(self.mp[bucket_index]), self.mp[bucket_index]]
self.num_of_elements_in_ht += 1
self.resize()
return [key, value]
def _get(self, bucket, key):
for ele in bucket:
if ele[0] == key:
return ele
return None
def get(self, key):
bucket_index = self.bucket(key, self.num_of_buckets)
get_resp = self._get(self.mp[bucket_index], key)
return get_resp[1] if get_resp else None
def remove(self, key):
bucket_index = self.bucket(key, self.num_of_buckets)
for ele in self.mp[bucket_index]:
if ele[0] == key:
self.mp[bucket_index].remove(ele)
self.resize()
self.num_of_elements_in_ht -= 1
if len(self.mp[bucket_index]) < self.longest_chain[0]:
self.longest_chain = [len(self.mp[bucket_index]), self.mp[bucket_index]]
return
def get_the_entire_map(self):
return self.mp.copy()
@staticmethod
def my_own_hash_function(key):
return 0
def get_longest_chain(self):
return self.longest_chain
def num_of_elements(self):
return self.num_of_elements_in_ht
def keys(self):
k = []
for linkedlist in self.mp:
for element in linkedlist:
k.append(element[0])
return k | {
"domain": "codereview.stackexchange",
"id": 44980,
"lm_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, reinventing-the-wheel, hash-map",
"url": null
} |
python, reinventing-the-wheel, hash-map
def main():
mp = HashMap(2, load_factor=1)
# mp.set("my_string", "my_string")
# mp.set("my_string2", "my_string")
# mp.set("my_string3", "my_string")
# mp.set("my_string4", "my_string")
# mp.set("my_string5", "my_string")
# mp.set("my_string6", "my_string")
# mp.set("my_string7", "my_string")
# mp.set("my_string8", "my_string")
# print(f"Size of map {len(mp.get_the_entire_map())} and number of elements is : {mp.num_of_elements()}")
import time
import random
start = time.time()
while True:
for my_count, my_string in enumerate(string_generator(20, random.randint(10, 50000))):
mp.set(my_string, my_string)
mp.set(my_string, my_string)
if time.time() - start >= 1:
print(
f"Size of map {len(mp.get_the_entire_map())} and number of elements is : {mp.num_of_elements()}. Longest chain {mp.get_longest_chain()[0]}")
time.sleep(0.200)
# start = time.time()
for key in mp.keys():
mp.remove(key)
if time.time() - start >= 1:
print(
f"Size of map {len(mp.get_the_entire_map())} and number of elements is : {mp.num_of_elements()}. Longest chain {mp.get_longest_chain()[0]}")
time.sleep(0.200)
start = time.time()
mp = HashMap(2)
# for idx, val in enumerate(mp.get_the_entire_map()):
# print(idx, len(val))
# print(mp.set("my_string", "my_string1"))
# print(mp.get("my_string"))
if __name__ == "__main__":
main()
Answer: cite your references
from random_things import string_generator | {
"domain": "codereview.stackexchange",
"id": 44980,
"lm_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, reinventing-the-wheel, hash-map",
"url": null
} |
python, reinventing-the-wheel, hash-map
Answer: cite your references
from random_things import string_generator
What is the meaning of this?
We need a # comment in the source code describing its provenance.
Based on pep-8
and how you wrote this, you're telling the Gentle Reader
that this dep comes from a library outside of the current project.
If that's not accurate, use
isort
to clarify your intent.
(OTOH your reference to mmh3
was very clear, thank you, as MurmurHash is available on pypi.)
extra parens
def __init__(self, num_of_buckets=4, load_factor=0.75):
...
self.num_of_buckets = num_of_buckets
This is perfectly nice and bog standard.
Consider renaming the first parameter so we assign like this:
self.num_of_buckets = initial_num_of_buckets
That would stress that the caller is only offering a hint,
and is not bound to that many buckets over the map's lifetime.
assert (num_of_buckets >= 1)
No.
Please elide the extra ( ) parentheses.
Suppose we get a feature request in future for
displaying the actual number upon failure.
We wouldn't want to trick some poor maintenance engineer
into accidentally writing the following erroneous code:
assert (num_of_buckets >= 1, num_of_buckets)
comments where appropriate
self.longest_chain = [-1, -1]
That's rather cryptic.
Offer a hint about how to interpret that 2-tuple.
And consider using tuple rather than list.
Bonus points for a self-describing
namedtuple.
Later on the whole cryptic ele[0] thing is
tedious and would similarly benefit from
a self-describing datastructure.
self.mp = [[] for i in range(num_of_buckets)] | {
"domain": "codereview.stackexchange",
"id": 44980,
"lm_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, reinventing-the-wheel, hash-map",
"url": null
} |
python, reinventing-the-wheel, hash-map
Sorry, you lost me there.
No idea how I should mentally pronounce "mp".
Please offer the Gentle Reader a clue about those two words.
(I really hope it isn't a vowel-less form of "map".
To avoid shadowing a builtin we conventionally append
an _ underscore, giving map_.)
Similarly, tell us about "ht" (num_of_elements_in_ht).
Wouldn't you like to use the conventional name of size ?
EDIT
Further down in the code you reveal it is a Hash Table.
I'd been expecting Hash Map based on the class name, whatever.
use object attributes
def bucket(self, key, num_of_buckets):
k = mmh3.hash(key)
return k % num_of_buckets
Ummm, sorry, you lost me there.
Why did we pass in 2nd parameter?
Instead of return k % self.num_of_buckets ?
EDIT
OIC, resize could have doubled self.num_of_buckets early,
but instead chose to do it late.
Consider doing it earlier, prior to looping.
# return HashMap.my_own_hash_function(key) % 3
Commented out code is fine during debugging.
But you're requesting review for a PR merge-to-main,
and that's the right time to prune such things from the source
before showing it to others.
use accurate names
for linkedlist in self.mp:
I see what the identifier is trying to tell me,
but it's not clear to me that we have a
linked list
of nodes that each have a node.next field.
If you had wanted that, I would have expected the import of
deque.
def resize(self):
Consider renaming this to maybe_resize,
since often the call will be a no-op.
use a None sentinel
def _get(self, bucket, key):
...
return None
Wow, I didn't see that one coming.
A HashMap is like a dict,
but one cannot store a {"foo": None} value?!?
And set doesn't complain when given a None?
App-level programmers are going to want to use None.
Recommend you create your own none_sentinel = object()
so you can return and test against that.
@staticmethod
def my_own_hash_function(key):
return 0 | {
"domain": "codereview.stackexchange",
"id": 44980,
"lm_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, reinventing-the-wheel, hash-map",
"url": null
} |
python, reinventing-the-wheel, hash-map
@staticmethod
def my_own_hash_function(key):
return 0
World's greatest hash function, I know.
In a """docstring""" you might spell out that this
is for testing. Plus this gives you a great opportunity
to specify what you expect of a hash function,
e.g. whether negative return values are acceptable.
Minimally you should annotate:
def my_own_hash_function(key: str) -> int:
public attributes
def get_longest_chain(self):
return self.longest_chain
Ok, I bit my tongue on the map .copy() thing,
but this is even more silly.
This public method is absolutely not pulling its weight,
given that it offers access to a public attribute.
Either rename to self._longest_chain
or delete this method.
def num_of_elements(self):
return self.num_of_elements_in_ht
Yup, not getting that one, either.
I would expect this container to
conform to the Sized protocol,
so that len(my_map) would be
how an app developer accesses this.
Suggesting a name of def __len__.
offer a generator
def keys(self):
This method is lovely, thank you.
It allocates storage proportional to map size.
Consider offering a yield element[0] generator instead.
If someone really needs a list they can just request list(my_map.keys()),
same as they would for a dict.
loop where appropriate
# mp.set("my_string8", "my_string")
Same remark as above -- review time is when we clean up comments.
But even before you commented it out, a for loop would
have been a much more convenient way to stimulate
the system-under-test.
stress the code
enumerate(string_generator(20, ... | {
"domain": "codereview.stackexchange",
"id": 44980,
"lm_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, reinventing-the-wheel, hash-map",
"url": null
} |
python, reinventing-the-wheel, hash-map
stress the code
enumerate(string_generator(20, ...
I'm guessing we insert twenty keys.
That's great during manual testing when you're trying
to initially get things working, so you're not
visually overwhelmed by a data dump.
Now that it works and you're obtaining timings,
I encourage you to fill it with many more keys.
That way if an operation isn't O(1) or O(N)
it will show up in the timing data.
I'm concerned this code may be rather on the slow side.
Publishing a self-evaluating
test suite
as part of this codebase wouldn't hurt.
This code appears to achieve its objectives.
Given a few trivial renames I would be willing to
delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 44980,
"lm_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, reinventing-the-wheel, hash-map",
"url": null
} |
python, comparative-review
Title: Best practice of communicating with instruments using Python
Question: I have seen two different methods - getter and setter method and property - being used in Python libraries which are written for communicating with instruments via VISA commands. An example is given below.
import pyvisa-sim
import pyvisa
# Method 1
class Instument1():
def __init__(self, rsc_addr, rn):
self._rm = pyvisa.ResourceManager(rm)
self._rm.timeout = 25000
self.instr = self._rm.open_resource(rsc_addr)
def get_freq(self):
return self.instr.query("freq?")
def set_freq(self, freq):
self.instr.write(f"freq:{freq}Hz")
# Method 2
class Instument2():
def __init__(self, rsc_addr, rm):
self._rm = pyvisa.ResourceManager(rm)
self._rm.timeout = 25000
self.instr = self._rm.open_resource(rsc_addr)
@property
def freq(self):
return self.instr.query("freq?")
@freq.setter
def freq(self, freq):
self.instr.write(f"freq:{freq}Hz")
if __name__ == "__main__":
freq = 150*10**9
rm = pyvisa.ResourceManager(sim_fpath)
addr = rm.list_resources()[0]
inst1 = Instrument1(rsc_addr=addr,rm='@sim')
inst1.set_freq(freq)
f1 = inst1.get_freq()
inst2 = Instrument2(rsc_addr=addr,rm='@sim')
inst2.freq = freq
f2 = inst2.freq
They both do the job. I personally like the property method more than the getter and setter method because of how concise it is to access the functions. However, widely, people use property for interacting with class variables so I am wondering what people think about this. In addition to this, what can you do if you require an argument for the getter function if using property?
Answer: conventional spelling
class Instument1():
Please spell Instrument in the usual way.
Also, no need for those extra ( ) parens,
as you're not inheriting from anything beyond the default of object.
self._rm.timeout = 25000 | {
"domain": "codereview.stackexchange",
"id": 44981,
"lm_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, comparative-review",
"url": null
} |
python, comparative-review
It's not a big deal in this particular case,
but consider spelling it 25_000 to highlight that this
is 25 seconds.
Or consider phrasing it as 25e3 to emphasize
that this is a floating point number of milliseconds,
so values like float('inf') would also be acceptable.
Further down within the if __name__ guard,
you might find it convenient to express freq as 150e9.
document the Public API
def __init__(self, rsc_addr, rn):
Local variables can be short,
but formal parameters exposed by your Public API
carry a higher documentation burden.
Consider spelling out resource_addr
so there's still no need for a """docstring""".
Also, rn appears to be a typo for resource_mgr.
type hints help with documentation
def get_freq(self):
return self.instr.query("freq?")
def set_freq(self, freq):
self.instr.write(f"freq:{freq}Hz")
Consider adding optional type hints,
which mitigate the need for a """docstring""":
def get_freq(self) -> float:
return self.instr.query("freq?")
def set_freq(self, freq: float) -> None:
self.instr.write(f"freq:{freq}Hz")
Or, IDK, maybe those are actually integer quantities?
As someone calling into your library,
I would wish to resolve such ambiguities.
Maybe the type depends on what kind of resource address the ctor received?
Do you possibly wish to insist on serving just certain types of instruments?
So many questions, so few docstrings.
missing import
rm = pyvisa.ResourceManager(sim_fpath)
I don't know what sim_fpath means here.
make method call explicit
f2 = inst2.freq
time.sleep(0.5)
f3 = inst2.freq | {
"domain": "codereview.stackexchange",
"id": 44981,
"lm_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, comparative-review",
"url": null
} |
python, comparative-review
make method call explicit
f2 = inst2.freq
time.sleep(0.5)
f3 = inst2.freq
Yeah, I agree with you, this doesn't feel especially natural.
(Despite what my friends over in Ruby land might say.)
We have a volatile quantity that can change on its own.
My concern is that things happen in the real world and on the lab bench,
so the act of reading may take significant time or may have
side effects, we might raise an error.
A @property typically will be "safe" and "immediate" to compute,
even if a bit of logging happens while it does that.
It models an internal aspect of the object,
rather than an interaction with the outside world.
The explicit () function call of inst1.get_freq()
reminds the reader of what's going on.
what can you do if you require an argument for the getter function if using property?
Yeah, that's just not a good fit.
This is a theoretical question that lacks review context,
so I can't speak to what you had in mind.
So I will make up a question and answer that.
Suppose we could request an average power level observation
that is low or high precision, at a cost of 10 msec or 10 seconds
to make the measurement.
A getter would ask for inst1.get_avg_power(Precision.LOW).
A @property can only ask for inst2.avg_power,
so we'll have to encode the precision in either
a constructor optional keyword argument, or
a "precision mode select" side effect on the inst2 that came back | {
"domain": "codereview.stackexchange",
"id": 44981,
"lm_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, comparative-review",
"url": null
} |
algorithm, strings, ruby, file
Title: Print last lines of file
Question: Task
Write a Ruby function, which accepts a path to a text file and returns a string consisting of the last n lines in reversed order, separated by commas.
Example input file:
0. Line of Text
1. Line of Text
2. Line of Text
3. Line of Text
4. Line of Text
5. Line of Text
6. Line of Text
7. Line of Text
8. Line of Text
9. Line of Text
My solution
def print_last_lines(filename, n)
lines = File.readlines(filename).last n # Get last n-lines
lines = lines.reverse # Reverse the order
lines.map! do |line|
line.chomp # Remove the line-breaks
end
lines.join ", " # Concatenate the lines together
end
require "./exercises/print_last_lines.rb"
puts print_last_lines "/Library/WebServer/Documents/ruby-playground/input.txt", 3
# Returns: '9. Line of Text, 8. Line of Text, 7. Line of Text'
The function provides the correct results for the examples which are provided with the exercise sheet. So I think my solution is formally correct.
What could become improved?
Would you have implemented the function differently? If yes: How and why?
Answer: If you are trying to show idiomatic Ruby maybe something like
def last_lines(filename, n)
File.readlines(filename)
.last(n)
.reverse
.map(&:chomp)
.join(', ')
end
The changes I made were
Removed 'print' from the method name. The method doesn't print anything
remove intermediate variables and avoid using the modifying map!
use parentheses around arguments
You can pass a method name to map
Most Ruby standards opt for single quoted strings when possible
As Toby mentioned you should at least add a comment that this is not optimal for large files | {
"domain": "codereview.stackexchange",
"id": 44982,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, strings, ruby, file",
"url": null
} |
c++, c++20
Title: C++ System data transfer design - Following 1
Question: Based on the previous question regarding Data transfer design, here's a major updated code per G. Sliepen's Answer recommendation per std::variant:
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <span>
#include <string_view>
#include <variant>
#include <functional>
#include <cstdint>
#include <unordered_map>
enum class RequestErrors : uint8_t
{
OK,
NOT_FOUND,
};
using DataReference = std::variant<std::string_view, std::span<uint8_t>>;
using Data = std::variant<std::string, std::vector<uint8_t>>;
using DataReferenceContainer = std::vector<DataReference>;
using DataContainer = std::vector<Data>;
class RequestPayload
{
DataReferenceContainer ploads;
public:
std::size_t size() const { return ploads.size(); };
auto begin() const { return ploads.begin(); }
auto end() const { return ploads.end(); }
auto& front() const { return ploads.front(); }
auto& back() const { return ploads.back(); }
auto& getVector() const { return ploads; } | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
auto& getVector() const { return ploads; }
RequestPayload(const char *str) : ploads(DataReferenceContainer{std::string_view{str}}) {}
RequestPayload(const char *str, size_t len) : ploads(DataReferenceContainer{std::string_view{str, len}}) {}
RequestPayload(const std::string &str) : ploads(DataReferenceContainer{str}) {}
RequestPayload(const std::string_view sv) : ploads(DataReferenceContainer{sv}) {}
RequestPayload(std::vector<uint8_t> &vec) : ploads(DataReferenceContainer{std::span<uint8_t>{vec.begin(), vec.size()}}) {}
RequestPayload(std::span<uint8_t> span) : ploads(DataReferenceContainer{span}) {}
RequestPayload(std::initializer_list<DataReference> list) : ploads(list) {}
RequestPayload(const DataReferenceContainer &ref) : ploads(ref) {}
};
class ConcreteData
{
DataContainer rets;
public:
std::size_t size() const { return rets.size(); };
auto begin() const { return rets.begin(); }
auto end() const { return rets.end(); }
auto& front() const { return rets.front(); }
auto& back() const { return rets.back(); }
auto& getVector() { return rets; }
ConcreteData(const char *str) : rets(DataContainer{std::string{str}}) {}
ConcreteData(const char *str, size_t len) : rets(DataContainer{std::string{str, len}}) {}
ConcreteData(const std::string &str) : rets(DataContainer{str}) {}
ConcreteData(const std::string_view sv) : rets(DataContainer{std::string(sv.data(), sv.length())}) {}
ConcreteData(std::vector<uint8_t> &vec) : rets(DataContainer{vec}) {}
ConcreteData(std::span<uint8_t> span) : rets(DataContainer{std::vector<uint8_t>{span.begin(), span.end()}}) {}
ConcreteData(std::initializer_list<Data> list) : rets(list) {}
ConcreteData(const DataContainer &ref) : rets(ref) {} | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
ConcreteData(const RequestPayload &rhs)
{
for (auto &reqData : rhs.getVector())
{
if (auto *rd = std::get_if<std::string_view>(&reqData))
{
std::string d{rd->data(), rd->size()};
rets.emplace_back(d);
}
else if (auto *rd = std::get_if<std::span<uint8_t>>(&reqData))
{
std::vector<uint8_t> d{rd->begin(), rd->end()};
rets.emplace_back(d);
}
}
}
ConcreteData& operator=(const RequestPayload &rhs)
{
// No need to check (this!=&rhs).
rets.clear();
rets.shrink_to_fit();
auto& rhsVec = rhs.getVector();
rets.reserve(rhsVec.size());
for (auto &reqData : rhsVec)
{
if (auto *rd = std::get_if<std::string_view>(&reqData))
{
std::string d{rd->data(), rd->size()};
rets.emplace_back(d);
}
else if (auto *rd = std::get_if<std::span<uint8_t>>(&reqData))
{
std::vector<uint8_t> d{rd->begin(), rd->end()};
rets.emplace_back(d);
}
}
return *this;
}
};
using ReturnData = ConcreteData;
using RequestReturn = std::pair<RequestErrors, ReturnData>;
using CallbackSignature = std::function<RequestReturn(const std::string &context, const RequestPayload &)>;
/* Simplified SystemInterface */
class SystemInterface
{
std::unordered_map<std::string, CallbackSignature> requests;
public:
void addRequest(const std::string &name, CallbackSignature cbf)
{
requests[name] = cbf;
}
RequestReturn execCmd(const std::string &name, const std::string &context, const RequestPayload &payload)
{
if (requests.count(name))
{
return requests[name](context, payload);
}
return std::make_pair(RequestErrors::NOT_FOUND, DataContainer{});
}
}; | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
Here's a working example based on this codebase.
I appreciate any kind of feedback.
Answer: #include Headers in Alphabetical Order
Or group them into categories, like angled <headers> first followed by quoted "header.h", keeping each category in order. That makes it much easier to spot when a header is already included or not.
Spell Identifiers Correctly
You didn’t dump all of namespace std into the global namespace. You also used <cstdint> instead of <stdint.h> Bravo, kudos, and yasher koach!
However, that means you should be using std::uint8_t instead of uint8_t. Implementations are allowed to make uint8_t an alias for std::uint8_t, and I believe all the popular ones do, but it’s not technically standard-conforming unless you write using std::uint8_t;. And you don’t want a header file you write to pollute the global namespave.
About Those Constructors
You currently have:
ConcreteData(const char *str)
ConcreteData(const char *str, size_t len)
ConcreteData(const std::string &str)
ConcreteData(const std::string_view sv)
ConcreteData(std::vector<uint8_t> &vec)
ConcreteData(std::span<uint8_t> span)
ConcreteData(std::initializer_list<Data> list)
ConcreteData(const DataContainer &ref)
There are a number of errors here.
Add Back the Default, Copy and Move Constructors
Because you wrote constructors of your own, the compiler will not create any default constructors, so for example you can no longer declare
RequestPayload payload;
You’ve also made your class uncopyable and unmoveable. Re-enable these constructors with = default:
RequestPayload() = default;
RequestPayload(const RequestPayload&) = default;
RequestPayload(RequestPayload&&) = default;
One of your classes also declares an assignment operator, and you should also declare these by the Rule of Five:
RequestPayload& operator=(const RequestPayload&) = default;
RequestPayload& operator=(RequestPayload&&) = default;
~RequestPayload() = default; // Must be virtual if you intend to make this a base class. | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
Make Constructors explicit (if Appropriate)
One of the few that cannot be explicit is the initializer-list, since you will typically want to initialize from one variant and not have to write out the conversion to Data explicitly:
const ConcreteData dataList = {"hello"s,
"world"s,
std::vector<std::uint8_t>{1,2,3}};
Another useful one to not make explicit is the converting constructor from const std::string_view, since that’s an efficient conversion from many stringy types that store their data contiguously. Having saves you from writing another converting constructor for const std::string& (although you might want an explicit move constructor from std::string&&). In my opinion, many std::string conversions are too expensive to happen implicitly.
For most of the others, you do not want surprises. For example, you might not want to have every type with a conversion to std::string use it implicitly.
Use Move Constructors Whenever Possible
Your internal rets is a std::vector, which is moveable. Furthermore, it's a std::vector of a std::variant of moveable types. This implies that you should be writing converting constructors with move overloads, and let the compiler implement things like assignment operators from those.
Consider Adding Template Converting Constructors
This can get a little complicated, but let’s walk through ConcreteData as an example.
First, all of these examples will get much easier to read if we define a few helper templates:
// A counterpart to std::same as that compares the underlying types.
// Suitable for checking the value types of ranges.
template<typename T, typename U>
concept different_from = !std::same_as<std::remove_cvref_t<T>, std::remove_cvref_t<U>>;
// Dereferences a multi-dimensional range by one level.
template<std::ranges::input_range T>
using row_t = std::remove_cvref_t<std::ranges::range_value_t<T>>; | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
// Dereferences a multi-dimensional range by two levels.
template<class T>
requires (std::ranges::input_range<T> &&
std::ranges::input_range<row_t<T>>)
using column_t = std::remove_cvref_t<
std::ranges::range_value_t<
std::ranges::range_value_t<T>>>;
// A range whose elements can be moved.
template<class T, typename Data>
concept container_of_movable =
std::ranges::input_range<T> &&
std::indirectly_movable<std::ranges::iterator_t<T>, Data*>;
Right now, you have an assignment operator from RequestPayload to ConcreteData. First, this should be a converting constructor. Second, it isn’t really a conversion from RequestPayload only. There’s no reason you couldn’t convert from a DataReferenceContainer instead. Or any other container that holds DataReference objects: the logic is identical. You iterate over begin and end, so the concept you want here is a range with the appropriate value type. One possible implementation:
// Initializes a list from a container of DataReference
template<class T> requires
std::same_as<row_t<T>, DataReference>
constexpr ConcreteData(const T& source) {
for (const auto& x : source) {
if (std::holds_alternative<std::string_view>(x)) {
rets.emplace_back(std::string{std::get<std::string_view>(x)});
} else if (std::holds_alternative<std::span<std::uint8_t>>(x)) {
const auto span = std::get<std::span<std::uint8_t>>(x);
rets.emplace_back(std::vector<std::uint8_t>{span.begin(), span.end()});
} else { // Unreachable!
std::cout.flush(); // Don't cross the streams!
std::cerr << "Logic Error: a DataReference held an impossible type!\n";
std::abort();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
We also want to be able to copy from any container or range of Data, not just the DataContainer type:
// Initializes a list from a range of Data
template<class T> requires
std::same_as<row_t<T>, Data>
constexpr ConcreteData(const T& source) {
for (const auto& x : source) {
rets.emplace_back(x);
}
}
You currently have a
ConcreteData(const DataContainer &ref) : rets(ref) {}
This is incorrect: it can neither read a const DataContainer&, nor does it optimize to a move constructor when it can, nor does it constant-fold an empty container. Replace it with:
explicit constexpr ConcreteData(DataContainer &&ref) : rets{std::move(ref)} {}
You also, as mentioned earlier, should declare a default move constructor, as:
ConcreteData(ConcreteData&&) = default;
The copy constructor we already implemented can cover the versions of both that copy instead of moving.
Now, the last two constructors cover the case where you can move from the source container to the destination container, but even when you can’t do that, you might be able to move each item from the source container, one by one. It is much better to move a large number of strings and vectors than make deep copies of all the data you’re about to discard anyway!
// Initializes a list from a range of moveable objects
template<class T> requires
container_of_movable<T, Data>
constexpr ConcreteData(T&& source) {
for (auto&& x : source) {
rets.emplace_back(std::move(x));
}
} | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
Finally, it would be convenient to be able to initialize our container of Data objects from two-dimensional containers, depending on whether their contents are stringy or not. If we take any two-dimensional container of char as a container of stringy things, those might look like:
// Initialize a list from a range of byte ranges:
template<class T> requires (
std::convertible_to<column_t<T>, std::uint8_t> &&
different_from<column_t<T>, char>)
constexpr ConcreteData(const T& source) {
for (const auto& x : source) {
rets.emplace_back(std::vector<std::uint8_t>{std::ranges::begin(x), std::ranges::end(x)});
}
}
// Initializes a list from a range of stringy types:
template<class T> requires
std::same_as<column_t<T>, char>
constexpr ConcreteData(const T& source) {
for (const auto& x : source) {
rets.emplace_back(std::string{std::ranges::begin(x), std::ranges::end(x)});
}
}
You might not want these, especially if your implementation defines both char and uint8_t as aliases for unsigned char. If you prefer, you can make the byte data std::byte or make the condition that the rows convert to std::string.
Use constexpr and noexcept Where Applicable
These can improve optimization.
Add const Overloads
You need these to be able to do anything useful on const instances. For example, it is currently not possible to call getContainer() on a const instance of ConcreteData. You want:
constexpr auto& getvector() noexcept { return rets; }
constexpr const auto& getVector() const noexcept { return rets; } | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
Implement Equality Operators
The default operator== will work, although I prefer to explicitly default them. However, you have a large number of classes that are comparable with each other: it should, for example, be possible to compare a DataContainer and ConcreteData. or RequestPayload.
In cases like this, for overloads to resolve correctly, you want to declare the equality operator as a non-member function. A possible implementation is:
constexpr bool operator==(const ConcreteData& left, const DataContainer& right) noexcept {
return left.getVector() == right;
}
constexpr bool operator==(const DataContainer& left, const ConcreteData& right) noexcept {
return left == right.getVector();
}
If you didn’t add a const overload for getVector(), you would need to declare these friend functions in DataContainer.
Once you do this, the compiler will add != automatically.
Add swap as Member and Non-Member Functions
Some compilers (such as Clang) will do this for you automatically, but I don’t believe that’s portable, and many algorithms use swap. Always implement this whenever you can do so efficiently.
Return a variant or optional, not a pair
You currently have
using RequestReturn = std::pair<RequestErrors, ReturnData>;
where
enum class RequestErrors : uint8_t
{
OK,
NOT_FOUND,
}; | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
However, the return value is always either valid data or an error, not both. This means it should be a std::variant, not a std::pair.
Returning a sum type like std::variant means you no longer need an OK error value: the absence of an error is instead represented by the return value holding something other than RequestErrors.
But that means that there is only one possible value of RequestErrors. If that’s only because this is a simplified example where you left the other possible errors out, you can keep the class. However, if the class doesn’t store any useful information about the error (that a program can act on, and could not deduce from the mere fact that an error occurred at that point), there is no need for it to exist. You could return a std::optional<ReturnData> instead, and let .has_value() indicate success.
Consider Generic Invocable Callbacks
You mention in a comment that the SystemInterface is “simplified,” so I’m not sure whether or not changing CallbackSignature to a generic std::invocable template parameter would get you anything, or just be needless complication. I suspect the latter. If you’re always passing an object-instance pair, though, it might be slightly more efficient to store std::bind of a member funtion and instance pointer than a std::function.
Implement the Rest of the Container Interface
You’ve implemented enough of the interface that it’s annoying to have to remember what’s not included, and you should just implement every other part of it that people actually use.
Consider Removing the Classes and Using Vectors | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
Consider Removing the Classes and Using Vectors
Really, RequestPayload and ConcreteData have are-a relationships to std::vector: THey’re vectors plus some extra constructors that can be passed to certain parts of your API. The implementation uses a lot of boilerplate just to say that multiple classes are vectors with some extra containers. It your implementation supports it, it would be more efficient to instead have them inherit from std::vector than to say, line by line, that it implements each and every part of the vector class by forwarding it to its one data member.
You might also replace the special constructors with factory functions that return std::vector, since that is how you implement all the converting constructors anyway.
If you intentionally don’t want to allow inserting items into a ConcreteData or RequestPayload instance after it is constructed, you can delete or override those member functions.
Putting it All Together
Here’s a starting-point that primarily makes changes to ConcreteData.
#include <cassert>
#include <concepts>
#include <cstdint>
#include <functional>
#include <iostream>
#include <iterator>
#include <ranges>
#include <span>
#include <string>
#include <string_view>
#include <unordered_map>
#include <utility>
#include <variant>
#include <vector> | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
// A counterpart to std::same as that compares the underlying types.
// Suitable for checking the value types of ranges.
template<typename T, typename U>
concept different_from = !std::same_as<std::remove_cvref_t<T>, std::remove_cvref_t<U>>;
// Dereferences a multi-dimensional range by one level.
template<std::ranges::input_range T>
using row_t = std::remove_cvref_t<std::ranges::range_value_t<T>>;
// Dereferences a multi-dimensional range by two levels.
template<class T>
requires (std::ranges::input_range<T> &&
std::ranges::input_range<row_t<T>>)
using column_t = std::remove_cvref_t<
std::ranges::range_value_t<
std::ranges::range_value_t<T>>>;
// A range whose elements can be moved.
template<class T, typename Data>
concept container_of_movable =
std::ranges::input_range<T> &&
std::indirectly_movable<std::ranges::iterator_t<T>, Data*>;
enum class RequestErrors : uint8_t
{
OK,
NOT_FOUND,
};
using DataReference = std::variant<std::string_view, std::span<uint8_t>>;
using Data = std::variant<std::string, std::vector<std::uint8_t>>;
using DataReferenceContainer = std::vector<DataReference>;
using DataContainer = std::vector<Data>;
class RequestPayload
{
DataReferenceContainer ploads;
public:
std::size_t size() const { return ploads.size(); };
auto begin() const { return ploads.begin(); }
auto end() const { return ploads.end(); }
auto& front() const { return ploads.front(); }
auto& back() const { return ploads.back(); }
auto& getVector() const { return ploads; } | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
auto& getVector() const { return ploads; }
RequestPayload() = default;
RequestPayload(const RequestPayload&) = default;
RequestPayload(RequestPayload&&) = default;
RequestPayload& operator=(const RequestPayload&) = default;
RequestPayload& operator=(RequestPayload&&) = default;
~RequestPayload() = default; // Must be virtual if you intend to make this a base class.
RequestPayload(const char *str) : ploads(DataReferenceContainer{std::string_view{str}}) {}
RequestPayload(const char *str, size_t len) : ploads(DataReferenceContainer{std::string_view{str, len}}) {}
RequestPayload(const std::string &str) : ploads(DataReferenceContainer{str}) {}
RequestPayload(const std::string_view sv) : ploads(DataReferenceContainer{sv}) {}
RequestPayload(std::vector<uint8_t> &vec) : ploads(DataReferenceContainer{std::span<uint8_t>{vec.begin(), vec.size()}}) {}
RequestPayload(std::span<uint8_t> span) : ploads(DataReferenceContainer{span}) {}
RequestPayload(std::initializer_list<DataReference> list) : ploads(list) {}
RequestPayload(const DataReferenceContainer &ref) : ploads(ref) {}
};
class ConcreteData
{
DataContainer rets;
public:
using iterator = typename decltype(rets)::iterator;
using const_iterator = typename decltype(rets)::const_iterator;
using pointer = typename decltype(rets)::pointer;
using const_pointer = typename decltype(rets)::const_pointer;
using reference = typename decltype(rets)::reference;
using const_reference = typename decltype(rets)::const_reference;
using value_type = typename decltype(rets)::value_type; | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
constexpr std::size_t size() const noexcept { return rets.size(); };
constexpr iterator begin() noexcept {return rets.begin();}
constexpr const_iterator begin() const noexcept { return rets.begin(); }
constexpr iterator end() noexcept {return rets.end();}
constexpr const_iterator end() const noexcept { return rets.end(); }
constexpr reference front() noexcept { return rets.front(); }
constexpr const_reference front() const noexcept { return rets.front(); }
constexpr reference back() noexcept { return rets.back(); }
constexpr const_reference back() const noexcept { return rets.back(); }
constexpr pointer data() noexcept {return rets.data();}
constexpr const_pointer data() const noexcept {return rets.data();}
constexpr auto& getvector() noexcept { return rets; }
constexpr const auto& getVector() const noexcept { return rets; } // TODO: You should implement the rest of the container interface.
// TODO: You should implement all of the container interface.
ConcreteData() = default;
ConcreteData(const ConcreteData&) = default;
ConcreteData(ConcreteData&&) = default;
explicit constexpr ConcreteData(const char *str, size_t len) : rets{std::string{str, len}} {}
explicit constexpr ConcreteData(const char *str) : rets{std::string{str}} {}
constexpr ConcreteData(std::initializer_list<Data> list) : rets{list} {}
explicit constexpr ConcreteData(DataContainer &&ref) : rets{std::move(ref)} {}
constexpr ConcreteData(const std::string_view str) : rets{std::string{str}} {}
explicit constexpr ConcreteData(std::string&& str) : rets{std::move(str)} {}
explicit constexpr ConcreteData(std::vector<std::uint8_t>&& vec) : rets{std::move(vec)} {}
template<std::size_t N>
constexpr ConcreteData(const char (&str)[N]) : rets{std::string{str, N}} {} | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
// Initialize a singleton list from a range of bytes:
template<class T>
requires (std::ranges::input_range<T> &&
std::convertible_to<row_t<T>, std::uint8_t> &&
!std::convertible_to<T, std::string_view> &&
different_from<T, DataContainer> &&
different_from<T, ConcreteData>)
constexpr ConcreteData(const T& source)
: rets{std::vector<std::uint8_t>{std::ranges::begin(source), std::ranges::end(source)}}
{}
// Initialize a list from a range of byte ranges:
template<class T> requires (
std::convertible_to<column_t<T>, std::uint8_t> &&
different_from<column_t<T>, char>)
constexpr ConcreteData(const T& source) {
for (const auto& x : source) {
rets.emplace_back(std::vector<std::uint8_t>{std::ranges::begin(x), std::ranges::end(x)});
}
}
// Initializes a list from a range of stringy types:
template<class T> requires
std::same_as<column_t<T>, char>
constexpr ConcreteData(const T& source) {
for (const auto& x : source) {
rets.emplace_back(std::string{std::ranges::begin(x), std::ranges::end(x)});
}
}
// Initializes a list from a range of Data
template<class T> requires
std::same_as<row_t<T>, Data>
constexpr ConcreteData(const T& source) {
for (const auto& x : source) {
rets.emplace_back(x);
}
} | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
// Initializes a list from a container of DataReference
template<class T> requires
std::same_as<row_t<T>, DataReference>
constexpr ConcreteData(const T& source) {
for (const auto& x : source) {
if (std::holds_alternative<std::string_view>(x)) {
rets.emplace_back(std::string{std::get<std::string_view>(x)});
} else if (std::holds_alternative<std::span<std::uint8_t>>(x)) {
const auto span = std::get<std::span<std::uint8_t>>(x);
rets.emplace_back(std::vector<std::uint8_t>{span.begin(), span.end()});
} else { // Unreachable!
std::cout.flush(); // Don't cross the streams!
std::cerr << "Logic Error: a DataReference held an impossible type!\n";
std::abort();
}
}
}
// Initializes a list from a range of moveable objects
template<class T> requires
container_of_movable<T, Data>
constexpr ConcreteData(T&& source) {
for (auto&& x : source) {
rets.emplace_back(std::move(x));
}
}
constexpr void swap(ConcreteData& other) noexcept {
rets.swap(other.rets);
}
ConcreteData& operator=(const ConcreteData&) = default;
ConcreteData& operator=(ConcreteData&&) = default;
bool operator==(const ConcreteData&) const = default;
~ConcreteData() = default; // Needs to be virtual if this is a base class.
};
constexpr void swap(ConcreteData& x, ConcreteData& y) noexcept {
x.swap(y);
}
constexpr bool operator==(const ConcreteData& left, const DataContainer& right) noexcept {
return left.getVector() == right;
}
constexpr bool operator==(const DataContainer& left, const ConcreteData& right) noexcept {
return left == right.getVector();
}
using ReturnData = ConcreteData;
using RequestReturn = std::pair<RequestErrors, ReturnData>; | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
using ReturnData = ConcreteData;
using RequestReturn = std::pair<RequestErrors, ReturnData>;
using CallbackSignature = std::function<RequestReturn(const std::string &context, const RequestPayload &)>;
/* Simplified SystemInterface */
class SystemInterface
{
std::unordered_map<std::string, CallbackSignature> requests;
public:
void addRequest(const std::string &name, CallbackSignature cbf)
{
requests[name] = cbf;
}
RequestReturn execCmd(const std::string &name, const std::string &context, const RequestPayload &payload)
{
if (requests.count(name))
{
return requests[name](context, payload);
}
return std::make_pair(RequestErrors::NOT_FOUND, ConcreteData{});
}
};
And a very basic test driver with only partial coverage:
using namespace std::literals::string_literals;
using namespace std::literals::string_view_literals;
using std::uint8_t;
static_assert(std::indirectly_movable<std::ranges::iterator_t<std::vector<std::vector<uint8_t>>&&>, std::vector<uint8_t>*>); | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, c++20
int main()
{
constexpr char hello[] = "hello, world!";
const ConcreteData data1 = hello;
const ConcreteData dataList = {"hello"s,
"world"s,
std::vector<std::uint8_t>{1,2,3}};
constexpr uint8_t matrix[3][3] = {{1,2,3}, {4,5,6}, {7,8,9}};
const ConcreteData dataMatrix = matrix;
constexpr std::string_view string_table[] = {"hello"sv, "world!"sv};
const ConcreteData dataStrins = string_table;
const ConcreteData fromContainer = DataContainer{"hello"s, "world"s};
std::string tempArray[] = {"hello"s, "world"s};
const ConcreteData fromTempArray = std::move(tempArray);
uint8_t toSpan[] = {1, 2, 3};
const DataReferenceContainer refs = {"hello"sv,
"world"sv,
std::span<uint8_t>{toSpan}};
const ConcreteData fromRefs = refs;
assert(fromRefs != DataContainer{});
assert(DataContainer{} != fromRefs);
const DataReference refArray[] = {"hello"sv,
"world"sv,
std::span<uint8_t>{toSpan}};
const ConcreteData fromRefArray = refArray;
assert(fromRefs == fromRefArray);
ConcreteData copyData = fromRefArray;
const ConcreteData moveData = std::move(fromRefArray);
return EXIT_SUCCESS;
}
And a link to the Godbolt compiler explorer. | {
"domain": "codereview.stackexchange",
"id": 44983,
"lm_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++20",
"url": null
} |
c++, beginner, unit-testing, socket
Title: Multi-Client Socket Communication with Thread Pool in C++
Question: I've been working on implementing a multi-client socket communication system with a thread pool in C++. The system comprises three main components: logger.h, socket.h, and thread.h, which handle logging, socket operations, and thread pooling respectively. Additionally, I have a test suite tests_multisock.cpp that verifies the functionality of the system.
The code has been designed to facilitate communication between multiple clients and a server using sockets. I'd greatly appreciate your expertise in reviewing my code for any potential issues, optimizations, or areas of improvement. I've outlined a brief summary of the components and included a snippet of the test code for context. If you have any suggestions or feedback, I'm eager to hear them.
Components:
logger.h: A logging class for capturing events and errors.
socket.h: A socket class to manage socket communication, supporting functions like creating, binding, listening, accepting, and sending/receiving data.
thread.h: A thread pool class to handle concurrent execution of tasks.
Test Suite:
tests_multisock.cpp: A suite of tests that validates the functionality of the multi-client socket communication and thread pool system.
include.h
#pragma once
#include <iostream>
#include <vector>
#include <queue>
#include <thread>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <ctime>
#include <string>
#include <fstream>
#include <thread>
#include <WinSock2.h>
#include <Ws2tcpip.h>
logger.h
#pragma once
#include "include.h"
enum class LogLevel
{
DEBUG,
INFO,
WARNING,
ERR
};
class Logger
{
public:
Logger(LogLevel minLogLevel = LogLevel::INFO, const std::string& fileName = "default_log.txt")
: minLogLevel(minLogLevel), fileName(fileName)
{
SetLogFile(fileName);
} | {
"domain": "codereview.stackexchange",
"id": 44984,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, unit-testing, socket",
"url": null
} |
c++, beginner, unit-testing, socket
~Logger()
{
if (logFile.is_open())
{
logFile.close();
}
}
void SetLogFile(const std::string& filename)
{
logFile.open(filename, std::ios::app);
if (!logFile.is_open())
{
std::cerr << "Failed to open log file: " << filename << std::endl;
}
}
void Log(LogLevel level, const char* file, int line, const std::string& message)
{
if (level >= minLogLevel)
{
std::string logEntry = GetTimeStamp() + " [" + LogLevelToString(level) + "] " + message +
" [" + file + ":" + std::to_string(line) + "]" + "\n";
std::cout << logEntry;
if (logFile.is_open())
{
logFile << logEntry;
logFile.flush();
}
}
}
std::string GetLogFile() const
{
return fileName;
}
private:
LogLevel minLogLevel;
std::ofstream logFile;
std::string fileName;
std::string LogLevelToString(LogLevel level) const
{
switch (level)
{
case LogLevel::DEBUG: return "DEBUG";
case LogLevel::INFO: return "INFO";
case LogLevel::WARNING: return "WARNING";
case LogLevel::ERR: return "ERROR";
default: return "UNKNOWN";
}
}
std::string GetTimeStamp() const
{
std::time_t now = std::time(nullptr);
char timestamp[20];
struct tm timeinfo;
#ifdef _WIN32
localtime_s(&timeinfo, &now);
#else
localtime_r(&now, &timeinfo);
#endif
std::strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", &timeinfo);
return timestamp;
}
};
thread.h
#include "logger.h"
class ThreadPool {
public:
ThreadPool(int numThreads, Logger& logger) : logger(logger), stop(false) {
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back([this]() { ThreadFunction(); });
}
} | {
"domain": "codereview.stackexchange",
"id": 44984,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, unit-testing, socket",
"url": null
} |
c++, beginner, unit-testing, socket
~ThreadPool() {
{
std::unique_lock<std::mutex> lock(mutex);
stop = true;
}
condition.notify_all();
for (std::thread& thread : threads) {
thread.join();
}
}
void Enqueue(std::function<void()> task) {
{
std::unique_lock<std::mutex> lock(mutex);
tasks.push(task);
}
condition.notify_one();
}
private:
void ThreadFunction() {
while (true) {
std::function<void()> task;
{
std::unique_lock<std::mutex> lock(mutex);
condition.wait(lock, [this]() { return stop || !tasks.empty(); });
if (stop && tasks.empty()) {
return;
}
task = tasks.front();
tasks.pop();
}
try {
logger.Log(LogLevel::DEBUG, __FILE__, __LINE__, "Task started.");
task();
logger.Log(LogLevel::DEBUG, __FILE__, __LINE__, "Task completed.");
}
catch (const std::exception& ex) {
logger.Log(LogLevel::DEBUG, __FILE__, __LINE__, "Task error: " + std::string(ex.what()));
}
}
}
private:
Logger& logger; // Reference to your Logger instance
std::vector<std::thread> threads;
std::queue<std::function<void()>> tasks;
std::mutex mutex;
std::condition_variable condition;
bool stop;
};
socket.h
#include "logger.h"
class Socket
{
public:
Socket(Logger& logger) : logger(logger) {}
bool Create()
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
logger.Log(LogLevel::WARNING, __FILE__, __LINE__, "WSAStartup failed");
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44984,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, unit-testing, socket",
"url": null
} |
c++, beginner, unit-testing, socket
m_socket = socket(AF_INET, SOCK_STREAM, 0);
if (m_socket == INVALID_SOCKET)
{
logger.Log(LogLevel::WARNING, __FILE__, __LINE__, "Failed to create socket: " + std::to_string(WSAGetLastError()));
return false;
}
return true;
}
bool Bind(int port)
{
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
hint.sin_addr.s_addr = INADDR_ANY;
return bind(m_socket, (sockaddr*)&hint, sizeof(hint)) != SOCKET_ERROR;
}
bool Listen()
{
return listen(m_socket, SOMAXCONN) != SOCKET_ERROR;
}
bool Accept(Socket& clientSocket)
{
SOCKET client = accept(m_socket, nullptr, nullptr);
if (client != INVALID_SOCKET)
{
clientSocket.m_socket = client;
return true;
}
return false;
}
bool Connect(const char* ipAddress, int port)
{
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
if (inet_pton(AF_INET, ipAddress, &hint.sin_addr) <= 0)
{
// Handle error, unable to convert IP address
return false;
}
return connect(m_socket, (sockaddr*)&hint, sizeof(hint)) != SOCKET_ERROR;
}
int Send(const char* data, int dataSize)
{
return send(m_socket, data, dataSize, 0);
}
int Receive(char* buffer, int bufferSize)
{
return recv(m_socket, buffer, bufferSize, 0);
}
void Close()
{
if (m_socket != INVALID_SOCKET)
{
closesocket(m_socket);
m_socket = INVALID_SOCKET;
logger.Log(LogLevel::DEBUG, __FILE__, __LINE__, "Socket closed.");
}
}
bool SendHttpRequest(const std::string& url, int port, const std::string& httpRequest, std::string& httpResponse)
{
if (!Create())
{
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44984,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, unit-testing, socket",
"url": null
} |
c++, beginner, unit-testing, socket
if (!Connect(url.c_str(), port))
{
return false;
}
if (Send(httpRequest.c_str(), httpRequest.size()) != static_cast<int>(httpRequest.size()))
{
return false;
}
const int bufferSize = 1024;
char recvBuffer[bufferSize];
httpResponse.clear();
int bytesRead = 0;
do
{
bytesRead = Receive(recvBuffer, bufferSize);
if (bytesRead > 0)
{
httpResponse.append(recvBuffer, bytesRead);
}
} while (bytesRead > 0);
return true;
}
private:
SOCKET m_socket;
Logger& logger; // Reference to the Logger instance
};
tests_multisock.cpp
#include "logger.h"
#include "socket.h"
#include "thread.h"
#include <gtest/gtest.h>
class MultiClientCommunicationTest : public testing::Test {
protected:
Logger logger;
void SetUp() override {}
void TearDown() override {}
};
TEST_F(MultiClientCommunicationTest, MultipleClients) {
Logger serverLogger(LogLevel::DEBUG, "server_log.txt");
Logger clientLogger(LogLevel::DEBUG, "client_log.txt");
// Start a server thread
std::thread serverThread([&serverLogger]() {
Socket serverSocket(serverLogger);
ASSERT_TRUE(serverSocket.Create());
ASSERT_TRUE(serverSocket.Bind(12345));
ASSERT_TRUE(serverSocket.Listen());
serverLogger.Log(LogLevel::DEBUG, __FILE__, __LINE__, "Server listening");
ThreadPool threadPool(50, serverLogger);
for (int i = 0; i < 50; ++i) {
threadPool.Enqueue([&serverSocket, i, &serverLogger]() {
Socket clientSocket(serverLogger);
ASSERT_TRUE(serverSocket.Accept(clientSocket));
serverLogger.Log(LogLevel::DEBUG, __FILE__, __LINE__, "Server accepted client connection"); | {
"domain": "codereview.stackexchange",
"id": 44984,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, unit-testing, socket",
"url": null
} |
c++, beginner, unit-testing, socket
const char* message = "Hello from server!";
ASSERT_EQ(clientSocket.Send(message, static_cast<int>(strlen(message) + 1)), static_cast<int>(strlen(message) + 1));
serverLogger.Log(LogLevel::DEBUG, __FILE__, __LINE__, "Server sent message to client");
});
}
});
// Start client threads
std::vector<std::thread> clientThreads;
for (int i = 0; i < 50; ++i) {
clientThreads.emplace_back([&clientLogger]() {
Socket clientSocket(clientLogger);
ASSERT_TRUE(clientSocket.Create());
ASSERT_TRUE(clientSocket.Connect("127.0.0.1", 12345));
clientLogger.Log(LogLevel::DEBUG, __FILE__, __LINE__, "Client socket connected to server");
char recvBuffer[1024] = { 0 };
ASSERT_EQ(clientSocket.Receive(recvBuffer, sizeof(recvBuffer)), strlen("Hello from server!") + 1);
clientLogger.Log(LogLevel::DEBUG, __FILE__, __LINE__, "Client received message from server");
ASSERT_STREQ(recvBuffer, "Hello from server!");
});
}
// Wait for server and client threads to finish
serverThread.join();
for (auto& thread : clientThreads) {
thread.join();
}
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | {
"domain": "codereview.stackexchange",
"id": 44984,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, unit-testing, socket",
"url": null
} |
c++, beginner, unit-testing, socket
Answer: Use of a thread pool
What was the point of creating a thread pool with 50 threads if you are going to submit exactly 50 tasks to it? You could have just used std::vector<std::thread> like you did for clientThreads.
The thread pool only makes sense if you are going to submit more tasks than you have threads, and you either want to avoid the overhead of creating and destroying lots of threads, or you have CPU-intensive tasks and you want to avoid running more threads concurrently than you have CPU cores. In the case of network communication, it's probably not the latter. But then you have to wonder: what if I have 100 clients connecting, and I only have a thread pool of size 50. The first 50 clients will be accepted, but the next 50 have to wait? What if you did more than just send "Hello from server!", but had a long running task for each connection?
More importantly though, if you only add 50 tasks that each accept one connection, how will you ever be able to service 100 clients? Instead of having each task call Accept(), you probably want to create one thread dedicated to accepting connections, and as soon as a connection is accepted, then create a thread that will further handle that connection.
Partial send()/recv() is not a bug
In your code you are assuming that send() will send the whole message in one go, and that the call to recv() will receive the whole message. However, there is no such guarantee, not even for blocking sockets. Make sure you check the return value (don't just use an assert), and use a loop to call send() repeatedly until either the whole message has been sent, or an error has occured.
For receiving you have to do the same, but it can even be more complicated if you don't know the size of the message you will receive in advance.
Validate the data that you receive | {
"domain": "codereview.stackexchange",
"id": 44984,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, unit-testing, socket",
"url": null
} |
c++, beginner, unit-testing, socket
Validate the data that you receive
The sender might send something different than you expect. You are calling Receive() with a buffer of 1024 bytes. What if the sender sends 1024 bytes, none of which are a NUL byte? Luckily you only accept a string containing "Hello from server!", but if you didn't know the length and contents of the message, you can no longer trust that the buffer will be NUL-terminated. | {
"domain": "codereview.stackexchange",
"id": 44984,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, unit-testing, socket",
"url": null
} |
neural-network, julia
Title: Neural Network in Julia (Multilayer Perceptron)
Question: I wrote a simple multilayer perceptron in Julia, which seems to work fine on different datasets, e.g. the MNIST dataset with a success rate of about 90% after a few seconds of training. But I would like constructive criticism of the program and I'm very new to the Julia programming language, so feedback on the formatting is very welcome.
This is network.jl:
# network: weighted sums, activations, weights, biases, gradient
mutable struct NN
dims :: Vector{Int}
z :: Vector{Vector{Float64}}
a :: Vector{Vector{Float64}}
w :: Vector{Matrix{Float64}}
b :: Vector{Vector{Float64}}
∇a :: Vector{Vector{Float64}}
∇w :: Vector{Matrix{Float64}}
∇b :: Vector{Vector{Float64}}
Σ∇w :: Vector{Matrix{Float64}}
Σ∇b :: Vector{Vector{Float64}}
end
Data = Vector{Tuple{Vector{Float64}, Vector{Float64}}}
# fill vectors and matrices, needs improvement
function init(dims :: Vector{Int}) :: NN
n = NN([], [], [], [], [], [], [], [], [], [])
n.dims = dims
for i in 1:length(dims)
push!(n.a, Vector{Float64}(undef, dims[i]))
push!(n.∇a, Vector{Float64}(undef, dims[i]))
end
for i in 2:length(dims)
push!(n.z, Vector{Float64}(undef, dims[i]))
push!(n.w, randn(dims[i], dims[i - 1]))
push!(n.∇w, Matrix{Float64}(undef, dims[i], dims[i - 1]))
push!(n.Σ∇w, Matrix{Float64}(undef, dims[i], dims[i - 1]))
push!(n.b, randn(dims[i]))
push!(n.∇b, Vector{Float64}(undef, dims[i]))
push!(n.Σ∇b, Vector{Float64}(undef, dims[i]))
end
return n
end
# leaky ReLU to avoid dead neurons
ReLU(x) = max(0.01 * x, x)
ReLU′(x) = x >= 0 ? 1 : 0.01
σ(x) = 1 / (1 + exp(-x))
σ′(x) = σ(x) * (1 - σ(x))
const act = σ
const act′ = σ′
function forward!(n :: NN)
for i in 1:length(n.dims) - 1
n.z[i] = n.w[i] * n.a[i] + n.b[i]
n.a[i + 1] = act.(n.z[i])
end
end | {
"domain": "codereview.stackexchange",
"id": 44985,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "neural-network, julia",
"url": null
} |
neural-network, julia
cost(output, expected) = sum((output - expected) .^ 2)
function backprop!(n :: NN, expected :: Vector{Float64})
len = length(n.dims)
n.∇a[len] = 2 .* (n.a[len] - expected)
for i in len - 1:-1:1
n.∇a[i] .= 0
n.∇b[i] = act′.(n.z[i]) .* n.∇a[i + 1]
for j in 1:dims[i + 1]
if i != 1
n.∇a[i] += n.w[i][j, :] .* n.∇b[i][j]
end
n.∇w[i][j, :] = n.a[i] .* n.∇b[i][j]
end
end
end
# data: [(input, expected)], only one batch!
function train!(n :: NN, data :: Data) :: Float64
for i in 1:length(n.dims) - 1
n.Σ∇w[i] .= 0
n.Σ∇b[i] .= 0
end
Σcost = 0
for d in data
n.a[1] = d[1]
forward!(n)
Σcost += cost(n.a[length(n.dims)], d[2]) / length(data)
backprop!(n, d[2])
n.Σ∇w .+= n.∇w / length(data)
n.Σ∇b .+= n.∇b / length(data)
end
# play around with factor
n.w -= 5 * n.Σ∇w
n.b -= 5 * n.Σ∇b
return Σcost
end
Example approximating sin(x)
I added the following example of approximating sin(x) using the above network to the GitLab repository. You might want to reduce the number of batches, depending on your computing resources.
Here is examples/sin.jl:
using Printf
include("../network.jl")
dims = [1, 10, 10, 10, 1]
len = length(dims)
n = init(dims)
# batched training data: [[(input, expected)]]
batches = [Data(undef, 5) for i in 1:100000]
for batch in batches
for j in eachindex(batch)
x = rand() * pi * 2
batch[j] = ([x], [sin(x) / 2 + 0.5])
end
end
for batch in batches
@printf "Σcost = %.12f\n" train!(n, batch)
end
println("\nTesting with random values:\n---------------------------")
for i in 1:10
n.a[1][1] = rand() * pi * 2
forward!(n)
expected = sin(n.a[1][1]) / 2 + 0.5
@printf "sin(%.6f) = %.6f | NN: %.6f\n" n.a[1][1] expected n.a[len][1]
end | {
"domain": "codereview.stackexchange",
"id": 44985,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "neural-network, julia",
"url": null
} |
neural-network, julia
I also wrote some Pluto.jl notebooks with a friend, that use the above neural network and train it on e.g. the MNIST dataset, if you want to have a look.
Answer: Overall this looks very good. The main change I would make is putting a @views on backprop! since slicing in Julia makes a copy by default.
function backprop!(n :: NN, expected :: Vector{Float64})
len = length(n.dims)
n.∇a[len] = 2 .* (n.a[len] - expected)
for i in len - 1:-1:1
n.∇a[i] .= 0
n.∇b[i] = act′.(n.z[i]) .* n.∇a[i + 1]
@views for j in 1:dims[i + 1]
if i != 1
n.∇a[i] += n.w[i][j, :] .* n.∇b[i][j]
end
n.∇w[i][j, :] = n.a[i] .* n.∇b[i][j]
end
end
end | {
"domain": "codereview.stackexchange",
"id": 44985,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "neural-network, julia",
"url": null
} |
python-3.x, graphics, pytorch, type-hinting
Title: Randomly rotate an image through right angles
Question: I'm new to Python, and coming from Typescript, I tried to include types, but it's not obvious sometimes.
Currently this is the way I type objects:
Write own simple types
Import type from a library like torch.Tensor below
Use typing package for anything that looks not obvious to build the types of
import torch
from typing import Optional, List, Tuple, Union
def rotate_image(
image: torch.Tensor, is_passive_image: bool
) -> Tuple[torch.Tensor, Optional[int]]:
"""
Args:
image (torch.Tensor): The input image tensor.
is_passive_image (bool): A boolean value indicating whether the image is passive or active.
Returns:
The transformed image tensor and the rotation value (if the image is active).
"""
if not is_passive_image:
rand_rot = int(torch.randint(4, size=(1,)).item())
angle = rand_rot * 90
image = transforms.functional.rotate(image, angle)
return image, rand_rot
else:
return image, 0
I would appreciate any comments regarding the use of types and the commenting of the function.
Answer: types are for documentation
tried to include types
You did great.
Please understand that type hint annotations are entirely optional,
though the Gentle Reader will love them.
The cPython interpreter essentially ignores type hints.
If you do write them,
definitely run the $ mypy *.py linter so you benefit from its warnings.
(Often it turns out that
$ mypy --no-namespace-packages --ignore-missing-imports *.py
produces the results I find most helpful.)
modern typing
from typing import ... List, Tuple, Union
Maybe you were reading a somewhat dated tutorial?
Or for some reason you need to run a downrev cPython interpreter like 3.7?
With modern interpreter, prefer the more concise:
def foo(xs: list[int], y: tuple[str, int|str]) -> None: | {
"domain": "codereview.stackexchange",
"id": 44986,
"lm_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, graphics, pytorch, type-hinting",
"url": null
} |
python-3.x, graphics, pytorch, type-hinting
It's almost always more readable to express the notion of Union[a, b]
using a | b syntax.
The Optional symbol you imported is still in common use.
We prefer the Optional[int] that you wrote
over int | None.
Your image: torch.Tensor annotation is very nice,
but I wonder if we could also reveal the type of
data lurking within that tensor.
docstring conventions
"""
Args:
...
Thank you for supplying an optional docstring, it is appreciated.
Convention is to begin each docstring with a single sentence,
optionally followed by blank line and other stuff.
Please start with """Returns a rotated copy of the input image."""
combined condition
if not is_passive_image:
This "maybe it's a no-op?" expression does not appear to be pulling its weight.
Consider having the caller evaluate it instead.
No need to request a rotate if caller already knows it's a no-op.
As it stands, the Public API is being made more complex
for little apparent gain.
return image, rand_rot
It appears to me that 25% of the time this, too, is a no-op.
If you do not take the previous advice about
deleting the is_passive_image parameter,
then consider constructing a bool condition
based on that plus whether the random rotation is 0.
Then the if just looks at that boolean.
Goal is to avoid calling a possibly expensive identity function.
optional ?
... -> Tuple[torch.Tensor, Optional[int]]:
No.
100% of the time we return an int
in the range 0 .. 3.
It is definitely not an Optional return type.
Overall, it looks like your heart is in the right place
and you are doing the right sort of things.
Keep it up! | {
"domain": "codereview.stackexchange",
"id": 44986,
"lm_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, graphics, pytorch, type-hinting",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Title: A recursive_foreach_all Template Function Implementation in C++
Question: This is a follow-up question for A recursive_fold_left_all Template Function Implementation in C++. As mentioned in G. Sliepen's answer, I am trying to implement recursive_foreach_all template function in this post.
The experimental implementation
recursive_foreach_all Template Function:
/* recursive_foreach_all template function performs specific function on input container exhaustively
*/
template<class T, class Proj = std::identity, class F>
constexpr auto recursive_foreach_all(T& value, F f, Proj proj = {})
{
return std::invoke(f, std::invoke(proj, value));
}
template<std::ranges::input_range T, class Proj = std::identity, class F>
constexpr auto recursive_foreach_all(T& inputRange, F f, Proj proj = {})
{
return std::ranges::for_each(inputRange, [&](auto& value) {
return recursive_foreach_all(value, f, proj);
});
}
Full Testing Code
The full testing code:
// A recursive_foreach_all Function Implementation in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <queue>
#include <ranges>
#include <stack>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
// is_reservable concept
template<class T>
concept is_reservable = requires(T input)
{
input.reserve(1);
};
// is_sized concept, https://codereview.stackexchange.com/a/283581/231235
template<class T>
concept is_sized = requires(T x)
{
std::size(x);
};
template<typename T>
concept is_summable = requires(T x) { x + x; }; | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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<typename T>
concept is_summable = requires(T x) { x + x; };
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
};
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
};
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type; | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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
// https://codereview.stackexchange.com/a/253039/231235
template<template<class...> class Container = std::vector, std::size_t dim, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times));
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output;
for (size_t i = 0; i < times; i++)
{
output[i] = n_dim_array_generator<dim - 1, times>(input);
}
return output;
}
}
namespace UL // unwrap_level
{
template< std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto make_view(const Container& input, const F& f) noexcept
{
return std::ranges::transform_view(
input,
[&f](const auto&& element) constexpr { return recursive_transform(element, f ); } );
}
/* Override make_view to catch dangling references. A borrowed range is
* safe from dangling..
*/
template <std::ranges::input_range T>
requires (!std::ranges::borrowed_range<T>)
constexpr std::ranges::dangling make_view(T&&) noexcept
{
return std::ranges::dangling();
} | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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
// clone_empty_container template function implementation
template< std::size_t unwrap_level = 1,
std::ranges::input_range Container,
std::copy_constructible F>
requires (std::ranges::view<Container>&&
std::is_object_v<F>)
constexpr auto clone_empty_container(const Container& input, const F& f) noexcept
{
const auto view = make_view(input, f);
recursive_variadic_invoke_result<unwrap_level, F, Container> output(std::span{input});
return output;
}
// recursive_transform template function implementation (the version with unwrap_level template parameter)
template< std::size_t unwrap_level = 1,
class T,
std::copy_constructible F>
requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
std::ranges::view<T>&&
std::is_object_v<F>)
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
auto output = clone_empty_container(input, f);
if constexpr (is_reservable<decltype(output)>&&
is_sized<decltype(input)>)
{
output.reserve(input.size());
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
}
else
{
std::ranges::transform(
input,
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
}
return output;
} | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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
);
}
return output;
}
else if constexpr(std::regular_invocable<F, T>)
{
return std::invoke(f, input);
}
else
{
static_assert(!std::regular_invocable<F, T>, "Uninvocable?");
}
} | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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
/* This overload of recursive_transform is to support std::array
*/
template< std::size_t unwrap_level = 1,
template<class, std::size_t> class Container,
typename T,
std::size_t N,
typename F >
requires (std::ranges::input_range<Container<T, N>>)
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
Container<recursive_variadic_invoke_result_t<unwrap_level, F, T>, N> output;
std::ranges::transform(
input,
std::ranges::begin(output),
[&f](auto&& element){ return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
// recursive_transform function implementation (the version with unwrap_level, without using view)
template<std::size_t unwrap_level = 1, class T, class F>
requires (unwrap_level <= recursive_depth<T>()&& // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
!std::ranges::view<T>)
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, T> output{};
std::ranges::transform(
input, // passing a range to std::ranges::transform()
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return std::invoke(f, input); // use std::invoke()
}
} | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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
// recursive_transform implementation (the version with unwrap_level, with execution policy)
template<std::size_t unwrap_level = 1, class ExPo, class T, std::copy_constructible F>
requires (unwrap_level <= recursive_depth<T>() && // handling incorrect unwrap levels more gracefully, https://codereview.stackexchange.com/a/283563/231235
std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_transform(ExPo execution_policy, const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, T> output{};
output.resize(input.size());
std::mutex mutex;
std::transform(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[&](auto&& element)
{
std::lock_guard lock(mutex);
return recursive_transform<unwrap_level - 1>(execution_policy, element, f);
});
return output;
}
else
{
return f(input);
}
} | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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
// recursive_transform implementation (binary case, the version with unwrap_level)
template<std::size_t unwrap_level = 1, class ExPo, std::ranges::input_range R1, std::ranges::input_range R2, std::copy_constructible F>
constexpr auto recursive_transform(ExPo execution_policy, const R1& input1, const R2& input2, const F& f)
{
if constexpr (unwrap_level > 0)
{
recursive_variadic_invoke_result_t<unwrap_level, F, R1> output{};
output.resize(input1.size());
std::mutex mutex;
std::transform(execution_policy, std::ranges::cbegin(input1), std::ranges::cend(input1), std::ranges::cbegin(input2), std::ranges::begin(output),
[&](auto&& element1, auto&& element2)
{
std::lock_guard lock(mutex);
return recursive_transform<unwrap_level - 1>(execution_policy, element1, element2, f);
});
return output;
}
else
{
return f(input1, input2);
}
}
}
// recursive_depth function implementation with target type
template<typename T_Base, typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<typename T_Base, std::ranges::input_range Range>
requires (!std::same_as<Range, T_Base>)
constexpr std::size_t recursive_depth()
{
return recursive_depth<T_Base, std::ranges::range_value_t<Range>>() + std::size_t{1};
}
/* recursive_foreach_all template function performs specific function on input container exhaustively
*/
template<class T, class Proj = std::identity, class F>
constexpr auto recursive_foreach_all(T& value, F f, Proj proj = {})
{
return std::invoke(f, std::invoke(proj, value));
} | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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, class F>
constexpr auto recursive_foreach_all(T& inputRange, F f, Proj proj = {})
{
return std::ranges::for_each(inputRange, [&](auto& value) {
return recursive_foreach_all(value, f, proj);
});
}
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 << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
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 << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
void recursive_foreach_all_test();
int main()
{
auto start = std::chrono::system_clock::now();
recursive_foreach_all_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;
} | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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_foreach_all_test()
{
auto print = [](const auto& n) { std::cout << ' ' << n; };
std::vector<std::pair<int, std::string>> pairs {{1,"one"}, {2,"two"}, {3,"three"}};
std::vector<std::vector<std::pair<int, std::string>>> pairs_vector{pairs, pairs};
std::cout << "project the pair::first: ";
recursive_foreach_all(pairs_vector, print, [](const auto& p) { return p.first; });
std::cout << "\n";
std::cout << "project the pair::second: ";
recursive_foreach_all(pairs_vector, print, [](const auto& p) { return p.second; });
std::cout << "\n\n";
std::cout << "Play with test_vectors:\n";
auto test_vectors = n_dim_container_generator<std::vector, 4, int>(1, 3);
recursive_foreach_all(test_vectors, [](auto& element){ ++element; return; });
recursive_print(test_vectors);
std::cout << "Play with test_arrays:\n";
auto test_arrays = n_dim_array_generator<4, 3>(1);
recursive_foreach_all(test_arrays, [](auto& element){ ++element; return; });
recursive_print(test_arrays);
}
The output of the test code above:
project the pair::first: 1 2 3 1 2 3
project the pair::second: one two three one two three | {
"domain": "codereview.stackexchange",
"id": 44987,
"lm_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
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.