text stringlengths 1 2.12k | source dict |
|---|---|
python, beginner, python-3.x, programming-challenge, rock-paper-scissors
Prefer:
while not win:
When you have a boolean variable, like win,
there's usually little need to explicitly compare it to True or False.
canonicalize
if player1_Choice.lower() == player2_Choice.lower() and player1_Choice.lower() in victory_cond.keys() and player2_Choice.lower() in victory_cond.values():
Same issue as noted above.
Assign the downcased string from the get go:
player2_choice = input(f" ... ").lower()
Also, that third conjunct is kind of weird.
Recall that this is a true statement: set(victory_cond.keys()) == set(victory_cond.values()).
Given that 1st is identical to 2nd, and 1st is valid,
we can conclude that 2nd is valid.
Also, randomly switching from keys to values leaves the reader scratching their head.
Also, doing a key lookup takes O(1) constant time,
but asking for all values will take O(N) linear time.
Doesn't matter for a dict of size three,
but there would be a noticeable speed difference
if you copy-n-pasted such code into a situation
where you're manipulating a "large" dictionary.
Consider validating user input immediately.
That will simplify the {win, lose, draw} logic.
Consider breaking out a helper function
which prompts for a response
and which guarantees it's returning a valid response.
choose names carefully
This is not a great identifier.
list_of_rcp = ["rock", "paper", "scissors"]
Resist the urge to put "list" in the name of something that's a list,
or "dict" when it's a dict.
I have no idea what that letter "c" denotes.
DRY -- these three items appear elsewhere as keys!
Prefer:
rps = list(victory_cond)
Or maybe call it weapons.
Now you're all set for when we add
Spock and Lizard.
DRY: You should define victory_cond just once, in one source file,
and import it as needed.
next step
You have very similar "adjudicate game play" logic in two modules.
Re-work it a little, so that "computer" can be seen as "player 2". | {
"domain": "codereview.stackexchange",
"id": 45401,
"lm_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, python-3.x, programming-challenge, rock-paper-scissors",
"url": null
} |
beginner, performance, c, caesar-cipher
Title: ROT13 algorithm in C
Question: I am trying to learn C and I came across the ROT13 scrambling system used to store some passwords.
Assuming the user types everything in correctly (uses 1 argument, uses a string not an int, etc.) would this be correct/safe to use? Or is there anything at all that I am doing wrong you can point out to me (techniques, indentation, anything at all)?
#include <stdio.h>
#include <string.h>
int main(int argc, char** argv)
{
char* word = argv[1];
int key = 13;
// all the letters in the first argument
for (int n = 0, len = strlen(word); n < len; n++)
{
int currentLetter = word[n];
char cipher = currentLetter + key;
// make sure the next letter isn't over 26 or it isn't a ascii letter
// if it is, do %26
if ((currentLetter - 'a') + key > 26)
{
key = (currentLetter - 'a') + key) % 26;
cipher = 'a' + key;
}
printf("%c", cipher);
// reset the key and do the next letter
key = 13;
}
}
printf("\n");
return 0;
}
Answer: Test your program with a variety of inputs.
Include "abcdefghijklmnopqrstuvwxyz".
Have a look what happens for 'n'.
Always try to make sure you test low values, high values and edge cases.
'Wrapping round' is a classic edge case.
Then look at this line:
if ((currentLetter - 'a') + key > 26)
This program only works for lower case 'passwords'.
You might look at the functions in #include <ctype.h> such as tolower(.) or islower(.) to extend to mixing upper and lower case.
NB Obviously ROT13 has no real cryptographic value of any kind.
I mention that because I have seen it (and things not better) used in applications.
You're doing this as a learning exercise. Right? | {
"domain": "codereview.stackexchange",
"id": 45402,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, performance, c, caesar-cipher",
"url": null
} |
bash, concurrency
Title: Blocking lock for dpkg
Question: My deployment and configuration process entails multiple processes trying to invoke dpkg on my VM at the same time. While dpkg has a locking mechanism, it causes anyone not holding the lock who is trying to acquire it to fail, as opposed to blocking.
I want blocking behavior, so I renamed dpkg to dpkg-exec and am using the following shell script as dpkg (on Ubuntu 22.04). One tricky bit is making the lock re-entrant for spawned invocations of dpkg -- we only want locking against independent processes calling dpkg.
What I have below seems to work. I know there is at least one race condition, involving writing the PID of the acquiring process into the lockfile after acquiring it (somebody might be checking their process tree against the contents of this file between these two steps). I would appreciate any suggestions or improvements.
#!/bin/bash
# Path to the original dpkg executable
DPKG_EXEC="/usr/bin/dpkg-exec"
# Lock file path
LOCKFILE="/var/lib/dpkg/lock-custom"
# Acquire an exclusive lock using a file descriptor
touch $LOCKFILE
exec {LOCK_FD}<>$LOCKFILE
# Function to check if a PID is an ancestor of the current process
is_ancestor() {
target_pid=$1
current_pid=$2
while [[ $current_pid -ne 1 ]]; do
if [[ $current_pid -eq $target_pid ]]; then
return 0
fi
current_pid=$(awk '{ print $4 }' "/proc/$current_pid/stat")
done
return 1
}
# Function to clean up lock on exit
cleanup() {
# Check if the current process holds the lock
if [[ "$(cat $LOCKFILE)" == "$$" ]]; then
echo "*** Process $$ releasing dpkg lock" >&2
rm -f $LOCKFILE
flock -u $LOCK_FD
fi
}
# Set up a trap to call cleanup on script exit
trap cleanup EXIT
# Create the lock file if it doesn't exist
touch $LOCKFILE | {
"domain": "codereview.stackexchange",
"id": 45403,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, concurrency",
"url": null
} |
bash, concurrency
# Create the lock file if it doesn't exist
touch $LOCKFILE
# Check if the lock is already held by an ancestor of this process
lock_pid=$(cat $LOCKFILE)
if ! is_ancestor "$lock_pid" $$; then
# Acquire an exclusive lock
echo "*** Process $$ trying to acquire dpkg lock" >&2
flock -x $LOCK_FD
echo "$$" > $LOCKFILE
echo "*** Process $$ acquired dpkg lock" >&2
fi
# Execute the original dpkg command with all arguments passed to the script
"$DPKG_EXEC" "$@"
```
Answer: tl;dr: I don't like the Theory of Operation. And I agree with you that it races.
existing design
There is a single filename, dpkg, which two classes of callers may invoke:
ordinary (RUN lines in your Dockerfile)
re-entrant (a dpkg child calling itself for a subtask)
There are two touches and a flock -x which race to create a
file which is either zero length or which may contain a PID.
exec {LOCK_FD}<>$LOCKFILE
If I needed to concisely explain to someone on the phone what that does I would
have trouble with it, so I am reluctant to sign up for maintaining this script.
I saw no comment describing its behavior.
argv
I haven't investigated.
I guess we're pretty confident that re-entrant calls
use hardcoded dpkg (or /usr/bin/dpkg),
ignoring argv[0]?
Patching the installer source code would let you honor argv[0],
obviating the need to worry about lock reentrancy.
The inconvenience of doing that would be comparable
to what's involved for the current scheme to switch files around.
shellcheck
touch $LOCKFILE | {
"domain": "codereview.stackexchange",
"id": 45403,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, concurrency",
"url": null
} |
bash, concurrency
nit: Please routinely quote such variable interpolations.
Yes, I know, in this case there's no whitespace so it doesn't matter
that it doesn't lint clean.
is_ancestor
This seems nice and I imagine it works correctly,
modulo certain assumptions about how PIDs come and go on a running system.
It is certainly non-portable (for example to a MacOS development system).
cleanup
We rm while in the critical section.
I would prefer to see no -f force flag,
since it is an invariant of this script
that we shall have exclusive access when we attempt the unlink.
Better to see a diagnostic on stderr if some surprise is lurking in there.
I am accustomed to letting flock -u be responsible for all lock cleanup.
nit: The idiosyncratic indents make this code harder to read than necessary.
exec
"$DPKG_EXEC" "$@"
Surely we could get away with exec "$DPKG_EXEC" "$@" there?
I mean, we don't need the current shell nor any of its
resources (like file descriptors) any more, right?
proposed design
Don't disturb the dpkg that Debian installed.
Two classes of callers will invoke the appropriate name, according to their needs.
ordinary: dpkg.sh
re-entrant: /usr/bin/dpkg
If it's inconvenient to list "dpkg.sh" on many lines of your Dockerfiles,
we can fix it up with an alias, prepending a small bin directory to $PATH,
a symlink, or similar tricks.
So "ordinary" callers agree to "play nice" and come in through the front door.
Now it's simple.
We can use flock in exactly the way its
man page suggests.
This reduces support costs and increases reliability.
Caller asks for some installs to happen,
flock exclusively locks,
time passes,
the installs are done,
flock releases.
Simple.
A racing caller asks for other installs,
gets hung up on the lock,
patiently waits to acquire it,
and then carries on as above.
Re-entrant calls to dpkg are honored immediately with no locking,
exactly as they're handled on every other production Debian system. | {
"domain": "codereview.stackexchange",
"id": 45403,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, concurrency",
"url": null
} |
bash, concurrency
alternate design
A daemon is always doing tail -f on an install request file, or named pipe.
We replace /usr/bin/dpkg with a simple script which >> appends PID
plus the command (dpkg-exec -i baz-dev) to that file.
Optionally it verifies the daemon is running,
starting a new background daemon if need be.
The script uses tail -f to poll a done.txt status file,
and exits when it sees its request satisfied.
Daemon runs each install request in sequence,
with no racing overlaps.
As it finishes each one, it appends requestor's PID to done.txt,
perhaps annotated with things like exit status and timestamp.
Or more simply,
script does “sleep 3600” (sleep forever).
Daemon sends ALRM kill signal to wake it up.
Script either does a simple “exit 0” immediately, or it takes a moment to “tail” the status file looking for the appropriate exit code. | {
"domain": "codereview.stackexchange",
"id": 45403,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, concurrency",
"url": null
} |
python, type-hinting
Title: Postel’s law implementation with number.Complex as example
Question: I’m trying to implement, for educational purposes only, an example of the Postel’s law on a demonstrative function.
This function is not for production code, it’s for pedagogical purposes only and might be considered as an over abstraction to an easy to understand list comprehension. This isn’t the topic I’m interrested here, only type-hints and what can be infered from.
def update_prices(
prices: typing.Iterable[numbers.Complex],
increase_percentage: numbers.Complex
) -> list[numbers.Complex]:
return [price * (1 + increase_percentage / 100) for price in prices]
From my point of view, I think that
since the code only need the * and / implemented, even if a Real is expected, we could ask for a Complex, the super-type of a Real,
a / operator on a Complex should return a Complex, can’t we be more specific?
In python documentation, https://docs.python.org/3/library/numbers.html, Number is mentioned, is it better than Complex or Real?
Postel’s law or robustness principle: https://en.m.wikipedia.org/wiki/Robustness_principle
Answer: You are conflating
LSP with the
Robustness Principle.
They are similar but distinct concepts. | {
"domain": "codereview.stackexchange",
"id": 45404,
"lm_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, type-hinting",
"url": null
} |
python, type-hinting
Decades ago, when Postel worked at ISI, I was a big fan of Robustness.
But after {supporting, diagnosing, designing} systems implementing
protocols like DNS, RIP, OSPF, BGP, FTP, SMTP, and HTTP(S), plus
documents they transport, I find the principle can get in the way
just as much as it helps.
If there are multiple ways to express e.g. "noon in London on January 21st",
then a conforming implementation must be tested for each of those ways.
And standards documents don't always supply comprehensive test vectors.
Keeping track of "peer A's bug prevents it from using standard format X"
and "peer B's bug prevents it from using standard format Y" soon becomes tedious.
And impossible to support, as bug fixes and new (buggy?) features are rolled out.
Only a small fraction of global email ever went through rfc822-compliant
mail servers. Thank goodness for the rfc2822 update, which is simpler
and more amenable to testing.
When designing a system that should be Robust, go for simplicity.
There should be one obvious way to accomplish a use case.
Demand that interoperating implementations all support some bare bones Profile.
If you want to get fancy, specify additional negotiated superset profile(s),
which are implemented entirely or not at all.
The spec's appendix should include Normative test vectors for bakeoff testing.
If the spec says that a peer sending the Wrong Thing shall immediately
tear down the session with fatal error, then implementors soon learn to
send the Right Thing instead, and field testing will be less chaotic.
Liskov Substitution Principle is an OO concept about inheritance and contracts,
which lets us prove theorems about code.
Duck Typing is a concept about protocols and contracts,
which lets an implementer worry about "what can this object do?",
instead of "what is this object?".
When authoring pythonic code we often try to accommodate duck typed collaborators.
review
signature
def update_prices(
prices: typing.Iterable[numbers.Complex], ... | {
"domain": "codereview.stackexchange",
"id": 45404,
"lm_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, type-hinting",
"url": null
} |
python, type-hinting
review
signature
def update_prices(
prices: typing.Iterable[numbers.Complex], ...
This signature doesn't read smoothly.
And since it was constructed for didactic purposes,
readability is one of its principle goals.
Prefer:
from numbers import Complex
from typing import Iterable
def update_prices(
prices: Iterable[Complex], ...
docstring
There isn't one.
So you are asking the function's name to do the heavy lifting. We are told the
contract
is to "update [inflate] prices" by some increase_percentage.
(That last is a lovely identifier, and I thank you for it.)
Absent some flowery language in a docstring about what a price is
and what use cases might call for increasing them, we are left
with the bog standard definition.
Now, I concede that one might choose to offer a paperback for sale
according to this vector price:
price = 10 + 10.91j
where to actually make the transaction with a business partner
we would unpack like this:
eur, usd = price.real, price.imag
But the docstring didn't spell out such details, so this is a
POLA
violation.
Now suppose that next year it sells for one-eighth more:
>>> price * 1.125
(11.25+12.27375j)
Piece of cake.
Americans will spend more than twelve bucks, got it.
But wait, there's more!
The signature promised me that I can make complex increases.
Let's suppose inflation is coming down and we can only
manage an 8% U.S. increase.
Easily computed, right?
>>> price * (1.125 + 1.08j)
(-0.5328000000000017+23.07375j)
Hold on, we're giving folks half a Euro to take the book
off our hands? And Americans pay twenty-three bucks?
OIC, should be much better when we use your formula.
>>> price
(10+10.91j)
>>>
>>> price * (1 + (12.5 + 8j) / 100)
(10.3772+13.07375j)
Whoops, quite the bargain, still not satisfying that business use case.
Ok, I've had enough fun playing with your proposal.
The code you submitted for review lacked several important elements:
requirements document
internal documentation
test suite | {
"domain": "codereview.stackexchange",
"id": 45404,
"lm_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, type-hinting",
"url": null
} |
python, type-hinting
requirements document
internal documentation
test suite
We can skimp on those and get away with it, sometimes.
But it's not a sure thing.
is [Number] better than Complex or Real?
No.
When authoring a function, only make promises you can keep.
That is, promises which you have already verified, in your automated test suite,
and which you are willing to take support calls for.
Suppose that update_prices, or some downstream consumer of its result,
wants to round() a price to the nearest Euro.
This works for Decimal, Fraction, float, and int.
But it blows up horribly for Complex.
Even if it doesn't, when we ignore rounding,
simple text formatting operations are likely to yield surprising results
when diverse input types are attempted.
Beyond exceeding a column width, we may run afoul of regexes
that try to parse "numeric" data using too small of a character set.
Often a software engineer gets to design the rules a system will play by.
The Robustness Principle asks you to write robust code.
If you craft conservatively simple rules, your system will be more robust. | {
"domain": "codereview.stackexchange",
"id": 45404,
"lm_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, type-hinting",
"url": null
} |
c++, algorithm, recursion, c++20
Title: recursive_any_of and recursive_none_of Template Functions Implementation in C++
Question: This is a follow-up question for A recursive_all_of Template Function Implementation in C++ and A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++. Besides recursive_all_of template function implementation, I am trying to implement recursive_any_of and recursive_none_of template functions.
The experimental implementation
Implementation of recursive_any_of and recursive_none_of template functions
// recursive_any_of template function implementation
template<class T, class Proj = std::identity, class UnaryPredicate>
constexpr auto recursive_any_of(T&& value, UnaryPredicate&& p, Proj proj = {})
{
return recursive_count_if_all(std::invoke(proj, value), p) > 0;
}
// recursive_none_of template function implementation
template<class T, class Proj = std::identity, class UnaryPredicate>
constexpr auto recursive_none_of(T&& value, UnaryPredicate&& p, Proj proj = {})
{
return recursive_count_if_all(std::invoke(proj, value), p) == 0;
}
Full Testing Code
The full testing code:
// recursive_any_of and recursive_none_of Template Functions Implementation in C++
#include <algorithm>
#include <array>
#include <chrono>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <ranges>
#include <string>
#include <utility>
#include <vector>
// is_reservable concept
template<class T>
concept is_reservable = requires(T input)
{
input.reserve(1);
};
// is_sized concept, https://codereview.stackexchange.com/a/283581/231235
template<class T>
concept is_sized = requires(T x)
{
std::size(x);
};
template<typename T>
concept is_summable = requires(T x) { x + x; };
// recursive_unwrap_type_t struct implementation
template<std::size_t, typename, typename...>
struct recursive_unwrap_type { }; | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
template<class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_unwrap_type<1, Container1<Ts1...>, Ts...>
{
using type = std::ranges::range_value_t<Container1<Ts1...>>;
};
template<std::size_t unwrap_level, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_unwrap_type<unwrap_level, Container1<Ts1...>, Ts...>
{
using type = typename recursive_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container1<Ts1...>>
>::type;
};
template<std::size_t unwrap_level, typename T1, typename... Ts>
using recursive_unwrap_type_t = typename recursive_unwrap_type<unwrap_level, T1, Ts...>::type;
// recursive_variadic_invoke_result_t implementation
template<std::size_t, typename, typename, typename...>
struct recursive_variadic_invoke_result { };
template<typename F, class...Ts1, template<class...>class Container1, typename... Ts>
struct recursive_variadic_invoke_result<1, F, Container1<Ts1...>, Ts...>
{
using type = Container1<std::invoke_result_t<F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
template<std::size_t unwrap_level, typename F, class...Ts1, template<class...>class Container1, typename... Ts>
requires ( std::ranges::input_range<Container1<Ts1...>> &&
requires { typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...>::type; }) // The rest arguments are ranges
struct recursive_variadic_invoke_result<unwrap_level, F, Container1<Ts1...>, Ts...>
{
using type = Container1<
typename recursive_variadic_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container1<Ts1...>>,
std::ranges::range_value_t<Ts>...
>::type>;
};
template<std::size_t unwrap_level, typename F, typename T1, typename... Ts>
using recursive_variadic_invoke_result_t = typename recursive_variadic_invoke_result<unwrap_level, F, T1, Ts...>::type;
// recursive_array_invoke_result implementation
template<std::size_t, typename, typename, typename...>
struct recursive_array_invoke_result { };
template< typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
struct recursive_array_invoke_result<1, F, Container<T, N>>
{
using type = Container<
std::invoke_result_t<F, std::ranges::range_value_t<Container<T, N>>>,
N>;
}; | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
template< std::size_t unwrap_level,
typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires ( std::ranges::input_range<Container<T, N>> &&
requires { typename recursive_array_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges
struct recursive_array_invoke_result<unwrap_level, F, Container<T, N>>
{
using type = Container<
typename recursive_array_invoke_result<
unwrap_level - 1,
F,
std::ranges::range_value_t<Container<T, N>>
>::type, N>;
};
template< std::size_t unwrap_level,
typename F,
template<class, std::size_t> class Container,
typename T,
std::size_t N>
using recursive_array_invoke_result_t = typename recursive_array_invoke_result<unwrap_level, F, Container<T, N>>::type;
// recursive_array_unwrap_type struct implementation, https://stackoverflow.com/a/76347485/6667035
template<std::size_t, typename>
struct recursive_array_unwrap_type { };
template<template<class, std::size_t> class Container,
typename T,
std::size_t N>
struct recursive_array_unwrap_type<1, Container<T, N>>
{
using type = std::ranges::range_value_t<Container<T, N>>;
}; | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
template<std::size_t unwrap_level, template<class, std::size_t> class Container,
typename T,
std::size_t N>
requires ( std::ranges::input_range<Container<T, N>> &&
requires { typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>>::type; }) // The rest arguments are ranges
struct recursive_array_unwrap_type<unwrap_level, Container<T, N>>
{
using type = typename recursive_array_unwrap_type<
unwrap_level - 1,
std::ranges::range_value_t<Container<T, N>>
>::type;
};
template<std::size_t unwrap_level, class Container>
using recursive_array_unwrap_type_t = typename recursive_array_unwrap_type<unwrap_level, Container>::type;
// https://codereview.stackexchange.com/a/253039/231235
template<template<class...> class Container = std::vector, std::size_t dim, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<Container, dim - 1, T>(input, times));
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
std::array<decltype(n_dim_array_generator<dim - 1, times>(input)), times> output;
for (size_t i = 0; i < times; i++)
{
output[i] = n_dim_array_generator<dim - 1, times>(input);
}
return output;
}
}
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + std::size_t{1};
} | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
// recursive_depth function implementation with target type
template<typename T_Base, typename T>
constexpr std::size_t recursive_depth()
{
return std::size_t{0};
}
template<typename T_Base, std::ranges::input_range Range>
requires (!std::same_as<Range, T_Base>)
constexpr std::size_t recursive_depth()
{
return recursive_depth<T_Base, std::ranges::range_value_t<Range>>() + std::size_t{1};
}
/* recursive_foreach_all template function performs specific function on input container exhaustively
https://codereview.stackexchange.com/a/286525/231235
*/
namespace impl {
template<class F, class Proj = std::identity>
struct recursive_for_each_state {
F f;
Proj proj;
};
template<class T, class State>
requires(!std::ranges::input_range<T>)
constexpr void recursive_foreach_all(T& value, State& state) {
std::invoke(state.f, std::invoke(state.proj, value));
}
template<std::ranges::input_range T, class State>
constexpr void recursive_foreach_all(T& inputRange, State& state) {
for (auto& item: inputRange)
impl::recursive_foreach_all(item, state);
}
template<class T, class State>
requires(!std::ranges::input_range<T>)
constexpr void recursive_reverse_foreach_all(T& value, State& state) {
std::invoke(state.f, std::invoke(state.proj, value));
}
template<std::ranges::input_range T, class State>
constexpr void recursive_reverse_foreach_all(T& inputRange, State& state) {
for (auto& item: inputRange | std::views::reverse)
impl::recursive_reverse_foreach_all(item, state);
}
}
template<class T, class Proj = std::identity, class F>
constexpr auto recursive_foreach_all(T& inputRange, F f, Proj proj = {})
{
impl::recursive_for_each_state state(std::move(f), std::move(proj));
impl::recursive_foreach_all(inputRange, state);
return std::make_pair(inputRange.end(), std::move(state.f));
} | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
template<class T, class Proj = std::identity, class F>
constexpr auto recursive_reverse_foreach_all(T& inputRange, F f, Proj proj = {})
{
impl::recursive_for_each_state state(std::move(f), std::move(proj));
impl::recursive_reverse_foreach_all(inputRange, state);
return std::make_pair(inputRange.end(), std::move(state.f));
}
template<class T, class I, class F>
constexpr auto recursive_fold_left_all(const T& inputRange, I init, F f)
{
recursive_foreach_all(inputRange, [&](auto& value) {
init = std::invoke(f, init, value);
});
return init;
}
template<class T, class I, class F>
constexpr auto recursive_fold_right_all(const T& inputRange, I init, F f)
{
recursive_reverse_foreach_all(inputRange, [&](auto& value) {
init = std::invoke(f, value, init);
});
return init;
}
// recursive_count_if template function implementation
template<class T, std::invocable<T> Pred>
constexpr std::size_t recursive_count_if_all(const T& input, const Pred& predicate)
{
return predicate(input) ? std::size_t{1} : std::size_t{0};
}
template<std::ranges::input_range Range, class Pred>
requires (recursive_depth<Range>() != 0)
constexpr auto recursive_count_if_all(const Range& input, const Pred& predicate)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if_all(element, predicate);
});
} | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
template<std::size_t unwrap_level, class T, class Pred>
requires(unwrap_level <= recursive_depth<T>())
constexpr auto recursive_count_if(const T& input, const Pred& predicate)
{
if constexpr (unwrap_level > 0)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if<unwrap_level - 1>(element, predicate);
});
}
else
{
return predicate(input) ? 1 : 0;
}
}
/* recursive_all_of template function implementation
*/
template<class T, class Proj = std::identity, class UnaryPredicate>
constexpr auto recursive_all_of(T&& value, UnaryPredicate p, Proj proj = {}) {
return std::invoke(p, std::invoke(proj, value));
}
template<std::ranges::input_range T, class Proj = std::identity, class UnaryPredicate>
constexpr auto recursive_all_of(T& inputRange, UnaryPredicate&& p, Proj proj = {}) {
return std::ranges::all_of(inputRange, [&](auto&& range) {
return recursive_all_of(range, std::forward<UnaryPredicate>(p), proj);
}, proj);
}
// recursive_any_of template function implementation
template<class T, class Proj = std::identity, class UnaryPredicate>
constexpr auto recursive_any_of(T&& value, UnaryPredicate&& p, Proj proj = {})
{
return recursive_count_if_all(std::invoke(proj, value), p) > 0;
}
// recursive_none_of template function implementation
template<class T, class Proj = std::identity, class UnaryPredicate>
constexpr auto recursive_none_of(T&& value, UnaryPredicate&& p, Proj proj = {})
{
return recursive_count_if_all(std::invoke(proj, value), p) == 0;
} | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
template<std::ranges::input_range T>
constexpr auto recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::transform(input.cbegin(), input.cend(), output.begin(),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<std::ranges::input_range T>
requires (std::ranges::input_range<std::ranges::range_value_t<T>>)
constexpr T recursive_print(const T& input, const int level = 0)
{
T output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
}
void recursive_any_of_tests()
{
std::cout << "***recursive_any_of_tests function***\n";
auto test_vectors_1 = n_dim_container_generator<std::vector, 4, int>(1, 3);
test_vectors_1[0][0][0][0] = 3;
std::cout << "Play with test_vectors_1:\n";
if (recursive_any_of(test_vectors_1, [](int i) { return i == 2; }))
std::cout << "2 is one of the elements in test_vectors_1\n";
if (recursive_any_of(test_vectors_1, [](int i) { return i == 3; }))
std::cout << "3 is one of the elements in test_vectors_1\n";
}
void recursive_none_of_tests()
{
std::cout << "***recursive_none_of_tests function***\n";
auto test_vectors_1 = n_dim_container_generator<std::vector, 4, int>(1, 3);
test_vectors_1[0][0][0][0] = 3;
std::cout << "Play with test_vectors_1:\n";
if (recursive_none_of(test_vectors_1, [](int i) { return i == 0; }))
std::cout << "None of the elements in test_vectors_1 is 0\n";
} | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
int main()
{
auto start = std::chrono::system_clock::now();
recursive_any_of_tests();
recursive_none_of_tests();
auto end = std::chrono::system_clock::now();
std::chrono::duration<double> elapsed_seconds = end - start;
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::cout << "Computation finished at " << std::ctime(&end_time) << "elapsed time: " << elapsed_seconds.count() << '\n';
return 0;
}
The output of the test code above:
***recursive_any_of_tests function***
Play with test_vectors_1:
3 is one of the elements in test_vectors_1
***recursive_none_of_tests function***
Play with test_vectors_1:
None of the elements in test_vectors_1 is 0
Computation finished at Mon Jan 22 02:37:36 2024
elapsed time: 0.00119631
Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_all_of Template Function Implementation in C++ and
A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++
What changes has been made in the code since last question?
I am trying to implement recursive_any_of and recursive_none_of template functions in this post.
Why a new review is being asked for?
Please review the recursive_any_of and recursive_none_of template functions and all suggestions are welcome. | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, algorithm, recursion, c++20
Answer: This implementation is not short-circuiting
The standard library's std::any_of() and std::none_of() are short-circuiting: they stop iterating as soon as they know the answer. So for both std::any_of() and std::none_of(), it stops at the first position where the predicate returns true. Your version never stops until it has visited all the items.
Instead of counting, use finding to implement any_of(), all_of() and none_of(). You can still do that recursively.
Test all features of your functions
You wrote some test cases, but none of the tests use projection. As soon as you do you'll find out that your code doesn't handle projection correctly. You shouldn't handle it yourself anyway, ideally you just pass the projection on to recursive_count_if_all() (or better, a recursive_find_if()). | {
"domain": "codereview.stackexchange",
"id": 45405,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, recursion, c++20",
"url": null
} |
c++, performance, api, symbolic-math
Title: Small Automatic Differentiation Library
Question: Introduction
As a programming exercise I recently wrote this automatic differentiation library based on forward accumulation. It should offer a simple way to create mathematical functions whose directional derivatives can be computed. For example:
#include <iostream>
#include "autodiff.h"
int main()
{
mx::Var x, y;
mx::SField f = mx::sqrt(mx::pow(x,2)+mx::pow(y,2));
f.setVariables({&x, &y});
std::cout << f({3.0, 4.0}) << std::endl; //prints 5
std::cout << f.derivative({-1.0, 0.0}, x) << std::endl; //prints -1
return 0;
}
It basically works as follows:
The class SField (scalar field) holds a vector of Var pointers and a pointer to the top node of an expression tree consisting of Nodes:
ConstNode's just hold a constant value. They are created when an SField is initialized from a double.
VarNodes hold the value of the variable objects (Var) they correspond to.
UnOpand BinOp hold pointers to basic mathematical operations (BaseUnOp and BaseBinOp) like addition and multiplication but also exponential and trigonometric functions. They also point to one or two input nodes which can be any of the node types in this list.
The objects of type BaseUnOp and BaseBinOp contain function pointers to the (hard coded) partial derivatives of the elementary operations. From this, the derivative can be computed by repeatedly applying the chain rule while traversing the expression tree. The base operation objects also contain the methods for combining two SField's (i.e. connecting the expression graphs).
The setVariable methods are necessary to specify in which order the variables shall be assigned when evaluating the function or its derivative.
Code
autodiff.h
#ifndef AUTODIFF_H_INCLUDED
#define AUTODIFF_H_INCLUDED
#include <memory>
#include <vector>
namespace mx
{
class SField;
class Var; | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
#include <memory>
#include <vector>
namespace mx
{
class SField;
class Var;
namespace IMPLEMENTATION
{
class Node;
class VarNode;
class ConstNode;
class UnOp;
class BinOp;
class BaseUnOp;
class BaseBinOp;
}
class SField
{
friend IMPLEMENTATION::BaseUnOp;
friend IMPLEMENTATION::BaseBinOp;
private:
std::shared_ptr<IMPLEMENTATION::Node> start_Node;
std::vector<Var*> var_ptrs;
SField(std::shared_ptr<IMPLEMENTATION::Node> head_node) : start_Node(head_node) {}
SField(std::shared_ptr<IMPLEMENTATION::Node> head_node, const std::vector<Var*>& Var_ptrs)
: start_Node(head_node), var_ptrs(Var_ptrs) {}
public:
SField(const double& const_val);
SField() : SField(0) {}
SField(Var& x);
SField(std::vector<Var>& Var_ptrs) : SField() {setVariables(Var_ptrs);}
void setVariables(const std::vector<Var*>& Var_ptrs) {this->var_ptrs = Var_ptrs;}
void setVariables(std::vector<Var>& vars);
double operator()(const std::vector<double>&) const;
double operator()(const double&) const;
double derivative(const std::vector<double>&, const std::vector<double>&) const;
double derivative(const std::vector<double>&, const Var&) const;
double derivative(const double&, const double&) const;
double valueAtLastPosition() const;
SField& operator+=(const SField&);
SField& operator*=(const SField&);
SField& operator-=(const SField&);
SField& operator/=(const SField&);
};
class Var
{
friend SField;
private:
std::shared_ptr<IMPLEMENTATION::VarNode> vn;
public:
Var();
};
namespace IMPLEMENTATION
{ | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
namespace IMPLEMENTATION
{
class Node
{
public:
mutable double value;
virtual double eval() const = 0;
virtual double derive() const = 0;
};
class VarNode : public Node
{
public:
double value_dot;
VarNode() = default;
double eval() const {return value;}
double derive() const {return value_dot;}
};
class ConstNode : public Node
{
public:
ConstNode(const double& const_val) {value = const_val;}
ConstNode() : ConstNode(0.0) {}
double eval() const {return value;}
double derive() const {return 0.0;}
};
class UnOp : public Node
{
private:
const BaseUnOp& f;
std::shared_ptr<Node> g;
public:
UnOp() = delete;
UnOp(const BaseUnOp& operation, std::shared_ptr<Node> input);
double eval() const;
double derive() const;
};
class BinOp : public Node
{
private:
const BaseBinOp& f;
std::shared_ptr<Node> g;
std::shared_ptr<Node> h;
public:
BinOp() = delete;
BinOp(const BaseBinOp& operation, std::shared_ptr<Node> input1, std::shared_ptr<Node> input2);
double eval() const;
double derive() const;
};
class BaseUnOp
{
typedef double fn(const double&);
private:
const fn* f;
public:
BaseUnOp() = delete;
BaseUnOp(fn* fun, fn* deriv) : f(fun), dfdx(deriv){}
double operator()(const double& x) const {return f(x);}
SField operator()(const SField& f) const;
const fn* dfdx;
}; | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
class BaseBinOp
{
typedef double fn(const double&, const double&);
private:
const fn* f;
public:
BaseBinOp() = delete;
BaseBinOp(fn* fun, fn* x_deriv, fn* y_deriv) : f(fun), dfdx(x_deriv), dfdy(y_deriv){}
double operator()(const double& x, const double& y) const {return f(x,y);}
SField operator()(const SField&, const SField&) const;
const fn* dfdx;
const fn* dfdy;
};
///////////////////////////////////////////////////////////////////////////////////////////////
//LIST OF BASE OPERATIONS//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
constexpr double b_add (const double& x, const double& y);
constexpr double b_add_del_x (const double& x, const double& y);
constexpr double b_add_del_y (const double& x, const double& y);
constexpr double b_multiply (const double& x, const double& y);
constexpr double b_multiply_del_x (const double& x, const double& y);
constexpr double b_multiply_del_y (const double& x, const double& y);
constexpr double b_subtract (const double& x, const double& y);
constexpr double b_subtract_del_x (const double& x, const double& y);
constexpr double b_subtract_del_y (const double& x, const double& y);
constexpr double b_divide (const double& x, const double& y);
constexpr double b_divide_del_x (const double& x, const double& y);
constexpr double b_divide_del_y (const double& x, const double& y);
double b_power (const double& x, const double& y);
double b_pow_del_x (const double& x, const double& y);
double b_pow_del_y (const double& x, const double& y);
double b_sqrt (const double& x);
double b_sqrt_del (const double& x); | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
double b_sqrt (const double& x);
double b_sqrt_del (const double& x);
constexpr double b_negate (const double& x);
constexpr double b_negate_del (const double& x);
double b_sin (const double& x);
double b_cos (const double& x);
double b_cos_del (const double& x);
double b_tan (const double& x);
double b_tan_del (const double& x);
double b_exp (const double& x);
double b_log (const double& x);
double b_log_del (const double& x);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//GLOBAL BASE OPERATION OBJECTS////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
extern const IMPLEMENTATION::BaseBinOp add;
extern const IMPLEMENTATION::BaseBinOp multiply;
extern const IMPLEMENTATION::BaseBinOp subtract;
extern const IMPLEMENTATION::BaseBinOp divide;
extern const IMPLEMENTATION::BaseBinOp pow;
extern const IMPLEMENTATION::BaseUnOp sqrt;
extern const IMPLEMENTATION::BaseUnOp negation;
extern const IMPLEMENTATION::BaseUnOp sin;
extern const IMPLEMENTATION::BaseUnOp cos;
extern const IMPLEMENTATION::BaseUnOp tan;
extern const IMPLEMENTATION::BaseUnOp exp;
extern const IMPLEMENTATION::BaseUnOp log;
//OPERATOR OVERLOADING
SField operator+(const SField& f, const SField& g);
SField operator*(const SField& f, const SField& g);
SField operator-(const SField& f, const SField& g);
SField operator/(const SField& f, const SField& g);
SField operator-(const SField& f);
}
#endif // AUTODIFF_H_INCLUDED
autodiff.cpp
#include "autodiff.h"
#include <cmath>
#include <cassert> | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
autodiff.cpp
#include "autodiff.h"
#include <cmath>
#include <cassert>
namespace mx
{
///////////////////////////////////////////////////////////////////////////////////////////////
//SFIELD///////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
SField::SField(const double& const_val) : start_Node(new IMPLEMENTATION::ConstNode(const_val)) {}
SField::SField(Var& x) : start_Node(x.vn)
{
var_ptrs.push_back(&x);
}
void SField::setVariables(std::vector<Var>& vars)
{
var_ptrs.clear();
auto end = vars.end();
for (auto it = vars.begin(); it != end; ++it)
{
var_ptrs.push_back(&(*it));
}
}
double SField::operator()(const std::vector<double>& position) const
{
unsigned N = position.size();
assert(N == var_ptrs.size());
for (unsigned i = 0; i != N; ++i)
{
var_ptrs[i]->vn->value = position[i];
}
return start_Node->eval();
}
double SField::operator()(const double& position) const
{
return this->operator()(std::vector<double>{position});
}
double SField::derivative(const std::vector<double>& position, const std::vector<double>& direction) const
{
unsigned N = var_ptrs.size();
assert(N == position.size());
assert(N == direction.size());
for (unsigned i = 0; i != N; ++i)
{
var_ptrs[i]->vn->value = position[i];
var_ptrs[i]->vn->value_dot = direction[i];
}
return start_Node->derive();
}
double SField::derivative(const std::vector<double>& position, const Var& var_ptr) const
{
unsigned N = var_ptrs.size();
assert(N == position.size()); | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
for (unsigned i = 0; i != N; ++i)
{
var_ptrs[i]->vn->value = position[i];
var_ptrs[i]->vn->value_dot = 0.0;
}
var_ptr.vn->value_dot = 1.0;
return start_Node->derive();
}
double SField::derivative(const double& position, const double& direction) const
{
return this->derivative(std::vector<double>{position},std::vector<double>{direction});
}
double SField::valueAtLastPosition() const
{
return start_Node->value;
}
SField& SField::operator+=(const SField& g) {return *this = *this+g;}
SField& SField::operator*=(const SField& g) {return *this = *this*g;}
SField& SField::operator-=(const SField& g) {return *this = *this-g;}
SField& SField::operator/=(const SField& g) {return *this = *this/g;}
///////////////////////////////////////////////////////////////////////////////////////////////
//VAR//////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
Var::Var() : vn(new IMPLEMENTATION::VarNode()) {}
namespace IMPLEMENTATION
{
///////////////////////////////////////////////////////////////////////////////////////////////
//NODE/////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
//CONSTNODE////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////// | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
///////////////////////////////////////////////////////////////////////////////////////////////
//UNOP/////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
UnOp::UnOp(const BaseUnOp& operation, std::shared_ptr<Node> input) : f(operation), g(input)
{
value = operation(input->value);
}
double UnOp::eval() const
{
return f(g->eval());
}
double UnOp::derive() const
{
const double& g_dot = g->derive();
value = f(g->value);
return f.dfdx(g->value)*g_dot;
}
///////////////////////////////////////////////////////////////////////////////////////////////
//BINOP////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
BinOp::BinOp(const BaseBinOp& operation, std::shared_ptr<Node> input1, std::shared_ptr<Node> input2): f(operation), g(input1), h(input2)
{
value = operation(input1->value, input2->value);
}
double BinOp::eval() const
{
return f(g->eval(),h->eval());
}
double BinOp::derive() const
{
const double& g_dot = g->derive();
const double& h_dot = h->derive();
value = f(g->value, h->value);
return ((g_dot == 0.0) ? 0.0 : f.dfdx(g->value, h->value)*g_dot)
+((h_dot == 0.0) ? 0.0 : f.dfdy(g->value, h->value)*h_dot);
} | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
///////////////////////////////////////////////////////////////////////////////////////////////
//BASEUNOP/////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
SField BaseUnOp::operator()(const SField& f) const
{
std::shared_ptr<UnOp> op_ptr(new UnOp(*this, f.start_Node));
return SField(op_ptr, f.var_ptrs);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//BASEBINOP////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
SField BaseBinOp::operator()(const SField& f, const SField& g) const
{
std::shared_ptr<BinOp> op_ptr(new BinOp(*this, f.start_Node, g.start_Node));
return SField(op_ptr, f.var_ptrs);
}
///////////////////////////////////////////////////////////////////////////////////////////////
//LIST OF BASE OPERATIONS//////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
constexpr double b_add (const double& x, const double& y) {return x+y;}
constexpr double b_add_del_x (const double& x, const double& y) {return 1.0;}
constexpr double b_add_del_y (const double& x, const double& y) {return 1.0;}
constexpr double b_multiply (const double& x, const double& y) {return x*y;}
constexpr double b_multiply_del_x (const double& x, const double& y) {return y;}
constexpr double b_multiply_del_y (const double& x, const double& y) {return x;} | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
constexpr double b_subtract (const double& x, const double& y) {return x-y;}
constexpr double b_subtract_del_x (const double& x, const double& y) {return 1.0;}
constexpr double b_subtract_del_y (const double& x, const double& y) {return -1.0;}
constexpr double b_divide (const double& x, const double& y) {return x/y;}
constexpr double b_divide_del_x (const double& x, const double& y) {return 1.0/y;}
constexpr double b_divide_del_y (const double& x, const double& y) {return -x/(y*y);}
double b_pow (const double& x, const double& y) {return std::pow(x,y);}
double b_pow_del_x (const double& x, const double& y) {return y*std::pow(x,y-1);}
double b_pow_del_y (const double& x, const double& y) {return (x == 0) ? 0 : std::pow(x,y)*std::log(x);}
double b_sqrt (const double& x) {return std::sqrt(x);}
double b_sqrt_del (const double& x) {return 0.5/std::sqrt(x);}
constexpr double b_negate (const double& x) {return -x;}
constexpr double b_negate_del (const double& x) {return -1.0;}
double b_sin (const double& x) {return std::sin(x);}
double b_cos (const double& x) {return std::cos(x);}
double b_cos_del (const double& x) {return -std::sin(x);}
double b_tan (const double& x) {return std::tan(x);}
double b_tan_del (const double& x) {double t = std::tan(x); return 1.0+t*t;}
double b_exp (const double& x) {return std::exp(x);}
double b_log (const double& x) {return std::log(x);}
double b_log_del (const double& x) {return 1.0/x;}
}
///////////////////////////////////////////////////////////////////////////////////////////////
//GLOBAL BASE OPERATION OBJECTS////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////// | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
const IMPLEMENTATION::BaseBinOp add(IMPLEMENTATION::b_add, IMPLEMENTATION::b_add_del_x, IMPLEMENTATION::b_add_del_y);
const IMPLEMENTATION::BaseBinOp multiply(IMPLEMENTATION::b_multiply, IMPLEMENTATION::b_multiply_del_x, IMPLEMENTATION::b_multiply_del_y);
const IMPLEMENTATION::BaseBinOp subtract(IMPLEMENTATION::b_subtract, IMPLEMENTATION::b_subtract_del_x, IMPLEMENTATION::b_subtract_del_y);
const IMPLEMENTATION::BaseBinOp divide(IMPLEMENTATION::b_divide, IMPLEMENTATION::b_divide_del_x, IMPLEMENTATION::b_divide_del_y);
const IMPLEMENTATION::BaseBinOp pow(IMPLEMENTATION::b_pow, IMPLEMENTATION::b_pow_del_x, IMPLEMENTATION::b_pow_del_y);
const IMPLEMENTATION::BaseUnOp sqrt(IMPLEMENTATION::b_sqrt, IMPLEMENTATION::b_sqrt_del);
const IMPLEMENTATION::BaseUnOp negation(IMPLEMENTATION::b_negate, IMPLEMENTATION::b_negate_del);
const IMPLEMENTATION::BaseUnOp sin(IMPLEMENTATION::b_sin, IMPLEMENTATION::b_cos);
const IMPLEMENTATION::BaseUnOp cos(IMPLEMENTATION::b_cos, IMPLEMENTATION::b_cos_del);
const IMPLEMENTATION::BaseUnOp tan(IMPLEMENTATION::b_tan, IMPLEMENTATION::b_tan_del);
const IMPLEMENTATION::BaseUnOp exp(IMPLEMENTATION::b_exp, IMPLEMENTATION::b_exp);
const IMPLEMENTATION::BaseUnOp log(IMPLEMENTATION::b_log, IMPLEMENTATION::b_log_del);
//OPERATOR OVERLOADS
SField operator+(const SField& f, const SField& g) {return add(f,g);}
SField operator*(const SField& f, const SField& g) {return multiply(f,g);}
SField operator-(const SField& f, const SField& g) {return subtract(f,g);}
SField operator/(const SField& f, const SField& g) {return divide(f,g);}
SField operator-(const SField& f) {return negation(f);}
}
Questions
I would be thankful if someone could comment on whether or not I was able to achieve the following goals (and of course if not, what I can improve): | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
Code structure, style and readability: Is the code comprehensible? Are there many bad practices?
User Interface I: I tried to make adequate use of data encapsulation, in the sense that the user of the library has only access to those features he should, neither more nor less.
User Interface II: The library should be user-friendly. I think I achieved that overall (probably not that hard with only two classes that the user has access to), but I wonder if there is a better way to set the order of the variables. At the moment one can either use setVariable or already start with the corresponding constructor and afterwards only use compound operators (e.g. +=) to change the SField. This is allowed because (e.g.) the sum of two SField contains only the Var pointers of the left operand.
const correctness and appropriate use of other keywords like mutable, constexpr, friend,...
Performance: Although I could avoid many unnecessary eval calls (in comparison to a prior version of this library) by caching the value in each node, I guess there are still ways to make the computation of the derivative more efficient. | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
Since performance requirements always depend on the application, I want to explain what I intend to do with the library:
I already used it to build a solver for arbitrary Hamiltonian systems and in particular computed the dynamics of a three-body system. I want to expand the library by vector fields and matrices and do more complicated physics simulations. As long as I don't want to simulate tens of thousands of particles I guess this should be possible even for real-time simulations.
I also plan to create a neural network class with the gradient descent being based on this library. I think here I will need at least \$10^4-10^5\$ variables (weights) already for simpler applications (e.g. training the MNIST set).
Do you think it is reasonable to use this library for those purposes? Of course, I could use a professional AD library, but since all I do is intended entirely for learning purposes and fun I think it is better to reuse my own code whenever possible.
Since this is my first question on SE, please don't hesitate to point out flaws in the question itself (too long, too broad, missing important details, inappropriate tags etc.).
Answer: I don't like the namespace name IMPLEMENTATION - most code styles reserve all-caps names for macros, and so this one "cries wolf" to my eyes.
Turn on more compiler warnings. In particular, this one really needs addressing:
244587.cpp:70:15: warning: ‘class mx::IMPLEMENTATION::Node’ has virtual functions and accessible non-virtual destructor [-Wnon-virtual-dtor]
70 | class Node
| ^~~~
244587.cpp:78:15: warning: base class ‘class mx::IMPLEMENTATION::Node’ has accessible non-virtual destructor [-Wnon-virtual-dtor]
78 | class VarNode : public Node
| ^~~~~~~
That's easy enough to correct:
virtual ~Node() noexcept = default; | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
c++, performance, api, symbolic-math
That's easy enough to correct:
virtual ~Node() noexcept = default;
Member functions that override really should be marked override to help us get better errors if we mistakenly overload instead (e.g. by forgetting a significant const).
The biggest issue I have with the API is that although we have most of the machinery for symbolic differentiation, the derivative returns a value at a single point, rather than a new expression which can be evaluated at one or more points. That's limiting, because we can't (for example) further differentiate the result. | {
"domain": "codereview.stackexchange",
"id": 45406,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, api, symbolic-math",
"url": null
} |
java, websocket
Title: utility for automatic websocket ping-pong and receiving round-trip time reports | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
Question: Without ping-pong websocket connections are usually dropped by intermediary proxies/routers after some time of inactivity, so you can't go make yourself a coffee because your chat connection will break by the time you come back ;-] (most browsers such as Chrome or Firefox currently do not do any automatic pinging and to my knowledge, there's even no JS API to do it manually). Java websocket API provides primitive methods for sending pings and reacting to pongs (reacting to pings is automatic), but doing this manually in every project is tedious, error prone, time wasting etc etc. This class provides an easy way to automate it.
This used to be a small and pretty simple class before I had to add RTT reporting to it. After that, some unobvious trade-offs and design choices had to be made. I'm mainly looking for opinions regarding these (they are documented in the comments starting with a phrase "design decision note") as I may be biased by the specific use-cases I was dealing with, so a broader perspective would be most welcome. Other than that, comments on API convenience and suggestions for its improvements would be very useful as well. Last, but not least, general comments on code & documentation quality as well as possible bug spotting are always great :)
The class is available on github and in maven-central both in javax and jakarta flavours. The below version comes from the cr-stackexchange-1 tag and tries to somehow deal with reporting of lost or timed-out pongs: these are not reported at all yet in the latest release: see "design decision note" below in the code for problems related to it. | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
Additional info: RTT reporting was originally requested by folks who develop some real-time online games. They use it mostly on their server side to calculate and adjust per-participant handicaps on the fly during matches or something like that, so they use intervals of about 200-500ms (to be honest I haven't yet put an effort to fully understand how they use it as I'm not really much of a gamer and at first it seemed like a straightforward thing on my side: it doesn't seem that straightforward anymore and I will definitely need to sit with them soon to analyze their use-case). Recently they've reported a bug/feature-request that they would love to receive reports about lost/timed-out pongs. Initially I've implemented sending such reports from scheduler's thread in PingPongPlayer.sendPing(...) method as soon as a loss was detected and then all hell broke out: both servers and clients that were using RTT reporting started to crash/misbehave as everyone (including myself and my own Endpoints ;-] ) silently expected that report delivery would adhere to container-thread concurrency contract... The below version tries to meet this expectation for the price of delaying loss reports. This fixed my own Endpoint crashes, but I guess some ppl may not be entirely happy because of the delayed loss reports. That's why before committing to any approach I decided to ask for opinions here, to have some more view-points to work with besides mine own and that of my good old online-gaming folks.
explanation for subsequent reviewers:
the puzzling if (Thread.interrupted()) break; is to stop the pinging if service.stop() happens in the middle of the loop: true in pingingTask.cancel(true) sends an interrupt to the worker thread if it happens that the task being cancelled is just being executed. I will add a comment to this line fore sure.
Even more clarifications | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
Even more clarifications
So first, let me emphasize again, that the main purpose of this utility is to keep websocket connections alive if there's no app-level activity (intermediary proxies and NAT routers tend to drop connections after some time of inactivity). This is especially important for web app servers as neither Chrome nor Firefox currently provide any pinging capabilities (neither automatic nor manual). Expecting timely pongs and RTT discovery are "bonus" features. It is a non-goal to provide a new higher-level/alternative API/protocol over websockets, but merely to make websocket usage in Java a bit less tedious/problematic.
motivation for expect-timely-pongs mode
expect-timely-pongs is intended to detect and disconnect buggy, dead-locked peers. It was added after a websocket service of one of my associates providing some form of RPC-over-websocket was unintentionally DoS-ed by another service (acting as a websocket client to the first one), that was keep spawning new connections on and on as its instances/threads were getting dead-locked.
expect-timely-pongs was not designed to detect dead TCP connections and I'm not sure if it is able to provide any real value in this area in its current form (I'm completely almost sure that setting TCP KEEPALIVE flag will do a better job in this regard).
motivation for keep-alive-only mode | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
motivation for keep-alive-only mode
After the above situation, for a moment expect-timely-pongs became the only mode of operation, but I received a sad email from a developer who was using this utility as a part of her desktop Java app acting as a websocket client. Some of the users of this app often had to work over a very poor internet connection resulting in frequent timeouts and automatic disconnects. This was extremely frustrating for these users as upon disconnecting they were losing their state on the server and usually wanted to wait patiently until their connectivity improved (the server was not in control of the developer of this desktop client app). As a quick workaround the developer set a very high failure limit, but we agreed, that in case of user-agent client apps, disconnecting should generally be a user decision, not automatic and since then the utility has 2 modes of operation.
(NEWER VERSION AVAILABLE: I've applied many of the suggestions from J_H's answer and posted for a review in a new question here)
// Copyright 2021 Piotr Morgwai Kotarbinski, Licensed under the Apache License, Version 2.0
package pl.morgwai.base.servlet.utils; | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.BiConsumer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.websocket.*;
import javax.websocket.CloseReason.CloseCodes;
import javax.websocket.RemoteEndpoint.Async;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.SECONDS;
/**
* Automatically pings and handles pongs from websocket {@link Session connections}.
* Depending on constructor used, operates in either
* {@link #WebsocketPingerService(int, int, boolean) expect-timely-pongs mode} or
* {@link #WebsocketPingerService(int, boolean) keep-alive-only mode}.
* The service can be used both on the client and the server side.
* <p>
* Instances are usually created at app startups and stored in locations easily reachable for
* {@code Endpoint} instances or a code that manages them (for example as a
* {@code ServletContext} attribute, a field in a class that creates client
* {@link Session connections} or on some static var).<br/>
* At app shutdowns, {@link #stop()} should be called to terminate the pinging
* {@link ScheduledExecutorService scheduler}.</p>
* <p>
* Connections can be registered for pinging using {@link #addConnection(Session)}
* and deregister using {@link #removeConnection(Session)}.</p>
* <p>
* If round-trip time discovery is needed, {@link #addConnection(Session, BiConsumer)} variant may
* be used to receive RTT reports on each pong.</p>
*/
public class WebsocketPingerService {
// design decision note: while it is possible to use unsolicited pongs for keep-alive-only,
// some ping-pong implementations confuse them with malformed pongs and close connections.
// Furthermore, using ping-pong allows to provide RTT reports in keep-alive-only mode also. | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
/** 55s as majority of proxies and NAT routers have a timeout of at least 60s. */
public static final int DEFAULT_INTERVAL_SECONDS = 55;
final int failureLimit; // negative value means keep-alive-only mode
final boolean synchronizeSending;
final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
/** Periodic on {@link #scheduler}, executes {@link #pingAllConnections()}. */
final ScheduledFuture<?> pingingTask;
final Random random = new Random(); // for ping content
final ConcurrentMap<Session, PingPongPlayer> connectionPingPongPlayers =
new ConcurrentHashMap<>(); | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
/**
* Configures and starts the service in {@code expect-timely-pongs} mode: each timeout adds to a
* given {@link Session connection}'s failure count, unmatched pongs are ignored.
* @param interval interval between pings and also timeout for pongs. While this class does not
* enforce any hard limits, values below 100ms are probably not a good idea in most cases
* and anything below 20ms is pure Sparta.
* @param unit unit for {@code interval}.
* @param failureLimit limit of lost or timed-out pongs: if exceeded the given
* {@link Session connection} is closed with {@link CloseCodes#PROTOCOL_ERROR}. Each
* matching, timely pong resets the {@link Session connection}'s failure counter.
* @param synchronizeSending whether to synchronize ping sending on a given
* {@link Session connection}. Whether it is necessary depends on the container
* implementation being used. For example it is not necessary on Jetty, but it is on Tomcat:
* see <a href="https://bz.apache.org/bugzilla/show_bug.cgi?id=56026">this bug report</a>.
* <br/>
* When using containers that do require such synchronization, all other message sending by
* {@code Endpoint}s must also be synchronized on the {@link Session connection} (please
* don't shoot the messenger...).
* @throws IllegalArgumentException if {@code interval} is smaller than 1ms.
*/
public WebsocketPingerService(
long interval,
TimeUnit unit,
int failureLimit,
boolean synchronizeSending
) {
this.failureLimit = failureLimit;
this.synchronizeSending = synchronizeSending;
pingingTask = scheduler.scheduleAtFixedRate(this::pingAllConnections, 0L, interval, unit);
} | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
// design decision note: using interval as timeout simplifies things A LOT. Using a separate
// SHORTER duration for a timeout is still pretty feasible and may be implemented if there's
// enough need for it. Allowing a timeouts longer than intervals OTHO would required stacking
// of pings and is almost certainly not worth the effort.
/**
* Configures and starts the service in {@code keep-alive-only} mode:
* {@link Session connections} will <b>not</b> be actively closed unless an {@link IOException}
* occurs. The params have the similar meaning as in
* {@link #WebsocketPingerService(long, TimeUnit, int, boolean)}.
*/
public WebsocketPingerService(long interval, TimeUnit unit, boolean synchronizeSending) {
this(interval, unit, -1, synchronizeSending);
} | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
// block of constructor variants using some default values:
/**
* Calls {@link #WebsocketPingerService(long, TimeUnit, int, boolean)
* WebsocketPingerService(intervalSeconds, SECONDS, failureLimit, synchronizeSending)}
* ({@code expect-timely-pongs} mode).
*/
public WebsocketPingerService(int intervalSeconds, int failureLimit, boolean synchronizeSending)
{
this(intervalSeconds, SECONDS, failureLimit, synchronizeSending);
}
/**
* Calls {@link #WebsocketPingerService(long, TimeUnit, int, boolean)
* WebsocketPingerService(intervalSeconds, SECONDS, failureLimit, false)}
* ({@code expect-timely-pongs} mode).
*/
public WebsocketPingerService(int intervalSeconds, int failureLimit) {
this(intervalSeconds, SECONDS, failureLimit, false);
}
/**
* Calls {@link #WebsocketPingerService(long, TimeUnit, int, boolean)
* WebsocketPingerService(interval, unit, failureLimit, false)} ({@code expect-timely-pongs
* } mode).
*/
public WebsocketPingerService(long interval, TimeUnit unit, int failureLimit) {
this(interval, unit, failureLimit, false);
}
/**
* Calls {@link #WebsocketPingerService(long, TimeUnit, boolean)
* WebsocketPingerService(intervalSeconds, SECONDS, synchronizeSending)}
* ({@code keep-alive-only} mode).
*/
public WebsocketPingerService(int intervalSeconds, boolean synchronizeSending) {
this(intervalSeconds, SECONDS, synchronizeSending);
}
/**
* Calls {@link #WebsocketPingerService(long, TimeUnit, boolean)
* WebsocketPingerService(intervalSeconds, SECONDS, false)} ({@code keep-alive-only} mode).
*/
public WebsocketPingerService(int intervalSeconds) {
this(intervalSeconds, SECONDS, false);
}
/**
* Calls {@link #WebsocketPingerService(long, TimeUnit, boolean)
* WebsocketPingerService(interval, unit, false)} ({@code keep-alive-only} mode).
*/ | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
* WebsocketPingerService(interval, unit, false)} ({@code keep-alive-only} mode).
*/
public WebsocketPingerService(long interval, TimeUnit unit) {
this(interval, unit, false);
}
/**
* Calls {@link #WebsocketPingerService(long, TimeUnit, boolean)
* WebsocketPingerService}<code>({@link #DEFAULT_INTERVAL_SECONDS}, SECONDS, false)</code>
* ({@code keep-alive-only} mode).
*/
public WebsocketPingerService() {
this(DEFAULT_INTERVAL_SECONDS, SECONDS, false);
} | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
/**
* Registers {@code connection} for pinging.
* Usually called in
* {@link javax.websocket.Endpoint#onOpen(Session, javax.websocket.EndpointConfig) onOpen(...)}.
*/
public void addConnection(Session connection) {
addConnection(connection, null);
} | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
/**
* Registers {@code connection} for pinging and receiving round-trip time reports via
* {@code rttObserver}.
* Usually called in
* {@link javax.websocket.Endpoint#onOpen(Session, javax.websocket.EndpointConfig) onOpen(...)}.
* <p>
* Upon receiving a pong matching the most recent ping sent to a given
* {@link Session connection}, {@code rttObserver} will be invoked with the round-trip time in
* nanoseconds as the second argument and the given {@link Session connection} as the first.</p>
* <p>
* {@code rttObserver} will be called by a container {@code Thread} bound by the websocket
* {@code Endpoint} concurrency contract, so as with normal websocket event handling, it should
* not be performing any long-running operations to not delay processing of subsequent events.
* Particularly, if {@code rttObserver} processing or processing of any other event blocks
* arrival of a pong, the corresponding RTT report will be inaccurate.</p>
* <p>
* If the most recent ping has timed out or has been lost, {@code rttObserver} will be called
* with a negative value as the second argument upon arriving of a <u>subsequent</u> pong. This
* means, that if the other side does not send pongs at all, {@code rttObserver} will not be
* called at all either: this is a consequence of the requirement for {@code rttObserver} to be
* called by a container {@code Thread}. If RTT reports receiving is critical for a given app,
* {@code expect-timely-pongs} mode should be used to disconnect misbehaving peers.<br/>
* If more than 1 ping gets lost in a row and some pong finally arrives from the other side,
* the number of reports indicating loss may be smaller than the actual number of pings lost.
* </p>
*/
public void addConnection(Session connection, BiConsumer<Session, Long> rttObserver) {
connectionPingPongPlayers.put(
connection, | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
connectionPingPongPlayers.put(
connection,
new PingPongPlayer(connection, failureLimit, synchronizeSending, rttObserver)
);
} | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
// design decision note: it seems that in vast majority of cases it is most conveniently for
// developers if a receiver of RTT reports is the Endpoint instance associated with the
// connection which reports concern. Container Threads calling Endpoints are bound by a
// concurrency contract requiring that each Endpoint instance is called by at most 1 Thread at a
// time. Therefore it would create a lot of problems for developers if delivering of RTT
// reports didn't adhere to this contract either.
/**
* Removes {@code connection} from this service, so it will not be pinged anymore.
* Usually called in
* {@link javax.websocket.Endpoint#onClose(Session, CloseReason) onClose(...)}.
* @return {@code true} if {@code connection} had been {@link #addConnection(Session) added} to
* this service before and has been successfully removed by this method, {@code false} if it
* had not been added and no action has taken place.
*/
public boolean removeConnection(Session connection) {
return connectionPingPongPlayers.remove(connection) != null;
}
/** Whether {@code connection} is {@link #addConnection(Session) registered} in this service. */
public boolean containsConnection(Session connection) {
return connectionPingPongPlayers.containsKey(connection);
}
/** The number of currently registered {@link Session connections}. */
public int getNumberOfConnections() {
return connectionPingPongPlayers.size();
} | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
/**
* Stops the service.
* After a call to this method the service becomes no longer usable and should be discarded.
* @return {@link Session connections} that were registered at the time this method was called.
*/
public Set<Session> stop(long timeout, TimeUnit unit) {
pingingTask.cancel(true);
scheduler.shutdown();
for (var pingPongPlayer: connectionPingPongPlayers.values()) pingPongPlayer.deregister();
try {
scheduler.awaitTermination(timeout, unit);
} catch (InterruptedException ignored) {}
if ( !scheduler.isTerminated()) { // this probably never happens
log.warning("pinging scheduler failed to terminate");
scheduler.shutdownNow(); // probably won't help as the task was cancelled already
}
final var remaining = Set.copyOf(connectionPingPongPlayers.keySet());
connectionPingPongPlayers.clear();
return remaining;
}
/** Calls {@link #stop(long, TimeUnit)} with a 500ms timeout. */
public Set<Session> stop() {
return stop(500L, MILLISECONDS);
}
/** Executed periodically in {@link #scheduler}'s {@link #pingingTask} */
void pingAllConnections() {
if (connectionPingPongPlayers.isEmpty()) return;
final var pingData = new byte[8]; // enough to avoid collisions, but not overuse random
random.nextBytes(pingData);
for (var pingPongPlayer: connectionPingPongPlayers.values()) {
if (Thread.interrupted()) break;
pingPongPlayer.sendPing(pingData);
}
}
/** Plays ping-pong with a single associated {@link Session connection}. */
static class PingPongPlayer implements MessageHandler.Whole<PongMessage> {
final Session connection;
final Async connector;
final int failureLimit;
final boolean synchronizeSending;
final BiConsumer<Session, Long> rttObserver; | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
int failureCount = 0;
/** Retained after the most recent ping for comparison with incoming pongs. */
ByteBuffer pingDataBuffer;
/**
* Send timestamp of the most recent ping to which a matching pong has not been received
* yet. {@code null} means that a matching pong to the most recent ping has been already
* received.
*/
Long pingTimestampNanos = null;
/**
* Raised in {@link #sendPing(byte[])} if the previous ping timed-out
* ({@link #pingTimestampNanos} not {@code null}) to indicate that a loss report should be
* sent to {@link #rttObserver} upon receiving a subsequent pong.
*/
boolean previousPingTimedOut = false;
/** For both modes: negative {@code failureLimit} means {@code keep-alive-only}. */
PingPongPlayer(
Session connection,
int failureLimit,
boolean synchronizeSending,
BiConsumer<Session, Long> rttObserver
) {
this.connection = connection;
this.connector = connection.getAsyncRemote();
this.synchronizeSending = synchronizeSending;
this.rttObserver = rttObserver;
this.failureLimit = failureLimit;
connection.addMessageHandler(PongMessage.class, this);
} | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
/** Called by the {@link #scheduler}'s worker {@code Thread}. */
synchronized void sendPing(byte[] pingData) {
if (pingTimestampNanos != null) { // the previous ping has timed-out
previousPingTimedOut = true; // report loss on receiving a subsequent pong
if (failureLimit >= 0) { // expect-timely-pongs mode
failureCount++;
if (failureCount > failureLimit) {
closeFailedConnection("too many lost or timed-out pongs");
return;
}
}
}
pingDataBuffer = ByteBuffer.wrap(pingData); // retain for comparison with pongs
try {
if (synchronizeSending) {
synchronized (connection) {
connector.sendPing(pingDataBuffer);
}
} else {
connector.sendPing(pingDataBuffer);
}
pingTimestampNanos = System.nanoTime();
pingDataBuffer.rewind(); // required for comparing: see equals() javadoc
} catch (IOException e) {
// on most container implementations the connection is PROBABLY already closed, but
// just in case:
closeFailedConnection("failed to send ping");
}
}
private void closeFailedConnection(String reason) {
if (log.isLoggable(Level.FINE)) {
log.fine("failure on connection " + connection.getId() + ": " + reason);
}
try {
connection.close(new CloseReason(CloseCodes.PROTOCOL_ERROR, reason));
} catch (IOException ignored) {} // this MUST mean the connection is already closed...
} | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
/** Called by a container {@code Thread}. */
@Override
public void onMessage(PongMessage pong) {
final var pongTimestampNanos = System.nanoTime();
boolean reportPreviousPingTimedOut;
Long rttToReport = null;
synchronized (this) {
reportPreviousPingTimedOut = rttObserver != null && previousPingTimedOut;
if (pong.getApplicationData().equals(pingDataBuffer)) {
rttToReport = rttObserver != null && !(/*collision*/ pingTimestampNanos == null)
? pongTimestampNanos - pingTimestampNanos
: null;
pingTimestampNanos = null; // indicate the expected pong was received on time
failureCount = 0;
}
}
if (reportPreviousPingTimedOut) rttObserver.accept(connection, -1L);
if (rttToReport != null) rttObserver.accept(connection, rttToReport);
}
/**
* Removes pong handler.
* Called by the service on {@link Session connections} remaining after {@link #stop()}.
*/
void deregister() {
try {
connection.removeMessageHandler(this);
} catch (RuntimeException ignored) {
// connection was closed in the mean time and some container implementations
// throw a RuntimeException in case of any operation on a closed connection
}
}
}
static final Logger log = Logger.getLogger(WebsocketPingerService.class.getName());
}
Answer:
as I may be biased by the specific use-cases I was dealing with, so a broader perspective ...
This is a wonderful remark, thank you for sharing.
There's always more for each of us to see.
magic number
/** 55s as majority of proxies and NAT routers have a timeout of at least 60s. */
Excellent, thank you for helping future maintenance engineers to understand | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
Excellent, thank you for helping future maintenance engineers to understand
the design rationale, and
what classes of device to test against if they make a change
I feel this is a moderately long time,
imposing only small overhead,
and so there should be little motivation to support keepalive-only mode.
If client pings, IMHO it is reasonable to expect a timely pong.
I will observe that fixed delays are undesirable, as
common-mode events (e.g. network burst from cron job at the top of each hour)
will cause network peers to all become synchronized together,
similar to the "pull in" effect of a
PLL.
Standard advice is "jitter your timers!" by rolling a random number.
Self synchronization badly affected North American core routers
for more than a year, to the point where BGP4 now specifies
details of how certain timers shall be jittered.
Oh, dear! I just saw the call to scheduleAtFixedRate().
My intent was along the lines of
timeOfNextScheduledEvent += 55 + uniformRandomPlusOrMinus(3); // seconds
but I suppose a scheduled event that randomly sleeps a few
seconds before sending is the next best thing.
I completely agree that "allowing timeouts longer than intervals" and
stacking them is out-of-scope.
The engineering assumption at the core of this is that
RTT
from speed-of-light, network queueing, and CPU queueing,
is much less than the configured ping interval.
Seems like a solid assumption to me.
(I appreciate and agree with your other Design Decision notes.)
overloads
There's a fair number of WebsocketPingerService signatures in there.
Maybe look at the dozen or two existing callers in production code,
and cull the unused overloads?
interrupted
void pingAllConnections() {
...
if (Thread.interrupted()) break; | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
I confess I don't understand what's happening here.
Shouldn't we throw fatal InterruptedException if someone asked us to shutdown?
And maybe also stop()?
I'm just unclear on the contract, on the various responsibilities.
keep-alive
/** For both modes: negative {@code failureLimit} means {@code keep-alive-only}. */
Maybe you need to support this?
If so, it's worth writing down the reasons.
Consider ditching support for it.
If you retain it, consider enforcing that failureLimit shall always
be positive, and introduce yet another boolean parameter
to select keep-alive mode.
I suggest this, just because I have seen a bunch of (nicely written)
comments that have to keep explaining the peculiar meaning of a negative limit.
Alternatively, consider creating a Config object for the various options.
(And, uhh, yeah, you have my sympathies about the whole TomCat
synchronizeSending thing.)
} catch (IOException ignored) {}
Thank you for the informative identifier in closeFailedConnection, very helpful.
Similarly in deregister, also accompanied by a helpful comment.
observer
OK, so I've read through a bunch of code,
and I still don't exactly see how an observer would make use of this
to offer an improved UX to a human user.
Here's the crux of it:
if (reportPreviousPingTimedOut) rttObserver.accept(connection, -1L);
if (rttToReport != null) rttObserver.accept(connection, rttToReport);
Given that we only notify observer when something arrives from
the network, it's unclear whether a limit of more than 1
would be useful.
I'm going to make up a scenario.
For five minutes you're using an app that created a single WebSocket,
and everything is peachy.
You go to fix a cup of coffee.
Some evil family member, perhaps your puppy,
powers off the WiFi router so there's no internet connectivity.
At subsequent times
you return to interact with the app, and
the WAP is powered back on so connectivity is restored (maybe not in that order). | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
Every 55 seconds the app queues up some TCP payload to deliver.
Now depending on the WiFi outage duration, TCP may have backed off
to very long (more than a minute) retrans attempts, or may have
given up, sent RST, and torn down the connection.
Let's assume TCP has backed off but is still hopeful of receiving an ACK.
So we sent PING 1 and heard a PONG, then the WAP died at noon,
we sent PING 2, then PING 3, the WAP powered up roughly a minute later,
and at maybe 12:03-ish we get PONG 2 immediately followed by PONG 3.
And we tell the observer -1, immediately followed by an RTT of many seconds.
(A subsequent PING 4 would quickly yield a PONG 4 measurement of less than 500 msec.)
Here's where I'm puzzled.
Should observer hear the -1 and immediately give up,
displaying fatal error to user?
Should observer hang out for a little while, hoping for the PONG 3 measurement?
We don't tell observer about outgoing PINGs.
Would it maybe be more helpful to the UX if we did,
and then observer expects response within 500 msec?
Observer could timeout after 500 msec and display
a Toast message or use some screen real estate
to display a "no net!" icon.
Maybe around the fifty second mark we should send observer a -1
to indicate the PING was lost?
That is, send the notification based on time,
rather than due to onMessage() being called.
Summary: It's not clear how observer would use the current Public API
to offer a better UX to the end user.
It's worth writing up in ReadMe / javadoc.
alternate protocol
There's nothing especially wrong with what you send on the wire currently.
But instead of random bytes, consider sending this:
Roll a secret GUID just once (it doesn't need to be very secret).
Fill the send buffer with (timestamp, SHA3(secret + timestamp)),
or at least with a hash prefix.
Validate the hash in onMessage, rather than using .equals() on
the most-recently-sent random bytes.
Send observer strictly positive latency measurements. | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
java, websocket
the most-recently-sent random bytes.
Send observer strictly positive latency measurements.
Let observer make the judgement call about what to do with "large" latencies. | {
"domain": "codereview.stackexchange",
"id": 45407,
"lm_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, websocket",
"url": null
} |
c++, performance, object-oriented, design-patterns
Title: Terminal Graphical Visualizer, using a queue of different matrices
Question: I built a project in which I provide a string input or a whole matrix to configure a frame, create a bunch of different frames and push them into a queue and finally print them in order of the queue.
I would like some advice on how to improve the design of the frame class as I feel it became a spaghetti code. I'll be happy to also know what changes I can make for better performance and maybe variable name ideas because I feel like I didn't give my variables proper and understandable names.
hpp file:
#pragma once
#include <vector>
#include <string>
#include <queue>
#include <chrono>
#include <unordered_map>
#include <map>
using frame_matrix = std::vector<std::vector<std::pair<char, std::string>>>;
const std::unordered_map<std::string, std::string> colors = {{"red", "\033[31m"}, {"green", "\033[32m"}, {"blue", "\033[34m"}, {"yellow", "\033[33m"}, {"reset", "\033[0m"}};
class frame
{
private:
std::string color;
void initialize_frame();
public:
frame_matrix current_frame;
const static size_t AMOUNT_OF_INPUT_OPTIONS = 6;
const static size_t FRAME_WIDTH = 30;
const static size_t FRAME_HEIGHT = 20;
const static char INPUT_DELIMITER = ',';
const static char BACKGROUND = '#';
frame();
frame(const std::string& input);
frame_matrix get_current_frame() const;
void alter_frame(const std::string& input);
void set_current_frame(const frame_matrix& new_current_frame);
void print_frame();
bool parse_input(const std::string& input);
bool is_valid_input(std::string height_start, std::string height_length, std::string range_start, std::string range_length, std::string printable_char,std::string color);
};
class graphical_visualizer
{
private:
std::queue<frame> frame_queue;
public:
graphical_visualizer(); | {
"domain": "codereview.stackexchange",
"id": 45408,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, object-oriented, design-patterns",
"url": null
} |
c++, performance, object-oriented, design-patterns
public:
graphical_visualizer();
std::queue<frame> get_frame_queue() const;
void add_frame(frame frame);
void print_sequence(const std::chrono::milliseconds millis);
};
struct input
{
size_t height_start;
size_t height_length;
size_t width_start;
size_t width_length;
char symbol;
std::string color;
};
cpp file
#include "graphical_visualizer.hpp"
#include <iostream>
#include <sstream>
#include <thread>
frame::frame()
{
initialize_frame();
}
frame::frame(const std::string& input)
{
initialize_frame();
alter_frame(input);
}
frame_matrix frame::get_current_frame() const
{
return current_frame;
}
void frame::alter_frame(const std::string& input)
{
parse_input(input);
}
void frame::set_current_frame(const frame_matrix& new_current_frame)
{
current_frame = new_current_frame;
}
void frame::print_frame()
{
for(const std::vector<std::pair<char, std::string>>& line : current_frame)
{
for(const std::pair<char, std::string>& current_char : line)
{
std::cout << current_char.second << current_char.first;
std::cout << colors.at("reset");
}
std::cout << std::endl;
}
}
bool frame::parse_input(const std::string& input)
{
std::stringstream input_stream(input);
std::string input_sections[AMOUNT_OF_INPUT_OPTIONS];
size_t input_sections_index = 0;
while(std::getline(input_stream, input_sections[input_sections_index], INPUT_DELIMITER))
++input_sections_index;
if(!is_valid_input(input_sections[0], input_sections[1], input_sections[2], input_sections[3], input_sections[4], input_sections[5]))
{
return false;
}
int height_start = std::stoi(input_sections[0]);
int height_length = std::stoi(input_sections[1]);
int range_start = std::stoi(input_sections[2]);
int range_length = std::stoi(input_sections[3]);
std::string color = colors.at(input_sections[5]); | {
"domain": "codereview.stackexchange",
"id": 45408,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, object-oriented, design-patterns",
"url": null
} |
c++, performance, object-oriented, design-patterns
char printable_char = input_sections[4][0]; //should always be a string of length 1
for(size_t i = height_start; i <= height_start + height_length - 1; ++i)
{
for(size_t j = range_start; j <= range_start + range_length - 1; ++j)
{
current_frame[i][j].first = printable_char;
current_frame[i][j].second = color;
}
}
return true;
}
void frame::initialize_frame()
{
for(size_t i = 0; i < FRAME_HEIGHT; ++i)
{
std::vector<std::pair<char, std::string>> line;
for(size_t j = 0; j < FRAME_WIDTH; ++j)
line.push_back({'#', colors.at("reset")});
current_frame.push_back(line);
}
}
bool is_a_number(std::string number)
{
for(const char& ch : number)
{
if(!std::isdigit(ch))
return false;
}
return true;
}
bool frame::is_valid_input(std::string height_start, std::string height_length, std::string range_start, std::string range_length, std::string printable_char,std::string color)
{
std::unordered_map<std::string, std::string>::const_iterator pos = colors.find(color);
if(pos == colors.end())
return false;
if(!is_a_number(height_start) || !is_a_number(height_start) || !is_a_number(height_start) || !is_a_number(height_start))
{
return false;
}
if(printable_char.size() != 1)
return false;
int height_start_int = std::stoi(height_start);
int height_length_int = std::stoi(height_length);
int range_start_int = std::stoi(range_start);
int range_length_int = std::stoi(range_length);
if(height_start_int < 0 || height_length_int + height_length_int - 1 >= FRAME_HEIGHT || range_start_int < 0 || range_start_int + range_length_int - 1 >= FRAME_WIDTH)
return false;
return true;
}
graphical_visualizer::graphical_visualizer()
{
frame_queue = {};
}
std::queue<frame> graphical_visualizer::get_frame_queue() const
{
return frame_queue;
} | {
"domain": "codereview.stackexchange",
"id": 45408,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, object-oriented, design-patterns",
"url": null
} |
c++, performance, object-oriented, design-patterns
std::queue<frame> graphical_visualizer::get_frame_queue() const
{
return frame_queue;
}
void graphical_visualizer::add_frame(frame frame)
{
frame_queue.push(frame);
}
void graphical_visualizer::print_sequence(const std::chrono::milliseconds millis)
{
std::queue<frame> local_temp_queue = frame_queue;
while(!local_temp_queue.empty())
{
local_temp_queue.front().print_frame();
local_temp_queue.pop();
std::this_thread::sleep_for(millis);
system("clear");
}
}
Answer: Don't use std::endl
Just output \n for a newline. See here.
std::size_t
The C++ standard defines std::size_t, not size_t.
const placing
I personally prefer type const& over const type&. Types are read right to left, so putting the const always to the right of the thing that is constant makes the type more consistent. Witness this comment.
Use more using
using frame_matrix = std::vector<std::vector<std::pair<char, std::string>>>;
// ...
for(const std::vector<std::pair<char, std::string>>& line : current_frame)
{
for(const std::pair<char, std::string>& current_char : line)
{
// ...
This is very verbose, you're repeating std::pair<char, std::string> over and over again. You could do instead:
using matrix_element = std::pair<char, std::string>>;
using frame_matrix = std::vector<std::vector<matrix_element>>;
// ...
for(const std::vector< matrix_element >& line : current_frame)
{
for(const matrix_element& current_char : line)
{
// ...
But of course better is to use auto:
for(const auto& line : current_frame)
{
for(const auto& current_char : line)
{
// ...
Prefer struct over std::pair
std::pair is convenient to put two pieces of information together, but what does << current_char.second << current_char.first mean? I'd prefer
struct frame_matrix {
char character;
std::string color_code;
};
// ... | {
"domain": "codereview.stackexchange",
"id": 45408,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, object-oriented, design-patterns",
"url": null
} |
c++, performance, object-oriented, design-patterns
// ...
std::cout << current_char.color_code << current_char.character;
It's just more readable, and it doesn't add a whole lot of code.
The matrix
There are two things about the way you store your data that makes it quite inefficient. A std::vector<std::vector<>> is usually a bad idea (double indirection, memory fragmentation, etc.). It is useful if all inner vectors have a different length, but that is not the case for you. Instead, use a simpler std::vector<>, of length FRAME_HEIGHT * FRAME_WIDTH, and while iterating simply count out how many values you read. You could iterate as follows:
std::size_t index = 0;
for(std::size_t i = 0; i < FRAME_HEIGHT; ++i) {
for(std::size_t j = 0; j < FRAME_WIDTH; ++j, ++index) {
std::cout << current_frame[index].color_code << current_frame[index].character;
std::cout << colors.at("reset");
}
std::cout << '\n';
}
When initializing the frame, you push_back() into an empty vector. Since you know what size the vector will have, you can reserve() the space first. This way the vector won't have to resize continuously, resizing is costly.
Using a plain vector instead of a vector of vectors makes initializing to an empty frame a lot easier as well. No loops!
Finally, the representation of the color in the frame could probably be simplified to make it more efficient. std::string is complex. All your color strings are the same size, so you don't need any of the complexity of std::string. One possible solution could be to using constant strings (char arrays) for your color codes, and put a pointer in your matrix:
struct frame_matrix {
char character;
char const* color_code;
};
const std::unordered_map<std::string, char const*> colors = {{"red", "\033[31m"}, {"green", "\033[32m"}, {"blue", "\033[34m"}, {"yellow", "\033[33m"}, {"reset", "\033[0m"}}; | {
"domain": "codereview.stackexchange",
"id": 45408,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, object-oriented, design-patterns",
"url": null
} |
c++, performance, object-oriented, design-patterns
This way you only store a pointer to the commonly used string, instead of copying it again and again.
Variable names
When you declare void add_frame(frame frame), you make things quite confusing. frame now means something different inside the function as it does outside. It is legal, but you're not making it easier on the reader. It is quite common in C++ to name classes with an uppercase letter. In this case your function declaration would be void add_frame(Frame frame), which is a lot less ambiguous.
Spaghetti code
I don't think this is spaghetti code, the structure is quite clear. One thing you could do to simplify the code is putting shorter function definitions in the header right where you declare them. This way the compiler can do more optimizations, and you reduce code duplication a bit.
class frame
{
private:
std::string color;
void initialize_frame();
public:
frame_matrix current_frame;
const static size_t AMOUNT_OF_INPUT_OPTIONS = 6;
const static size_t FRAME_WIDTH = 30;
const static size_t FRAME_HEIGHT = 20;
const static char INPUT_DELIMITER = ',';
const static char BACKGROUND = '#';
frame()
{
initialize_frame();
}
frame(const std::string& input)
{
initialize_frame();
alter_frame(input);
}
frame_matrix get_current_frame() const
{
return current_frame;
}
void alter_frame(const std::string& input)
{
parse_input(input);
}
void set_current_frame(const frame_matrix& new_current_frame)
{
current_frame = new_current_frame;
}
void print_frame();
bool parse_input(const std::string& input);
bool is_valid_input(std::string height_start, std::string height_length, std::string range_start, std::string range_length, std::string printable_char, std::string color);
}; | {
"domain": "codereview.stackexchange",
"id": 45408,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, object-oriented, design-patterns",
"url": null
} |
c++, performance, object-oriented, design-patterns
Things to think about: What is the purpose of alter_frame() if all it does is call parse_input()? You have one function with two names! And do you really want is_valid_input() to be part of the public API? Should this not be a private function?
By the way, is_valid_input() takes std::strings by value. This should be const references:
bool is_valid_input(
std::string const& height_start,
std::string const& height_length,
std::string const& range_start,
std::string const& range_length,
std::string const& printable_char,
std::string const& color
);
is_valid_input() also converts the inputs to numbers, the result of the conversion is discarded. You call is_valid_input() in parse_input(), which also converts these strings to numbers. It is good to separate out functionality, but maybe put more of the validation in parse_input() (just verify the limits for the integers), so that you don't need to duplicate code. | {
"domain": "codereview.stackexchange",
"id": 45408,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, object-oriented, design-patterns",
"url": null
} |
c++, strings, search
Title: Fast search for the longest repeating substrings in large text (Rev.2)
Question: This is the second iteration of the Fast search for the longest repeating substrings in large text code review. Special thanks goes to G. Sliepen who conducted the first review.
Functional specification
Having a large text and already built suffix array find the longest substrings (limited by the number of repetitions) getting benefit from already existing prefix array, if reasonable. Provide the version which would benefit from multithreading keeping the code as simple as possible.
(*One thing I am still in two minds about here in the spec. is should the function return the longest substring which repeats the exact number of times or "this number and more". The problem with the more precise former is that the line which repeated N times may be shorter than line repeated N+1 and this could be not what the user want to see. Again provide options? It will overcomplicate the solution.)
Implementation
The fully functional demo.
Reservation: current implementation utilizes execution policies, so using ranges/projections/views under the question; would work if multi-threading requirement from above met.
The further details make sense only as addition to aforementioned first Code Review with answer to it.
List of major changes | {
"domain": "codereview.stackexchange",
"id": 45409,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
The interface was redesigned according to the proposal and a little bit even more. Since function could fine many different substrings which will repeat the specified number of times, it returns the vector of string_views with all entries in the text so that many resulting substrings with their positions in text could be returned.
Prefix array reworked to suffix array which allowed to use algorithms in forward direction.
Proposed version of atomic_fetch_max is used instead of update_max.
Defect related to returning duplicates, described in first review fixed. To make sure that function finds substring with exact number of repetitions border checks have been added in the calculateAdjacents functions.
Two versions of calculateAdjacents function provided just for code review to make sure I got correctly the way to implement with std::transform_reduce. They can be switched by macro at the beginning of the code. Please don’t try to remove duplication code because caused by this, only one function will survive. I will conduct performance testing on real data shortly.
Function findMatchLengthWithOffsetInSuffixArray extracted to avoid complex code in calculateAdjacents functions.
My concerns on the current code | {
"domain": "codereview.stackexchange",
"id": 45409,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
My concerns on the current code
To fix the defect when function finds substrings which are repeated not exactly requested number of times, but even more frequently I had to add border checks to ensure the number of repeats (see 2 extra calls to findMatchLengthWithOffsetInSuffixArray in calculateAdjacents functions and I hate this code most because of “almost duplication” of this code. Still looking for a way to collapse it in something shorter.
// Returns found sequence(s) length
size_t calculateAdjacentsByForEach(const std::string& text,
const std::vector<index_t>& index,
std::vector<index_t>& adjacent_matches,
size_t repetitions)
{
std::fill(std::execution::par_unseq, adjacent_matches.begin(), adjacent_matches.end(), 0);
std::atomic<size_t> max_match_length = 0;
std::for_each(std::execution::par_unseq, index.begin(), index.end() - (repetitions - 1), [&](const index_t& item) {
size_t idx = &item - std::data(index);
// Meets exactly min_repetitions times
size_t match_length = findMatchLengthWithOffsetInSuffixArray(text, index, idx, (repetitions - 1));
// Not more than min_repetitions times before item
if (&item > std::data(index)) {
size_t prev_match_length = findMatchLengthWithOffsetInSuffixArray(text, index, idx, -1);
if (prev_match_length == match_length)
return;
}
// Not more than min_repetitions times after item
if ((size_t)((&item + repetitions) - std::data(index)) < index.size()) {
size_t next_match_length = findMatchLengthWithOffsetInSuffixArray(text, index, idx, repetitions);
if (next_match_length == match_length)
return;
}
adjacent_matches[idx] = (index_t)match_length;
atomic_fetch_max(&max_match_length, match_length);
});
return max_match_length;
} | {
"domain": "codereview.stackexchange",
"id": 45409,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
return max_match_length;
}
I still dislike the max_repetitions threshold. It seems that it is better to limit by maximum and minimum length of found substrings, although this is not so straightforward, since by a new criterion line repeated (exactly) 3 times could be longer than line repeated 2 times, so it is hard to develop stop-criteria this way.
The inner loop in function collectRepeatingSubstrings is still hard to read.
struct SubstringOccurences {
std::string_view str;
std::vector<index_t> pos;
};
std::vector<SubstringOccurences>
collectRepeatingSubstrings(const std::string& text,
const std::vector<index_t>& index,
std::vector<index_t> adjacent_matches,
size_t repetitions,
size_t max_match_length)
{
std::vector<SubstringOccurences> result;
for (size_t i = 0; i < adjacent_matches.size() - 1; ++i) {
if (adjacent_matches[i] == max_match_length) {
SubstringOccurences occur;
occur.str = std::string_view(text.data() + index[i], max_match_length);
for (size_t match = i; match <= std::min(i + (repetitions - 1), adjacent_matches.size() - 1); ++match) {
occur.pos.emplace_back(index[match]);
}
result.emplace_back(occur);
}
}
return result;
}
I really hate the idea to pass 5 parameters to collectRepeatingSubstrings function despite its benefits. Too many and too way easy to mix parameters, especially when comes it last size_t variables.Well, text, index and adjacent_matches could be wrapped in one structure, but the naming and composing question is still open: The best place to store index to data
Four parameters passed to calculateAdjacents functions is not good, as well.
Having both findMatchLengthWithOffsetInSuffixArray and findMatchLength now seems to be redundant, but I don’t see a good way to get rid of one of them. | {
"domain": "codereview.stackexchange",
"id": 45409,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
I would be happy to avoid this std::fill at the beginning of calculateAdjacents function, but I am not sure if this is possible.
size_t findMatchLength(std::string_view str1, std::string_view str2) {
return std::ranges::mismatch(str1, str2).in1 - str1.begin();
}
size_t findMatchLengthWithOffsetInSuffixArray(const std::string& text,
const std::vector<index_t>& index,
const size_t idx,
ptrdiff_t offset)
{
return findMatchLength(std::string_view(text.begin() + index[idx], text.end()),
std::string_view(text.begin() + index[idx + offset], text.end()));
}
To put in a nutshell, despite the obvious fact that the code now has fixed defect and better decomposed, I still don’t like it because of the following reasons:
Too many helper functions in the scope of high-level functions. This is in my way as a client of this module (namespace) to understand what is the interface and what is the implementation (even when divided to h and cpp files).
Some code is still hard to read.
Functions have too many arguments which make it hard to call them. Seems like I am “cutting artificially something alive in a wrong place”, leaving too many connections.
Utility functions are still not “generic” for future reuse. Out of context of this task it is hard to explain and document what for and how (with which preconditions, postconditions, etc.) they could be used.
Is there any way to improve this code? Any mistakes or issues? Could you please help conducting further steps of code review?
Answer: It's always nice to see people improve their code after a review!
About your concerns
One thing I am still in two minds about here in the spec. is should the function return the longest substring which repeats the exact number of times or "this number and more". | {
"domain": "codereview.stackexchange",
"id": 45409,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
What behavior does the user need? If the choice doesn't matter for some reason, then just pick one and go with it.
To fix the defect when function finds substrings which are repeated not exactly requested number of times, but even more frequently I had to add border checks to ensure the number of repeats (see 2 extra calls to findMatchLengthWithOffsetInSuffixArray in calculateAdjacents functions and I hate this code most because of “almost duplication” of this code. Still looking for a way to collapse it in something shorter.
If you go for the "this number or more" version, then you can remove one of the calls to findMatchLengthWithOffsetInSuffixArray(). But then there is another subtle defect: when it returns the longest equal sequence repeated at least N times, it will only collect exactly N positions of the repeated sequences, even if there are more.
I still dislike the max_repetitions threshold. It seems that it is better to limit by maximum and minimum length of found substrings, although this is not so straightforward, since by a new criterion line repeated (exactly) 3 times could be longer than line repeated 2 times, so it is hard to develop stop-criteria this way.
If you set max_repetitions to text.size() you will have a valid stop-criterion. This will cause a lot of work to be done for long inputs though.
A better criterion can be found by analyzing the suffix array, and finding the longest consecutive sequence of entries that have the same first character, and use the length of that sequence as max_repetitions.
The inner loop in function collectRepeatingSubstrings is still hard to read.
Let's look at that inner loop:
for (size_t match = i; match <= std::min(i + (repetitions - 1), adjacent_matches.size() - 1); ++match) {
occur.pos.emplace_back(index[match]);
} | {
"domain": "codereview.stackexchange",
"id": 45409,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
Why is the call to std::min() there? We already know we have at least repetitions entries starting at i. So we can remove that. Then we can let the loop go from 0 to repetitions:
for (size_t match = 0; match < repetitions; ++match) {
occur.pos.emplace_back(index[i + match]);
}
Maybe now it's easier to see that we are just copying a slice from index into occur.pos. But your spider senses should be tingling at this point: surely the standard library has some way to copy a subrange from a vector into another vector? There are indeed various ways to do this. One of them is by using the overload of std::vector's constructor that takes two iterators. Now you don't need the inner loop at all anymore, and you can just write:
for (size_t i = 0; i < adjacent_matches.size() - 1; ++i) {
if (adjacent_matches[i] == max_match_length) {
result.emplace_back(
std::string_view(text.data() + index[i], max_match_length),
std::vector(&index[i], &index[i + repetitions])
);
}
}
I really hate the idea to pass 5 parameters to collectRepeatingSubstrings function despite its benefits. Too many and too way easy to mix parameters, especially when comes it last size_t variables. Well, text, index and adjacent_matches could be wrapped in one structure, but the naming and composing question is still open: [The best place to store index to data][3]
I think you've already answered it mostly yourself. Now you just need to come up with a good name for that structure. I would try this yourself first, as this is a good exercise.
Four parameters passed to calculateAdjacents functions is not good, as well.
That is solved in exactly the same way.
Having both findMatchLengthWithOffsetInSuffixArray and findMatchLength now seems to be redundant, but I don’t see a good way to get rid of one of them. | {
"domain": "codereview.stackexchange",
"id": 45409,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
Since findMatchLength() is only ever called from findMatchLengthWithOffsetInSuffixArray(), you could inline the former into the latter. But why not just keep them both?
I would be happy to avoid this std::fill' at the beginning of calculateAdjacents` function, but I am not sure if this is possible.
There are several ways to do this. First, you can just use std::vector::assign():
adjacent_matches.assign(index.size(), 0);
But instead of passing it as an out-parameter, just make it part of the return value. Then you can just initialize a fresh new vector:
struct AdjacentMatches {
std::size_t max_match_length;
std::vector<std::size_t> adjacent_matches;
};
AdjacentMatches calculateAdjacentsByForEach(const std::string& text,
const std::vector<index_t>& index,
size_t repetitions)
{
AdjacentMatches result{0, std::vector<std::size_t>(index.size(), 0)};
…
result.adjacent_matches[idx] = match_length;
…
result.max_match_length = max_match_length;
}
And then you have a nice struct to pass to collectRepeatingSubstrings(). The only possible drawback is that these methods don't allow for parallelism. But unless the input is huge, I don't think it matters, and even if it does, consider that zeroing a vector would probably be memory bandwidth bound instead of CPU bound.
Use std::string_view from the very start
If findRepeatedSubsequences() doesn't need to modify the passed in string, make it take it as a std::string_view instead of a const std::string&. The caller doesn't have to change anything. But we can avoid the ugly conversion of a substring to std::string_view, and instead write:
occur.str = text.substr(index[i], max_match_length); | {
"domain": "codereview.stackexchange",
"id": 45409,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
c++, strings, search
And:
size_t findMatchLengthWithOffsetInSuffixArray(std::string_vioew text,
const std::vector<index_t>& index,
const size_t idx,
ptrdiff_t offset)
{
return findMatchLength(text.substr(index[idx]),
text.substr(index[idx + offset]));
} | {
"domain": "codereview.stackexchange",
"id": 45409,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, strings, search",
"url": null
} |
python, algorithm, functional-programming
Title: Map coloring algorithm functional implementation in python
Question: I'm an autodidact working on map coloring algorithms with backtracking, see chapter 2 of this book.
I tested this implementation with success but I'm still unsure whether it is tricking me somewhere, or if I could improve it.
Color = int
def paint(graph: dict[Node, list[Node]]) -> list[tuple[Node, Color]]:
"""An interface."""
def init(nodes: list[Node]) -> list[tuple[Node, Color]]:
"""Starts out with no colors assigned"""
return [(n, -1) for n in nodes]
def is_legal(color: Color, node: Node, ns: list[tuple[Node, Color]]) -> bool:
"""True if parent's color is different from childrens' color"""
for child in graph[node]:
if (child, color) in ns:
return False
return True
def _paint(i: int, ns: list[tuple[Node, Color]], max_colors: int):
"""Helper function"""
if i == len(ns):
return ns # we did it
if i < 0:
# tried everything possible but nope
return _paint(0, init(sorted_adjacent), max_colors + 1)
node, color = ns[i]
if color + 1 == max_colors:
return _paint(i - 1, ns, max_colors) # backtrack
ns[i] = (node, color + 1)
if is_legal(color + 1, node, ns):
return _paint(i + 1, ns, max_colors) # go to next node
else:
return _paint(i, ns, max_colors) # try with next color
sorted_adjacent = sorted(graph.keys(), key=lambda r: -len(graph[r]))
return _paint(0, init(sorted_adjacent), 2)
This is the rest of the code, with an example graph input, which is defined as a simple dictionary with nodes as keys, and a list of nodes (the adjacent regions) as values:
class Node:
def __init__(self, s: str):
self.s = s
def __repr__(self):
return f"Node('{self.s}')" | {
"domain": "codereview.stackexchange",
"id": 45410,
"lm_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, algorithm, functional-programming",
"url": null
} |
python, algorithm, functional-programming
def __repr__(self):
return f"Node('{self.s}')"
if __name__ == "__main__":
graph_ = {
(n1 := Node("1")): [(n2 := Node("2"))],
n2: [n1, (n3 := Node("3")), (n4 := Node("4")), (n5 := Node("5")), (n6 := Node("6"))],
n3: [n2, n4],
n4: [n2, n3, n5],
n5: [n2, n4, n6],
n6: [n2, n5],
}
output = paint(graph_)
Answer: meaningful identifier
class Node:
def __init__(self, s: str): ...
Fine, we can read this as "s of string".
But wouldn't you like to offer a friendlier identifier, perhaps name ?
nit: In init(), rather than n (number?) prefer the longer
return [(node, -1) for node in nodes]
In general, it's hard to go wrong by saying for thing in plural_things.
Similarly, ns could become nodes.
OTOH, aliasing integer as Color was very nice, thank you.
nested functions
I recommend you avoid nested def's, for these reasons:
The shared namespaces produce the same coupling troubles that lead to globals being so reviled.
It's hard to separately unit test those buried hidden functions
In fortran we might say COMMON SORTED_ADJACENT.
In python we might prefer to invent a new class,
and then refer to self.sorted_adjacent.
docstring
"""Helper function""" | {
"domain": "codereview.stackexchange",
"id": 45410,
"lm_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, algorithm, functional-programming",
"url": null
} |
python, algorithm, functional-programming
By naming it _paint(), you already pretty much told us that it
is a helper function. (And then you buried it by nesting,
so it's not like it shall be exported from the module namespace anyway.)
Maybe we see the tail wagging the dog here, given that most of the
function's body disappeared down into the helper.
OIC, it's a recursive helper, with mainline doing the setup, got it.
This is at best a # comment.
Please write an English sentence, explaining what the function does,
when writing function docstrings.
Optionally add a blank line and more information
if you feel there's more to say.
I would have been grateful, if you'd written an actual docstring --
some explanation about the strategy would be very helpful here.
color high degree nodes first
... key=lambda r: -len(graph[r]))
This is very nice.
Consider turning the anonymous lambda into a named def function.
And then the function's docstring might acknowledge Wetherell's hint about
Regions that have many neighbors will probably be hardest to color, since they have the most constraints on them.
This code appears to achieve its design goals.
It scores about middle-of-the-road for maintainability, neither great nor terrible. | {
"domain": "codereview.stackexchange",
"id": 45410,
"lm_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, algorithm, functional-programming",
"url": null
} |
beginner, rust, fractals
Title: Mandelbrot Set image generator in Rust
Question: I'm learning Rust, and as-is tradition, I'm starting out with a Mandelbrot Set explorer as my first project (although, it just produces images so far). When run, it just creates and writes an image to the CWD. The coordinates and coloring function that are hardcoded produce my avatar. Eventually, there will be a GUI using Druid that allows changing these at runtime, but one step at a time.
text.rs is technically dead code, but I figured I'd include it because it works when hooked up. It produces ASCII images of the Set.
This is the first large chunk of code I've written in Rust, and would like feedback on anything. Not really anything in particular yet. I just want to make sure I'm not doing any bad habits early on. Am I doing it correctly? It feels kind of awkward to set up. Speed will eventually be a concern, so if I'm doing anything wonky that will bite me in terms of performance later on, I'd like to know about that as well.
Actually, I'd like comments on char_for_iterations if possible. It looks off to me. It requires tons of casting, and then also requires as_bytes which seems to be O(1), but I can't find anything concrete saying that. That function gave me a really hard time for some reason.
I'll post the code inline below, but it's also here in case that's easier to read.
main.rs
mod ui;
mod logic;
fn main() {
let width = 7000;
let height = width * 2/3;
let start = std::time::Instant::now();
ui::image::draw_area("mandelbrot.png", 0.3539265474695936, 0.3607889277625950, 0.3531315391015801, 0.3599939193945812, width, height, 200, 2);
println!("Elapsed: {:?}", start.elapsed());
}
logic.rs
pub mod mandelbrot_iteration;
logic/mandelbrot_iteration.rs
use num::complex::Complex;
pub type ComplexPoint = Complex<f64>; | {
"domain": "codereview.stackexchange",
"id": 45411,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, fractals",
"url": null
} |
beginner, rust, fractals
logic/mandelbrot_iteration.rs
use num::complex::Complex;
pub type ComplexPoint = Complex<f64>;
fn mandelbrot_iteration(initial: ComplexPoint, current: ComplexPoint) -> ComplexPoint {
let current_sq = current * current;
return Complex {
re: current_sq.re + initial.re,
im: current_sq.im + initial.im,
};
}
fn is_under_limit(current: ComplexPoint, infinity_limit: u32) -> bool {
let real_sq = current.re * current.re;
let imag_sq = current.im * current.im;
return (real_sq + imag_sq) <= (infinity_limit * infinity_limit) as f64;
}
pub fn test_point(initial: ComplexPoint, max_iterations: u32, infinity_limit: u32) -> u32 {
let mut current = initial;
let mut i = 0;
while i < max_iterations {
if is_under_limit(current, infinity_limit) {
current = mandelbrot_iteration(initial, current);
} else {
break;
}
i += 1;
}
return i;
}
/// Callback arguments: real, imag, display_x, display_y, iters
pub fn test_area
<F: FnMut(f64, f64, u32, u32, u32) -> ()>
(
real_min: f64,
real_max: f64,
imag_min: f64,
imag_max: f64,
display_width: u32,
display_height: u32,
max_iterations: u32,
infinity_limit: u32,
mut point_callback: F,
) -> () {
let real_length = real_max - real_min;
let imag_length = imag_max - imag_min;
let real_step = real_length / display_width as f64;
let imag_step = imag_length / display_height as f64;
for display_y in 0..display_height {
let imag = imag_min + (display_y as f64) * imag_step;
for display_x in 0..display_width {
let real = real_min + (display_x as f64) * real_step;
let c = Complex::new(real, imag);
let iters = test_point(c, max_iterations, infinity_limit);
point_callback(real, imag, display_x, display_y, iters);
}
}
}
ui.rs
pub mod text;
pub mod image; | {
"domain": "codereview.stackexchange",
"id": 45411,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, fractals",
"url": null
} |
beginner, rust, fractals
ui.rs
pub mod text;
pub mod image;
ui/image.rs
use image::{ImageBuffer, Rgb};
use num::{clamp, Num};
use crate::logic::mandelbrot_iteration;
fn wrap<N: Num + Copy>(n: N, min_n: N, max_n: N) -> N {
let limit = max_n - min_n;
return (n % limit) + min_n;
}
fn color_f(real: f64, imag: f64, iters: u32) -> Rgb<u8> {
let f_iters = iters as f64;
let red = clamp(real * f_iters * 6.0, 0.0, 255.0);
let green = clamp(imag * f_iters * 3.0, 0.0, 255.0);
let blue = clamp(f_iters * f_iters * 0.01, 0.0, 255.0);
return Rgb([red as u8, green as u8, blue as u8]);
}
pub fn draw_area(file_path: &str, real_min: f64, real_max: f64, imag_min: f64, imag_max: f64, display_width: u32, display_height: u32, max_iterations: u32, infinity_limit: u32) -> () {
let mut buffer = ImageBuffer::new(display_width, display_height);
let total_pixels = display_width * display_height;
let report_every = total_pixels as u32 / 10;
let mut current_pixel = 0;
mandelbrot_iteration::test_area(real_min, real_max, imag_min, imag_max, display_width, display_height, max_iterations, infinity_limit, |real, imag, x, y, iters | {
let pixel = buffer.get_pixel_mut(x, y);
*pixel = color_f(real, imag, iters);
current_pixel += 1;
if current_pixel % report_every == 0 {
let perc = current_pixel as f32 / total_pixels as f32;
println!("Progress: {}/{} ({}%)", current_pixel, total_pixels, perc * 100.0);
}
});
match buffer.save(file_path) {
Ok(_) => println!("Saved successfully"),
Err(err) => println!("Error: {}", err),
};
}
ui/text.rs
use crate::logic::mandelbrot_iteration;
// Looks better with less chars for some reason
const DENSITY_SORTED_CHARS: &str = " .-:;~*\\/i({vx?@"; | {
"domain": "codereview.stackexchange",
"id": 45411,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, fractals",
"url": null
} |
beginner, rust, fractals
fn char_for_iterations(n_iterations: u32, max_iterations: u32) -> char {
let density_perc = n_iterations as f32 / (max_iterations + 1) as f32;
let index = ((DENSITY_SORTED_CHARS.len()) as f32 * density_perc) as usize;
return DENSITY_SORTED_CHARS.as_bytes()[index] as char;
}
pub fn draw_area(real_min: f64, real_max: f64, imag_min: f64, imag_max: f64, display_width: u32, display_height: u32, max_iterations: u32, infinity_limit: u32) -> String {
let mut result = String::new();
mandelbrot_iteration::test_area(real_min, real_max, imag_min, imag_max, display_width, display_height, max_iterations, infinity_limit, | _real, _imag, x, _y, iters | {
result.push(char_for_iterations(iters, max_iterations));
if x >= display_width - 1 {
result.push('\n');
}
});
return result;
}
Answer: Couple of things I noticed:
infinity_limit is constant for a given call to draw_area. Its only use is in is_under_limit in this form:
return (real_sq + imag_sq) <= (infinity_limit * infinity_limit) as f64;
The compiler might be able to figure this out and optimize it but I'd compute infinity_limit * infinity_limit once at the top level and pass it down as an f64. Best case it saves you max_iteration * num_pixel multiplications.
Official Rust style I think is to omit return (i.e. instead of fn myfn() { ...; return x; } write fn myfn() { ...; x }
mandelbrot_iteration can be simplified to
fn mandelbrot_iteration(initial: ComplexPoint, current: ComplexPoint) -> ComplexPoint {
current * current + initial
}
test_point can be simplified by moving the is_under_limit check into the while condition:
pub fn test_point(initial: ComplexPoint, max_iterations: u32, infinity_limit: u32) -> u32 {
let mut current = initial;
let mut i = 0;
while is_under_limit(current, infinity_limit) && i < max_iterations {
current = mandelbrot_iteration(initial, current);
i += 1;
}
i
} | {
"domain": "codereview.stackexchange",
"id": 45411,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, fractals",
"url": null
} |
beginner, rust, fractals
DENSITY_SORTED_CHARS is not used as a string so shouldn't be one - an array of char will be a much better fit. Actually using a slice means you can omit the number of elements:
const MY_ARRAY: &[char] = &[' ', '.', '-', ':', ';', '~', '*', '\\', '/', 'i', '(', '{', 'v', 'x', '?', '@'];
A rationale for why string indexing is not provided is given here: https://stackoverflow.com/a/24542502/220986
If you keep away from fractions and compute percentage and keep computations in the integer realm you can probably save a bunch of castings in char_for_iterations. Might lose some precision but I don't think it matters:
fn char_for_iterations(n_iterations: u32, max_iterations: u32) -> char {
const scale: u32 = 100;
let density = n_iterations * scale / (max_iterations + 1);
let index = (DENSITY_SORTED_CHARS.len() as u32) * density / scale;
DENSITY_SORTED_CHARS[index as usize]
}
Scale factor of 100 is basically the equivalent of turning a fraction into a percentage value between 0 and 100. In some basic tests this yields a difference of 1 index in ~6% of all cases. If you set scale to 10_000 then there is no difference (with max_iterations = 200) | {
"domain": "codereview.stackexchange",
"id": 45411,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust, fractals",
"url": null
} |
homework, database, cobol
Title: COBOL Database Program
Question: For a school project I've created a database program in COBOL and now that I'm finished, I have to write a report on the project.
As one aspect of the report, we have to discuss whether the product (the program) achieved all of the "success criteria" we created earlier in the process. One of my success criteria was code style and readability. More specifically: "The source code of the final product must be easily readable, clear, and logical."
I wanted to get an outside opinion on this so I've come to this website.
IDENTIFICATION DIVISION.
PROGRAM-ID. COBDB.
ENVIRONMENT DIVISION.
INPUT-OUTPUT SECTION.
FILE-CONTROL.
SELECT OPTIONAL DB-FILE
ASSIGN USING DB-FILE-NAME
ORGANIZATION IS SEQUENTIAL
ACCESS IS SEQUENTIAL.
DATA DIVISION.
FILE SECTION.
FD DB-FILE.
01 CHAR PIC X(1). | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
WORKING-STORAGE SECTION.
01 PARSING-DATA.
05 DB-FILE-NAME-INDEX PIC 9(3) USAGE IS
COMPUTATIONAL.
05 PARSING-DONE PIC 9(1).
05 NUM-RECORDS-PARSING-START PIC 9(1).
05 NUM-RECORDS-PARSING-STARTED PIC 9(1).
05 NUM-RECORDS-PARSING-INDEX PIC 9(2).
05 DB-FILE-NAME PIC X(500).
01 DATA-REGISTERS.
05 DATA-REGISTER PIC X(4096).
05 LENGTH-REGISTER PIC 9(4) USAGE IS
DISPLAY.
01 HEADER-DATA.
05 ROW-NUM USAGE IS COMP-2.
05 FILE-INITIALIZED PIC 9(1).
05 FILE-EMPTY PIC 9(1).
05 HEADER-PARSE-STARTED PIC 9(1).
05 NUM-RECORDS PIC 9(18).
05 COL-VALS OCCURS 1 TO 4096 TIMES
DEPENDING ON ROW-NUM INDEXED
BY COL-VALS-INDEX.
10 COL-VAL PIC 9(1) USAGE IS COMP-3.
01 INITIALIZATION-DATA.
05 INPUT-COL-VALS-INDEX PIC 9(4).
05 INITIALIZATION-STARTED PIC 9(1).
05 INITIALIZATION-FAILED PIC 9(1).
01 MISC-DATA.
05 EOF PIC 9(1).
05 INPUT-DATA PIC X(4096).
05 DATA-MODE PIC 9(1).
05 DIVIDER PIC X(80).
05 COMMAND PIC X(10).
01 WRITE-PARSING-DATA.
05 WRITE-PARSING-INDEX PIC 9(4).
05 WRITE-PARSING-STARTED PIC 9(1).
05 WRITE-PARSING-FAILED PIC 9(1).
05 WRITE-PARSING-LEN PIC 9(4). | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
05 WRITE-PARSING-LEN PIC 9(4).
05 WRITE-PARSING-LEN-INDEX PIC 9(1).
05 WRITE-PARSING-VALS-CURRENTLY PIC 9(1).
05 WRITE-PARSING-LEN-CURRENTLY PIC 9(1).
05 WRITE-PARSING-CHAR PIC X(1).
05 WRITE-PARSING-CHAR-AS-INT
REDEFINES WRITE-PARSING-CHAR PIC 9(1).
05 FINAL-CHARACTER-INDEX PIC 9(4).
01 READ-DEL-PARSING-DATA.
05 SEARCH-KEY PIC 9(18).
05 COLS-INDEX PIC 9(4).
05 READING-LEN-INDEX PIC 9(1).
05 SEARCH-FAILED PIC 9(1).
05 SEARCH-DONE PIC 9(1).
05 READING-LEN PIC 9(1).
05 READDEL-VAL PIC 9(1).
05 REGISTER-INDEX PIC 9(4).
05 PARSING-DELED-REC PIC 9(1). | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
PROCEDURE DIVISION.
MAIN.
PERFORM INIT-DATA.
PERFORM GET-INPUT.
PERFORM OPEN-FILE.
INITIALIZE COMMAND.
DISPLAY "Please enter command"
ACCEPT COMMAND.
IF COMMAND = "INITIALIZE"
DISPLAY "Please enter input"
PERFORM INITIALIZE-FILE
ELSE IF COMMAND = "WRITE "
DISPLAY "Please enter input"
PERFORM WRITE-REC
ELSE IF COMMAND = "READ "
DISPLAY "Please enter input"
PERFORM READ-REC
ELSE IF COMMAND = "DELETE "
DISPLAY "Please enter input"
PERFORM DELETE-REC
ELSE
DISPLAY "Error: Invalid command"
END-IF.
STOP RUN.
INIT-DATA.
INITIALIZE PARSING-DATA.
INITIALIZE DATA-REGISTERS.
INITIALIZE HEADER-DATA.
INITIALIZE MISC-DATA.
INITIALIZE INITIALIZATION-DATA.
INITIALIZE WRITE-PARSING-DATA.
INITIALIZE READ-DEL-PARSING-DATA.
GET-INPUT.
ACCEPT DB-FILE-NAME FROM COMMAND-LINE.
MOVE 501 TO DB-FILE-NAME-INDEX.
PERFORM UNTIL PARSING-DONE = 1
SUBTRACT 1 FROM DB-FILE-NAME-INDEX
IF NOT DB-FILE-NAME (DB-FILE-NAME-INDEX : 1) = ' '
MOVE 1 TO PARSING-DONE
END-IF
END-PERFORM. | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
OPEN-FILE.
SET COL-VALS-INDEX TO 1.
MOVE 1 TO FILE-EMPTY
MOVE 1 TO NUM-RECORDS-PARSING-INDEX
OPEN INPUT DB-FILE.
PERFORM UNTIL FILE-INITIALIZED = '1' OR EOF = '1' OR
CHAR = '$'
READ DB-FILE
AT END
MOVE '1' TO EOF
IF (FILE-EMPTY = 0) AND
(FILE-INITIALIZED = 0) AND
(NUM-RECORDS-PARSING-STARTED = 0)
DISPLAY "File is corrupted. Please ensur
- "e that you are inputting a proper cobDB
- " file or an empty/non existant file. Ex
- "iting...1"
CLOSE DB-FILE
EXIT PROGRAM
END-IF
NOT AT END
IF FILE-EMPTY = 1
MOVE 0 TO FILE-EMPTY
END-IF
IF HEADER-PARSE-STARTED = 0
IF CHAR = '@'
MOVE 1 TO HEADER-PARSE-STARTED
ELSE
DISPLAY "File is corrupted. Please en
- "sure that you are inputting a proper
- " cobDB file or an empty/non existant
- " file. Exiting...2"
CLOSE DB-FILE
EXIT PROGRAM
END-IF
ELSE IF NUM-RECORDS-PARSING-START = 1
IF CHAR IS NUMERIC
MOVE CHAR TO NUM-RECORDS
(NUM-RECORDS-PARSING-INDEX : 1) | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
(NUM-RECORDS-PARSING-INDEX : 1)
ADD 1 TO NUM-RECORDS-PARSING-INDEX
IF NUM-RECORDS-PARSING-STARTED = 0
MOVE 1 TO
NUM-RECORDS-PARSING-STARTED
END-IF
ELSE IF CHAR = '$'
CONTINUE
ELSE
DISPLAY "0"
CLOSE DB-FILE
EXIT PROGRAM
END-IF
ELSE
IF CHAR IS NUMERIC
MOVE CHAR TO COL-VALS
(COL-VALS-INDEX)
SET COL-VALS-INDEX UP BY 1
ELSE IF CHAR = '#'
MOVE 1 TO NUM-RECORDS-PARSING-START
ELSE
DISPLAY "File is corrupted. Please en
- "sure that you are inputting a proper
- " cobDB file or an empty/non existant
- " file. Exiting...3"
CLOSE DB-FILE
EXIT PROGRAM
END-IF
END-IF
END-READ
END-PERFORM.
CLOSE DB-FILE. | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
INITIALIZE-FILE.
ACCEPT INPUT-DATA.
MOVE 0 TO INITIALIZATION-STARTED.
OPEN OUTPUT DB-FILE.
MOVE '@' TO CHAR.
WRITE CHAR END-WRITE.
PERFORM VARYING INPUT-COL-VALS-INDEX FROM 1 BY 1 UNTIL
INPUT-COL-VALS-INDEX IS GREATER THAN 4096
EVALUATE INPUT-DATA (INPUT-COL-VALS-INDEX : 1)
WHEN 'I'
MOVE '1' TO CHAR
WRITE CHAR END-WRITE
IF INITIALIZATION-STARTED = 0
MOVE 1 TO INITIALIZATION-STARTED
END-IF
WHEN 'F'
MOVE '2' TO CHAR
WRITE CHAR END-WRITE
IF INITIALIZATION-STARTED = 0
MOVE 1 TO INITIALIZATION-STARTED
END-IF
WHEN 'S'
MOVE '3' TO CHAR
WRITE CHAR END-WRITE
IF INITIALIZATION-STARTED = 0
MOVE 1 TO INITIALIZATION-STARTED
END-IF
WHEN ' '
IF INITIALIZATION-STARTED = 0
DISPLAY "Error: Initialization failed. In
- "itialization string was not properly for
- "matted."
MOVE 1 TO INITIALIZATION-FAILED
END-IF
NEXT SENTENCE
WHEN OTHER
DISPLAY "Error: Initialization failed. Initia
- "lization string was not properly formatted."
MOVE 1 TO INITIALIZATION-FAILED
CLOSE DB-FILE
NEXT SENTENCE
END-EVALUATE | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
NEXT SENTENCE
END-EVALUATE
END-PERFORM.
IF INITIALIZATION-FAILED = 0
MOVE '#' TO CHAR
WRITE CHAR END-WRITE
MOVE 0 TO NUM-RECORDS
PERFORM 18 TIMES
MOVE '0' TO CHAR
WRITE CHAR END-WRITE
END-PERFORM
MOVE '$' TO CHAR
WRITE CHAR END-WRITE
END-IF.
CLOSE DB-FILE. | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
WRITE-REC.
ACCEPT INPUT-DATA.
IF INITIALIZATION-FAILED = 1
DISPLAY "Error"
END-IF.
MOVE 0 TO WRITE-PARSING-STARTED.
MOVE 0 to WRITE-PARSING-FAILED.
MOVE 0 TO WRITE-PARSING-LEN-INDEX.
MOVE 0 TO WRITE-PARSING-VALS-CURRENTLY.
MOVE 0 TO WRITE-PARSING-LEN-CURRENTLY.
PERFORM VARYING WRITE-PARSING-INDEX FROM 1 BY 1 UNTIL
WRITE-PARSING-INDEX IS GREATER THAN 4096
MOVE INPUT-DATA (WRITE-PARSING-INDEX : 1) TO
WRITE-PARSING-CHAR
IF WRITE-PARSING-STARTED = 0
IF WRITE-PARSING-CHAR IS NUMERIC
ADD 1 TO WRITE-PARSING-LEN-INDEX
MOVE WRITE-PARSING-CHAR-AS-INT TO
WRITE-PARSING-LEN (WRITE-PARSING-LEN-INDEX : 1)
MOVE 0 TO WRITE-PARSING-VALS-CURRENTLY
MOVE 1 TO WRITE-PARSING-LEN-CURRENTLY
MOVE 1 TO WRITE-PARSING-STARTED
ELSE
MOVE 1 TO WRITE-PARSING-FAILED
DISPLAY "2"
NEXT SENTENCE
END-IF
ELSE
IF WRITE-PARSING-LEN-CURRENTLY = 1
IF WRITE-PARSING-CHAR IS NUMERIC
ADD 1 TO WRITE-PARSING-LEN-INDEX
MOVE WRITE-PARSING-CHAR-AS-INT TO
WRITE-PARSING-LEN (WRITE-PARSING-LEN-INDEX :
1)
IF WRITE-PARSING-LEN-INDEX = 4
MOVE 0 TO WRITE-PARSING-LEN-CURRENTLY
MOVE 1 TO WRITE-PARSING-VALS-CURRENTLY
MOVE 0 TO WRITE-PARSING-LEN-INDEX
END-IF
ELSE
MOVE 1 TO WRITE-PARSING-FAILED
DISPLAY "3" | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
MOVE 1 TO WRITE-PARSING-FAILED
DISPLAY "3"
NEXT SENTENCE
END-IF
ELSE IF WRITE-PARSING-VALS-CURRENTLY = 1
SUBTRACT 1 FROM WRITE-PARSING-LEN
IF WRITE-PARSING-LEN = 0
MOVE 0 TO WRITE-PARSING-VALS-CURRENTLY
END-IF
ELSE
IF WRITE-PARSING-CHAR IS NUMERIC
ADD 1 TO WRITE-PARSING-LEN-INDEX
MOVE WRITE-PARSING-CHAR-AS-INT TO
WRITE-PARSING-LEN (WRITE-PARSING-LEN-INDEX :
1)
MOVE 1 TO WRITE-PARSING-LEN-CURRENTLY
ELSE IF WRITE-PARSING-CHAR = ' '
MOVE WRITE-PARSING-INDEX TO
FINAL-CHARACTER-INDEX
NEXT SENTENCE
ELSE
MOVE 1 TO WRITE-PARSING-FAILED
DISPLAY "4"
NEXT SENTENCE
END-IF
END-IF
END-IF
END-PERFORM.
IF WRITE-PARSING-FAILED = 0
OPEN EXTEND DB-FILE
PERFORM VARYING WRITE-PARSING-INDEX FROM 1 BY 1 UNTIL
WRITE-PARSING-INDEX = FINAL-CHARACTER-INDEX
MOVE INPUT-DATA (WRITE-PARSING-INDEX : 1) TO CHAR
WRITE CHAR END-WRITE
END-PERFORM
CLOSE DB-FILE
ADD 1 TO NUM-RECORDS
OPEN I-O DB-FILE
PERFORM UNTIL CHAR = '#'
READ DB-FILE
END-PERFORM
PERFORM VARYING WRITE-PARSING-INDEX FROM 1 BY 1
UNTIL WRITE-PARSING-INDEX IS GREATER THAN 18 | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
UNTIL WRITE-PARSING-INDEX IS GREATER THAN 18
READ DB-FILE END-READ
MOVE NUM-RECORDS (WRITE-PARSING-INDEX : 1) TO
CHAR
REWRITE CHAR
END-PERFORM
CLOSE DB-FILE
END-IF. | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
READ-REC.
MOVE ALL '_' TO DIVIDER (1 : 80).
MOVE 0 TO SEARCH-FAILED.
MOVE 0 TO SEARCH-DONE.
MOVE 1 TO READING-LEN.
MOVE 1 TO READING-LEN-INDEX.
MOVE 0 TO READDEL-VAL.
MOVE 1 TO REGISTER-INDEX.
MOVE 0 TO PARSING-DELED-REC.
MOVE COL-VALS-INDEX TO COLS-INDEX.
SUBTRACT 1 FROM COLS-INDEX.
MOVE ' ' TO CHAR.
ACCEPT SEARCH-KEY.
IF SEARCH-KEY IS GREATER THAN (NUM-RECORDS - 1)
DISPLAY "6"
EXIT
END-IF.
OPEN INPUT DB-FILE.
PERFORM UNTIL CHAR = '$'
READ DB-FILE
END-PERFORM
PERFORM UNTIL (SEARCH-DONE = 1) OR (SEARCH-FAILED = 1)
READ DB-FILE
IF PARSING-DELED-REC = 1
IF CHAR = '^'
MOVE 0 TO PARSING-DELED-REC
MOVE 1 TO READING-LEN
MOVE 0 TO READDEL-VAL
MOVE 1 TO READING-LEN-INDEX
END-IF
ELSE IF READING-LEN = 1
IF CHAR IS NUMERIC
IF CHAR = '9'
IF READING-LEN-INDEX = 1
MOVE 1 TO PARSING-DELED-REC
END-IF
END-IF
MOVE CHAR TO LENGTH-REGISTER
(READING-LEN-INDEX : 1)
ADD 1 TO READING-LEN-INDEX
IF READING-LEN-INDEX = 5
MOVE 1 TO READING-LEN-INDEX
MOVE 0 TO READING-LEN
MOVE 1 TO READDEL-VAL
IF DATA-MODE = 1
DISPLAY LENGTH-REGISTER
END-IF | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
DISPLAY LENGTH-REGISTER
END-IF
END-IF
ELSE
DISPLAY "7"
MOVE 1 TO SEARCH-FAILED
END-IF
ELSE IF READDEL-VAL = 1
IF SEARCH-KEY IS GREATER THAN 0
SUBTRACT 1 FROM LENGTH-REGISTER
IF LENGTH-REGISTER = 0
MOVE 1 TO READING-LEN
MOVE 0 TO READDEL-VAL
SUBTRACT 1 FROM COLS-INDEX
IF COLS-INDEX = 0
MOVE COL-VALS-INDEX TO COLS-INDEX
SUBTRACT 1 FROM COLS-INDEX
SUBTRACT 1 FROM SEARCH-KEY
END-IF
END-IF
ELSE
MOVE CHAR TO DATA-REGISTER (REGISTER-INDEX :
1)
SUBTRACT 1 FROM LENGTH-REGISTER
ADD 1 TO REGISTER-INDEX
IF LENGTH-REGISTER = 0
MOVE 1 TO READING-LEN
MOVE 0 TO READDEL-VAL
SUBTRACT 1 FROM COLS-INDEX
DISPLAY DATA-REGISTER (1 :
REGISTER-INDEX)
MOVE 1 TO REGISTER-INDEX
MOVE ALL ' ' TO DATA-REGISTER (1 : 4096)
IF DATA-MODE = 0
DISPLAY DIVIDER
END-IF
IF COLS-INDEX = 0
MOVE 1 TO SEARCH-DONE
END-IF
END-IF
END-IF | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
END-IF
END-IF
END-PERFORM.
CLOSE DB-FILE.
DELETE-REC.
MOVE 0 TO SEARCH-FAILED.
MOVE 0 TO SEARCH-DONE.
MOVE 1 TO READING-LEN.
MOVE 1 TO READING-LEN-INDEX.
MOVE 0 TO READDEL-VAL.
MOVE COL-VALS-INDEX TO COLS-INDEX.
SUBTRACT 1 FROM COLS-INDEX.
MOVE ' ' TO CHAR.
ACCEPT SEARCH-KEY.
IF SEARCH-KEY IS GREATER THAN (NUM-RECORDS - 1)
DISPLAY "6"
EXIT
END-IF.
OPEN I-O DB-FILE.
PERFORM UNTIL CHAR = '$'
READ DB-FILE
END-PERFORM.
PERFORM UNTIL (SEARCH-DONE = 1) OR (SEARCH-FAILED = 1)
READ DB-FILE
IF READING-LEN = 1
IF CHAR IS NUMERIC
MOVE CHAR TO LENGTH-REGISTER
(READING-LEN-INDEX : 1)
ADD 1 TO READING-LEN-INDEX
IF READING-LEN-INDEX = 5
MOVE 1 TO READING-LEN-INDEX
MOVE 0 TO READING-LEN
MOVE 1 TO READDEL-VAL
IF DATA-MODE = 1
DISPLAY LENGTH-REGISTER
END-IF
END-IF
IF SEARCH-KEY = 0
MOVE '9' TO CHAR
REWRITE CHAR END-REWRITE
END-IF
ELSE
DISPLAY "7"
MOVE 1 TO SEARCH-FAILED
END-IF
ELSE IF READDEL-VAL = 1
IF SEARCH-KEY IS GREATER THAN 0
SUBTRACT 1 FROM LENGTH-REGISTER
IF LENGTH-REGISTER = 0 | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
IF LENGTH-REGISTER = 0
MOVE 1 TO READING-LEN
MOVE 0 TO READDEL-VAL
SUBTRACT 1 FROM COLS-INDEX
IF COLS-INDEX = 0
MOVE COL-VALS-INDEX TO COLS-INDEX
SUBTRACT 1 FROM COLS-INDEX
SUBTRACT 1 FROM SEARCH-KEY
END-IF
END-IF
ELSE
SUBTRACT 1 FROM LENGTH-REGISTER
IF LENGTH-REGISTER = 0
MOVE '^' TO CHAR
REWRITE CHAR END-REWRITE
MOVE 1 TO READING-LEN
MOVE 0 TO READDEL-VAL
SUBTRACT 1 FROM COLS-INDEX
IF COLS-INDEX = 0
MOVE 1 TO SEARCH-DONE
END-IF
ELSE
MOVE ' ' TO CHAR
REWRITE CHAR END-REWRITE
END-IF
END-IF
END-IF
END-PERFORM.
CLOSE DB-FILE. | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
Answer: ZOMG, that is frightening along so many dimensions.
Disclaimer: Within the last decade I wrote lots of python code to parse production COBOL database record formats. And as an undergraduate I had roommates who studied COBOL in a non-ironic way.
format
Ok, style points for leaving room for six-digit card sequence numbers,
plus a blank.
But, didn't you want to start out by telling us what language dialect you were coding to?
Like, IDK, COBOL-2014 or something?
I hear you don't even have to use ALL CAPS EBCDIC any more.
This feels more like I'm reading a green-bar printout in the lobby of
the Computer History Museum than reading a recently authored
source file on github.
review context
I'm not seeing any comments, and maybe that's not an entirely bad thing.
But the OP submission included no ReadMe.md file,
and no narrative remarks about what problem we're trying to solve,
what approach we took, and what the pre-defined success criteria are.
In a word, there's no
contract.
Such promises mattered to Rear Adm. Grace Hopper, and they matter to me.
If someone has to maintain what you wrote, it will matter to them.
arbitrarily out-of-sequence
INIT-DATA.
...
INITIALIZE HEADER-DATA.
INITIALIZE MISC-DATA.
INITIALIZE INITIALIZATION-DATA.
I don't like this.
It corresponds to:
01 HEADER-DATA.
...
01 INITIALIZATION-DATA.
...
01 MISC-DATA.
We have nightmarish
DRY
issues all over the place as a design relic from 1958,
and no automated support from awk, m4, or similar preprocessors,
so you're asking humans to do the manual error checking.
To randomly reorganize the order is not a kindness to the Gentle Reader.
magic number
GET-INPUT.
...
MOVE 501 TO DB-FILE-NAME-INDEX. | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
WTF, where did 501 come from?
We don't like naming our magic constants?
My difficulty is, I simply don't know what it means,
and grep'ing for 501 fails.
OIC, the related DB-FILE-NAME can hold 500 characters.
What, there's no LENGTH-OF-STORAGE-ELEMENT(DB-FILE-NAME)
defined in this dialect of the language?
Ok, fine, it is what it is.
The GET-INPUT identifier is kind of true,
but it doesn't tell the whole story,
we might have gone with a longer identifier.
Scanning for last non-blank filename character
seems to be most of what it's responsible for.
Apparently you had the opportunity to put an * asterisk
in column seven, followed by descriptive comments,
and you elected not to do so.
trim
I was going to suggest writing a TRIM-BLANKS utility function.
But it turns out that folks working with modern IBM COBOL products
will use FUNCTION LENGTH(DB-FILE-NAME-INDEX) to obtain the integer 500,
and will use FUNCTION TRIM(db-file-name-index TRAILING)
to strip whitespace from the end,
for example during a MOVE.
(I was just adding emphasis -- compiler likely wants to see upcased identifier.)
We've had 65 years to perfect this operation.
I recommend you avoid re-inventing the wheel.
open-file
PERFORM UNTIL FILE-INITIALIZED = '1' OR ...
IF (FILE-EMPTY = 0) AND ... | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
homework, database, cobol
Sorry, I'm getting distracted by the gratuitous datatype changes.
We declared both of those as PIC 9(1).
Yet sometimes we talk about them as character variables,
and sometimes as numeric variables.
Yes, I understand the language lets you get away with it.
But if you're trying to communicate a concept to a human reader,
it's better to stick to just a single convention.
Prefer to think of booleans as numeric, rather than as character data.
Also, I bet I don't even want to know about order-of-operations,
and how tightly AND and OR bind.
Your use of ( ) parens for conjuncts and disjuncts is inconsistent,
which makes me nervous about what the underlying language rules might be.
EDIT:
It turns out that OR binds
least tightly,
as you might expect, so that's OK.
For example a AND b OR c AND d is (a AND b) OR (c AND d).
diagnostic message
DISPLAY "File is corrupted. Please ensur
- "e that you are inputting a proper cobDB
- " file or an empty/non existant file. Ex
- "iting...1" | {
"domain": "codereview.stackexchange",
"id": 45412,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "homework, database, cobol",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.