text stringlengths 1 2.12k | source dict |
|---|---|
c++, object-oriented, socket, wrapper
In make_reply, it's unclear why we write the root delay and root dispersion in native byte-order rather than network order - that definitely needs an explanatory comment.
refid has an inbuilt assumption that we're building for an ASCII (or compatible) platform - requires either a comment or a code change to eliminate that assumption, e.g. refid = 0x4c4f434c.
We need to include cstring to get a declaration of std::memcpy. And we can combine the two calls into one with twice the length.
read_callback produces a lot to std::cout that ought to be going to the log stream.
ntp-server.hpp
Many missing includes - don't rely on "select-server.hpp" bringing in everything we need, as that makes it fragile.
Again, attempting to use uint16_t and size_t from the global namespace instead of std.
Constructor should be explicit.
select-server.cpp
Again, prefer C++ standard headers <cerrno> and <cstring>.
The destructor avoids closing the file descriptor when it is 0, but the failure return from socket() is -1, so that test is incorrect.
The constructor should return early when socket() fails - bind() isn't going to succeed either. It's probably best to use std::perror() for both of these.
Include <cstdlib> to declare std::exit().
select() is unnecessary when we're listening to a single file descriptor. But perhaps we should be listening to more - standard practice is to use a pipe so that a signal handler can tell the loop to exit cleanly.
The fixed timeout is also pointless, given that all we do is repeat the select() if it expires.
The hardcoded receive buffer size (48) could be too small for most applications - this looks to have been determined by SNTP, and it makes this class much less reusable than I'd like.
select-server.hpp
The familiar misspellings of std::size_t and std::uint16_t.
Instead of providing callback as a std::function, consider requiring implementers to subclass and implement a pure-static function. That's why we provided a virtual destructor, isn't it? | {
"domain": "codereview.stackexchange",
"id": 44614,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, object-oriented, socket, wrapper",
"url": null
} |
python, beginner, file-system
Title: Python File Transfer Script
Question: I'm still pretty new at Python and working on a small database program, where at the start of the program new files are imported from another folder (approx. 2000), and older files are backed up. Subfolders of the import folder sometimes contain multiple files with the same name (I always want just one of them, but the newest version isn't always the one I want). This is an unfortunate situation that I don't have control over.
Because I don't have that much experience yet, I find it very difficult to judge if this is a "valid" way of doing it, and it would be great to have some feedback as for its readability and general usability.
The transfer-settings referred to in the script:
# settings.py
class FileTransferSettings:
def __init__(self):
self.input_folder: str = r"./input"
self.search_subdirectories: bool = True
self.output_folder: str = r"./output"
self.backup_folder: str = r"./backup"
self.report_folder: str = r"./reports"
self.file_type_filter: list | None = [".yaml", ".csv"]
self.file_name_filter: str | None = "standardized"
transfer_settings = FileTransferSettings()
The file transfer script:
# file_transfer.py
from collections import defaultdict
import os
from pathlib import Path
import shutil
import time
from logs import file_transfer_log
from settings import transfer_settings as ts
def _find_valid_files():
def generate_glob_search_patterns() -> list[str]:
file_filters = (ts.file_type_filter, ts.file_name_filter) | {
"domain": "codereview.stackexchange",
"id": 44615,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, file-system",
"url": null
} |
python, beginner, file-system
match file_filters:
case (None, None):
return ["*"]
case (None, ts.file_name_filter):
return [f"*{ts.file_name_filter.lower()}*"]
case (ts.file_type_filter, None):
return [f"*{file_type}" for file_type in ts.file_type_filter]
case (ts.file_type_filter, ts.file_name_filter):
return [f"*{ts.file_name_filter.lower()}*{file_type}" for file_type in ts.file_type_filter]
def find_all_matching_files(pattern_list: list[str]) -> dict[str, list[Path]]:
result = defaultdict(list)
for pattern in pattern_list:
if ts.search_subdirectories:
for path in Path(ts.input_folder).rglob(pattern):
if path.is_file():
result[path.name].append(path)
elif not ts.search_subdirectories:
for path in Path(ts.input_folder).glob(pattern):
if path.is_file():
result[path.name].append(path)
return result
def resolve_duplicate_file_names(path_object_dict: dict[str, list[Path]]) -> list[Path]:
def print_duplicate_file_information(paths_to_print: list[Path]):
print(f"\nDuplicate file names found:\n")
for i, path in enumerate(paths_to_print):
print(f"{i}:\n"
f"Full path : {path.resolve()}\n"
f"Last modified : {time.ctime(os.path.getmtime(path))}\n")
def choose_file_to_transfer(paths_to_choose_from: list[Path]) -> int:
while True:
user_choice = input("Which file do you want to transfer? Input number here: ") | {
"domain": "codereview.stackexchange",
"id": 44615,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, file-system",
"url": null
} |
python, beginner, file-system
if not user_choice.isnumeric():
print("Invalid input, input a number.\n")
elif int(user_choice) < 0 or int(user_choice) > len(paths_to_choose_from) - 1:
print("Invalid input, number is not available.\n")
else:
return int(user_choice)
result = []
for path_name in path_object_dict:
path_objects_with_same_name = path_object_dict[path_name]
path_index = 0
if len(path_objects_with_same_name) > 1:
print_duplicate_file_information(path_objects_with_same_name)
path_index = choose_file_to_transfer(path_objects_with_same_name)
result.append(path_objects_with_same_name[path_index])
return result
glob_patterns = generate_glob_search_patterns()
path_list = resolve_duplicate_file_names(find_all_matching_files(glob_patterns))
return path_list
def _transfer_file(path: Path):
def is_file_to_transfer_newer(file_to_transfer: Path) -> bool:
duplicate_file_in_output_folder = f"{ts.output_folder}/{file_to_transfer.name}"
if os.path.getmtime(file_to_transfer) > os.path.getmtime(duplicate_file_in_output_folder):
return True
def backup_old_file(path_to_transfer: Path):
file_to_backup = Path(f"{ts.output_folder}/{path_to_transfer.name}")
filename, extension = file_to_backup.stem, file_to_backup.suffix
version_number = 1
while True:
if os.path.exists(f"{ts.backup_folder}/{filename}_version_{version_number}{extension}"):
version_number += 1
else:
backup = file_to_backup.rename(f"{ts.output_folder}/{filename}_version_{version_number}{extension}")
shutil.move(backup, ts.backup_folder)
break | {
"domain": "codereview.stackexchange",
"id": 44615,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, file-system",
"url": null
} |
python, beginner, file-system
if not os.path.exists(f"{ts.output_folder}/{path.name}"):
shutil.copy2(path, ts.output_folder)
file_transfer_log.add_new(path)
else:
if is_file_to_transfer_newer(path):
backup_old_file(path)
shutil.copy2(path, ts.output_folder)
file_transfer_log.add_updated(path)
else:
file_transfer_log.add_old(path)
def transfer_files():
for file_path in _find_valid_files():
_transfer_file(file_path)
Answer: use Path
self.input_folder: str = r"./input"
The raw r-string is odd, unless you translated
this from a Windows r".\input" directory.
You're clearly going for type safety, which is a laudable goal.
It allows mypy and your IDE to help you out, offering hints.
Consider adding a pathlib import,
and then assign Path("./input"),
or more simply just Path("input").
Path is a good way to tell the Gentle Reader that
we're talking about something in the filesystem,
plus it offers some nice convenience functions.
use top-level functions
You are clearly going to some trouble to organize the code,
with _locally scoped identifiers and nested function defs.
Which is laudable.
But I usually try to steer clear of nested functions
for at least two reasons.
The parent function's local variables are in-scope for a nested function, which can be convenient but may lead to the usual coupling problems that global variables suffer from.
A nested function is needlessly difficult to unit test.
I don't go so far as to say one should never nest.
Just think carefully and write down the reason(s)
you're using nesting instead of other techniques.
Here are two techniques you might use in this codebase.
Turn each top-level function into a module that contains the various helper functions.
If you notice "same variables" being repeatedly passed around, turn a top-level function into a class and access those variables as self attributes. | {
"domain": "codereview.stackexchange",
"id": 44615,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, file-system",
"url": null
} |
python, beginner, file-system
namedtuple
Kudos on making file_filters a tuple (rather than a list).
You might find it convenient to define a
namedtuple
or dataclass.
from collections import namedtuple
FileFilter = namedtuple("FileFilter", ("name", "type"))
The code sometimes mentions the file type first,
which feels backwards.
There seems to be a "filenames shall be lowercase" invariant.
Let's enforce that at assignment time,
so we don't need to remember a .lower() call at use time.
Similar remarks for when print_duplicate_file_information
has to remember to .resolve() -- you might prefer to do that
at assignment time.
The match technique is interesting.
But maybe it's overkill.
We could deal with name, then deal with type,
then return the combined result.
Then there would be a little less code duplication.
Using a None sentinel to denote "no filtering"
is a perfectly sensible choice.
But you may find denoting that with "*" to be more convenient.
(And then adjust the Optional aspect of the type hint.)
"else" suffices
In find_all_matching_files this is needlessly hard to read:
elif not ts.search_subdirectories:
Simplify it down to else: and be done with it.
We see three lines of code,
twice,
with the only difference being .rglob() / .glob().
Assign the desired glob variant to a variable,
and make a function call indirect via that variable.
use convenience methods
f"Last modified : {time.ctime(os.path.getmtime(path))}\n")
That makes perfect sense for a str path.
nit: Given a Path path, the usual idiom would be
path.stat().st_ctime.
Similar remark for is_file_to_transfer_newer.
From a UX perspective it seems slightly odd to not print
small integer indexes next to the file details.
Back in find_all_matching_files, notice that .glob()
doesn't sort. The UX might be improved if glob'd
files were always consistently displayed in sorted() order. | {
"domain": "codereview.stackexchange",
"id": 44615,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, file-system",
"url": null
} |
python, beginner, file-system
put types in type hints, not the name
You're definitely shooting for clarity
when you invent new identifiers, and that's admirable.
Some of them get to be a bit verbose, which doesn't help the reader.
For example, rather than assigning path_objects_with_same_name,
paths_with_same_name would suffice.
Use a type hint if you want to make it explicit that
we'll find a Path rather than a str in that container.
For that particular identifier, consider dup_paths.
Interestingly, I usually request that an
author write more """docstrings""" in their code,
yet I didn't feel that way about the current
submission. Functions are small and
names are clear.
Nonetheless, writing a """single sentence"""
on your public API entry points wouldn't hurt.
add automated tests
There is some slightly involved logic here.
If you were to refactor some code, you would want
the ability to quickly tell it is working properly,
before and after a change.
Define a TestFileTransfer class that inherits from
TestCase.
Verify some aspect like glob'ing or obtaining ctime.
Notice that there will never be a unit test
for choose_file_to_transfer, and that is perfectly fine.
This code is well structured, showing attention
to detail and to readability.
It adheres to the
single responsibility principle.
Fine work. Keep it up!
I would not be willing to delegate or accept maintenance
tasks on this codebase in its current form, as a maintainer
could not add a small test in order to work on a small feature.
If the recommended class or module refactoring is adopted
to de-nest some functions, then I would be happy to delegate
or accept such tasks. | {
"domain": "codereview.stackexchange",
"id": 44615,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, file-system",
"url": null
} |
strings, bash, io
Title: pure Bash way to trim
Question: How can I improve this? I added the while read loop to handle preceding newlines.
trim()
{
# skip leading whitespace
while read -r string; do [[ -n "${string}" ]] && break; done
string="${string#"${string%%[![:space:]]*}"}"
string="${string%"${string##*[![:space:]]}"}"
printf "${string}"
}
Usage:
$ echo " hello " | trim; echo
hello
$ echo "
hello multi-line
" | trim
hello multi-line
$
Answer: The comment is misleading - the function does skip leading whitespace-only lines, but it also removes all lines after the first non-whitespace.
I would simplify to read all of the input into string, and then remove the whitespace:
string=$(cat)
string="${string#"${string%%[![:space:]]*}"}"
Don't make the result the format-string for printf - any % in the input will be substituted (e.g. trim <<<%d results in 0 as output). Instead, use %s as the format string:
printf %s "$string"
Modified code
trim()
{
string=$(cat)
string=${string#${string%%[![:space:]]*}}
printf %s "${string%${string##*[![:space:]]}}"
}
And some improved tests:
tests=(
' hello '
'
hello multi-line ''
'
'
two
lines
'
'%d'
' '
'
'
)
for s in "${tests[@]}"
do
printf '%s\n^%s$\n\n' "${s@Q}" "$(trim <<<"$s")"
done | {
"domain": "codereview.stackexchange",
"id": 44616,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, bash, io",
"url": null
} |
java, algorithm, sorting, queue, mergesort
Title: Queue-mergesort: a mergesort that does optimal number of comparisons in the worst case in Java
Question: Here is the code for queue-mergesort by Mordecai J. Golin and Robert Sedgewick:
com.github.coderodde.util.QueueMergesort.java:
package com.github.coderodde.util;
import java.util.Arrays;
import java.util.Comparator;
/**
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Apr 1, 2023)
* @since 1.6 (Apr 1, 2023)
*/
public class QueueMergesort { | {
"domain": "codereview.stackexchange",
"id": 44617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, sorting, queue, mergesort",
"url": null
} |
java, algorithm, sorting, queue, mergesort
private static final class ListItem<E> {
E datum;
ListItem<E> next;
ListItem(E datum) {
this.datum = datum;
}
}
private static final class Queue<E> {
private final ListItem<E>[] buffer;
private int headIndex = 0;
private int tailIndex = 0;
private int size = 0;
Queue(int bufferCapacity) {
this.buffer = new ListItem[bufferCapacity];
}
int size() {
return size;
}
ListItem<E> get() {
ListItem<E> listHead = buffer[headIndex];
headIndex = (headIndex + 1) % buffer.length;
size--;
return listHead;
}
void put(ListItem<E> tail) {
buffer[tailIndex] = tail;
tailIndex = (tailIndex + 1) % buffer.length;
size++;
}
}
public static <E> void sort(E[] array, Comparator<? super E> comparator) {
if (array.length < 2) {
return;
}
Queue<E> queue = new Queue(array.length);
for (E element : array) {
queue.put(new ListItem<>(element));
}
while (queue.size() > 1) {
ListItem<E> lst1 = queue.get();
ListItem<E> lst2 = queue.get();
queue.put(merge(lst1, lst2, comparator));
}
int index = 0;
for (ListItem<E> list = queue.get(); list != null; list = list.next) {
array[index++] = list.datum;
}
}
private static <E> ListItem<E> merge(ListItem<E> lst1,
ListItem<E> lst2,
Comparator<? super E> comparator) {
ListItem<E> mergedList;
ListItem<E> mergedListTail;
if (comparator.compare(lst1.datum, lst2.datum) <= 0) {
mergedList = lst1; | {
"domain": "codereview.stackexchange",
"id": 44617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, sorting, queue, mergesort",
"url": null
} |
java, algorithm, sorting, queue, mergesort
if (comparator.compare(lst1.datum, lst2.datum) <= 0) {
mergedList = lst1;
lst1 = lst1.next;
} else {
mergedList = lst2;
lst2 = lst2.next;
}
mergedListTail = mergedList;
while (lst1 != null && lst2 != null) {
if (comparator.compare(lst1.datum, lst2.datum) <= 0) {
mergedListTail.next = lst1;
mergedListTail = lst1;
lst1 = lst1.next;
} else {
mergedListTail.next = lst2;
mergedListTail = lst2;
lst2 = lst2.next;
}
}
if (lst1 != null) {
mergedListTail.next = lst1;
} else {
mergedListTail.next = lst2;
}
return mergedList;
}
public static void main(String[] args) {
Integer[] array = { 5, 2, 1, 4, 3 };
QueueMergesort.sort(array, Integer::compareTo);
System.out.println(Arrays.toString(array));
}
} | {
"domain": "codereview.stackexchange",
"id": 44617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, sorting, queue, mergesort",
"url": null
} |
java, algorithm, sorting, queue, mergesort
com.github.coderodde.util.QueueMergesortTest.java:
package com.github.coderodde.util;
import java.util.Arrays;
import java.util.Random;
import static junit.framework.Assert.assertTrue;
import org.junit.Test;
public class QueueMergesortTest {
private static final int TEST_RUNS = 100;
private static final int MAX_ARRAY_LENGTH = 1_000;
private static final int UPPER_ELEMENT_BOUND = 600;
@Test
public void bruteForceTest() {
Random random = new Random(100L);
for (int i = 0; i < TEST_RUNS; i++) {
int arrayLength = random.nextInt(MAX_ARRAY_LENGTH) + 1;
Integer[] array = getRandomArray(arrayLength, random);
Integer[] referenceArray = array.clone();
com.github.coderodde.util.QueueMergesort.sort(
array,
Integer::compareTo);
java.util.Arrays.sort(referenceArray, Integer::compareTo);
assertTrue(Arrays.equals(referenceArray, array));
}
}
private static Integer[] getRandomArray(int size, Random random) {
Integer[] array = new Integer[size];
for (int i = 0; i < array.length; i++) {
array[i] = random.nextInt(UPPER_ELEMENT_BOUND);
}
return array;
}
}
Critique request
As always, please tell me anything what comes to mind. | {
"domain": "codereview.stackexchange",
"id": 44617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, sorting, queue, mergesort",
"url": null
} |
java, algorithm, sorting, queue, mergesort
Critique request
As always, please tell me anything what comes to mind.
Answer: The instantiation of Queue should probably read new Queue<>(array.length) -
but why roll your own Queue when the point of the exercise is something else?
If you don't like java.util.Queue<ListItem<E>> for offer() and poll(), create a wrapper.
In merge(), don't repeat yourself.
Bored of introducing a dummy ListItem and setting tail to it:
/** Merges linked lists of <code>ListItem</code>s according to <code>order</code>.
* Both <code>list1</code> and <code>list2</code> need to be cycle-free lists.
* At least one instance member <code>next</code> will be mutated.
* @returns the merged list */
private static <E> ListItem<E>
merge(ListItem<E> list1, ListItem<E> list2, Comparator<? super E> order) {
ListItem<E> preferred, deferred, merged, next;
if (order.compare(list1.datum, list2.datum) <= 0) {
preferred = list1;
deferred = list2;
} else {
preferred = list2;
deferred = list1;
}
merged = preferred;
while (true) {
E challenger = deferred.datum;
while (true) {
next = preferred.next;
if (null == next) {
preferred.next = deferred;
return merged;
}
if (0 < order.compare(next.datum, challenger)) {
break;
}
preferred = next;
}
preferred.next = deferred;
preferred = deferred; // won compared to next
deferred = next;
}
} | {
"domain": "codereview.stackexchange",
"id": 44617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, sorting, queue, mergesort",
"url": null
} |
java, algorithm, sorting, queue, mergesort
(While preferred.next = deferred; looks common to "both ifs", it would be harmful if the inner loop continues, thus should not be done unconditionally before the first if.
I think it apparent that challenger is dispensable -
there is readability, Occam, and coding the way one thinks about solution.
(I'd expect the average number of trips through the inner loop to be 2.
And execution time to be dominated entirely by pointer chasing once data exceeds cache capacity significantly.)) | {
"domain": "codereview.stackexchange",
"id": 44617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, sorting, queue, mergesort",
"url": null
} |
c++, array
Title: Custom array class in C++
Question: I wrote a custom array class in C++ to suit my personal use case. The main important rule in this project is that no unassigned element is allowed between 2 assigned elements; please review for improvement:
#ifndef ARRAY_H
#define ARRAY_H
#include <limits>
template <typename T>
class Array {
public:
size_t ofs_to_pos(size_t ofs);
size_t pos_to_ofs(size_t pos);
Array();
Array(size_t size);
~Array();
void resize(size_t newSize);
void extendBy(size_t val);
void shrinkBy(size_t val);
void shrinkToFit();
void del();
void assign(T val, size_t ofs);
void fill(T val);
void push(T val);
void unshift(T val);
void deassign(size_t n);
void clear();
void insert(T val, size_t ofs);
void append(T val);
void prepend(T val);
void load(const T *src, size_t srcLen, size_t ofs);
void remove(size_t ofs);
void pop();
void shift();
bool empty();
bool full();
Array *clone();
const T& operator[] (size_t ofs);
const T *getBuf();
size_t getLen();
size_t getSize();
private:
T *buf;
size_t len;
size_t size;
};
template <typename T>
size_t Array<T>::ofs_to_pos(size_t ofs)
{
if (ofs == SIZE_MAX)
{
return ofs;
}
else
{
return ofs + 1;
}
}
template <typename T>
size_t Array<T>::pos_to_ofs(size_t pos)
{
if (pos == 0)
{
return pos;
}
else
{
return pos - 1;
}
}
template<typename T>
Array<T>::Array()
{
buf = nullptr;
len = 0;
size = 0;
}
template<typename T>
Array<T>::Array(size_t size)
{
buf = new T[size];
if (!buf)
{
this->size = 0;
}
else
{
this->size = size;
}
len = 0;
}
template <typename T>
Array<T>::~Array()
{
delete buf;
} | {
"domain": "codereview.stackexchange",
"id": 44618,
"lm_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++, array",
"url": null
} |
c++, array
template <typename T>
Array<T>::~Array()
{
delete buf;
}
template<typename T>
void Array<T>::resize(size_t newSize)
{
if (newSize == size)
{
return;
}
else if (newSize == 0)
{
delete buf;
buf = nullptr;
len = 0;
size = 0;
}
else
{
T *blk = new T[newSize];
if (blk)
{
if (len > newSize)
{
len = newSize;
}
if (!empty())
{
std::memcpy(blk, buf, len * sizeof(T));
}
delete buf;
buf = blk;
size = newSize;
}
}
}
template <typename T>
void Array<T>::extendBy(size_t val)
{
if (SIZE_MAX - val < size)
{
return;
}
resize(size + val);
}
template<typename T>
void Array<T>::shrinkBy(size_t val)
{
if (val > size)
{
return;
}
resize(size - val);
}
template<typename T>
void Array<T>::shrinkToFit()
{
resize(len);
}
template<typename T>
void Array<T>::del()
{
resize(0);
}
template<typename T>
void Array<T>::assign(T val, size_t ofs)
{
if (ofs > len || ofs == size)
{
return;
}
buf[ofs] = val;
if (ofs == len)
{
len += 1;
}
}
template<typename T>
void Array<T>::fill(T val)
{
for (size_t i = 0; i < size; i++)
{
buf[i] = val;
}
len = size;
}
template<typename T>
void Array<T>::push(T val)
{
if (len < size)
{
assign(val, len);
}
}
template<typename T>
inline void Array<T>::unshift(T val)
{
assign(val, 0);
}
template<typename T>
void Array<T>::deassign(size_t n)
{
if (n > len)
{
return;
}
len -= n;
}
template<typename T>
void Array<T>::clear()
{
len = 0;
} | {
"domain": "codereview.stackexchange",
"id": 44618,
"lm_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++, array",
"url": null
} |
c++, array
template<typename T>
void Array<T>::clear()
{
len = 0;
}
template<typename T>
void Array<T>::insert(T val, size_t ofs)
{
if (ofs > len)
{
return;
}
if (len == size)
{
T *blk = new T[size + 1];
if (!empty())
{
std::memcpy(blk, buf, ofs * sizeof(T));
}
if (ofs < len)
{
std::memcpy(blk + (ofs + 1), buf + ofs, (len - ofs) * sizeof(T));
}
delete buf;
buf = blk;
size += 1;
}
else
{
if (ofs < len)
{
std::memmove(buf + (ofs + 1), buf + ofs, (len - ofs) * sizeof(T));
}
}
buf[ofs] = val;
len += 1;
}
template<typename T>
void Array<T>::append(T val)
{
insert(val, len);
}
template<typename T>
void Array<T>::prepend(T val)
{
insert(val, 0);
}
template<typename T>
void Array<T>::load(const T *src, size_t src_len, size_t ofs)
{
if (src_len == 0 || ofs > len)
{
return;
}
if (len + src_len > size)
{
T *blk = new T[len + src_len];
std::memcpy(blk, buf, ofs * sizeof(T));
std::memcpy(blk + ofs, src, src_len * sizeof(T));
if (ofs < len)
{
std::memcpy(blk + (ofs + src_len), buf + ofs, (len - ofs) * sizeof(T));
}
delete buf;
buf = blk;
size = len + src_len;
}
else
{
if (ofs < len)
{
std::memmove(buf + (ofs + src_len), buf + ofs, src_len * sizeof(T));
}
std::memcpy(buf + ofs, src, src_len * sizeof(T));
}
len += src_len;
}
template<typename T>
void Array<T>::remove(size_t ofs)
{
if (ofs >= len)
{
return;
}
if (ofs < (len - 1))
{
std::memmove(buf + ofs, buf + (ofs + 1), (len - ofs) * sizeof(T));
}
len -= 1;
}
template<typename T>
inline void Array<T>::pop()
{
if (!empty())
{
remove(len - 1);
}
} | {
"domain": "codereview.stackexchange",
"id": 44618,
"lm_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++, array",
"url": null
} |
c++, array
template<typename T>
void Array<T>::shift()
{
remove(0);
}
template<typename T>
bool Array<T>::empty()
{
return (len == 0);
}
template<typename T>
bool Array<T>::full()
{
return (len == size);
}
template<typename T>
Array<T> *Array<T>::clone()
{
Array *arr = new Array(size);
arr->load(buf, len, 0);
return arr;
}
template<typename T>
const T& Array<T>::operator[](size_t ofs)
{
return buf[ofs];
}
template<typename T>
const T *Array<T>::getBuf()
{
return buf;
}
template<typename T>
size_t Array<T>::getLen()
{
return len;
}
template<typename T>
size_t Array<T>::getSize()
{
return size;
}
#endif
Answer: The copy-constructor doesn't copy any of the content, so we get a double-free in the destructor - running your unit-tests under Valgrind should demonstrate that.
We're missing at least
#include <cstddef>
#include <cstring>
using std::size_t;
Personally, I don't recommend using in headers - write the type in full, and don't pollute the user's global namespace.
The interface is too different to the standard container interface - it can't be used by generic algorithms. The lack of iterators is particularly constraining.
I recommend getting rid of the memory management completely, and instead wrapping a standard container (probably std::vector) to provide robust memory management for you. | {
"domain": "codereview.stackexchange",
"id": 44618,
"lm_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++, array",
"url": null
} |
python-3.x, array, integer, byte
Title: Mangle words to bytearray of lo/hibytes
Question: I would like to refactor the following code snippet adapted from a project I'm involved. It is part of a code to control power outlets via network. The code snippet was written by myself based on the original code for demonstration and review related purposes. E.g. the original code was part of a class containing the self parameter, it only took two words and the words were part of a challenge response from the power outlet.
Latter is given as background information, only.
def mangle_lo_hi_bytes(word1, word2, word3, word4):
answer = [
word1 & 0xFF,
word1 >> 8 & 0xFF,
word2 & 0xFF,
word2 >> 8 & 0xFF,
word3 & 0xFF,
word3 >> 8 & 0xFF,
word4 & 0xFF,
word4 >> 8 & 0xFF,
]
return bytes(answer)
->
2211443366558877
Please review the code in terms of
DRY paradigm
Performance
Reusability
Compactness
Resource usage
Examples:
The code extracts each lo/hibyte of each word in extra statements. It does not use looping or list comprehension. Therefore it is repetitive.
The code does everything manually and does not make use of pythons built in functionalities. This may affect, e.g. performance.
The code relies on the endianness of the host machine. This may result in difficult traceable bugs.
The code first sets up a list and then converts this list into bytes. This eats up additional memory.
What I tried:
Use a list comprehension to make the code more compact -> I ran into the issue that I could not nest a list comprehension of a list into another list comprehension like so: answer = [byte for byte in [lo(word), hi(word)] for word in [word1, word2, word3, word4]]
Trying to apply num.to_bytes(2, byteorder="little"). Here is my code: b"".join([num.to_bytes(2, byteorder="little") for num in nums]) where nums would be a list of word1...word4.
Answer: You wrote essentially
def mangle_lo_hi_bytes(word1: int, word2: int, word3: int, word4: int): | {
"domain": "codereview.stackexchange",
"id": 44619,
"lm_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, array, integer, byte",
"url": null
} |
python-3.x, array, integer, byte
It likely would be more convenient for the caller if it accepts a vector of words:
def mangle_lo_hi_bytes(words: Iterable[int]):
In any event, the signature should absolutely be accompanied
by a """docstring""" that explains how expected input
will be mapped to output, including some mention of endianess.
You complain that per-word nesting is inconvenient
to process: [(lo1, hi1), (lo2, hi2), ...].
The standard library offers
chain.from_iterable
to flatten such an iterable.
On to the meat of it.
Your shifting / masking approach seems to be a straightforward
translation of some C code, perhaps even an unrolled loop.
You point out it has several shortcomings.
An easy way to DRY it up would be to generate byte pairs:
def gen_lo_hi(word: int):
yield word & 0xFF
yield word1 >> 8 & 0xFF
words = (word1, word2, word3, word4)
result = bytes(map(gen_lo_hi, words))
You mentioned a performance concern,
which motivates avoiding the slight generator overhead.
The most natural way to address your serialization use case
is to simply use
pack
from the standard library.
It was designed for precisely what you're trying to do.
For 16-bit words your format string should be "HHHH"
plus the appropriate
byte order.
This code achieves only a subset of its goals.
Prior to merging down to main,
it should be replaced by the standard pack(...) approach. | {
"domain": "codereview.stackexchange",
"id": 44619,
"lm_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, array, integer, byte",
"url": null
} |
python, primes, interview-questions
Title: Generate nth prime number in Python
Question: Today I had an interview, where I was asked to solve this problem:
Generate nth prime number. Given a signature below, write python logic
to generate the nth prime number:
def nth_prime_number(n):
# n = 1 => return 2
# n = 4 => return 7
# n = 10 => return 29
I wrote this code, but couldn't get through:
def nth_prime_number(n):
if n==1:
return 2
count = 1
num = 3
while(count <= n):
if is_prime(num):
count +=1
if count == n:
return num
num +=2 #optimization
def is_prime(num):
factor = 2
while (factor < num):
if num%factor == 0:
return False
factor +=1
return True
The overall feedback was that the code quality could be improved a lot, and that I should be more optimal in my approach. How can I improve this code?
Answer: Your is_prime() function checks if num is a multiple of any number below it. This means that it checks if it is a multiple of 2, 4, 6, 8, 10, etc. We know that if it isn't a multiple of 2, it won't be a multiple of 4, etc. This goes for all other numbers, if it isn't a multiple of 3, it won't be a multiple of 27 (3x3x3).
What you need to do is check if num is a multiple of any prime number before it.
def nth_prime_number(n):
# initial prime number list
prime_list = [2]
# first number to test if prime
num = 3
# keep generating primes until we get to the nth one
while len(prime_list) < n:
# check if num is divisible by any prime before it
for p in prime_list:
# if there is no remainder dividing the number
# then the number is not a prime
if num % p == 0:
# break to stop testing more numbers, we know it's not a prime
break | {
"domain": "codereview.stackexchange",
"id": 44620,
"lm_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, primes, interview-questions",
"url": null
} |
python, primes, interview-questions
# if it is a prime, then add it to the list
# after a for loop, else runs if the "break" command has not been given
else:
# append to prime list
prime_list.append(num)
# same optimization you had, don't check even numbers
num += 2
# return the last prime number generated
return prime_list[-1]
I'm sure someone else here will come up with an even more efficient solution, but this'll get you started. | {
"domain": "codereview.stackexchange",
"id": 44620,
"lm_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, primes, interview-questions",
"url": null
} |
python, beginner
Title: A small script that analyses a sentence
Question: I came up with 2 solutions for this small problem exercise - the script should take a sentence from the user and return 4 things - the number of lower case letters, the number of uppercase letters, the number of punctuation characters and the total number of characters (i.e. anything except spaces). Spaces are ignored. Would appreciate to know what could be improved and which one of them reads better or makes more sense, if at all?
The output looks like this:
Type a sentence: See u 2morrow!
Upper case: 1
Lower case: 9
Punctuation: 1
Total chars: 12
Solution 1
sentence = input("Type a sentence: ")
# Initialize a dictionary to store the counts
counts = {}
# Loop through each character in the sentence
counts["Upper case"] = len([char for char in sentence if char.isupper()])
counts["Lower case"] = len([char for char in sentence if char.islower()])
counts["Punctuation"] = len([char for char in sentence if not char.isalnum() and not char.isspace()])
counts["Total chars"] = len([char for char in sentence if not char.isspace()])
# Print the results
for k, v in counts.items():
print(f"{k}: {v}")
Solution 2
sentence = input("Type a sentence: ")
# Initialize a dictionary to store the counts
counts = {"Upper case": 0, "Lower case": 0, "Punctuation": 0, "Total chars": 0}
# Loop through each character in the sentence
for char in sentence:
if not char.isspace():
counts["Total chars"] += 1
if not char.isalnum():
counts["Punctuation"] += 1
elif char.isalpha():
if char.isupper():
counts["Upper case"] += 1
else:
counts["Lower case"] += 1
# Print the results
for k, v in counts.items():
print(f"{k}: {v}")
Answer:
len([char for char in sentence if char.isupper()]) | {
"domain": "codereview.stackexchange",
"id": 44621,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, beginner
Answer:
len([char for char in sentence if char.isupper()])
You create a list of \$O(n)\$ size. We can instead change the algorithm to use \$O(1)\$ memory by using sum(1 for ...). Similar to how you're summing in Solution 2.
We can DRY (Don't Repeat Yourself) the code by moving the line I highlighted into a function. We can then use lambda to make anonymous functions. The functions will take a char and return whether we want to count the value.
from typing import Callable
def count(chars: str, wanted: Callable[[str], bool]) -> int:
return sum(
1
for char in chars
if wanted(char)
)
...
counts["Upper case"] = count(sentence, str.isupper)
counts["Lower case"] = count(sentence, str.islower)
counts["Punctuation"] = count(sentence, lambda char: not char.isalnum() and not char.isspace())
counts["Total chars"] = count(sentence, lambda char: not char.isspace())
Solution 2 contains the 'Arrow anti-pattern'. You may be able to see; the start of each line is starting to look like an arrow head. The effect is harder to see in Python. As Python uses white space for indentation we don't have a lot of } to complete the arrow head. To resolve the 'Arrow anti-pattern' you can normally use break, continue or return statements to use less indentation.
We can flatten all the ifs onto the same indentation. However, doing so makes the groupings you have made readable far harder to read. So I'd use the following:
for char in sentence:
if char.isspace():
continue
counts["Total chars"] += 1
if not char.isalnum():
counts["Punctuation"] += 1
elif char.isalpha():
if char.isupper():
counts["Upper case"] += 1
else:
counts["Lower case"] += 1 | {
"domain": "codereview.stackexchange",
"id": 44621,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, beginner
However, we can change what you define the groupings to be to make the ifs fit on one indentation and still be readable.
for char in sentence:
if char.isspace():
continue
counts["Total chars"] += 1
if char.isupper():
counts["Upper case"] += 1
elif char.islower():
counts["Lower case"] += 1
elif not char.isalnum():
counts["Punctuation"] += 1
I find both to be quite readable in two very different ways. The first shows us what each value is quite easily. The second shows us the groupings quite easily. However neither succeed at doing both.
For the challenge, since we're not really grouping chars, Solution 1 is likely easier to understand. | {
"domain": "codereview.stackexchange",
"id": 44621,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, python-3.x, pygame
Title: Drawing a tilemap using python and pygame
Question: I am creating a tile-map in python using pygame. The code I have (see below) works OK, but I was wandering if there were any improvements.
This code creates a tilemap and scrolls it horizontally:
from enum import Enum
import pygame
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 500
TILE_SIZE = 50
class TileTypes(Enum):
AIR = 0
GRASS = 1
ROCK = 2
LAVA = 3
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen.fill((255,) * 3)
clock = pygame.time.Clock()
MAP_WIDTH = SCREEN_WIDTH // TILE_SIZE
MAP_HEIGHT = SCREEN_HEIGHT // TILE_SIZE
map_layout = [[TileTypes.AIR for j in range(MAP_WIDTH)]
for i in range(MAP_HEIGHT)]
def draw_map():
y = 0
for row in map_layout:
x = 0
for tile in row:
match tile:
case TileTypes.AIR:
pass
case TileTypes.GRASS:
pygame.draw.rect(screen, (0, 255, 0), (x, y, TILE_SIZE, TILE_SIZE))
case TileTypes.ROCK:
pygame.draw.rect(screen, (150, 150, 150), (x, y, TILE_SIZE, TILE_SIZE))
x += TILE_SIZE
y += TILE_SIZE
def scroll_map():
for row in map_layout:
row.append(row.pop(0))
map_layout[-2] = map_layout[-1] = [TileTypes.ROCK for i in range(MAP_WIDTH)]
map_layout[-3] = [TileTypes.GRASS for i in range(MAP_WIDTH)]
map_layout[-4][2:4] = map_layout[-4][6:8] = [TileTypes.GRASS for i in range(2)]
done = False
while not done:
if any(event.type == pygame.QUIT for event in pygame.event.get()):
done = True
scroll_map()
screen.fill((255,) * 3)
draw_map()
pygame.display.flip()
clock.tick(20)
pygame.quit()
I would be grateful for any improvements. | {
"domain": "codereview.stackexchange",
"id": 44622,
"lm_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, pygame",
"url": null
} |
python, python-3.x, pygame
clock.tick(20)
pygame.quit()
I would be grateful for any improvements.
Answer: I like this code.
It accomplishes a simple goal in a simple way, very direct and clear.
Conforming to pep8 and using Enum is very nice.
It reminds me of POKE -16298, 0 for LORES graphic mode.
Let's examine low level details first.
__main__ guard
pygame.init()
...
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
screen.fill((255,) * 3)
I'm not crazy about doing a bunch of stuff at top level.
Prefer to protect such statements with a main guard.
The standard idiom is:
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
Why do we do this?
Well, I understand that no file has an import scrolling_game
statement, yet.
But we anticipate that could happen in future.
For example if you write a
unit test
or use a couple of modules to implement a fancier game.
The idea is that another file should be able to import
this one with no side effects, e.g. print() statements
or game windows opening.
So class / function definitions are fair game,
plus constants like width / height.
But the meat of the application typically goes into
def main(): which we run according to what
the module __name__ is.
Notice that, for someone importing this module,
the module name will look like "scrolling_game"
rather than "__main__".
That third statement, which blanks out the screen with white,
appears to be leftover from initial development / debug,
and should just be deleted.
Once the main display loop begins it becomes superfluous.
And defining a WHITE
manifest constant
wouldn't hurt.
cells dictate the display
def draw_map():
...
match tile:
case TileTypes.AIR:
pass
while not done:
...
screen.fill((255,) * 3) # <-- recommend you delete this
draw_map() | {
"domain": "codereview.stackexchange",
"id": 44622,
"lm_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, pygame",
"url": null
} |
python, python-3.x, pygame
while not done:
...
screen.fill((255,) * 3) # <-- recommend you delete this
draw_map()
I'm not keen on the pass, there.
Prefer to repaint every tile, every time,
rather than defaulting all tiles to AIR
followed by selective repaint of non-AIR tiles.
The current code makes sense, but I will
introduce an alternate repainting strategy below.
Also, the match works out fine.
But it would be better to put a color attribute
on each Enum value, so we could unconditionally
do lookup + render.
use an array
map_layout = [[TileTypes.AIR for j in range(MAP_WIDTH)]
for i in range(MAP_HEIGHT)]
In Lisp and in Python a list-of-lists datastructure
can be a very nice representation of N items
that are "all the same thing", like tiles.
But it suffers from chasing N object pointers,
which aren't cache friendly.
CPU hardware is good at predicting and prefetching
sequential reads, but less so for random reads.
Prefer to represent N tiles with a vector, perhaps an
array or an
ndarray.
That leaves us with something like
map_layout = np.ones((MAP_WIDTH, MAP_HEIGHT)) * TileTypes.AIR
slice when scrolling
A central concern is how to efficiently move the grid by
one tile in any direction.
Let's start with a level that spans several screens:
level = np.ones((5 * MAP_WIDTH, 3 * MAP_HEIGHT)) * TileTypes.AIR
Pure AIR would be boring, so fill in additional level tiles to taste.
Now let's render a portion of that level:
x, y = get_current_position()
map_layout = level[x : x+MAP_WIDTH][y : y+MAP_HEIGHT]
We can advance x or y by +/- 1 pixel
and re-render to scroll to a new spot within the level.
Rather than interpreted bytecode we are looping in C,
so it's essentially MAP_HEIGHT memcpy()'s per screen refresh,
with no random reads from chasing object pointers.
If all levels have similar dimensions, then you could
move from two dimensions to a three-dimensional array:
level[lvl][x][y] | {
"domain": "codereview.stackexchange",
"id": 44622,
"lm_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, pygame",
"url": null
} |
python, python-3.x, pygame
This is solid code.
I would be happy to delegate or accept maintenance tasks for it.
Recommend the use of array slicing for frame updates. | {
"domain": "codereview.stackexchange",
"id": 44622,
"lm_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, pygame",
"url": null
} |
python, tkinter
Title: A small REPL implementation using Tkinter
Question: I made a small POC for a REPL using Tkinter:
# importing modules
import tkinter as tk
import sys
import io
class REPL(tk.Frame):
def __init__(self, master=None):
# setting up widgets and needed variables
super().__init__(master)
self.master = master
self.master.title("REPL")
self.pack(fill=tk.BOTH, expand=True)
self.create_widgets()
self.history = []
self.history_index = 0
# useful for testing things, can be removed
self.master.wm_attributes("-topmost", True)
def create_widgets(self):
# set up the first text widget that will act as a "prompt", similar to python interpreter
# for both the first and second text widget, we hide the separation between them, mostly for aesthetic
self.prompt_widget = tk.Text(self, height=20, width=4, borderwidth=0, highlightthickness=0)
self.prompt_widget.pack(side=tk.LEFT, fill=tk.Y)
self.prompt_widget.insert(tk.END, ">>> ")
# set up the second text widget that will act as the input/output for our repl
self.text_widget = tk.Text(self, height=20, width=76, borderwidth=0, highlightthickness=0)
self.text_widget.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
self.text_widget.focus()
# set up a basic colorscheme, I preferred this one because of eyesight
self.prompt_widget.configure(bg='black', fg='white')
self.text_widget.configure(bg='black', fg='white')
# invert color of blinking cursor to match the background and foreground
self.text_widget.config(insertbackground="white") | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
# adding mousewheel support, so we can scroll on both text widget at the same time, in a synchronous way
# to match the prompt related to the start of each input in the second widget
self.text_widget.bind("<MouseWheel>", self.sync_scrolls)
self.prompt_widget.bind("<MouseWheel>", self.sync_scrolls)
# Here is the main way to either type a newline, or execute our input
# Using Shift+Return to execute commands, and Return to just type a normal newline
self.text_widget.bind("<Shift-Return>", self.execute_command)
self.text_widget.bind("<Return>", self.newline)
# goes up and down in history
self.text_widget.bind('<Up>', self.history_show)
self.text_widget.bind('<Down>', self.history_show)
# useful for preventing any "input" if the blinking cursor happen to be on any other places than the latest prompt
self.text_widget.bind('<Key>', self.is_last_line)
# prevent clicking on the prompt widget
self.prompt_widget.bind("<Button-1>", self.do_nothing)
# copy,paste,cut using Ctrl+c,Ctrl+v,Ctrl+x respectively
self.text_widget.bind("<Control-c>", self.copy)
self.text_widget.bind("<Control-v>", self.paste)
self.text_widget.bind("<Control-x>", self.cut)
def copy(self, event):
# copy, which isn't supported by default in this case
self.text_widget.event_generate("<<Copy>>")
return "break"
def paste(self, event):
# supported by default for some reason, but still set it up anyway
self.text_widget.event_generate("<<Paste>>")
return "break"
def cut(self, event):
# cut, also already supported by default on Windows 10, but you never know...
self.text_widget.event_generate("<<Cut>>")
return "break" | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
def sync_scrolls(self, event):
# sync the two text widget scrolling, doesn't seem to always work
if event.delta == -120:
self.prompt_widget.yview_scroll(1, "units")
self.text_widget.yview_scroll(1, "units")
elif event.delta == 120:
self.prompt_widget.yview_scroll(-1, "units")
self.text_widget.yview_scroll(-1, "units")
return "break"
def newline(self, event):
# make a newline for Return
self.text_widget.insert(tk.END, "\n")
return "break"
def do_nothing(self, event):
# just useful to make a tkinter component do nothing. Might not always work (eg: for tag related method/function, etc)
return "break"
def execute_command(self, event):
# set up variable for the last line of the prompt widget, last line text/secondary widget, and command
prompt_last_line = int(self.prompt_widget.index(tk.END).split(".")[0]) - 1
text_last_line = int(self.text_widget.index(tk.END).split(".")[0]) - 1
command = self.text_widget.get(f"{prompt_last_line}.0", f"{text_last_line}.end").strip()
# check if the command variable is empty, which happens if only the Return key or any key mapped to the newline method is used
if not command:
self.prompt_widget.insert(tk.END, "\n>>> ")
self.text_widget.insert(tk.END, "\n")
return "break"
# append to history
self.history.append(command)
self.history_index = len(self.history) | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
# here we execute and show result if there is any
code = command
self.text_widget.see(tk.END)
try:
# so here we both cache the result of any print() used, and reuse the global namespace and local namespace,
# so we can execute command "non-continuously", like modern REPL, eg: ipython
stdout = sys.stdout
sys.stdout = io.StringIO()
global_ns = sys.modules['__main__'].__dict__
local_ns = {}
exec(code, global_ns, local_ns)
result = sys.stdout.getvalue()
sys.stdout = stdout
global_ns.update(local_ns)
except Exception as e:
result = str(e)
# we insert the result
self.text_widget.insert(tk.END, f"\n{result}")
# this part is to "fill" the prompt widget, so we can delimit the starting and end of an input/output on the second widget
current_line = int(self.text_widget.index(tk.INSERT).split(".")[0])
prompt_line_index = f"{current_line}.0"
if current_line > prompt_last_line:
for i in range(prompt_last_line + 1, current_line + 1):
self.prompt_widget.insert(f"{i}.0", "\n")
self.prompt_widget.insert(prompt_line_index, "\n>>> ")
def is_last_line(self, event):
# useful method to know if our blinking cursor is currently on current valid latest prompt, which is equal to the latest "\n>>> " in the first widget, and current line in the second widget
current_line = int(self.text_widget.index(tk.INSERT).split(".")[0])
prompt_last_line = int(self.prompt_widget.index(tk.END).split(".")[0]) - 1 | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
# if the blinking cursor is before the latest prompt
if current_line < prompt_last_line:
return "break"
# if blinking cursor is at first line of valid prompt of the second widget/last line of prompt widget, prevent backspace from occuring, since it can circuvent the binding to <Key>
elif current_line == prompt_last_line and event.keysym == "BackSpace":
cursor_index = self.text_widget.index(tk.INSERT)
if cursor_index == f"{current_line}.0":
return "break"
# Same as for the backspace. technically this one isn't needed since we allow the cursor to move freely when clicking with the mouse, at least on the second widget
elif current_line == prompt_last_line and event.keysym == "Left":
cursor_index = self.text_widget.index(tk.INSERT)
if cursor_index == f"{current_line}.0":
return "break"
else:
pass | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
def history_show(self, event):
# show history in a very rudimentary way. no deduplication, history replacement on edit, etc.
prompt_last_line = int(self.prompt_widget.index(tk.END).split(".")[0]) - 1
current_line = int(self.text_widget.index(tk.INSERT).split(".")[0])
text_last_line = int(self.text_widget.index(tk.END).split(".")[0]) - 1
if event.keysym == "Up" and current_line == prompt_last_line:
if self.history_index > 0:
self.history_index -= 1
self.text_widget.delete(f"{prompt_last_line}.0", f"{text_last_line}.end")
self.text_widget.insert(f"{prompt_last_line}.0", self.history[self.history_index])
return "break"
elif event.keysym == "Down" and text_last_line == prompt_last_line:
if self.history_index < len(self.history) - 1:
self.history_index += 1
self.text_widget.delete(f"{prompt_last_line}.0", f"{text_last_line}.end")
self.text_widget.insert(f"{prompt_last_line}.0", self.history[self.history_index])
return "break"
root = tk.Tk()
repl = REPL(master=root)
repl.mainloop()
I'm wondering if there is any way to improve this, aside from adding new features (eg: autocomplete, etc) since I want to concentrate on solidifying what I already have first.
I mostly made this as a learning experience, and also because of other project where I wanted to try and use my own REPL, and work my way up (I already know about common libraries for this, such as bpython, ipython, etc to name a few)
Added comments. Here is the keybindings: | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
Ctrl+c -> Copy
Ctrl+v -> Paste
Ctrl+x -> Cut
Arrow keys (Up, Down, Left, Right) -> Move the blinking cursor around the current prompt (not outside of it). Up and Down show history whenever the cursor is either on last or first line.
Return/Enter key -> Normal behavior/produce a newline
Shift+Return -> Execute command, show output if there is any (need to use print since it cache its output)
Up/Down arrow key -> If commands were executed previously, then they will be shown when using those keys.
Left Mouse click -> only move the blinking cursor, and support selecting text on the input/output widget. Does nothing if used on the first widget, where the prompts appear.
MouseWheel -> (not tested on touchpad, works on external mouse). Support scrolling up and down.
Python version: 3.8.10
Tkinter version: 8.6.9
OS: Windows 10
Repository: https://github.com/secemp9/tkinter-repl
Any feedback is appreciated. | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
Answer: If nothing else, this was a good reminder to me that tkinter is a pain.
Drop comments like # importing modules that make the code less obvious than just reading the code.
Consider moving from is-a (inherit from Frame) to has-a (instantiate Frame) for better encapsulation.
Don't use master as a variable name.
Rather than packing, I find the grid layout to be more maintainable. Don't make fixed-size widgets. I am going to go further and suggest that you don't need separate widgets at all: instead, you can have a single multi-line Text and work with indices. Among other advantages, this will obviate your alignment problems.
Don't assign new variables to self outside of the constructor.
Your current solution has not redirected stderr; it needs to do that.
Your newline and execute key bindings are backwards to what most users will expect. <Return> should execute, and some modifier should insert a new line in the statement.
Make a utility method to decode index strings.
I don't think that it's wise to use __main__ for your namespace. Make one fresh namespace for each of globals and locals, and persist it throughout the program.
exec is not used correctly here. Currently your code will only show stdout and cannot evaluate expressions. This is not what most users of a repl will expect. Instead, the proper usage is a two step compile/exec in mode single.
Don't str(e). You should show a backtrace. I demonstrate how to do this.
Protect the last three statements in a __main__ guard.
Suggested
import tkinter as tk
import traceback
from sys import exc_info
from typing import Optional, Callable, Iterator
class StdoutSys:
def __init__(self, handler: Callable[[str], None]) -> None:
import sys
self.sys = sys
self.write = handler
self.old_stdout = sys.stdout
self.old_stderr = sys.stderr
def __enter__(self) -> 'StdoutSys':
self.sys.stdout = self
self.sys.stderr = self
return self | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
def __exit__(self, exc_type, exc_val, exc_tb) -> None:
self.sys.stdout = self.old_stdout
self.sys.stderr = self.old_stderr
class REPL:
def __init__(self, parent: Optional[tk.Tk] = None) -> None:
self.text = text = tk.Text(
parent, background='black', foreground='white',
insertbackground='white')
text.grid(row=0, column=0, sticky='NSEW')
text.focus()
text.bind('<Return>', self.handle_execute)
text.bind('<Up>', self.history_show)
text.bind('<Down>', self.history_show)
text.bind('<Key>', self.handle_key)
self.history: list[str] = []
self.history_index = 0
self.local_ns = {}
self.global_ns = {}
self.prompt_index = '0.0'
self.new_prompt()
def coord(self, index: Optional[str] = None) -> Iterator[int]:
"""Convert from tk y.x coordinate string format to integers"""
if index is None:
index = self.prompt_index
for part in self.text.index(index).split('.'):
yield int(part)
def new_prompt(self) -> None:
self.write('>>> ')
self.move_to_end()
self.prompt_index = self.text.index(tk.INSERT)
def move_to_end(self) -> None:
self.text.mark_set(markName=tk.INSERT, index=tk.END)
def execute(self, command: str) -> None:
self.history.append(command)
self.history_index = len(self.history)
with StdoutSys(self.write):
try:
expr = compile(source=command, filename='<input>', mode='single')
exec(expr, self.global_ns, self.local_ns)
except SystemExit:
# Allow exit() to close the program
raise
except BaseException:
# Skip the first level of the stack (this function)
exc, value, tb = exc_info()
self.write(''.join(traceback.format_exception(exc, value, tb.tb_next))) | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
def handle_execute(self, event: tk.Event) -> Optional[str]:
alt_shift_ctrl = 0b1101
if event.state & alt_shift_ctrl:
# Do not execute on a modified return; allow editing
return
self.write('\n')
command = self.text.get(self.prompt_index, tk.END).rstrip()
if command:
self.execute(command)
self.new_prompt()
return 'break'
def write(self, content: str) -> None:
self.text.insert(tk.END, content)
def handle_key(self, event: tk.Event) -> Optional[str]:
y, x = self.coord('insert')
if event.keysym == 'BackSpace':
delta = -1
else:
delta = 1
key_pos = y, x + delta
prompt_pos = tuple(self.coord())
if key_pos >= prompt_pos:
return # editing in prompt; everything is OK
# We're before the prompt. Move to the end before editing.
self.move_to_end()
if event.keysym == 'BackSpace':
# Disallow deleting pre-prompt
return 'break'
def history_show(self, event: tk.Event) -> Optional[str]:
"""show history in a very rudimentary way. no deduplication, history replacement on edit, etc."""
prompt_line, _ = self.coord()
current_line, _ = self.coord(tk.INSERT)
last_line, _ = self.coord(tk.END)
last_line -= 1
if event.keysym == 'Up' and current_line == prompt_line:
if self.history_index <= 0:
return
self.history_index -= 1
elif event.keysym == 'Down' and current_line == last_line:
if self.history_index >= len(self.history) - 1:
return
self.history_index += 1
else:
return
self.text.delete(self.prompt_index, tk.END)
self.write(self.history[self.history_index])
return 'break' | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
python, tkinter
def main() -> None:
root = tk.Tk()
root.title('REPL')
root.rowconfigure(index=0, weight=1)
root.columnconfigure(index=0, weight=1)
REPL(parent=root)
root.mainloop()
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 44623,
"lm_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, tkinter",
"url": null
} |
strings, rust, pig-latin
Title: piglatin exercise in rust
Question: This is my attempt to make the exercise suggested at the end of this chapter of rust's official tutorial
pub fn to_pig_latin(phrase: &String) -> String {
let mut result = String::new();
for word in phrase.split(" ") {
let pig_latin_word = word;
let first_char = match pig_latin_word.chars().nth(0){
None => panic!("can't get first char in word: {}", phrase),
Some(c) => c,
};
if is_vowel(first_char) {
result += &(pig_latin_word.to_owned() + "-hay ");
} else {
result += &(pig_latin_word[1..].to_owned() + "-" + &first_char.to_string() + "ay ");
}
}
result[0..(result.len()-1)].to_string()
}
fn is_vowel(c :char)-> bool{
c.to_string() == String::from("a") ||
c.to_string() == String::from("e") ||
c.to_string() == String::from("i") ||
c.to_string() == String::from("o") ||
c.to_string() == String::from("u")
}
Edge cases such as empty input can be ignored.
I find this very ugly, but to be fair every rust program looks ugly to me.
I don't understand why I need to add to_owned() when I use pig_latin_word , I'm not writing to it seems, actually I did let pig_latin_word = word; exactly because I didn't want ownership problems with word (that is part of phrase).
So far rust's manual memory management feels like just following compiler's help messages until it compiles.
Answer: Not a bad start. Some ways it could be improved:
Use &str for String Slices
Currently, you cannot call to_pig_latin("apple"), because the input is a &String. It requires to_pig_latin(&String::from("apple")).
You don’t need to modify or move the input, so the signature should be
pub fn to_pig_latin(phrase: &str) -> String | {
"domain": "codereview.stackexchange",
"id": 44624,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, rust, pig-latin",
"url": null
} |
strings, rust, pig-latin
Now it will understand all stringy types, including a String, a &str or a string literal.
There are Some Bugs
Try this with an empty input string, one with all spaces, or one starting with capital A, E, I, O or U. In fact:
Write Test Cases
Maybe you did, but there are none included here. A basic start:
pub fn main() {
assert_eq!(to_pig_latin( "a b c d e f g h i j k l m n o p q r s t u v w x y z"),
"a-hay -bay -cay -day e-hay -fay -gay -hay i-hay -jay -kay -lay -may -nay o-hay -pay -qay -ray -say -tay u-hay -vay -way -xay -yay -zay" );
assert_eq!(to_pig_latin( "Australian babies complain dingoes eat flavorful girls hungrily in jumping kangaroo lairs munching no other poorer quoditian refreshment so teach utterly verily when xpounding youths zoology"),
"Australian-hay abies-bay omplain-cay ingoes-day eat-hay lavorful-fay irls-gay ungrily-hay in-hay umping-jay angaroo-kay airs-lay unching-may o-nay other-hay oorer-pay uoditian-qay efreshment-ray o-say each-tay utterly-hay erily-vay hen-way pounding-xay ouths-yay oology-zay");
assert_eq!(to_pig_latin(""), "");
assert_eq!(to_pig_latin(" "), "");
}
Don’t Make Expensive Copies You Don’t Need
The biggest problem with the efficiency of this program is that it creates a lot of temporary strings, does round-trip conversions from the native UTF-8 format to 32-bit char and back, copies all but the last character of the result string into a new String object, and so on. Each of these needs to create an object, perform an allocation, and copy some data in linear time.
A good example is the implementation of is_vowel:
fn is_vowel(c :char)-> bool{
c.to_string() == String::from("a") ||
c.to_string() == String::from("e") ||
c.to_string() == String::from("i") ||
c.to_string() == String::from("o") ||
c.to_string() == String::from("u")
} | {
"domain": "codereview.stackexchange",
"id": 44624,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, rust, pig-latin",
"url": null
} |
strings, rust, pig-latin
This creates two String objects at runtime and compares them. You could just have compared
(c == 'a') || (c == 'e') || (c == 'i') || (c == 'o') || (c == 'u') ||
(c == 'A') || (c == 'E') || (c == 'I') || (c == 'O') || (c == 'U')
Or written the if is_vowel(first_char) test as a match expression:
match first_char {
'a' | 'e' | 'i' | 'o' | 'u' | 'A' | 'E' | 'I' | 'O' | 'U' => {
unimplemented!(); // You want to write these yourself.
}
'b' | 'c' | 'd' | 'f' | 'g' | 'h' | 'j' | 'k' | 'l' | 'm' |
'n' | 'p' | 'q' | 'r' | 's' | 't' | 'v' | 'w' | 'x' | 'y' |
'z' => {
unimplemented!(); // You want to write these yourself.
}
'B' | 'C' | 'D' | 'F' | 'G' | 'H' | 'J' | 'K' | 'L' | 'M' |
'N' | 'P' | 'Q' | 'R' | 'S' | 'T' | 'V' | 'W' | 'X' | 'Y' |
'Z' => {
unimplemented!(); // You want to write these yourself.
}
_ => {
unimplemented!(); // You want to write these yourself.
}
}
If you really, truly do need a comparison like this, at least compare to a const or static value or a literal, instead of creating a new temporary.
Similarly, instead of copying all but one char of result to a new String, you would be better off truncating result, or using a different approach, such as:
if !result.is_empty() {
result.push(' ');
}
or:
let separator : &str = if accumulator.is_empty() {""} else {" "};
Another of these, you noticed yourself and asked for feedback on:
result += &(pig_latin_word.to_owned() + "-hay "); | {
"domain": "codereview.stackexchange",
"id": 44624,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, rust, pig-latin",
"url": null
} |
strings, rust, pig-latin
The reason this needed .to_owned() is that you can’t add string slices—only a slice to a String (so .to_string() or String::from would also have worked). There’s no space at the end of a slice to add anything to, and no way to resize it. So you end up creating a temporary String on the right hand side of +=, then converting that to a slice. Not only does this look ugly, it ends up copying all the bytes that you append, twice.
One way around this would be to write:
result += word;
result += "-hay";
(You don’t need pig_latin_word, since you just set it to word and never modify it, but this copy is harmless.) However, there’s a nicer alternative. Even though this more fluent style looks as if it would need to make a temporary copy of result, in fact, rustc is able to optimize away the extra copy when you write:
result = result + word + "-hay"; | {
"domain": "codereview.stackexchange",
"id": 44624,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, rust, pig-latin",
"url": null
} |
strings, rust, pig-latin
So this is a zero-cost abstraction. The reason this works is that, in Rust (unlike C++ or Java), adding something to a string consumes the string on the left side of the +. (Therefore, if you do want to add something to a String and also use the original again, you want something like let hello_world = hello.clone() + ", world!";.)
Work on Slices Instead
Whenever possible, you want to be working with slices of the underlying array of bytes, which can be created, resized or passed around in constant time. This is a bit tricky to do here, because a Rust String is, internally, not an array of char like in many other languages. It’s really an array of u8 holding bytes encoded in UTF-8, so you do not have random access to each char, only sequential. Therefore, concatenating string slices is a zero-cost abstraction, but iterating over each char in a string is not: it has to convert between UTF-8 and UCS-4.
The interface you actually want to do this efficiently is not taught in the Rust Book: str::char_indices. So here’s a hint:
let mut indices = word.char_indices();
if let Some((0, first_char)) = indices.next() {
let mid = match indices.next() {
None => word.len(),
Some((i, _)) => i,
};
let (first_slice, rest_of_word) = word.split_at(mid);
/* Now first_slice is a slice containing the first letter of the word,
* and rest_of_word is a (possibly-empty) slice containing the rest of the
* word. As before, first_char is the first Unicode character of the
* word as a 32-bit char. You decide what to do with them here.
*/
} else {
unreachable!("A word was not valid UTF-8");
} | {
"domain": "codereview.stackexchange",
"id": 44624,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, rust, pig-latin",
"url": null
} |
strings, rust, pig-latin
Consider Refactoring with a Helper Function
Currently, you have a for loop that iterates over the words in the input as string slices. This is a good approach! But there are alternatives that you’ve seen if you’ve done functional programming before, but not in the Rust Book so far.
You can start by factoring out the body of the loop into a helper function, which can be nested inside to_pig_latin:
fn helper(accumulator: String, word: &str) -> String
What this should do is append the Pig-Latin translation of the word slice to the accumulator string, separated by a space, and return the updated accumulator. (You can move accumulator with let mut result = accumulator; to update it in place, or implement the function without that.) Doing it this way avoids creating any String other than accumulator, which can be moved instead of copied. This can simplify your for loop, but the real benefit of this is that there’s a very elegant abstraction for iterating over a sequence and passing each item to a function like this, then returning the final value.
The body of the to_pig_latin function can become simply
phrase.split_whitespace()
.fold(String::new(), helper)
Plus of course the definition of fn helper. I personally strongly prefer this style over a for loop. | {
"domain": "codereview.stackexchange",
"id": 44624,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "strings, rust, pig-latin",
"url": null
} |
java, algorithm, tree, validation, groovy
Title: Find Invalid User Relationships in User to Manager Map (validate map as valid tree structure with no circular relationships)
Question: We have a new service where an admin can upload a spreadsheet of new users they want to add to our application. During our processing we make a union map of all the users both existing and new additions, and check to make sure that the users will still be in a valid tree structure(s) after the update goes through.
Requirements:
For the user relationship tree structure to be valid,
There can be no circular references (ex. Users cannot be each other's manager)
A single branch of the tree cannot exceed 50 users (ex. There should not be 50 middle-management managers between CEO and Janitor).
Its ok if the tree is severed into multiple trees when a user does not have a manager. Separate warnings are generated for that circumstance.
This may need to scale to up to 1,000,000 user relationships, so far, the current solution supports at least 10,000 user relationships in a reasonable amount of time (less than 1 minute running locally).
FYI this is Groovy/Java
Solution So Far:
I have a method that takes a HashMap of user relationships and it returns a list of invalid users ids.
Map<String, String> userRelationships = [["userId1": "userId2"], ["userId2": "userId3"], ...]
def invalidRelationships = findInvalidRelationships(userRelationships) | {
"domain": "codereview.stackexchange",
"id": 44625,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, tree, validation, groovy",
"url": null
} |
java, algorithm, tree, validation, groovy
.
/**
* Takes a map of user relationships (user with corresponding manager)
* For each relationship, climb up the tree and look to see if the user is repeated in their branch
* If user is found again up the tree branch, that is a bad circular reference
* If the current branch goes on past 50 users, that is too long and also invalid
* Report all users that are part of that bad relationship
* userRelationship.key is the user
* userRelationship.value is the manager
*/
def findInvalidUserRelationships(Map<String, String> userRelationships) {
Set<String> invalidUserRelationshipUsers = []
userRelationships.each { Entry<String, String> currentUserRelationship ->
Set<String> usersInCurrentBranch = []
Entry<String, String> nextIterationRelationship = currentUserRelationship
while (
nextIterationRelationship?.value && //while not top of tree (not null manager)
!invalidUserRelationshipUsers.contains(nextIterationRelationship.key) && //while user not part of circular relationship
!usersInCurrentBranch.contains(nextIterationRelationship.key) //while user not connected to other circular relationship
) {
usersInCurrentBranch << nextIterationRelationship.key
//if bad circular relationship found or branch has more than max users, report users as invalid
if (nextIterationRelationship.value == currentUserRelationship.key || usersInCurrentBranch?.size() > 50) {
invalidUserRelationshipUsers += usersInCurrentBranch
}
//set next user relationship to check in next iteration (manager's manager) - (go upline)
nextIterationRelationship = new MapEntry(
nextIterationRelationship.value, //manager of current iteration user will be next user
userRelationships[nextIterationRelationship.value as String] //manager's manager
)
}
} | {
"domain": "codereview.stackexchange",
"id": 44625,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, tree, validation, groovy",
"url": null
} |
java, algorithm, tree, validation, groovy
)
}
}
return invalidUserRelationshipUsers as List<String>
} | {
"domain": "codereview.stackexchange",
"id": 44625,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, tree, validation, groovy",
"url": null
} |
java, algorithm, tree, validation, groovy
I have already made lots of optimizations, at least compared to how bad it was before using only Lists instead of Maps and Sets, but I was wondering if there would be a more efficient solution to this problem. I wondered if a Java TreeMap would be appropriate somewhere here, but could not figure out how it could improve performance.
Answer: Using TreeMap?
You have a tree represented in a HashMap, which is completely fine. A TreeMap has a specific tree structure based on comparable. I don't think the hierarchy of the employees can be expressed with a suitable comparable.
Variable names
Meaningful variable names are good. In this case, the operation of findInvalidUserRelationships is purely mathematical (finding cycles in a graph, checking whether the height of a tree exceeds 50) and I find it easier to understand the method using more math related names. It might also be more readable here to use
map.each { k, v -> println("key: $k, value: $v") }
instead of
map.each { entry -> println("key: $entry.key, value: $entry.value") }
So I have rewritten your method and in the following I will refer to the rewritten version.
List<String> findInvalidNodes(Map<String, String> edges) {
Set<String> invalidNodes = []
edges.each { String currentNode, _ ->
Set<String> nodes = []
String child = currentNode
String parent = edges[currentNode]
while ( parent && !invalidNodes.contains(child) && !nodes.contains(child) ) {
nodes << child
if (parent == currentNode || nodes.size() > 50) {
invalidNodes.addAll(nodes)
}
child = parent
parent = edges[parent]
}
}
return invalidNodes as List<String>
} | {
"domain": "codereview.stackexchange",
"id": 44625,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, tree, validation, groovy",
"url": null
} |
java, algorithm, tree, validation, groovy
I have already conducted a minor change by replacing invalidNodes += nodes with invalidNodes.addAll(nodes). This can be a slight improvement of performance since invalidNodes grows over time and += creates a new list each time it is invoked while addAll simply adds items to the existing list.
Performance
You traverse the tree starting from each node to the top. Therefore there are several nodes that are visited multiple times. Think about a linear tree structure.
Map edges = (1..51).collectEntries { [it+1 as String, it as String] }
findInvalidNodes(edges)
The tree has 52 nodes and is therefore invalid. But since I built the map edges so that the order of entries is worst case, you start with nodes 1, 2, ..., 51 and need 1+2+3+...+51 = 1326 loops to detect that the nodes are invalid. If you started with the last entry of the map it would only take 51 loops.
Since the height is limited to a constant amount I would see the method still as scalable. You can think about saving information for visited nodes and use that information once you find a visited node.
Is the Method working as intended?
Root node missing
Due to the while condition while(parent) a child with no parent (therefore all roots of the trees) cannot be treated as invalid. For the same reason a root node will never show up in nodes list so effectively you check for tree height > 51 and not tree height > 50.
Child of invalid Parent not invalid
Due to the while condition while ( !invalidNodes.contains(child) ) the loop breaks once the parent of a child is invalid. But the child is never added to the invalidNodes list. Is this really intended?
Map edges = (1..101).collectEntries { [it+1 as String, it as String] }}
assert findInvalidNodes(edges) == [2, 3, ..., 52] | {
"domain": "codereview.stackexchange",
"id": 44625,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, tree, validation, groovy",
"url": null
} |
java, algorithm, tree, validation, groovy
This tree has 102 nodes, but only [2, 3, ..., 52] are invalid. 53, 54, ..., 102 are not treated as invalid. If you add one more
Map edges = (1..102).collectEntries { [it+1 as String, it as String] }}
findInvalidNodes(edges)
assert findInvalidNodes(edges) == [2, 3, ..., 103]
all nodes are recognized as invalid.
This also implies that the order of the entries in edges affects which nodes appear in the invalidNodes list:
Map<String, String> edges = [:]
edges["53"] = "51"
edges.putAll( (1..51).collectEntries { [it+1 as String, it as String] } )
assert findInvalidNodes(edges) == [2, 3, ..., 50, 51, 53]
Map<String, String> edges = [:]
edges.putAll( (1..51).collectEntries { [it+1 as String, it as String] } )
edges["53"] = "51"
assert findInvalidNodes(edges) == [2, 3, ..., 50, 51, 52]
Final words
Having said all this, for me as a non graph theory expert the task you are conducting - despite sounding so easy - is far from being trivial. So I would probably wind up with a lot of bugs in my code. But if I had to, I would rebuild the tree in a custom tree structure so that I can traverse the tree starting from the root. That is very flexible, but has great overhead compared to a simple HashMap.
EDIT
I thought it would only be fair to give a solution (that might contain bugs). This uses a HashMap as a tree representation, but with parent as key and a list of children as value. I wasn't sure if you really wanted a height limit of 51 or just 50 so this should be adjusted to your requirements.
List findInvalidNodesUsingMap(Map edges) {
/*
convert tree representation
from child -> parent
to parent -> children
*/
Map tree = edges.groupBy { child, parent -> parent }
.collectEntries { parent, Map children -> [parent, children.keySet()] }
// nodes without parents must be roots
Set roots = edges.values().findAll { !(it in edges.keySet()) } | {
"domain": "codereview.stackexchange",
"id": 44625,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, tree, validation, groovy",
"url": null
} |
java, algorithm, tree, validation, groovy
/*
since all nodes can have at most one parent,
all paths with cycles cannot have a root node.
therefore, all nodes that cannot be accessed starting
from one of the root nodes must be part of a path
containing a cycle
*/
Set validRoots = roots.findAll { heightBelowLimit(it, 1, tree) }
Set validNodes = []
validRoots.each { collectNodes(it, tree, validNodes) }
Set invalidNodes = (roots + edges.keySet()).findAll { !(it in validNodes) }
return invalidNodes as List
}
Boolean heightBelowLimit(String node, int level, Map tree){
if(level > 50){
false
}else {
!tree.containsKey(node)
? true
: tree[node].every { heightBelowLimit(it, level + 1, tree) }
}
}
void collectNodes(String node, Map tree, Set nodes){
nodes << node
if(tree.containsKey(node)){
tree[node].each { collectNodes(it, tree, nodes) }
}
} | {
"domain": "codereview.stackexchange",
"id": 44625,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, tree, validation, groovy",
"url": null
} |
performance, c, multithreading, pathfinding
Title: Multithreading a shortest path algorithm | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
Question: I would like to modify my shortest path finding code to use multithreading and improve its performance. The algorithm must be able to work with negative weights, and as a result, we cannot use Dijkstra's algorithm. Instead, our approach combines three algorithms: Bellman-Ford, SPFA_Queue (shortest path fast algorithm, an improvement over Bellman-Ford that uses a queue and is faster in some cases), and SPFA_MinHeap (a second variation of SPFA that uses a minheap).
After carrying out a large number of tests, we have determined the optimal conditions for selecting one of the three algorithms based on the size and density of the graph.
The question now is how to integrate multithreading in the most efficient way possible based on the way each algorithm works. If necessary, we are open to rewriting parts of the algorithms to enable multithreading and improve performance, we would like to retain the use of these three algorithms since they have proven to be very efficient so far, and we hope to preserve the performance gains obtained from previous work while achieving maximum optimization through multithreading.
I'm not asking for a full code review here. We're quite satisfied with the single-threaded code itself, and all the headers and used methods are properly defined and tested in separate files (which can be provided upon request).
However, our main concern is to find the most efficient strategy to implement multithreading into the current logic.
Here is the code in question:
/**
* Computes the shortest path between a given source node and all other nodes in a weighted graph using either the Bellman-Ford or SPFA_SLF algorithm based on the density and number of nodes in the graph.
*
* Arguments:
* links: A 2D array of integers representing the links between nodes. Each row represents a link and contains the indices of the two nodes and the cost of the link.
* links_size: The number of links in the links array. | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
* links_size: The number of links in the links array.
* s: The index of the starting node.
* dist: An array of size nb_nodes to store the shortest distances from each node to s.
* path: An array of size nb_nodes to store the shortest paths from each node to s.
* nb_nodes: The total number of nodes in the graph.
*
* Returns:
* 0 if the computation succeeded, 1 if a negative cycle was detected in the graph.
**/ | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
int shortest_path(sint links[][3], uint links_size, uint s, lsint *dist, uint *path, uint nb_nodes)
{
// Select algorithm based on graph density and number of nodes
if (links_size <= 100 || nb_nodes <= 100)
{
return bellman_ford(links, links_size, s, dist, path, nb_nodes);
}
else if (((double)links_size / (double)(nb_nodes)) < 1)
{
return SPFA_queue(links, links_size, s, dist, path, nb_nodes);
}
else
{
return SPFA_minheap(links, links_size, s, dist, path, nb_nodes);
}
}
// Version 1: classical Bellman-Ford algorithm
int bellman_ford(sint links[][3], uint links_size, uint s, lsint *dist, uint *path, uint nb_nodes)
{
int updates;
uint i;
uint j;
uint k;
// Initialize all elements of dist to INT64_MAX ("infinity").
for (i = 0; i < nb_nodes; i++)
{
dist[i] = INT64_MAX;
}
// Initialise path
memset(path, -1, nb_nodes * sizeof(sint));
dist[s] = 0;
// Perform nb_nodes - 1 iterations of Bellman-Ford algorithm
for (i = 0; i < nb_nodes - 1; i++)
{
updates = 0;
// For each link in the links array, attempt to update shortest distances for each node.
for (j = 0; j < links_size; j++)
{
uint node_from = links[j][0];
uint node_to = links[j][1];
lsint cost = links[j][2];
// If a shorter distance is found, store it in the dist array and update the path array
if ((dist[node_from] != INT64_MAX) && (dist[node_from] + cost < dist[node_to]))
{
dist[node_to] = dist[node_from] + cost;
path[node_to] = node_from;
updates++;
}
}
// If no update was made during the previous iteration, exit the loop
if (updates == 0)
{
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
// Check for negative cycle in the graph
for (k = 0; k < links_size; k++)
{
uint node_from = links[k][0];
uint node_to = links[k][1];
lsint cost = links[k][2];
// If a shorter distance is still found, there is a negative cycle
if ((dist[node_from] != INT64_MAX) && (dist[node_from] + cost < dist[node_to]))
{
// printf("Negative cycle detected\n");
return 1;
}
}
return 0;
}
// Version 2: SPFA using small label first method and a queue
int SPFA_queue(sint links[][3], uint links_size, uint s, lsint *dist, uint *path, uint nb_nodes)
{
queue_t *queue = create_queue(); // Initialize the queue
if (queue == NULL)
{
fprintf(stderr, "Failed to allocate memory for queue.\n");
return 1;
}
uint i;
uint *length = calloc(nb_nodes, sizeof *length); // Array to store the number of nodes in the shortest path for each node in the graph.
if (length == NULL)
{
fprintf(stderr, "Failed to allocate memory for length.\n");
free_queue(queue);
return 1;
}
// Initialize all elements of dist to INT64_MAX ("infinity").
for (i = 0; i < nb_nodes; i++)
{
dist[i] = INT64_MAX;
}
// Initialise path
memset(path, -1, nb_nodes * sizeof(sint));
dist[s] = 0; // Set the distance of the source node to 0
enqueue(queue, s); // Add the source node to the queue
length[s] = 1;
bool *in_queue = calloc(nb_nodes, sizeof(bool));
in_queue[s] = true; | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
bool *in_queue = calloc(nb_nodes, sizeof(bool));
in_queue[s] = true;
// While the queue is not empty, perform iterations of the algorithm
while (!is_empty(queue))
{
uint current_node = dequeue(queue); // Dequeue the next node to process
in_queue[current_node] = false;
// If the length of the shortest path for any link reaches nb_nodes, there is a negative cycle in the graph
if (length[current_node] >= nb_nodes)
{
// printf("Negative cycle detected\n");
free(length);
free(in_queue);
free_queue(queue);
return 1;
}
int min_node = -1;
lsint min_dist = INT64_MAX;
// Iterate through all the links in the graph
for (i = 0; i < links_size; i++)
{
// If the current link starts from the dequeued node (current_node)
if (links[i][0] == current_node)
{
uint node_from = links[i][0];
uint node_to = links[i][1];
lsint cost = links[i][2];
// If a shorter path is found, update the distances and paths
if (dist[node_from] + cost < dist[node_to])
{
dist[node_to] = dist[node_from] + cost;
path[node_to] = node_from;
length[node_to] = length[node_from] + 1;
// If the destination node (node_to) is not in the queue, enqueue it
if (!in_queue[node_to])
{
enqueue(queue, node_to);
in_queue[node_to] = true;
}
} | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
// Update the minimum distance and node for Small Label First (SLF)
if (dist[node_to] < min_dist)
{
min_dist = dist[node_to];
min_node = node_to;
}
}
}
if (min_node != -1)
{
// Move the node with the minimum distance to the front of the queue
move_to_front(queue, min_node);
}
}
free(length);
free(in_queue);
free_queue(queue);
return 0;
}
// Version 3: SPFA using a min_heap
int SPFA_minheap(sint links[][3], uint links_size, uint s, lsint *dist, uint *path, uint nb_nodes)
{
// Create a min heap to store the nodes and their distances.
MinHeap *heap = create_minheap(nb_nodes);
if (heap == NULL)
{
fprintf(stderr, "Failed to allocate memory for min heap.\n");
return EXIT_FAILURE;
}
uint i;
// Allocate memory for an integer array to keep track of whether a node is already in the heap.
uint *in_heap = calloc(nb_nodes, sizeof *in_heap);
if (in_heap == NULL)
{
fprintf(stderr, "Failed to allocate memory for in_heap.\n");
free_minheap(heap);
return EXIT_FAILURE;
}
// Create an array to store the number of nodes in the shortest path for each node in the graph.
uint *length = calloc(nb_nodes, sizeof *length); // Array to store the number of nodes in the shortest path for each node in the graph.
if (length == NULL)
{
fprintf(stderr, "Failed to allocate memory for length.\n");
free_minheap(heap);
free(in_heap);
return EXIT_FAILURE;
}
// Initialize all elements of dist to INT64_MAX ("infinity").
for (i = 0; i < nb_nodes; i++)
{
dist[i] = INT64_MAX;
}
// Initialize all elements of `path` to -1.
memset(path, -1, nb_nodes * sizeof(sint)); | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
// Initialize all elements of `path` to -1.
memset(path, -1, nb_nodes * sizeof(sint));
// Create an adjacency list to represent the graph.
adjacency_node_t **adj_list = create_adjacency_list(nb_nodes, links, links_size);
if (adj_list == NULL)
{
fprintf(stderr, "Failed to allocate memory for adj_list.\n");
free(length);
free(in_heap);
free_minheap(heap);
return EXIT_FAILURE;
}
// Set the distance of the source node to 0.
dist[s] = 0;
// Add the source node to the heap.
heap = insert_minheap(heap, s);
in_heap[s] = 1;
// Set the length of the shortest path for the source node to 1.
length[s] = 1;
// While the heap is not empty, perform iterations of the algorithm
while (heap->size != 0)
{
// Extract the node with the minimum distance from the heap.
uint current_node = get_min(heap);
heap = delete_minimum(heap);
in_heap[current_node] = 0;
// If the length of the shortest path for any link reaches nb_nodes, there is a negative cycle in the graph
if (length[current_node] >= nb_nodes)
{
// printf("Negative cycle detected\n");
free(length);
free_adjacency_list(adj_list, nb_nodes);
free(in_heap);
free_minheap(heap);
return EXIT_FAILURE;
}
adjacency_node_t *adj_node = adj_list[current_node];
// Loop over all the edges that start from the current node
while (adj_node != NULL)
{
uint node_to = adj_node->node_to;
lsint cost = adj_node->cost;
// If a shorter path is found, update the distances and paths
if (dist[current_node] + cost < dist[node_to])
{
dist[node_to] = dist[current_node] + cost;
path[node_to] = current_node;
length[node_to] = length[current_node] + 1; | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
// If the destination node (node_to) is not in the heap, insert it
if (!in_heap[node_to])
{
insert_minheap(heap, node_to);
in_heap[node_to] = 1;
}
}
adj_node = adj_node->next;
}
}
free(length);
free_adjacency_list(adj_list, nb_nodes);
free_minheap(heap);
free(in_heap);
return EXIT_SUCCESS;
}
Answer: Avoid redefining integer types
I see types like sint and uint, I think somewhere you have lines like:
typedef signed int sint;
typedef unsigned int uint;
However, I strongly recommend you avoid doing that. Your particular typedefs are unfamiliar to other people, who now have to check what sint means. It saved you some typing, but made the code harder to read. I recommend you use a combination of these two alternatives instead:
Use the standard fixed-width integer types like int32_t and uint32_t. They have the benefit that they have a well-defined size, whereas something like int and long int does not, and might vary between CPU architectures and even operating systems. For example, long int might not be 64-bits, and thus storing INT64_MAX in a lsint might not do what you want.
Also, for sizes, counts and indices, prefer using size_t.
Give them a name that reflects how they are used. For example, you might want to create type aliases named node_id and node_cost.
Create structs to group related data
Instead of representing links as arrays of length 3, create a struct to hold all the information:
struct link {
node_id from;
node_id to;
node_cost cost;
};
Then you don't have to remember the exact order in which things are stored in the array, and you can mix different types. It also avoids having to pass two-dimensional arrays to shortest_path:
int shortest_path(struct link links[], …) {…} | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
Avoid unnecessary floating point math
Converting integers to/from floating points can be expensive, and if your data is all integers, I would try to avoid it. For example:
else if (((double)links_size / (double)(nb_nodes)) < 1)
Can be rewritten as:
else if (links_size < nb_nodes) | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
Parallelizing the code
Not all algorithms lend themselves to be parallelized. Most require that the steps are done in a well-defined order, and having multiple threads work at the same time on the same problem might prevent that.
You can add mutexes to prevent multiple threads from modifying the same bit of data simultaneously. However, mutexes add some overhead, and if multiple threads try to access the same mutex often, a multi-threaded version of an algorithm might even be slower than a single-threaded version.
Even without the overhead of mutexes, using multiple threads only makes sense if a large part of the work can be done independently, and there is little need for synchronization between the threads (see Amdahl's law).
Finally, multiple threads allow more computation to be done at the same time, but unless you are on a NUMA system, all cores share access to the main memory, which can be a bottleneck. For example, it doesn't make sense to parallelize memset(), as one core can probably saturate the available memory bandwidth.
With all that in mind, let's look at the algorithms:
Bellman-Ford
In the main part of the algorithm, you could decide to parallelize the inner for-loop. Most of the time, each thread will work on a link between two nodes that none of the other threads are working on. However, the problem is that sometimes they might work on links with overlapping nodes. The algorithm only works correctly if the whole if-statement is executed atomically. That would require mutexes, and the overhead of that compared to the whole if-statement probably does not make it worth parallelizing. | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
performance, c, multithreading, pathfinding
You could try partitioning the graph into segments that have the least amount of links to other segments, and then have each thread do the interior links of one segment, and then afterwards process all the links between segments in a single-threaded way. That might work for some graphs, and would probably need very large graphs before the effort spent partitioning would give a net benefit.
SFPA
While Bellman-Ford didn't care about the order in which links were processed, the same is not true for the shortest path fast algorithms. The problem is that each time a node is visited, it modifies the order of the queue or heap. You would need a mutex to protect the queue or heap, but even then you cannot start multiple threads because you don't know what the right order is to visit the nodes. This makes it very hard to parallelize. I don't think this is a candidate for parallelization at all. | {
"domain": "codereview.stackexchange",
"id": 44626,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, multithreading, pathfinding",
"url": null
} |
python, performance
Title: Getting all combinations of an array by looping through binary numbers
Question: I need to loop through all possible combinations of an array for a project I'm doing. I'm doing this by looping through all integers in binary from 0 to 2^length of array - 1. Then, a 0 represents to not include the item at that index, and 1 represents to include the item at that index. Here is my code:
def binary_combinations(array):
combinations = []
total_combinations = 2 ** len(array) - 1
for i in range(total_combinations + 1):
binary_indexes = ("{:0" + str(len(array)) + "d}").format(int(str(bin(i))[2:]))
current_combination = []
for j in range(len(binary_indexes)):
if binary_indexes[j] == "1":
current_combination.append(array[j])
combinations.append(current_combination)
return combinations
So if I called print(binary_combinations([1, 2, 3, 4]), the output would be [[], [4], [3], [3, 4], [2], [2, 4], [2, 3], [2, 3, 4], [1], [1, 4], [1, 3], [1, 3, 4], [1, 2], [1, 2, 4], [1, 2, 3], [1, 2, 3, 4]].
In the context of my project, I want to check each combination as it is generated, instead of waiting for the entire array to be finished generating (so check the array [], if it works, break, otherwise move on to [4].
I am looking for the smallest possible array that satisfies a condition, so I need to loop through the sub-arrays from least to greatest length, and I don't have enough time to wait for the entire array of combinations to generate and then loop through it.
Is there a way to optimize the order of combinations I am creating, so the combinations are created in order of least to longest length?
Answer: DeathIncarnate's answer is already comprehensive in terms of code review. I would just like to address this point you made: | {
"domain": "codereview.stackexchange",
"id": 44627,
"lm_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, performance",
"url": null
} |
python, performance
I am looking for the smallest possible array that satisfies a condition, so I need to loop through the sub-arrays from least to greatest length, and I don't have enough time to wait for the entire array of combinations to generate and then loop through it.
Algorithmically, this is of the highest importance, as early stopping can mitigate the effects of combinatorial explosion as you pass in longer arrays.
The standard library function itertools.combinations already mentioned can be used to great effect here, with the use of yield from:
import itertools
def ordered_combinations(array):
for i in range(len(array) + 1):
yield from itertools.combinations(array, i)
This returns a "flat" generator over all combinations, starting with the 0-length combination, then 1-length combinations, 2-length combinations and so on:
>>> list(ordered_combinations([1, 2, 3]):
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
When used in a loop that stops when your condition is met, you never need to generate combinations longer than that minimum valid combination:
for sub_array in ordered_combinations([1, 2, 3]):
if condition(sub_array):
break
Or as a generator of matching combinations:
matches = (sub_array for sub_array in ordered_combinations([1, 2, 3]) if condition(sub_array))
first_match = next(matches)
(Just remember to not accidentally cast the generator to a list (with [, ]), as that obviates this benefit.) | {
"domain": "codereview.stackexchange",
"id": 44627,
"lm_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, performance",
"url": null
} |
c++, image
Title: A simple Image class utilizing the XTensor library
Question: I've been teaching myself C++, and I recently created a simple Image class that makes use of the XTensor library. With my Image class, users can easily read and write PNG or JPG images and convert an RGB image to a grayscale image.
If you're interested, you can check out the code for yourself in this repository. Please forgive the extensive comments in the code - I'm still in the process of learning C++.
Declaration of Image Class
To make things easier to read and review here, I've removed some of the extensive comments from my code.
The declaration of Image class:
#ifndef IMAGE_XTENSOR_HPP
#define IMAGE_XTENSOR_HPP
#include <memory>
#include <string>
#include <xtensor/xarray.hpp>
#include <xtensor/xio.hpp>
#include <xtensor/xview.hpp>
namespace mypackage::image {
struct ImageXTensor {
ImageXTensor();
explicit ImageXTensor(std::string file_path);
explicit ImageXTensor(int c, int h, int w);
explicit ImageXTensor(const xt::xtensor<double, 3> &input_matrix);
explicit ImageXTensor(const ImageXTensor &other);
ImageXTensor(ImageXTensor &&other);
ImageXTensor &operator=(const ImageXTensor &other);
ImageXTensor &operator=(ImageXTensor &&other);
~ImageXTensor();
bool operator==(const ImageXTensor &other) const;
int channels; // aka comp in std_image
int height;
int width;
int size;
std::unique_ptr<xt::xtensor<double, 3>> pixels;
bool save(std::string file_path);
void swap(ImageXTensor &other);
};
ImageXTensor rgb_to_grayscale_xtensor(const ImageXTensor &img);
xt::xarray<double> rgb_to_grayscale_xtensor(const xt::xarray<double> &pixels);
} // namespace mypackage::image
#endif | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
} // namespace mypackage::image
#endif
I hope you find that the declaration of the Image class is easy to understand. However, I have a question about the move constructor ImageXTensor(ImageXTensor &&other);. If I attach explicit keyword to the move constructor like explicit ImageXTensor(ImageXTensor &&other);, it will lead to a compilation error like below:
/home/lai/cmake_template/src/mypackage/image/image_xtensor.cpp: In function ‘mypackage::image::ImageXTensor mypackage::image::rgb_to_grayscale_xtensor(const mypackage::image::ImageXTensor&)’:
/home/lai/cmake_template/src/mypackage/image/image_xtensor.cpp:309:10: error: no matching function for call to ‘mypackage::image::ImageXTensor::ImageXTensor(mypackage::image::ImageXTensor&)’
309 | return gray;
| ^~~~
/home/lai/cmake_template/src/mypackage/image/image_xtensor.cpp:18:1: note: candidate: ‘mypackage::image::ImageXTensor::ImageXTensor()’
18 | ImageXTensor::ImageXTensor()
| ^~~~~~~~~~~~
/home/lai/cmake_template/src/mypackage/image/image_xtensor.cpp:18:1: note: candidate expects 0 arguments, 1 provided
make[2]: *** [src/mypackage/image/CMakeFiles/image_xtensor.dir/build.make:76: src/mypackage/image/CMakeFiles/image_xtensor.dir/image_xtensor.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:506: src/mypackage/image/CMakeFiles/image_xtensor.dir/all] Error 2
make: *** [Makefile:146: all] Error 2 | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
I tried to understand this error from this SO question, but I'm still not quite sure why this is happening. I understand explicit is used to prevent compilers do implicit conversion, and as a believer of explicit is always better than implicit, I think using explicit everywhere should be always preferred.
Thus, I would appreciate any insights or suggestions you might have.
Definition of Image class
Here is the complete definition of the Image class.
#include <cassert>
#include <cmath>
#include <filesystem>
#include <iostream>
#include <mypackage/image/image_xtensor.hpp>
#include <utility>
#include <xtensor/xadapt.hpp>
#include <xtensor/xarray.hpp>
#include <xtensor/xio.hpp>
#include <xtensor/xtensor.hpp>
#include <xtensor/xview.hpp>
#include <stb/stb_image.h>
#include <stb/stb_image_write.h>
namespace mypackage::image {
ImageXTensor::ImageXTensor()
: channels{0}, height{0}, width{0}, size{0}, pixels{nullptr} {
std::clog << "The default constructor takes no paramters.\n";
}
ImageXTensor::ImageXTensor(std::string file_path) {
std::clog << "The constructor takes a file path.\n";
unsigned char *img_data =
stbi_load(file_path.c_str(), &width, &height, &channels, 0);
if (img_data == nullptr) {
const char *error_msg = stbi_failure_reason();
std::cerr << "Failed to load image: " << file_path.c_str() << "\n";
std::cerr << "Error msg (stb_image): " << error_msg << "\n";
std::exit(1);
}
pixels = std::make_unique<xt::xtensor<double, 3>>(
xt::zeros<double>({channels, height, width}));
size = pixels->size();
std::clog << "The image shape: " << channels << " x " << height << " x "
<< width << '\n';
assert(size == channels * height * width); | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
for (int c = 0; c < channels; c++) {
// PNG's pixels order is mysterious for me.
std::size_t src_idx = y * width * channels + x * channels + c;
// Rescale uint8 to float 0-1.
(*pixels)(c, y, x) = img_data[src_idx] / 255.;
}
}
}
if (channels == 4)
channels = 3; // ignore alpha channel
stbi_image_free(img_data);
}
ImageXTensor::ImageXTensor(int c, int h, int w)
: channels{c}, height{h}, width{w}, size{c * h * w},
pixels{std::make_unique<xt::xtensor<double, 3>>(
xt::zeros<double>({c, h, w}))} {}
ImageXTensor::ImageXTensor(const xt::xtensor<double, 3> &input_matrix) {
channels = input_matrix.shape(0);
height = input_matrix.shape(1);
width = input_matrix.shape(2);
size = input_matrix.size();
pixels = std::make_unique<xt::xtensor<double, 3>>(input_matrix);
}
ImageXTensor::ImageXTensor(const ImageXTensor &other)
: channels{other.channels}, height{other.height}, width{other.width},
size{other.size}, pixels{std::make_unique<xt::xtensor<double, 3>>(
xt::zeros<double>(
{other.channels, other.height, other.width}))} {
std::clog << "Copy Constructor\n";
*pixels = *other.pixels;
}
ImageXTensor &ImageXTensor::operator=(const ImageXTensor &other) {
std::clog << "Copy Assignment Operator\n";
if (this != &other) {
channels = other.channels;
height = other.height;
width = other.width;
size = other.size;
pixels = std::make_unique<xt::xtensor<double, 3>>(
xt::zeros<double>({other.channels, other.height, other.width}));
*pixels = *other.pixels;
}
return *this;
}
ImageXTensor::ImageXTensor(ImageXTensor &&other)
: channels{other.channels}, height{other.height}, width{other.width},
size{other.size}, pixels{std::move(other.pixels)} {
std::clog << "Move Constructor\n";
swap(other);
} | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
ImageXTensor &ImageXTensor::operator=(ImageXTensor &&other) {
std::clog << "Move Assignment Operator\n";
swap(other);
return *this;
}
ImageXTensor::~ImageXTensor() { std::clog << "Destruct Image.\n"; }
bool ImageXTensor::operator==(const ImageXTensor &other) const {
return (width == other.width) && (height == other.height) &&
(channels == other.channels) && (size == other.size) &&
(*pixels == *other.pixels);
}
bool ImageXTensor::save(std::string file_path) {
auto file_extension = std::filesystem::path(file_path).extension();
unsigned char *out_data = new unsigned char[width * height * channels];
/** NOTE: There seems to be no easy way to unfold a 3D array into a 1D array
* with the desired order.
*/
for (auto x = 0; x < width; x++) {
for (auto y = 0; y < height; y++) {
for (auto c = 0; c < channels; c++) {
int dst_idx = y * width * channels + x * channels + c;
// Fill out_data with uint8 values range 0-255.
out_data[dst_idx] = std::roundf((*pixels)(c, y, x) * 255.);
}
}
}
bool success{false};
if (file_extension == std::string(".jpg") ||
file_extension == std::string(".JPG")) {
auto quality = 100;
success = stbi_write_jpg(file_path.c_str(), width, height, channels,
out_data, quality);
} else if (file_extension == std::string(".png") ||
file_extension == std::string(".png")) {
auto stride_in_bytes = width * channels;
success = stbi_write_png(file_path.c_str(), width, height, channels,
out_data, stride_in_bytes);
} else {
std::cerr << "Unsupported file format: " << file_extension << "\n";
}
if (!success)
std::cerr << "Failed to save image: " << file_path << "\n";
delete[] out_data;
return true;
} | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
delete[] out_data;
return true;
}
void ImageXTensor::swap(ImageXTensor &other) {
std::swap(channels, other.channels);
std::swap(height, other.height);
std::swap(width, other.width);
std::swap(size, other.size);
std::swap(pixels, other.pixels);
}
ImageXTensor rgb_to_grayscale_xtensor(const ImageXTensor &img) {
assert(img.channels >= 3);
ImageXTensor gray(1, img.height, img.width);
xt::xarray<double> red = xt::view(*img.pixels, 0, xt::all(), xt::all());
xt::xarray<double> green = xt::view(*img.pixels, 1, xt::all(), xt::all());
xt::xarray<double> blue = xt::view(*img.pixels, 2, xt::all(), xt::all());
xt::view(*gray.pixels, 0, xt::all(), xt::all()) =
0.299 * red + 0.587 * green + 0.114 * blue;
return gray;
}
xt::xarray<double> rgb_to_grayscale_xtensor(const xt::xarray<double> &pixels) {
assert(pixels.shape(0) >= 3);
auto height = pixels.shape(1);
auto width = pixels.shape(2);
xt::xarray<double>::shape_type shape = {1, height, width};
xt::xarray<double> gray(shape);
xt::xarray<double> red = xt::view(pixels, 0, xt::all(), xt::all());
xt::xarray<double> green = xt::view(pixels, 1, xt::all(), xt::all());
xt::xarray<double> blue = xt::view(pixels, 2, xt::all(), xt::all());
xt::view(gray, 0, xt::all(), xt::all()) =
0.299 * red + 0.587 * green + 0.114 * blue;
return gray;
}
} // namespace mypackage::image
I hope you find the implementation of the Image class to be straightforward.
Usage of Image class (You can find the code here)
Pass Image object to rgb_to_grayscale_xtensor:
bool rgb2gray_image_xtensor(std::string input, std::string output) {
mypackage::image::ImageXTensor in_img{input};
auto out_img = mypackage::image::rgb_to_grayscale_xtensor(in_img);
out_img.save(output);
return 0;
}
Pass xt::xarray<double> to rgb_to_grayscale_xtensor: | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
Pass xt::xarray<double> to rgb_to_grayscale_xtensor:
bool rgb2gray_image_xtensor_PassByTensor(std::string input,
std::string output) {
mypackage::image::ImageXTensor in_img{input};
mypackage::image::ImageXTensor out_img{in_img.channels, in_img.height,
in_img.width};
*out_img.pixels = mypackage::image::rgb_to_grayscale_xtensor(*in_img.pixels);
out_img.save(output);
return 0;
}
Unit test: (You can find the code here)
Test constructor and assignment operator:
#include <gtest/gtest.h>
#include <iostream>
#include <mypackage/image/image_xtensor.hpp>
#include <vector>
#include <xtensor/xadapt.hpp>
TEST(ImageXTensor, ClassAssertion) {
mypackage::image::ImageXTensor test_img1(2, 3, 4);
int counter = 0;
for (int x = 0; x < test_img1.width; x++) {
for (int y = 0; y < test_img1.height; y++) {
for (int c = 0; c < test_img1.channels; c++) {
(*test_img1.pixels)(c, y, x) = counter;
++counter;
}
}
}
std::clog << "test_img1:\n" << (*test_img1.pixels) << '\n';
std::clog << "Test Copy Constructor.\n";
mypackage::image::ImageXTensor test_img2{test_img1};
std::clog << "test_img2:\n" << (*test_img2.pixels) << '\n';
EXPECT_EQ(test_img2, test_img1);
std::clog << "Test Copy Assignment Operator.\n";
mypackage::image::ImageXTensor test_img3;
test_img3 = test_img1;
std::clog << "test_img3\n" << (*test_img3.pixels) << '\n';
EXPECT_EQ(test_img3, test_img1);
std::clog << "Test Move Assignment Operator.\n";
mypackage::image::ImageXTensor test_img4;
test_img4 = std::move(test_img1);
// test_img1 becomes unspecified after it's moved from.
EXPECT_EQ(test_img1.pixels, nullptr);
EXPECT_EQ(test_img4, test_img2);
} | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
As I'm still learning C++, I'm trying to focus on modern C++ and adhere to the best coding practices. If it's not too much trouble, I would appreciate it if you could review the code with modern C++ (especially those from C++17 and beyond) in mind. Additionally, any tips on following C++ best coding practices would be greatly appreciated.
Thank you.
Answer: Overview
My main question is if pixels actually needs to be a std::unique_ptr? Does xt::xtensor not support the empty set of pixels efficiently? If it does not support the empty set OR there is an efficiency concern then sure std::unique_ptr is a reasonable approach, otherwise it is overkill and you should remove it.
Since I don't know about xt::xtensor I am going to assume unique_ptr is a valid technique. BUT if not then your class be significantly simplified and all the compiler generated methods will work perfectly.
Answers to Questions / Comments
To make things easier to read and review here, I've removed some of the extensive comments from my code.
Comments are also subject to review usually.
I have seen some really bad omments that needed to be removed.
I understand explicit is used to prevent compilers do implicit conversion, and as a believer of explicit is always better than implicit, I think using explicit everywhere should be always preferred.
Really on needed for constructors that take 1 parameter as an argument. This will prevent the compiler auto converting the object by using the constructor implicitly where you might not have expected.
would appreciate it if you could review the code with modern C++ (especially those from C++17 and beyond) in mind.
I still use (param) when constructing an object a lot. Some people prefer {param}. There are a few corner case it helps solve. I tend to reserve '{}' for initializer lists.
Code Review
You have made this a struct:
struct ImageXTensor { | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
This means all members are public by default. That is probably not what you want because it looks like these memebrs:
int channels; // aka comp in std_image
int height;
int width;
int size;
std::unique_ptr<xt::xtensor<double, 3>> pixels;
maintain a valid state of the object. You may want to provide some form of validation or checking on member variables before they can be modified.
Minor syntax quible:
const xt::xtensor<double, 3> &variable
You use a C style of declaration. Putting the & beside the variable name mimiks the style used in C where the * is placed next to the variable. The more normal way is to put all type information in one place (left side) and then place the variable on the right.
const xt::xtensor<double, 3>& variable; // This is more normal in c++
The usage of explicit on constructors is only really needed on single argument constructors.
explicit ImageXTensor(std::string file_path);
explicit ImageXTensor(int c, int h, int w);
explicit ImageXTensor(const xt::xtensor<double, 3> &input_matrix);
explicit ImageXTensor(const ImageXTensor &other);
The idea is to prevent the compiler auto converting objects of one type into an ImageXTensor when the engineer is not paying attention.
So I would remove explicit from:
explicit ImageXTensor(int c, int h, int w);
explicit ImageXTensor(const ImageXTensor &other);
Looks like you the default constructor ImageXTensor() could be dropped and replaced by ImageXTensor(int c = 0, int h = 0, int w = 0) where you use default arguments.
The more normal way to define the assignment operator in a class that uses both move and copy is to define a single method that utilizes the move/copy constructor.
So:
ImageXTensor &operator=(const ImageXTensor &other);
ImageXTensor &operator=(ImageXTensor &&other);
Can be replaced by the single method:
ImageXTensor& operator=(ImageXTensor other); | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
Can be replaced by the single method:
ImageXTensor& operator=(ImageXTensor other);
I will go into more detail below. But using the value parameter forces a copy in situations where the parameter is an L-Value and a move in situations when the parameter is an R-Value. Thus the body of the assignment simply needs to swap the current content with the parameter to get an effective assignment.
Not sure why this is a stand a lone method.
ImageXTensor rgb_to_grayscale_xtensor(const ImageXTensor &img);
xt::xarray<double> rgb_to_grayscale_xtensor(const xt::xarray<double> &pixels);
Could have been a member of ImageXTensor.
ImageXTensor::ImageXTensor(std::string file_path) {
....
if (img_data == nullptr) {
...
// If an object fails to construct correctly then throw an exception.
// At exit will not unwind the stack. An exception will unwind the
// stack and if not caught cause the application to exit.
// I would replace this with a throw.
// Put the error message in the exception and
// print the error message from the exception in main()
std::exit(1);
}
Another minor syntactical thing:
for (int x = 0; x < width; x++) {
This again looks like C. In C++ I would write this as:
for (int x = 0; x < width; ++x) {
// ^^. prefer prefix increment. | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
The code generated will not be different in this situation. But we often use this kind f loop with iterators. And here there may be a minor efficiency issue (probably not). But by using the prefix increment you always get the more effecient version (assuming the standard pattern for implementing iterators).
So if this is not an iterator why is it important. 1: Consistency. 2: If you use it all the time you will always use the correct increment. 3: A lot of times in C++ code we simply change the code by changing a type (so your integer may change to an iterator without you noticing). If you use the pre increment you don't need to go check usage of objects after you change the type.
Another minor thing:
(*pixels)(c, y, x) = img_data[src_idx] / 255.;
Don't like the 255. hard to spot that this is a floating point number. Just add the zero. 255.0.
Curious why you ignore alpha by default.
if (channels == 4)
channels = 3; // ignore alpha channel
Also add the braces to prevent accidental scope issues:
if (channels == 4) {
channels = 3; // ignore alpha channel
}
Where you allocate and then release a resource. I would always use RAII to make sure that the resource is freed even when exceptions happen (read above about stack unwinding).
stbi_image_free(img_data);
I would change the code to:
{
using ImageDate = unsigned char*;
using ImageRes = std::unique_ptr<ImageData, decltype(&stbi_image_free)>;
ImageRes img{
stbi_load(file_path.c_str(), &width, &height, &channels, 0),
stbi_image_free
};
// Stuff that could throw.
// We will call stbi_image_free() when
// img goes out of scope at the end of this function
// automatically.
} | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
Prefer to use the initializer list:
ImageXTensor::ImageXTensor(const xt::xtensor<double, 3> &input_matrix)
// In all the other constructors
// You initialized the members here.
// ----
// You should prefer to do it here.
// If the types are complex and use a constructor
// You would be constructing them here
// then using the assignment operator below
// thus effectively constructing them twice.
{
channels = input_matrix.shape(0);
height = input_matrix.shape(1);
width = input_matrix.shape(2);
size = input_matrix.size();
pixels = std::make_unique<xt::xtensor<double, 3>>(input_matrix);
}
Like this:
ImageXTensor::ImageXTensor(const xt::xtensor<double, 3> &input_matrix)
: channels(input_matrix.shape(0))
, height(input_matrix.shape(1))
, width(input_matrix.shape(2))
, size(input_matrix.size())
, pixels(std::make_unique<xt::xtensor<double, 3>>(input_matrix))
{}
Bug:
ImageXTensor::ImageXTensor(ImageXTensor &&other)
: channels{other.channels}, height{other.height}, width{other.width},
size{other.size}, pixels{std::move(other.pixels)} {
std::clog << "Move Constructor\n";
// This looks like a bug.
// You have already moved the pointer in `pixels`
// With this swap you are putting it back.
swap(other);
}
So this is bad practice (testing for assignment to self).
ImageXTensor &ImageXTensor::operator=(const ImageXTensor &other) {
std::clog << "Copy Assignment Operator\n";
if (this != &other) {
channels = other.channels;
height = other.height;
width = other.width;
size = other.size;
pixels = std::make_unique<xt::xtensor<double, 3>>(
xt::zeros<double>({other.channels, other.height, other.width}));
*pixels = *other.pixels;
}
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
c++, image
This means you are de-optimizing the most common situation (assignment not to self). Sure we have to cope with self assignment, but it happens so very rarely. So we try and optimize for the normal situaiton (not the none normal).
So we have developed the technique of copy and swap for copy assignment. This uses the copy constructor.
ImageXTensor &ImageXTensor::operator=(ImageXTensor const& rhs) {
ImageXTensor other(rhs)
swap(other);
return *this;
}
Now if we look at the move assignment:
ImageXTensor &ImageXTensor::operator=(ImageXTensor &&other) {
swap(other);
return *this;
}
It looks like the copy the only difference is the internal variable being swapped into. But if we change this assignment into:
ImageXTensor &ImageXTensor::operator=(ImageXTensor rhs)
{
swap(rhs);
return *this;
}
Now this function handles both move and copy effeciently. If the parameter is an L-Value then it is copyied into rhs, alternatively if the parameter is an R-Value then it is moved into rhs. We can then simply swap rhs and the content of the current object. When rhs goes out of scope it cleans everything.
Sure for logging:
ImageXTensor::~ImageXTensor() { std::clog << "Destruct Image.\n"; }
But normally you don't want to define the destructor if it does nothing.
If a method does not have a chance of throwing an exception it should be marked no-except. This is especially true if the method is move constructor. Also swap comes into that. | {
"domain": "codereview.stackexchange",
"id": 44628,
"lm_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++, image",
"url": null
} |
python, python-3.x, tkinter, caesar-cipher
Title: Simple encryption/decryption program using python (and tkinter)
Question: I am creating a simple program with a GUI to encrypt/decrypt text using different ciphers. I tried to make it so that it would be easy to add new ciphers.
This is my code:
import tkinter as tk
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
class Cipher:
# encode_fun and decode_fun should take in args (key, message).
def __init__(self, encode_fun, decode_fun):
self.encode_fun = encode_fun
self.decode_fun = decode_fun
self.output = None
def encode(self, key, message):
try:
self.output.delete(0, "end")
self.output.insert(0, self.encode_fun(key, message))
except:
return
def decode(self, key, message):
try:
self.output.delete(0, "end")
self.output.insert(0, self.decode_fun(key, message))
except:
return
def display(self, master):
frame = tk.Frame(master)
frame.pack()
encode_button = tk.Button(frame, text="Encode")
encode_button.pack(side="left")
decode_button = tk.Button(frame, text="Decode")
decode_button.pack(side="right")
tk.Label(frame, text="Key:").pack()
key_text_box = tk.Entry(frame)
key_text_box.pack()
tk.Label(frame, text="Text:").pack()
message_text_box = tk.Entry(frame)
message_text_box.pack()
self.output = tk.Entry(frame, background="gray", foreground="white")
self.output.pack()
encode_button.config(command=
lambda: self.encode(key_text_box.get(), message_text_box.get()))
decode_button.config(command=
lambda: self.decode(key_text_box.get(), message_text_box.get()))
def caesar_shift_encode(key, message):
encoded_message = ""
for char in message.lower():
try:
encoded_message += ALPHABET[(ALPHABET.index(char) + int(key)) % len(ALPHABET)] | {
"domain": "codereview.stackexchange",
"id": 44629,
"lm_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, tkinter, caesar-cipher",
"url": null
} |
python, python-3.x, tkinter, caesar-cipher
except:
encoded_message += char
return encoded_message
def caesar_shift_decode(key, message):
return caesar_shift_encode(str(-int(key)), message)
def xor_cipher_encode(key, message):
return "".join(
[ALPHABET[ALPHABET.index(key_char) ^ ALPHABET.index(message_char)]
for key_char, message_char in zip(key, message)]
)
root = tk.Tk()
caesar_shift = Cipher(caesar_shift_encode, caesar_shift_decode)
caesar_shift.display(root)
xor_cipher = Cipher(xor_cipher_encode, xor_cipher_encode)
xor_cipher.display(root)
tk.mainloop()
GUI:
I would be grateful to hear about any improvements that could be made to this code.
Answer: ALPHABET = "abcdefghijklmnopqrstuvwxyz"
We don't like from string import ascii_lowercase ? Ok, whatever.
self.output = None
def encode(self, key, message):
try:
self.output.delete(0, "end")
I don't understand what's going on here.
Did we want to initialize output to the [] empty list, instead?
self.output.insert(0, self.encode_fun(key, message))
Note that inserting at front is O(N),
while appending at end is O(1).
Consider using a
deque.
[EDIT: Later we see self.output = tk.Entry(frame, ....
Maybe the identifier output is on the vague side and
could be renamed to suggest that it's a display window?
Or maybe just a # commment here would help to
better communicate the intent.]
except:
return | {
"domain": "codereview.stackexchange",
"id": 44629,
"lm_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, tkinter, caesar-cipher",
"url": null
} |
python, python-3.x, tkinter, caesar-cipher
No.
This should apparently mention pass instead of return,
though there's no difference in behavior ATM.
A pass emphasizes to the Gentle Reader that
we're evaluating this method for side effects.
If we did want return for some reason,
consider making it an explicit return None,
since that is what happens. Prefer pass,
consistent with the signature's (lack of) type hints.
Avoid "bare except".
Prefer except Exception:,
so as not to interfere with KeyboardException.
Better yet, use except AttributeError: if
that's what you're expecting,
and fix the code defect which triggers "'NoneType' object has no attribute 'delete'"
if that's what motivated the try.
Kudos on keeping the Tk graphic calls confined to .display().
For one thing, this makes it easy to add
unit tests
later on for encode / decode.
I also appreciate how everything is a local variable
rather than defining self.this, self.that, and self.the_other.
It reduces coupling, and means the Reader has fewer
things to worry about when reading other bits of code.
Please add these type hints:
def caesar_shift_encode(key: str, message: str) -> str:
I initially expected key: int, based on the
usual definition of a Caesar cipher.
except:
encoded_message += char
No.
Here, at least, it is apparent that Author's Intent was
to cope with "ValueError: substring not found".
So say that explicitly.
In any event, don't use a bare except.
def xor_cipher_encode(key, message):
This is an odd signature.
It suggests parallel structure with the Caesar signature
that accepted a single integer f"{key}".
But it's not that.
In a crypto context we might expect 128 bits or 512 bits
of high-entropy keying material.
But it's not that.
It turns out the "key" is a "one-time pad". Ok.
I'm just surprised is all.
Validate that len(otp) >= len(message),
so caller won't be surprised by silent truncation.
root = tk.Tk() ...
Please protect this with a guard:
if __name__ == "__main__":
root = tk.Tk() ... | {
"domain": "codereview.stackexchange",
"id": 44629,
"lm_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, tkinter, caesar-cipher",
"url": null
} |
python, python-3.x, tkinter, caesar-cipher
Please protect this with a guard:
if __name__ == "__main__":
root = tk.Tk() ...
Why?
At some point you or a collaborator will want to
write a unit test,
which should be able to import this
without side effects.
This program accomplishes its design goals,
with fairly clear and mostly bug free code.
I would be happy to delegate or accept maintenance
tasks on this codebase. | {
"domain": "codereview.stackexchange",
"id": 44629,
"lm_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, tkinter, caesar-cipher",
"url": null
} |
c++, math-expression-eval
Title: C++ Binary Mathematics Class
Question: I am working on an arbitrary math lib. Below is a class I use to handle the binary mathematics needed for the library.
The class is quite simple. All it does is wrap around a vector of any unsigned integral type designated. Which in turn support binary operations on individual bits, or whole register words. Basic binary mathematics is supported. That way other classes using this to implement general arithmetic can be checked against this if needed for testing or troubleshooting purposes.
One specific area of concern is comparison using a float, for a return type. I use it to support partial ordering later in the project. Should this be updated to the C++20 way of handling it, or be left as is for support in other project not using C++20?
Any feedback is welcomed! I am trying to identify any blind spots I have in my coding abilities.
#include <bitset>
#include <limits>
#include <vector>
#include "../support_files/Type_Defines.h"
namespace Olly {
/********************************************************************************************/
//
// 'Binary_Register' class
//
// The Binary_Register class implements a series of binary registers sized to
// the integral type passed during to the template at definition.
//
// Support for all of the binary operation is provides, along with binary
// based mathematical operations. The implementation is little endian.
//
/********************************************************************************************/
template<typename N>
class Binary_Register {
static_assert(std::numeric_limits<N>::is_integer,
"The Binary_Register template argument T must be an unsigned integral.");
static_assert(std::numeric_limits<N>::is_signed ? false : true,
"The Binary_Register template argument T must be an unsigned integral."); | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
public:
using Word = N;
using Register = std::vector<N>;
static const N MASK = ~N(0);
static const std::size_t BITS = std::numeric_limits<N>::digits;
Binary_Register();
Binary_Register(const Text& value, Text base = "10");
Binary_Register(const std::size_t& size, Word value);
explicit
Binary_Register(const std::size_t& size);
virtual ~Binary_Register();
bool is() const; // bool conversion.
bool all() const; // bool test for all bits being set to 1.
std::size_t count() const; // The count of bits set to 1.
std::size_t lead_bit() const; // Return the lead bit.
std::size_t last_bit() const; // Return the last bit.
Word lead_reg() const; // Return the leading register.
Word last_reg() const; // Return the last register.
bool at_bit(std::size_t index) const; // Return the value of a bit at the index.
Word& at_reg(std::size_t index); // Return the word at the indexed register.
Word at_reg(std::size_t index) const;
Text to_string() const; // Return a string representation at radix 10.
Text to_string(N base) const; // Return a string representation at radix 'base'.
void to_string(Text_Stream& stream) const; // Send a string representation to a stream_type.
std::size_t size_bits() const; // Get the total size in bits of the register.
std::size_t size_regs() const; // Get the total size of words in the register. | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Binary_Register& resize_regs(std::size_t size); // Resize the register to 'size' number of elements.
Binary_Register& resize_regs(std::size_t size, Word n);
Binary_Register& set(); // Set all bits to true.
Binary_Register& set(std::size_t index); // Set a bit at 'index' to true.
Binary_Register& reset(); // Set all bits to false.
Binary_Register& reset(std::size_t index); // Set a bit at 'index' to false.
Binary_Register& flip(); // Flip the truth of every bit in the register.
Binary_Register& flip(std::size_t index); // Flip the truth of a bit at 'index'.
bool operator==(const Binary_Register& b) const;
bool operator!=(const Binary_Register& b) const;
bool operator< (const Binary_Register& b) const;
bool operator> (const Binary_Register& b) const;
bool operator<=(const Binary_Register& b) const;
bool operator>=(const Binary_Register& b) const;
Binary_Register& operator&=(const Binary_Register& other);
Binary_Register& operator|=(const Binary_Register& other);
Binary_Register& operator^=(const Binary_Register& other);
Binary_Register& operator<<=(std::size_t index);
Binary_Register& operator>>=(std::size_t index);
Binary_Register operator&(const Binary_Register& b) const;
Binary_Register operator|(const Binary_Register& b) const;
Binary_Register operator^(const Binary_Register& b) const;
Binary_Register operator~() const;
Binary_Register operator<<(std::size_t index) const;
Binary_Register operator>>(std::size_t index) const; | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Binary_Register& operator+=(const Binary_Register& other);
Binary_Register& operator-=(const Binary_Register& other);
Binary_Register& operator*=(const Binary_Register& other);
Binary_Register& operator/=(const Binary_Register& other);
Binary_Register& operator%=(const Binary_Register& other);
Binary_Register operator+(const Binary_Register& b) const;
Binary_Register operator-(const Binary_Register& b) const;
Binary_Register operator*(const Binary_Register& b) const;
Binary_Register operator/(const Binary_Register& b) const;
Binary_Register operator%(const Binary_Register& b) const;
Binary_Register& operator++();
Binary_Register operator++(int);
Binary_Register& operator--();
Binary_Register operator--(int);
template<typename I>
N to_integral() const; // Cast the register to an integral of type T.
Binary_Register bin_comp() const; // Return the binary compliment of the register.
// Get both the qotient and the remainder of the regester divided by 'other'.
void div_rem(Binary_Register& other, Binary_Register& qot, Binary_Register& rem) const;
float compare(const Binary_Register& other) const;
Binary_Register& trim(); // Remove all trailing zeros, from the register.
// But leave atleast one register, even if a value of zero.
private:
typedef std::bitset<BITS> single_prc_bitset;
typedef std::bitset<BITS + BITS> double_prc_bitset;
static const N ONE = 1;
Register _reg;
void get_shift_index(std::size_t& index, std::size_t& reg_index, std::size_t& bit_index) const;
void divide_remainder(const Binary_Register& x, Binary_Register y, Binary_Register& q, Binary_Register& r) const;
Text get_string(N base) const; | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Text get_string(N base) const;
void left_shift_bits(std::size_t& word_index, std::size_t& bit_index);
void right_shift_bits(std::size_t& word_index, std::size_t& bit_index);
};
/********************************************************************************************/
//
// 'Binary_Register' implimentation
//
/********************************************************************************************/
template<typename N>
inline Binary_Register<N>::Binary_Register() : _reg(1, 0) {
}
template<typename N>
inline Binary_Register<N>::Binary_Register(const std::size_t& size) : _reg((size > 0 ? size : 1), 0) {
}
template<typename N>
inline Binary_Register<N>::Binary_Register(const std::size_t& size, Word value) : _reg((size > 0 ? size : 1), value) {
}
template<typename N>
inline Binary_Register<N>::Binary_Register(const Text& value, Text base) : _reg(1, 0) {
N base_radix = to<N>(base); // Get the base radix to use.
Binary_Register<N> radix(1, base_radix); // Define a Binary_Register to act as the radix.
for (auto i : value) { // Loop through each digit and add it to the Binary_Register.
Text digit_str = "";
digit_str.push_back(i);
N n = to<N>(digit_str);
if (n < base_radix) {
Binary_Register<N> digit(1, n);
operator*=(radix);
operator+=(digit);
}
}
}
template<typename N>
inline Binary_Register<N>::~Binary_Register() {
}
template<typename N>
inline bool Binary_Register<N>::is() const {
for (auto i : _reg) {
if (i) {
return true;
}
}
return false;
}
template<typename N>
inline bool Binary_Register<N>::all() const {
for (auto i : _reg) { | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
for (auto i : _reg) {
if (i != MASK) {
return false;
}
}
return true;
}
template<typename N>
inline std::size_t Binary_Register<N>::count() const {
std::size_t count = 0;
for (const auto i : _reg) {
auto n = i;
while (n > 0) {
if (n & 1) {
count += 1;
}
n >>= 1;
}
}
return count;
}
template<typename N>
inline std::size_t Binary_Register<N>::lead_bit() const {
std::size_t word_index = _reg.size();
Word mask = (ONE << (BITS - ONE));
for (auto i = _reg.crbegin(); i != _reg.crend(); ++i) {
word_index -= 1;
auto a = *i;
std::size_t bit_index = BITS;
while (a) {
if (a & mask) {
return bit_index + (word_index * BITS);
}
a <<= 1;
bit_index -= 1;
}
}
return 0;
}
template<typename N>
inline std::size_t Binary_Register<N>::last_bit() const {
std::size_t word_index = 0;
Word mask = 1;
for (auto i = _reg.cbegin(); i != _reg.cend(); ++i) {
auto a = *i;
std::size_t bit_index = 1;
while (a) {
if (a & mask) {
return bit_index + (word_index * BITS);
}
a >>= 1;
bit_index += 1;
}
word_index += 1;
}
return 0;
}
template<typename N>
inline N Binary_Register<N>::lead_reg() const {
if (_reg.empty()) {
return N(0);
}
return _reg.back();
}
template<typename N>
inline N Binary_Register<N>::last_reg() const {
if (_reg.empty()) {
return N(0);
}
return _reg.front();
} | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
if (_reg.empty()) {
return N(0);
}
return _reg.front();
}
template<typename N>
inline bool Binary_Register<N>::at_bit(std::size_t index) const {
std::size_t reg_index, bit_index;
get_shift_index(index, reg_index, bit_index);
if (reg_index < _reg.size()) {
return _reg[reg_index] & (ONE << (bit_index - ONE));
}
return false;
}
template<typename N>
inline N& Binary_Register<N>::at_reg(std::size_t index) {
while (index >= _reg.size()) {
_reg.push_back(0);
}
return _reg[index];
}
template<typename N>
inline N Binary_Register<N>::at_reg(std::size_t index) const {
if (index < _reg.size()) {
return _reg[index];
}
return Word(0);
}
template<typename N>
inline Text Binary_Register<N>::to_string() const {
return to_string(10);
}
template<typename N>
inline Text Binary_Register<N>::to_string(N base) const {
if (base > 360) {
return "Radix must be between 0 and 360.";
}
if (base == 0) {
Text_Stream stream;
to_string(stream);
return stream.str();
}
if (!is()) {
return "0";
}
return get_string(base);
}
template<typename N>
inline void Binary_Register<N>::to_string(Text_Stream& stream) const {
std::size_t i = _reg.size();
while (i-- > 1) {
stream << "word[" << i << "] = " << single_prc_bitset(_reg[i]).to_string() << "\n";
}
stream << "word[" << 0 << "] = " << single_prc_bitset(_reg[i]).to_string();
}
template<typename N>
inline std::size_t Binary_Register<N>::size_bits() const {
return _reg.size() * BITS;
}
template<typename N>
inline std::size_t Binary_Register<N>::size_regs() const {
return _reg.size();
} | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::resize_regs(std::size_t size) {
_reg.resize(size);
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::resize_regs(std::size_t size, Word n) {
_reg.resize(size, n);
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::set() {
for (auto i = _reg.begin(); i != _reg.end(); ++i) {
*i = MASK;
}
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::set(std::size_t index) {
std::size_t reg_index, bit_index;
get_shift_index(index, reg_index, bit_index);
while (reg_index >= _reg.size()) {
_reg.push_back(0);
}
_reg[reg_index] |= (ONE << (bit_index - ONE));
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::reset() {
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] = Word(0);
}
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::reset(std::size_t index) {
std::size_t reg_index, bit_index;
get_shift_index(index, reg_index, bit_index);
while (reg_index >= _reg.size()) {
_reg.push_back(0);
}
_reg[reg_index] &= ~(1 << (bit_index - 1));
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::flip() {
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] = ~_reg[i];
}
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::flip(std::size_t index) {
std::size_t reg_index, bit_index;
get_shift_index(index, reg_index, bit_index);
while (reg_index >= _reg.size()) { | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
while (reg_index >= _reg.size()) {
_reg.push_back(0);
}
_reg[reg_index] ^= (1 << (bit_index - 1));
return *this;
}
template<typename N>
inline bool Binary_Register<N>::operator==(const Binary_Register<N>& b) const {
return compare(b) == 0;
}
template<typename N>
inline bool Binary_Register<N>::operator!=(const Binary_Register<N>& b) const {
return compare(b) != 0;
}
template<typename N>
inline bool Binary_Register<N>::operator<(const Binary_Register<N>& b) const {
return compare(b) < 0;
}
template<typename N>
inline bool Binary_Register<N>::operator>(const Binary_Register<N>& b) const {
return compare(b) > 0;
}
template<typename N>
inline bool Binary_Register<N>::operator<=(const Binary_Register<N>& b) const {
return compare(b) <= 0;
}
template<typename N>
inline bool Binary_Register<N>::operator>=(const Binary_Register<N>& b) const {
return compare(b) >= 0;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator&=(const Binary_Register<N>& other) {
while (_reg.size() < other._reg.size()) {
_reg.push_back(0);
}
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] &= other.at_reg(i);
}
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator|=(const Binary_Register<N>& other) {
while (_reg.size() < other._reg.size()) {
_reg.push_back(0);
}
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] |= other.at_reg(i);
}
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator^=(const Binary_Register<N>& other) {
while (_reg.size() < other._reg.size()) {
_reg.push_back(0);
} | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
while (_reg.size() < other._reg.size()) {
_reg.push_back(0);
}
for (std::size_t i = 0, end = _reg.size(); i < end; i += 1) {
_reg[i] ^= other.at_reg(i);
}
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator<<=(std::size_t index) {
std::size_t word_index, bit_index;
get_shift_index(index, word_index, bit_index);
if (word_index) {
_reg.insert(_reg.begin(), word_index, 0);
}
if (bit_index) {
left_shift_bits(word_index, bit_index);
}
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator>>=(std::size_t index) {
std::size_t word_index, bit_index;
get_shift_index(index, word_index, bit_index);
if (word_index) {
if (word_index < _reg.size()) {
_reg.erase(_reg.begin(), _reg.begin() + word_index);
}
else {
for (auto i = _reg.begin(), end = _reg.end(); i != end; ++i) {
*i = 0;
}
return *this;
}
}
if (bit_index) {
right_shift_bits(word_index, bit_index);
}
return *this;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator&(const Binary_Register<N>& b) const {
Binary_Register<N> a(*this);
a &= b;
return a;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator|(const Binary_Register<N>& b) const {
Binary_Register<N> a(*this);
a |= b;
return a;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator^(const Binary_Register<N>& b) const {
Binary_Register<N> a(*this);
a ^= b;
return a;
} | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Binary_Register<N> a(*this);
a ^= b;
return a;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator~() const {
Binary_Register<N> a = *this;
for (std::size_t i = 0, end = a._reg.size(); i < end; i += 1) {
a._reg[i] = ~a._reg[i];
}
return a;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator<<(std::size_t index) const {
Binary_Register<N> a(*this);
a <<= index;
return a;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator>>(std::size_t index) const {
Binary_Register<N> a(*this);
a >>= index;
return a;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator+=(const Binary_Register<N>& other) {
Binary_Register<N> b(other);
Binary_Register<N> c;
while (b.is()) {
c = (*this & b) << 1;
*this ^= b;
b = c;
}
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator-=(const Binary_Register<N>& other) {
if (other >= *this) {
return reset();
}
Binary_Register<N> b = other;
while (b.size_regs() < size_regs()) {
b._reg.push_back(0);
}
b = b.bin_comp();
b._reg.push_back(0); // Add a word to handle the two's compliment overflow.
*this += b;
_reg.pop_back(); // Get rid of the two's compliment overflow.
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator*=(const Binary_Register<N>& other) {
*this = *this * other;
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator/=(const Binary_Register<N>& other) {
*this = *this / other; | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
*this = *this / other;
return *this;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator%=(const Binary_Register<N>& other) {
*this = *this % other;
return *this;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator+(const Binary_Register<N>& b) const {
Binary_Register<N> a = *this;
a += b;
return a;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator-(const Binary_Register<N>& b) const {
Binary_Register<N> a = *this;
a -= b;
return a;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator*(const Binary_Register<N>& b) const {
std::size_t count = 0;
Binary_Register<N> x;
Binary_Register<N> y = b;
while (y.is()) {
if (y.at_bit(1)) {
x += (*this << count);
}
count += 1;
y >>= 1;
}
return x;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator/(const Binary_Register<N>& b) const {
Binary_Register<N> q;
Binary_Register<N> r = *this;
divide_remainder(*this, b, q, r);
return q;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator%(const Binary_Register<N>& b) const {
Binary_Register<N> q;
Binary_Register<N> r = *this;
divide_remainder(*this, b, q, r);
return r;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator++() {
Binary_Register<N> one(1, 1);
operator+=(one);
return *this;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator++(int) {
Binary_Register<N> a(*this);
operator++();
return a;
} | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Binary_Register<N> a(*this);
operator++();
return a;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::operator--() {
Binary_Register<N> one(1, 1);
operator-=(one);
return *this;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::operator--(int) {
Binary_Register<N> a(*this);
operator--();
return a;
}
template<typename N>
inline Binary_Register<N> Binary_Register<N>::bin_comp() const {
Binary_Register<N> a = ~*this;
Binary_Register<N> one(1, 1);
a += one;
return a;
}
template<typename N>
inline void Binary_Register<N>::div_rem(Binary_Register& other, Binary_Register& qot, Binary_Register& rem) const {
rem = *this;
divide_remainder(*this, other, qot, rem);
}
template<typename N>
inline float Binary_Register<N>::compare(const Binary_Register<N>& other) const {
std::size_t i = size_regs() > other.size_regs() ? size_regs() : other.size_regs();
while (i --> 0) {
auto x = at_reg(i);
auto y = other.at_reg(i);
if (x > y) {
return 1.0;
}
if (x < y) {
return -1.0;
}
}
return 0.0;
}
template<typename N>
inline Binary_Register<N>& Binary_Register<N>::trim() {
while (!_reg.empty() && _reg.back() == 0) {
_reg.pop_back();
}
if (_reg.empty()) {
_reg.push_back(0);
}
return *this;
}
template<typename N>
inline void Binary_Register<N>::get_shift_index(std::size_t& index, std::size_t& reg_index, std::size_t& bit_index) const {
if (index) {
if (index >= BITS) {
reg_index = index / BITS;
bit_index = index % BITS; | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
reg_index = index / BITS;
bit_index = index % BITS;
if (!bit_index) {
--reg_index;
bit_index = BITS;
}
return;
}
reg_index = 0;
bit_index = index;
return;
}
reg_index = 0;
bit_index = 0;
}
template<typename N>
inline void Binary_Register<N>::divide_remainder(const Binary_Register<N>& x, Binary_Register<N> y, Binary_Register<N>& q, Binary_Register<N>& r) const {
if (!y.is() || !x.is() || x < y) {
return;
}
std::size_t lead_x = x.lead_bit();
std::size_t lead_y = y.lead_bit();
std::size_t bit_dif = (lead_x - lead_y);
y <<= bit_dif;
bit_dif += 2;
while (bit_dif-- > 1) {
if (r >= y) {
q.set(bit_dif);
r -= y;
}
y >>= 1;
}
}
template<typename N>
inline Text Binary_Register<N>::get_string(N base) const {
Binary_Register<N> radix(1, base);
Binary_Register<N> n = *this;
Text_Stream stream;
while (n.is()) {
Binary_Register<N> q;
Binary_Register<N> r = n;
divide_remainder(n, radix, q, r);
n = q;
stream << r.at_reg(0);
}
Text res = stream.str();
std::reverse(res.begin(), res.end());
return res;
}
template<typename N>
inline void Binary_Register<N>::left_shift_bits(std::size_t& word_index, std::size_t& bit_index) {
std::size_t i = _reg.size();
_reg.push_back(0);
auto bit_mask = double_prc_bitset(MASK);
while (i-- > 0) {
auto buffer = double_prc_bitset();
buffer |= double_prc_bitset(_reg[i]);
buffer <<= bit_index;
_reg[i] = static_cast<N>((buffer & bit_mask).to_ullong()); | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
_reg[i] = static_cast<N>((buffer & bit_mask).to_ullong());
buffer >>= BITS;
buffer |= double_prc_bitset(_reg[i + 1]);
_reg[i + 1] = static_cast<N>(buffer.to_ullong());
}
if (_reg.back() == 0) {
_reg.pop_back();
}
}
template<typename N>
inline void Binary_Register<N>::right_shift_bits(std::size_t& word_index, std::size_t& bit_index) {
bool pop_back = word_index ? false : true;
if (word_index) {
word_index -= 1;
}
_reg.push_back(0);
auto inv_index = BITS - bit_index;
std::size_t end = (_reg.size() - 1);
auto bit_mask = double_prc_bitset(MASK);
for (std::size_t i = 0; i < end; i += 1) {
auto buffer = double_prc_bitset();
buffer |= double_prc_bitset(_reg[i + 1]);
buffer <<= inv_index;
_reg[i] >>= bit_index;
_reg[i] |= static_cast<N>((buffer & bit_mask).to_ullong());
}
_reg[end] >>= bit_index;
while (word_index-- > 0) {
_reg.push_back(0);
}
if (pop_back) {
_reg.pop_back();
}
}
template<typename N>
template<typename I>
inline N Binary_Register<N>::to_integral() const {
static_assert(std::numeric_limits<I>::is_integer, "Integral required.");
if (!_reg.empty()) {
auto bits_of_I = std::numeric_limits<I>::digits;
if (bits_of_I >= BITS && !_reg.empty()) {
return I(_reg.front());
}
I n = 0;
for (int i = BITS / bits_of_I; i >= 0; i -= 1) {
n <<= bits_of_I;
n += at_reg(i);
}
return static_cast<N>(n);
}
return I(0);
}
} | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
c++, math-expression-eval
Answer: Does this Need to be a Template Class?
You tell us that it can operate on vectors of any unsigned integral type, but is there any use case other than the native word size as an element type? (Which is normally size_t, although maybe you want to write it as using word_t = std::size_t just in case you need to define it differently for some weird target.)
You don’t actually need a double-width word to test for unsigned carry, because you can just compare the result to either operand. For multiplication, the only completely standard and portable way would be to convert 32-bit operands to unsigned long long so that all the bits of the product will fit, but some architectures have extensions you can use to do this faster.
If you really do need the template parameter, you can, as an alternative to the static_assert statements you have now, specify it as the C++20 concept template<std::unsigned_integral N>. It’s also one of several surprising names in the code. I would have expected a N template parameter to be an integral constant, not an integral type. If you do keep it, consider a name like Word.
Use a Spaceship Operator
You could use the code from your compare function to implement <=> and cut down on a lot of the boilerplate for comparisons. You probably still want operator== and operator!= declared separately, but I believe those can just be default.
Follow the Rule of Five
Or actually, six. This type wraps a std::vector, which is much more efficient to move than to copy, so it should have a copy constructor, a move constructor (which can both be default) and a swap operation.
Rvalue Reference Overloads Would be More Efficient | {
"domain": "codereview.stackexchange",
"id": 44630,
"lm_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++, math-expression-eval",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.