text stringlengths 1 2.12k | source dict |
|---|---|
c++, beginner, rock-paper-scissors
do {
if (std::cin >> matches) {
// Read worked.
}
else {
// If the failure was because of EOF.
// Then you can't get any more input and it
// simply fail again so exit.
if (std::cin.eof()) {
throw std::runtime_error("Bad EOF on input stream");
}
// Read failed we need to reset the state of the
// stream before we do another read.
std::cin.clear();
// Since interactive user input is line based.
// Let us ignore the rest of the line.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
if (matches < 1) {
std::cout << "Please enter a valid number.\n";
std::cout << "How many games do you want to play? \n";
}
}
while (matches < 1);
You are making an assumption that if the user fails they will get it correct the second time. I would put that in a loop until they get it correct.
if (userInput != 'r' && userInput != 'p' && userInput != 's')
{
std::cout << "Please enter a valid character. \n";
std::cout << "Rock, paper or scissors? (r-p-s): \n";
std::cin >> userInput;
}
Initialize this only once. Then re-use.
std::mt19937 mt{static_cast<std::mt19937::result_type>(std::chrono::steady_clock::now().time_since_epoch().count())};
This object is relatively expensive to create. Best to create once then reuse the same object. To do that make it a static object.
Also we have a random seed generator!
static std::random_device rd;
static std::mt19937 mt{rd()};
I think this is overly verbose.
switch (r)
{
case 1:
return 'r';
break;
case 2:
return 'p';
break;
case 3:
return 's';
break;
} | {
"domain": "codereview.stackexchange",
"id": 45368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, rock-paper-scissors",
"url": null
} |
c++, beginner, rock-paper-scissors
Also no need for a break after a return. I would write like this:
// PS: Why 1->3 we are programmers.
// Numbers start at zero!
switch (r)
{
case 1: return 'r';
case 2: return 'p';
case 3: return 's';
}
But I would use an array.
static char result[] = {'r', 'p', 's'};
return result[r-1];
Don't add code that will never be used.
return 0;
}
Sure:
void showValue(char x)
{
switch (x)
{
case 'r':
std::cout << "Rock\n";
break;
case 'p':
std::cout << "Paper\n";
break;
case 's':
std::cout << "Scissors\n";
break;
}
}
Rather than a switch, I would again use a data structure.
static std::map<char, std::string> pritty {{'r', "Rock"}, {'p', "Paper"}, {'s', "Scissors"}};
std::cout << pritty[x] << "\n"; | {
"domain": "codereview.stackexchange",
"id": 45368,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, beginner, rock-paper-scissors",
"url": null
} |
python, python-3.x, classes, python-requests
Title: Mapping an API's setting IDs to setting names with class methods, enabling clearer utilization
Question: I'm trying to access an API using the requests library in as clean a manner as possible. The API is accessing various settings of various devices. I'd like to keep my code as readable and comprehensible as possible, thus I want to avoid setting up my API access functions too abstractly. Therefore, instead of setting_101 I want to edit settings by their associated name.
I reckon a class mapping a the various setting names to their values is the most desirable approach, but given my inexperience with classes I would appreciate some feedback on my attempt.
My ultimate goal is to have a class allowing me to simply access a setting, once an instance is setup, through read.setting_name(). Previously I simply defined individual functions for every setting which while functional was massively inefficient and a bit of an anti-pattern.
The code below is my attempt at implementing the desired functionality. It works, but it still feels a bit 'rough'.
import requests
class SettingReader:
def __init__(self, domain, headers, device_serial):
self.domain = domain
self.headers = headers
self.device_serial = device_serial
self.setting_ids = {
'setting_A': 1,
'setting_B': 2,
'setting_C': 3,
}
def read_setting_A(self):
return self._read_setting(self.setting_ids['setting_A'])
def read_setting_B(self):
return self._read_setting(self.setting_ids['setting_B'])
def read_setting_C(self):
return self._read_setting(self.setting_ids['setting_C'])
def _read_setting(self, setting_id):
url = f'{self.domain}/device/{self.device_serial}/settings/{setting_id}/read'
response = requests.request('POST', url, headers=self.headers)
return response
domain = "https://my_dummy_api.com"
headers = {"Authorization": "my_token"} | {
"domain": "codereview.stackexchange",
"id": 45369,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes, python-requests",
"url": null
} |
python, python-3.x, classes, python-requests
domain = "https://my_dummy_api.com"
headers = {"Authorization": "my_token"}
reader = SettingReader(domain, headers, 'my_device_serial')
result_A = reader.read_setting_A()
result_B = reader.read_setting_B()
result_C = reader.read_setting_C()
For these relatively simple query it does give the correct output. I want to be sure of this approach before implementing more complex queries.
print(result_A.json())
print(result_B.json())
print(result_C.json())
> {'data': {'value': val_A}}
> {'data': {'value': val_B}}
> {'data': {'value': val_C}}
While this already feels like a significant improvement (and notably also an easily expandable option for more complex API calls than simple reads) over individually defined functions, I'd rather do it fully right this time around than having to rewrite this code again in the future.
Do you agree a class (and this implementation) is the correct approach for this issue, and are there any changes you'd suggest? | {
"domain": "codereview.stackexchange",
"id": 45369,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes, python-requests",
"url": null
} |
python, python-3.x, classes, python-requests
Answer: One can try the approach of creating the methods dynamically. The answer posted by Linny is one way of doing this. Linny's solution implements a __getattr__ that is called when an attribute such as read_setting_A is undefined when calling reader.read_setting_A() and then sees if the read_setting_A is a key in self.settings_id and if so returns an appropriate lambda function for the missing attribute. If the function should be called again, the read_setting_A attribute will still be undefined and the __getattr__ method will be invoked again.
Let me suggest two approaches, the second of which is the best if you are willing to access the setting values as read/only properties rather than as method calls:
Approach 1: Create the Class with All Required Methods Up Front
We can define a function create_SettingReader_class that returns a class definition with all the necessary methods defined based on your settings_ids dictionary, called SETTINGS_IDS in the following code:
def create_SettingReader_class():
import requests
import types
SETTINGS_IDS = {
'setting_A': 1,
'setting_B': 2,
'setting_C': 3,
}
# Define the methods we will always have:
def __init__(self, domain, headers, device_serial):
self.domain = domain
self.headers = headers
self.device_serial = device_serial
def _read_setting(self, setting_id):
"""For demo purposes, just return the setting_id argument."""
print('_read_setting called with setting_id =', setting_id, 'domain =', self.domain)
return setting_id
"""
url = f'{self.domain}/device/{self.device_serial}/settings/{setting_id}/read'
response = requests.request('POST', url, headers=self.headers)
return response
""" | {
"domain": "codereview.stackexchange",
"id": 45369,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes, python-requests",
"url": null
} |
python, python-3.x, classes, python-requests
def create_read_setting_function(value):
"""Create a method that calls self._read_setting with the specified
value as the argument. Note that this function returns a closure."""
return lambda self: self._read_setting(value)
# Create a dictionary wuth the methods
# we will always have:
cls_dict = {
'__init__': __init__,
'_read_setting': _read_setting
}
# Add to this dictionary dynamically created methods, one for
# each key/value pair in SETTINGS_ID. For example, method
# read_setting_A will be created and it will call _read_setting
# with the setting_id argument set to 1:
cls_dict.update({
'read_' + setting_id: create_read_setting_function(value)
for setting_id, value in SETTINGS_IDS.items()
})
# Return the new class to be assigned to a global variable SettingReader:
return types.new_class('SettingReader', (), {}, lambda ns: ns.update(cls_dict))
SettingReader = create_SettingReader_class()
domain = "https://my_dummy_api.com"
headers = {"Authorization": "my_token"}
reader = SettingReader(domain, headers, 'my_device_serial')
result_A = reader.read_setting_A()
result_B = reader.read_setting_B()
result_C = reader.read_setting_C()
Prints:
_read_setting called with setting_id = 1 domain = https://my_dummy_api.com
_read_setting called with setting_id = 2 domain = https://my_dummy_api.com
_read_setting called with setting_id = 3 domain = https://my_dummy_api.com | {
"domain": "codereview.stackexchange",
"id": 45369,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes, python-requests",
"url": null
} |
python, python-3.x, classes, python-requests
A Second Approach: Use Descriptors
Descriptors are very powerful. Properties are implemented as descriptors and we will be creating specialized properties. Now a client will access property setting_A rather than calling method read_setting_A. If you do not mind the change of syntax, I believe this is a simpler approach than the previous one:
class SettingProperty:
@staticmethod
def read_setting(setting_id, domain, headers, device_serial):
"""For demo purposes, just return the setting_id argument."""
print('read_setting called with setting_id =', setting_id, 'domain =', domain)
return setting_id
"""
url = f'{domain}/device/{device_serial}/settings/{setting_id}/read'
response = requests.request('POST', url, headers=headers)
return response
"""
def __init__(self, setting_id):
self._setting_id = setting_id
def __set_name__(self, owner, name):
"""We aren't really interested in the name of this property."""
self._name = name
def __get__(self, obj, objtype=None):
return SettingProperty.read_setting(
self._setting_id,
obj.domain,
obj.headers,
obj.device_serial)
class SettingReader:
# Now instead of a dictionary, we have:
setting_A = SettingProperty(1)
setting_B = SettingProperty(2)
setting_C = SettingProperty(3)
def __init__(self, domain, headers, device_serial):
self.domain = domain
self.headers = headers
self.device_serial = device_serial
domain = "https://my_dummy_api.com"
headers = {"Authorization": "my_token"}
reader = SettingReader(domain, headers, 'my_device_serial')
result_A = reader.setting_A
result_B = reader.setting_B
result_C = reader.setting_C | {
"domain": "codereview.stackexchange",
"id": 45369,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes, python-requests",
"url": null
} |
python, python-3.x, classes, python-requests
Prints:
read_setting called with setting_id = 1 domain = https://my_dummy_api.com
read_setting called with setting_id = 2 domain = https://my_dummy_api.com
read_setting called with setting_id = 3 domain = https://my_dummy_api.com
Notes
In both approaches when a read-setting method is called or a setting property is accessed, a new request is made to get the value. If this value does not change from call to call, then it could be saved as an attribute in the SettingReader instance. Naturally you would check to see if the attribute exists before issuing a network request.
This is the modified code for the second approach that caches the setting values:
class SettingProperty:
@staticmethod
def read_setting(setting_id, domain, headers, device_serial):
"""For demo purposes, just return the setting_id argument."""
print('read_setting called with setting_id =', setting_id, 'domain =', domain)
return setting_id
"""
url = f'{domain}/device/{device_serial}/settings/{setting_id}/read'
response = requests.request('POST', url, headers=headers)
return response
"""
def __init__(self, setting_id):
self._setting_id = setting_id
def __set_name__(self, owner, name):
"""Now we are interested in the property's name."""
self._name = name
def __get__(self, obj, objtype=None):
attribute_name = '_' + self._name
value = getattr(obj, attribute_name, None)
if value is None:
# We must go out to the network:
value = SettingProperty.read_setting(
self._setting_id,
obj.domain,
obj.headers,
obj.device_serial)
setattr(obj, attribute_name, value)
return value
class SettingReader:
# Now instead of a dictionary, we have:
setting_A = SettingProperty(1)
setting_B = SettingProperty(2)
setting_C = SettingProperty(3) | {
"domain": "codereview.stackexchange",
"id": 45369,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes, python-requests",
"url": null
} |
python, python-3.x, classes, python-requests
def __init__(self, domain, headers, device_serial):
self.domain = domain
self.headers = headers
self.device_serial = device_serial
domain = "https://my_dummy_api.com"
headers = {"Authorization": "my_token"}
reader = SettingReader(domain, headers, 'my_device_serial')
print(reader.setting_A)
print(reader.setting_A)
Prints:
read_setting called with setting_id = 1 domain = https://my_dummy_api.com
1
1 | {
"domain": "codereview.stackexchange",
"id": 45369,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, classes, python-requests",
"url": null
} |
python, game, numpy
Title: Text-mode 2048 in Python (using numpy)
Question: Good evening. I am studying mathematics at the moment, so I have little to no formal education in actual computer engineering. However, I am trying my hands at learning Python because I will need lots of it for my future career. I hope you can point out any bad practices or mistakes on my part, so that I can fix them early on in my journey. I thank all of you in advance.
I have coded a command line implementation of the "2048" game. I have written a "game engine", implemented as the Game class of the two048.py python module. This module is imported by main.py and an instance of Game is then used to actually play the game.
The Game class is implemented to be as general as possible: it can be used to play the "2048" game on a nxn game table with the goal of going over any positive m. The game table is stored as a numpy array to make the code as efficient as possible.
Here comes the code:
file1 - main.py
"""Play a command line "2048" game."""
from two048 import *
# Create a new "2048" game, set a random entry and display it.
game = Game(4, 2048)
game.display()
# As long as the game is not won or lost, allow the player to make moves by inputting characters.
# Illegal moves or meaningless strings are ignored.
while game.status == Status.IN_PROGRESS:
c = input()
if c == "w":
game.shift_up()
elif c == "d":
game.shift_right()
elif c == "s":
game.shift_down()
elif c == "a":
game.shift_left()
else:
continue
game.insert_random_2()
game.update_status()
game.display()
if game.status == Status.LOST:
print("You lost!")
elif game.status == Status.WON:
print("You won!")
file2 - two048.py
"""Game engine for "2048".
This module defines a class Game whose instances are 2048 games.
""" | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
This module defines a class Game whose instances are 2048 games.
"""
# Import useful libraries:
# - numpy: the "2048" game is played on a numpy array
# - random: random handles
# - enum: the status of the "2048" game is memorized as an Enum
# - re: we use the sub function to print the game table
import numpy as np
import random
from enum import Enum
from re import sub
random.seed()
Status = Enum("Status", ["WON", "LOST", "IN_PROGRESS"])
class Game:
"""Each instance represents a 2048 game.
The game table is represented as a nxn numpy array (n is provided by the user an is usually set = 4).
Use the shift_left, shift right, shift_up, shift_down methods to
shift the numbers on the table. These methods represent moves the player can make.
A move is legal if it results in at least one number shifting or changing.
Every time the player makes a legal move, a 2 is randomly inserted on the table.
If the player cannot make any legal move, they lose.
If the player manages to obtain a number >= winning number (winning number is provided by the user and is usually
set = 2048), they win.
The status of the game (WON - LOST - IN_PROGRESS) is memorized as a Status Enum.
"""
def __init__(self, n, winning_number):
"""Initialize a 2048 game and set up all the instance variables.
Arguments:
self
n -- integer representing the size of the game table
winning_number -- integer representing the number that the user should exceed to win
"""
self.n = n
self.table = np.zeros((n, n), dtype=int)
self.winning_number = winning_number
self.status = Status.IN_PROGRESS
self.insert_random_2()
def shift_left(self):
"""Shift the table left. | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
self.insert_random_2()
def shift_left(self):
"""Shift the table left.
The same algorithm is applied to every row:
- compact the row to the left by removing empty space
- replace consecutive equal integers with a single integer equal to their sum
"""
# i -- row index
# j -- column index
for i in range(self.n):
# We need to keep track of the number eliminated elements to avoid getting stuck in a loop.
num_eliminated_elements = 0
# Iterate over the i-th row to compact the row by eliminating null entries.
j = 0
while j < self.n - num_eliminated_elements - 1:
if self.table[i, j] == 0:
# Compact the array by "eliminating" self.table[i, j]. The concatenate function is used for the sake
# of efficiency.
self.table[i, j:] = np.concatenate((self.table[i, j + 1:], np.zeros(1)))
num_eliminated_elements += 1
else:
j += 1
# Iterate over the i-th row again to sum up consecutive equal entries.
j = 0
while j < self.n - num_eliminated_elements - 1:
if self.table[i, j] == self.table[i, j + 1]:
self.table[i, j + 1] = 2*self.table[i, j + 1]
self.table[i, j:] = np.concatenate((self.table[i, j + 1:], np.zeros(1)))
num_eliminated_elements += 1
else:
j += 1
def shift_right(self):
"""Shift the table right. | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
def shift_right(self):
"""Shift the table right.
The same algorithm is applied to every row:
- compact the row to the right by removing empty space
- replace consecutive equal integers with a single integer equal to their sum
"""
# i -- row index
# j -- column index
for i in range(self.n):
# We need to keep track of the number eliminated elements to avoid getting stuck in a loop.
num_eliminated_elements = 0
# Iterate through the i-th row in reverse order to compact the row by eliminating null entries.
j = self.n - 1
while j > num_eliminated_elements:
if self.table[i, j] == 0:
# Compact the array by "eliminating" self.table[i, j]. The concatenate function is used for the sake
# of efficiency.
self.table[i, :j + 1] = np.concatenate((np.zeros(1), self.table[i, :j]))
num_eliminated_elements += 1
else:
j -= 1
# Iterate over the i-th row again to sum up consecutive equal entries.
j = self.n - 1
while j > num_eliminated_elements:
if self.table[i, j] == self.table[i, j - 1]:
self.table[i, j - 1] = 2 * self.table[i, j - 1]
self.table[i, :j + 1] = np.concatenate((np.zeros(1), self.table[i, :j]))
num_eliminated_elements += 1
else:
j -= 1
def shift_up(self):
"""Shift the table up. | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
def shift_up(self):
"""Shift the table up.
The same algorithm is applied to every column:
- compact the column above by removing empty space
- replace consecutive equal integers with a single integer equal to their sum
"""
# i -- column index
# j -- row index
for i in range(self.n):
# We need to keep track of the number eliminated elements to avoid getting stuck in a loop.
num_eliminated_elements = 0
# Iterate through the i-th column in reverse order to compact the row by eliminating null entries.
j = 0
while j < self.n - num_eliminated_elements - 1:
if self.table[j, i] == 0:
# Compact the array by "eliminating" self.table[i, j]. The concatenate function is used for the sake
# of efficiency.
self.table[j:, i] = np.concatenate((self.table[j + 1:, i], np.zeros(1)))
num_eliminated_elements += 1
else:
j += 1
# Iterate over the i-th column again to sum up consecutive equal entries.
j = 0
while j < self.n - num_eliminated_elements - 1:
if self.table[j, i] == self.table[j + 1, i]:
self.table[j + 1, i] = 2 * self.table[j + 1, i]
self.table[j:, i] = np.concatenate((self.table[j + 1:, i], np.zeros(1)))
num_eliminated_elements += 1
else:
j += 1
def shift_down(self):
"""Shift the table down. | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
def shift_down(self):
"""Shift the table down.
The same algorithm is applied to every column:
- compact the column below by removing empty space
- replace consecutive equal integers with a single integer equal to their sum
"""
# i -- column index
# j -- row index
for i in range(self.n):
# We need to keep track of the number eliminated elements to avoid getting stuck in a loop.
num_eliminated_elements = 0
# Iterate through the i-th column in reverse order to compact the row by eliminating null entries.
j = self.n - 1
while j > num_eliminated_elements:
if self.table[j, i] == 0:
# Compact the array by "eliminating" self.table[i, j]. The concatenate function is used for the sake
# of efficiency.
self.table[:j + 1, i] = np.concatenate((np.zeros(1), self.table[:j, i]))
num_eliminated_elements += 1
else:
j -= 1
# Iterate over the i-th column again to sum up consecutive equal entries.
j = self.n - 1
while j > num_eliminated_elements:
if self.table[j, i] == self.table[j - 1, i]:
self.table[j - 1, i] = 2 * self.table[j - 1, i]
self.table[:j + 1, i] = np.concatenate((np.zeros(1), self.table[:j, i]))
num_eliminated_elements += 1
else:
j -= 1 | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
def update_status(self):
"""Check whether the game has been won or lost and update the self.status instance variable if necessary."""
# If there is at least one element in self.table >= self.winning_number, update the game status to WON.
if np.any(self.table >= self.winning_number):
self.status = Status.WON
return
# If any entry of the table is null, the game is certainly not lost. Since at this point we know that the game
# is not lost, any subsequent check becomes unnecessary.
if np.any(self.table == 0):
return
# At this point, we know that the game is not won and that no entry of self.table is null. Check if the player
# can make any legal move, i.e. if there are two consecutive equal elements of self.table along either axis.
# If this is the case, no further check is needed and we can return. If the player can make no legal move,
# the game is lost.
for i in range(self.n):
for j in range(self.n):
# The indexing may fail due to out of bounds errors and thus a try block is required. If the indexing
# fail, just try a different pair of indeces.
try:
if self.table[i,j] == self.table[i+1,j]:
return
except:
pass
try:
if self.table[i,j] == self.table[i,j+1]:
return
except:
pass
self.status = Status.LOST | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
def display(self):
"""Display the game table in a legible format."""
# We use the array_str numpy method to convert the table to a string, and then we use a regular expression to
# remove the brackets. The first bracket needs to be replaced by a space to preserve indentation.
# A blank line is printed before and after the table.
print()
print(sub("[\[\]]", "", " " + np.array_str(self.table)))
print()
def insert_random_2(self):
"""Replace a random null entry of self.table with the number 2. Nothing is done if there is no null entry."""
if np.any(self.table == 0):
# Select random indices i,j until self.table[i, j] == 0. Then set self.table[i, j] = 2.
i = random.randrange(self.n)
j = random.randrange(self.n)
while self.table[i, j] != 0:
i = random.randrange(self.n)
j = random.randrange(self.n)
self.table[i, j] = 2
The following aspects of the code concern me the most:
The four methods that shift the numbers on the table are all fairly similar and feel quite repetitive. Nevertheless, any other solution I can come up with would make the code much more complicated and difficult to understand. Is this amount of repetition normal in professional code?
I'm not 100% sure if making main.py handle the game loop is a good idea. On one hand, the game loop feels like part of the game logic, and thus I think should be in two048.py. On the other hand, I would like the Game class to be quite generic. For instance, I wouldn't mind reusing it as is to implement a GUI version of the game in the future, and the game loop wood look very different there.
This is the first Python project I have taken seriously enough to document everything properly. How did I do? Are the docstrings and comments explicative enough? Is my code understandable? | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
Any feedback and advice is welcome, regardless of how harsh. Thanks everyone and have nice day.
Answer: Yay! Modules have docstrings, excellent. And same for classes.
Recommend that you routinely include .idea/ in .gitignore,
so files peculiar to certain IDE version won't leak out
into the public repo.
wildcard import
Don't do it.
from two048 import *
Prefer:
from two048 import Game, Status
When writing source code we always want to support Local Analysis.
We want it to be easy for the reader to understand all the pieces in motion.
The * star is opaque; the reader would have to pause,
go analyze that entire source file, then return here.
Be kind, list the symbols explicitly, it's a good habit.
constructor
I like the Game ctor, including the call to randomly insert a "2".
There's a line in the docstring which just says "self" and doesn't
make much sense. Simply elide it.
There's two occurrences of the "integer representing" phrase.
They make sense, but often such qualifiers will be redundant
with the signature, and it's best to say a thing just once.
I would prefer to elide both phrases, and use type annotation,
so mypy can read it, too.
def __init__(self, n: int, winning_number: int):
insert_random_2
This randomized algorithm does work -- eventually it will
stumble upon that last empty square.
But late in the game it takes much longer than necessary to do so.
Better that you not keep retrying a non-empty cell.
Scan the n ** 2 cells, emitting (i, j) coordinates for any zeros found.
Now pick a random coordinate from that list, and set the cell to 2.
display
The comments mostly describe the "how", rather than the "why", and should be elided.
OTOH this comment is insightful and should be preserved:
# The first bracket needs to be replaced by a space to preserve indentation. | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
Consider using import re rather than from re import sub,
so the re.sub( ... ) call will more clearly be about regular expressions.
update_status
Please
lint
your code every now and again.
We see this bit of lint advice:
E722 Do not use bare `except`
Never write except:, as it catches "too many" exceptions,
including the one corresponding to CTRL-C.
Prefer except Exception:.
Or something more narrowly focused.
Here, we care about except IndexError:
user prompt
elif c == "a":
game.shift_left()
else:
continue
I anticipated that the game would offer a brief line of instructions
before starting its loop.
Or maybe that's not needed, since repeat players already know what to do.
But at the continue, to silently taunt the player seems cruel.
This is the perfect opportunity to remind them that the w a s d keys
control game play.
questions
The four methods that shift the numbers on the table are all fairly similar and feel quite repetitive. ... Is this amount of repetition normal in professional code? | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
No. (But sometimes yes, at least in a first draft.)
The four shift_DIRECTION() methods work and are a good first step.
You could certainly stop here.
There are several refactoring avenues for improvement.
If you begin following my suggestions and then lose interest,
that's fine, you can stop at any time and will still have working code.
I will focus on shift_up just because it's the first one called (for w key).
You have a working shift_up, good. Now write a
test
named test_shift_up, so it shows Green bar.
Return to shift_up, look at those loops,
and notice that it's doing more than one thing.
Break out helpers that adhere to the
single responsibility principle.
Writing the test for a helper is usually simpler than for the bigger function.
Verify that you still see a Green bar.
Now visit shift_down.
How could we delete much of this code?
Could we define a dy delta y, with value +1 or -1,
which could be passed in for the helpers to use?
Use copy-n-paste (this is normal for tests, which are dirt simple)
to produce a test_shift_down method.
Verify that you still see a Green bar.
Now let's think about the remaining shift_left and shift_right.
Recall that numpy treats rows as axis 0 and columns as axis 1.
Is there a small integer we could pass in to the helpers
that would turn the existing column operations into row operations?
Verify that you still see a Green bar.
There may be a detail of worrying about IndexError at edge of square.
One approach worth considering is to embed the game of side N
in the center of an N+2 square, with sentinel values on the edges.
Now there's no need to probe too near the edge.
Yes, making main.py handle the game loop is a good idea.
The only thing I would change is to bury the existing
code within def main():, and then add the usual main guard at end:
if __name__ == "__main__":
main() | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
python, game, numpy
We usually want just class + function definitions in a source file,
for the most part. Nothing with side effects, such as print().
That lets other modules, including unit tests, silently import
those definitions. The main guard handles the case where we
actually want to run the script, rather than import it.
Again, following that convention is a good habit to get into.
Are the docstrings and comments [appropriate]?
The Game class docstring is brilliant.
I tend to like most of your comments.
Some of them can be a little on the obvious or verbose side.
Focus on explaining the "why", since the code explains the "how".
When you're about to write an explanation in the middle of a function,
consider whether introducing a well named helper, maybe
def sum_up_consecutive_equal_entries():, would obviate
the need for a comment.
This codebase achieves its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45370,
"lm_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, game, numpy",
"url": null
} |
c, file-system, posix, portability, c89
Title: Portable old-school filesystem tool
Question: I recently made a tool called mkfh to create a FHS compliant filesystem structure.
I aimed to make it as portable as possible, so I wrote it in C89 and also tried to catch the vibe of old-school tools!
Did I achieve that? Is it really that portable? Anything I could improve?
It consists of 2 files, mkfh.c and usr.c, where the later defines umkdir and utouch to create a directory and file respectively. As these could potentially be the least portable, I put them in a separate file so someone porting it can easily modify the source code.
Note that usr.c is inherently not very portable and takes some liberties.
*portable as in "works on very old and very new *nix systems", not potentially windows NT and such.
mkfh.c:
/* Source: MKFH, License: MIT */
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
#endif
#ifndef EXIT_FAILURE
# define EXIT_FAILURE 1
#endif
#define OPTIONAL 1
#define REQUIRED 0
#define USR_SUCCESS 1
#define USR_FAIL 0
#define SEPERATOR "/"
/* user functions */
extern int umkdir(const char*);
extern int utouch(const char*);
/* options */
int ask_optional = 0; /* 0 ask ; 1 no ; 2 yes */
int silent = 0;
int verbose = 0;
int nouser = 0;
int quiterr = 0;
char* progname = 0;
char* root = 0;
/* NOTE: old C compilers have global struct
member mangling, so added a prefix */
struct dir {
char* dir_idf;
struct dir* dir_sub;
int dir_opt;
};
int usage(void);
int help(void);
int ask(char*);
int vout(char*);
int trav(struct dir*, char*);
struct dir tree(void);
int main(int argc, char** argv) {
struct dir tr;
char* options = 0;
progname = *argv;
if(argc == 2) root = argv[1];
else if(argc == 3) options = argv[1],
root = argv[2];
else usage(); | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
if(!options && ( !strcmp(root, "-h") || !strcmp(root, "-u") ))
options = root;
if(options != 0)
while(*options)
switch(*options++) {
case 'a': ask_optional = 1;
break;
case 'A': ask_optional = 2;
break;
case 'h': help();
break;
case 'q': quiterr = !quiterr;
break;
case 's': silent = !silent;
break;
case 'u': usage();
break;
case 'U': nouser = !nouser;
break;
case 'v': verbose = !verbose;
break;
case '-':
break;
default:
fprintf(stderr, "Unknown option %c\n",
*--options);
exit(EXIT_FAILURE);
}
tr = tree();
trav(&tr, "");
/* tree freeing itself upon exit */
return EXIT_SUCCESS;
}
int help(void) {
fprintf(stderr,
"%s (make filesystem hierarchy)\n"
"LabRicecat (License: MIT) (FHS: 3.0)\n\n"
"Usage: %s [-aAhsvuU] ROOT\n"
"Creates a file hierarchy at ROOT\n\n"
"Options:\n"
" a : NO to all optionals\n"
" A : YES to all optionals\n"
" q : dont quit on errors\n"
" h : this\n"
" u : show usage\n"
" U : dont execute user functions\n"
" v : verbose output\n"
" - : nothing\n"
, progname, progname);
exit(EXIT_SUCCESS);
}
int usage(void) {
fprintf(stderr, "Usage: %s [-aAhqsvuU] ROOT\n", progname);
exit(EXIT_FAILURE);
}
/* gets one char and eats the rest */
int cgetc(void) {
int c, r;
c = r = getchar();
while(c != '\n' && c != EOF)
c = getchar();
return r;
} | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
return r;
}
int acc(char c) {
return c == 'y'
|| c == 'Y';
}
int ask(char* c) {
if(ask_optional == 1) return USR_FAIL;
if(ask_optional == 2) return USR_SUCCESS;
fprintf(stderr,"Create %s [y/N]:",c);
return acc(cgetc());
}
int vout(char* c) {
if(verbose)
fputs(c, stdout);
return verbose;
}
struct dir newdir(char* name, int opt, struct dir sub[]) {
struct dir d;
d.dir_idf = name;
d.dir_sub = sub;
d.dir_opt = opt;
return d;
}
struct dir* dirlst(int vlz, ...) {
struct dir* ds;
int i;
va_list vl;
ds = malloc(sizeof(struct dir) * (vlz + 1));
va_start(vl, vlz);
for(i = 0; i < vlz; ++i)
ds[i] = va_arg(vl,struct dir);
ds[vlz] = newdir(NULL, REQUIRED, NULL);
va_end(vl);
return ds;
}
char* strsum(char* s1, char* s2) {
int sz, i;
char* r;
sz = strlen(s1) + strlen(s2);
r = malloc(sz + 1);
r[sz] = 0;
for(i = 0; i < sz; ++i)
r[i] = *s1 ? *(s1)++ : *(s2++);
return r;
}
/* joins directories */
char* djoin(char* parent, char* child) {
char* r, *c, *sp;
sp = SEPERATOR;
if(!strcmp(parent, SEPERATOR) || !strcmp(parent,""))
sp = "";
c = strsum(parent, sp);
r = strsum(c, child);
free(c);
return r;
}
/* traverses the tree */
int trav(struct dir* d, char* parent) {
char* nm, *c;
nm = djoin(parent, d->dir_idf);
if(!d || ( d->dir_opt && ask(nm) )) {
free(nm);
return EXIT_FAILURE;
}
vout(nm);
vout("\n");
while(d->dir_sub && d->dir_sub->dir_idf) {
c = djoin(nm, d->dir_sub->dir_idf);
if(!nouser && umkdir(c) == USR_FAIL) {
free(c);
fputs("umkdir() failed", stderr);
if(!quiterr)
break;
}
else
free(c);
trav(d->dir_sub, nm);
++d->dir_sub;
}
free(nm);
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
struct dir tree(void) {
return
newdir(root, REQUIRED, dirlst(14,
newdir("bin", REQUIRED, NULL),
newdir("boot", REQUIRED, NULL),
newdir("dev", REQUIRED, NULL),
newdir("etc", REQUIRED,
dirlst(4,
newdir("opt", REQUIRED, NULL),
newdir("X11", OPTIONAL, NULL),
newdir("sgml", OPTIONAL, NULL),
newdir("xml", OPTIONAL, NULL)
)),
newdir("lib", REQUIRED,
dirlst(1,
newdir("modules", OPTIONAL, NULL)
)),
newdir("media", REQUIRED,
dirlst(4,
newdir("floppy", OPTIONAL, NULL),
newdir("cdrom", OPTIONAL, NULL),
newdir("cdrecorder", OPTIONAL, NULL),
newdir("zip", OPTIONAL, NULL)
)),
newdir("mnt", REQUIRED, NULL),
newdir("opt", REQUIRED, NULL),
newdir("run", REQUIRED, NULL),
newdir("sbin", REQUIRED, NULL),
newdir("srv", REQUIRED, NULL),
newdir("tmp", REQUIRED, NULL),
newdir("usr", REQUIRED,
dirlst(10,
newdir("bin", REQUIRED, NULL),
newdir("lib", REQUIRED, NULL),
newdir("local", REQUIRED,
dirlst(10,
newdir("bin", REQUIRED, NULL),
newdir("etc", REQUIRED, NULL),
newdir("games", REQUIRED, NULL),
newdir("include", REQUIRED, NULL),
newdir("lib", REQUIRED, NULL),
newdir("man", REQUIRED, NULL),
newdir("sbin", REQUIRED, NULL),
newdir("share", REQUIRED,
dirlst(15, | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
newdir("share", REQUIRED,
dirlst(15,
newdir("man", REQUIRED,
dirlst(8,
newdir("man1", OPTIONAL, NULL),
newdir("man2", OPTIONAL, NULL),
newdir("man3", OPTIONAL, NULL),
newdir("man4", OPTIONAL, NULL),
newdir("man5", OPTIONAL, NULL),
newdir("man6", OPTIONAL, NULL),
newdir("man7", OPTIONAL, NULL),
newdir("man8", OPTIONAL, NULL)
)),
newdir("misc", REQUIRED, NULL),
newdir("color", OPTIONAL,
dirlst(1,
newdir("icc", OPTIONAL, NULL)
)),
newdir("dict", OPTIONAL, NULL),
newdir("doc", OPTIONAL, NULL),
newdir("games", OPTIONAL, NULL),
newdir("info", OPTIONAL, NULL),
newdir("locale", OPTIONAL, NULL),
newdir("nls", OPTIONAL, NULL),
newdir("ppd", OPTIONAL, NULL),
newdir("sgml", OPTIONAL,
dirlst(4,
newdir("docbook", OPTIONAL, NULL),
newdir("tei", OPTIONAL, NULL),
newdir("html", OPTIONAL, NULL), | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
newdir("html", OPTIONAL, NULL),
newdir("mathml", OPTIONAL, NULL)
)),
newdir("terminfo", OPTIONAL, NULL),
newdir("tmac", OPTIONAL, NULL),
newdir("xml", OPTIONAL,
dirlst(3,
newdir("docbook", OPTIONAL, NULL),
newdir("xhtml", OPTIONAL, NULL),
newdir("mathml", OPTIONAL, NULL)
)),
newdir("zoneinfo", OPTIONAL, NULL)
)),
newdir("src", REQUIRED, NULL),
newdir("lib64", OPTIONAL, NULL)
)),
newdir("sbin", REQUIRED, NULL),
newdir("share", REQUIRED,
dirlst(15,
newdir("man", REQUIRED,
dirlst(8,
newdir("man1", OPTIONAL, NULL),
newdir("man2", OPTIONAL, NULL),
newdir("man3", OPTIONAL, NULL),
newdir("man4", OPTIONAL, NULL),
newdir("man5", OPTIONAL, NULL),
newdir("man6", OPTIONAL, NULL),
newdir("man7", OPTIONAL, NULL),
newdir("man8", OPTIONAL, NULL)
)),
newdir("misc", REQUIRED, NULL),
newdir("color", OPTIONAL,
dirlst(1, | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
newdir("color", OPTIONAL,
dirlst(1,
newdir("icc", OPTIONAL, NULL)
)),
newdir("dict", OPTIONAL, NULL),
newdir("doc", OPTIONAL, NULL),
newdir("games", OPTIONAL, NULL),
newdir("info", OPTIONAL, NULL),
newdir("locale", OPTIONAL, NULL),
newdir("nls", OPTIONAL, NULL),
newdir("ppd", OPTIONAL, NULL),
newdir("sgml", OPTIONAL,
dirlst(4,
newdir("docbook", OPTIONAL, NULL),
newdir("tei", OPTIONAL, NULL),
newdir("html", OPTIONAL, NULL),
newdir("mathml", OPTIONAL, NULL)
)),
newdir("terminfo", OPTIONAL, NULL),
newdir("tmac", OPTIONAL, NULL),
newdir("xml", OPTIONAL,
dirlst(3,
newdir("docbook", OPTIONAL, NULL),
newdir("xhtml", OPTIONAL, NULL),
newdir("mathml", OPTIONAL, NULL)
)),
newdir("zoneinfo", OPTIONAL, NULL)
)),
newdir("games", OPTIONAL, NULL),
newdir("include", OPTIONAL,
dirlst(1,
newdir("bsd", OPTIONAL, NULL)
)),
newdir("libexec", OPTIONAL, NULL),
newdir("lib64", OPTIONAL, NULL),
newdir("src", OPTIONAL, NULL)
)), | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
newdir("src", OPTIONAL, NULL)
)),
newdir("var", REQUIRED,
dirlst(14,
newdir("cache", REQUIRED,
dirlst(3,
newdir("fonts", OPTIONAL, NULL),
newdir("man", OPTIONAL, NULL),
newdir("www", OPTIONAL, NULL)
)),
newdir("lib", REQUIRED,
dirlst(4,
newdir("misc", REQUIRED, NULL),
newdir("color", OPTIONAL, NULL),
newdir("hwclock", OPTIONAL, NULL),
newdir("xdm", OPTIONAL, NULL)
)),
newdir("local", REQUIRED, NULL),
newdir("lock", REQUIRED, NULL),
newdir("log", REQUIRED, NULL),
newdir("opt", REQUIRED, NULL),
newdir("run", REQUIRED, NULL),
newdir("spool", REQUIRED,
dirlst(5,
newdir("lpd", OPTIONAL,
dirlst(1,
newdir("printer", OPTIONAL, NULL)
)),
newdir("mqueue", OPTIONAL, NULL),
newdir("news", OPTIONAL, NULL),
newdir("rwho", OPTIONAL, NULL),
newdir("uucp", OPTIONAL, NULL)
)),
newdir("tmp", REQUIRED, NULL),
newdir("account", OPTIONAL, NULL),
newdir("crash", OPTIONAL, NULL),
newdir("games", OPTIONAL, NULL),
newdir("mail", OPTIONAL, NULL),
newdir("yp", OPTIONAL, NULL)
)),
newdir("home", OPTIONAL, NULL),
newdir("root", OPTIONAL, NULL), | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
newdir("home", OPTIONAL, NULL),
newdir("root", OPTIONAL, NULL),
newdir("lib64", OPTIONAL, NULL)
));
} | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
usr.c
#include <sys/stat.h>
#include <stdio.h>
#define USR_SUCCESS 1
#define USR_FAIL 0
/* define user functions here */
/* create a directory at relative path PATH */
int umkdir(const char* path) {
struct stat st = {0};
if(stat(path, &st) == -1)
return mkdir(path, 0700) == 0 ? USR_SUCCESS : USR_FAIL;
return USR_SUCCESS;
}
/* create a file at relative path PATH */
/* currently unused */
int utouch(const char* path) {
FILE* f;
f = fopen(path, "r");
if(!f)
return USR_FAIL;
fclose(f);
return USR_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
Answer: EXIT_SUCCESS and EXIT_FAILURE
The language spec promises that EXIT_SUCCESS and EXIT_FAILURE are defined by stdlib.h. Having included that header, you do not need to check whether they are defined. Moreover, the point of these is that the specific values (other than 0) that convey success and failure to the exit() function are not necessarily portable, so if you could not rely on these macros in fact being defined, then defining them yourself would conflict with your goal of maximum portability.
Define headers
Your mkfh.c and usr.c both declare some of the same functions and define some of the same macros, each independent of the other. The definitions of these macros and (forward) declarations of these functions should go in a header file, which both source files #include.
"global struct member wrangling"
I guess the comment about struct member wrangling refers to ancient versions of C in which the identifiers of struct members were not scoped to the struct definitions in which they appeared. This is the reason for some of the very old standard struct types having member names with distinctive prefixes. But you have chosen C89 for portability, and that can provide portability only for C implementations that in fact conform to C89 or, with some limitations, to one of its successors. There is nothing that could be characterized as struct member wrangling in C89.
It's not wrong, per se, to prefix the names of your structure members, but it's superfluous. And if it means you limit yourself to fewer characters for expressing meaningful member names, then it is counterproductive.
Null pointer constants
It is valid and portable to use 0 as a null pointer constant, but you shouldn't. Use the macro NULL when a null pointer constant is what you mean. This is much clearer.
Compound statements (blocks) | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
Compound statements (blocks)
As a matter of good code style, use compound statements (brace-enclosed code blocks) in conjunction with conditional and looping statements, even when they contain only one simple statement. Especially do not use the comma operator to squeeze what would ordinarily be two separate expression statements into a single one in order to avoid braces.
For example, this ... | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
if(argc == 2) root = argv[1];
else if(argc == 3) options = argv[1],
root = argv[2];
else usage();
should be
if (argc == 2) {
root = argv[1];
} else if (argc == 3) {
options = argv[1];
root = argv[2];
} else {
usage();
}
Option processing
It is conventional to recognize options by the leading '-' character, but your program recognizes them only positionally. Moreover, it requires all the options to be presented in the same argument, which is not normal.
Variadic functions
You appear to have implemented variadic function dirlst() correctly (congratulations!), and I even think I understand why you chose that implementation approach. Too bad I hate what you did with it, but don't take that personally.
The target directory tree structure would be much better expressed as data instead of as code. You do get half a pass on this, though, for you need C99 compound literals for a clean way to express the structure as data, and those are not available because of your choice to limit yourself to C89. That doesn't mean you couldn't have structured it as data, though, only that the data would been messier.
Or reading the directory structure from a file would have been an option, too. That would make your program easier to customize. In fact, it would not be too big a step from there to it being a more general-purpose directory-tree-creation tool.
Miscellaneous | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c, file-system, posix, portability, c89
the correct spelling is "separator" (not "seperator")
function cgetc() would be more efficiently written in terms of the fgets() function.
the return value of function vout() is not actually computed by the function, and it is never used anyway. This function probably should not return anything.
for clarity and efficiency, function strsum() should be written in terms of strcpy(). Or maybe strcat(). Or even sprintf().
for clarity, function djoin() should probably be written in terms of one call to sprintf() instead of two to strsum(). | {
"domain": "codereview.stackexchange",
"id": 45371,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, file-system, posix, portability, c89",
"url": null
} |
c++, error-handling, c++20, exception
Title: Wrap a noexcept C++ library method with a method throwing exceptions with usable explanatory strings to stay DRY
Question: In our apps we're using a shared inhouse library which provides filesystem functions. All the functions are noexcept.
In several apps i found that similar or identical error return translations are implemented again and again [which are then reported on a console or some windows app] and was wondering
if it might be a good design to provide default error strings which are transported with exceptions as part of a additional function in the library
or if each of these functions should be wrapped in the respective application because the error strings might need application specific context (in this case they don't in their current implementation)
or if i should stick with the existing function and reimplement the translation on every invocation (which is how it's implemented currently)
or generally what's the best way to approach this.
The code is windows only and not planned to be ported to other platforms.
The existing functions in the library can't be changed but it's possible to add new functions.
Here's the code: (Live Demo)
The new function createDirectory_CanThrow is part of the library and provides default translations of the error codes.
#include <cassert>
#include <iostream>
#include <string_view>
#include <windows.h>
namespace myorg::filesystem {
// cannot change this enum
enum class CreateDirectoryResult {
Ok = 0,
See_GetLastError, // windows specific; use ::GetLastError() to get the reason
CollidesWithAFileHavingTheSameName,
};
// cannot change this method
CreateDirectoryResult createDirectory(std::string_view directory) noexcept {
// ...
return CreateDirectoryResult::Ok;
} | {
"domain": "codereview.stackexchange",
"id": 45372,
"lm_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++, error-handling, c++20, exception",
"url": null
} |
c++, error-handling, c++20, exception
// is this good design?
// reimplement it per app?
// repeat it on every invocation and don't create a wrapper?
void createDirectory_CanThrow(std::string_view directory) {
switch (createDirectory(directory))
{
default:
assert(false);
[[fallthrough]];
case CreateDirectoryResult::Ok:
break;
case CreateDirectoryResult::CollidesWithAFileHavingTheSameName:
throw std::runtime_error("Cannot create the directory because its name collides with a file with the same name.");
case CreateDirectoryResult::See_GetLastError: {
LPVOID buf;
::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, (LPCVOID)::GetLastError(), 0, 0, (LPSTR)&buf, 0, NULL);
std::string msg = (char const*)buf;
::LocalFree(buf);
throw std::runtime_error(msg);
}
}
}
}
int main()
{
try
{
myorg::filesystem::createDirectory_CanThrow("C:\\test");
}
catch (std::runtime_error const& e)
{
std::cout << "Error creating directory: " << e.what() << "\n";
}
}
Answer: Alternatives to exceptions
There are various ways to approach it. You don't necessarily need exceptions to ensure your code stays DRY. For example, if you just want to get an error message to print, you could just write something that takes a CreateDirectoryResult as input and returns a std::string. Let's call it what(), it's not a great name but it's to show the equivalence with your exception-handling code:
std::string what(CreateDirectoryResult result) {
using enum CreateDirectoryResult;
switch(result) {
…
case CollidesWithAFileHavingTheSameName:
return "Cannot create the directory because its name collides with a file with the same name.";
…
}
} | {
"domain": "codereview.stackexchange",
"id": 45372,
"lm_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++, error-handling, c++20, exception",
"url": null
} |
c++, error-handling, c++20, exception
Then in main() you can write:
auto result = myorg::filesystem::createDirectory("C:\\test");
if (result != CreateDirectoryResult::Ok) {
std::cerr << "Error creating directory: " << what(result) << "\n";
}
Or maybe you can add a check() function that does the printing, and returns a bool so you can also easily use it to decide how to continue after an error:
[[nodiscard]] bool check(CreateDirectoryResult result) {
if (result != CreateDirectoryResult::Ok) {
std::cerr << "Error creating directory: " << what(result) << "\n";
return false;
} else {
return true;
}
}
The [[nodiscard]] attribute will ensure the compiler warns if you ever call check() but don't look at its return value. So then you can write:
auto result = myorg::filesystem::createDirectory("C:\\test");
if (!check(result)) {
return EXIT_FAILURE;
}
The advantage of exceptions of course is that errors won't be ignored if you forget to check for them, and you can also do multiple actions in a single try-catch block without having to check the result of each individual action.
Make it easy to wrap lots of functions
Your createDirectory_CanThrow() has a lot of code in it. What if you want to wrap another function that also returns a CreateDirectoryResult? The what() function I wrote might be helpful then. You can also make a function like check() that throws the exception for you:
void check(CreateDirectoryResult result) {
if (result != CreateDirectoryResult::Ok) {
throw std::runtime_error("Error creating directory: " + what(result) + "\n");
}
}
So then you can write:
void createDirectory_CanThrow(std::string_view directory) {
check(createDirectory(directory));
}
You can also consider creating a template that can wrap any function:
template<auto Function>
class MakeThrow {
public:
template<typename... Args>
void operator()(Args&&... args) const {
check(Function(std::forward<Args>(args)...));
}
}; | {
"domain": "codereview.stackexchange",
"id": 45372,
"lm_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++, error-handling, c++20, exception",
"url": null
} |
c++, error-handling, c++20, exception
This is a bit advanced, but it allows you to write:
auto createDirectory_CanThrow = MakeThrow<createDirectory>{};
It still needs you to write overloads for check() that handle all the possible return types that your non-throwing functions can return, but creating the wrapper function is now trivial.
Alternatively, you can create a preprocessor macro that creates wrapped functions. You can make it so you only have to write:
WRAP(createDirectory)
To have it define the createDirectory_CanThrow function that you want. Personally I would try to avoid macros where possible, but here it is one of the DRYest solutions if you have to wrap many functions. Note that the macro doesn't need to do much, it can still rely on helper functions like what(), check(), and the MakeThrow template, for example:
#define WRAP(function) auto function ## _CanThrow = MakeThrow<function>{}; | {
"domain": "codereview.stackexchange",
"id": 45372,
"lm_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++, error-handling, c++20, exception",
"url": null
} |
java, performance, hash-map
Title: Map constructor utility class in Java 8
Question: In a Java 8 project, I'm using several maps, many of which contain static or default content. In Java 9 and newer, there's the convenient Map.of() method and I want something similar convenient. So, I came up with the following implementation:
public class CollectionUtils {
private static final String INCOMPATIBLE_TYPE_MSG_TMP = "The %sth argument is not compatible with the %s type %s"; | {
"domain": "codereview.stackexchange",
"id": 45373,
"lm_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, performance, hash-map",
"url": null
} |
java, performance, hash-map
/**
* Shortcut to create a map
* @param keyClass type class of keys
* @param valueClass type class of values
* @param keysAndValues array with keys and values (even indices: keys, odd indices: values)
* @param <KeyT> type of keys
* @param <ValueT> type of values
* @return unmodifiable map
*/
public static <KeyT, ValueT> Map<KeyT, ValueT> map(
Class<KeyT> keyClass,
Class<ValueT> valueClass,
Object... keysAndValues) {
if (keysAndValues.length % 2 != 0) {
throw new IllegalArgumentException("The number of keys and values must be even");
}
Map<KeyT, ValueT> outputMap = new HashMap<>();
KeyT key = null;
for (int i = 0; i < keysAndValues.length; i++) {
Object keyOrValue = keysAndValues[i];
if (i % 2 == 0) {
if (!keyClass.isInstance(keyOrValue)) {
String message = String.format(INCOMPATIBLE_TYPE_MSG_TMP, i, "key", keyClass.getName());
throw new IllegalArgumentException(message);
}
key = keyClass.cast(keyOrValue);
} else {
ValueT value;
try {
value = valueClass.cast(keyOrValue);
} catch (ClassCastException e) {
String message = String.format(INCOMPATIBLE_TYPE_MSG_TMP, i, "value", valueClass.getName());
throw new IllegalArgumentException(message, e);
}
outputMap.put(key, value);
}
}
return Collections.unmodifiableMap(outputMap);
}
} | {
"domain": "codereview.stackexchange",
"id": 45373,
"lm_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, performance, hash-map",
"url": null
} |
java, performance, hash-map
I did quite a lot of tinkering to get this implementation and I believe there's still room for improvement. For example, the first two arguments must be the key and value classes to get the types correctly, which Java 9's Map.of() doesn't require. Besides implementational improvements, I'm also open to comments regarding efficiency, security and anything sub-optimal with this implementation.
Answer: I don't see why you sould want to throw an IllegalArgumentException when the error case is actually a literal ClassCastException. This is actually counterproductive as you are hiding the fact that the error was caused by class incompatibility and replacing it with a generic illegal argument exception. For example, the java.util.List.remove(Object) throws a ClassCastException if you feed it the wrong type of objects.
Since you know that the length of the array is divisible by two, you can pick both key and value from it at the same time without having to track the state the loop is in, and advance the loop counter by 2.
The loop becomes quite simple now:
Map<KeyT, ValueT> outputMap = new HashMap<>(keysAndValues.length / 2);
for (int i = 0; i < keysAndValues.length; i += 2) {
outputMap.put(
keyClass.cast(keysAndValues[i]),
valueClass.cast(keysAndValues[i + 1]));
}
Is your code actually a performance bottle neck? There is not much one can do to make converting an array to map much faster. Giving the HashMap it's initial size to perevent it from doing unnecessary rehashings is one thing. | {
"domain": "codereview.stackexchange",
"id": 45373,
"lm_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, performance, hash-map",
"url": null
} |
c++, performance, r, rcpp
Title: Acceleration of Hidden Markov Modell likelihood calculation in Rcpp
Question: I wrote the following code in Rcpp, i.e. it is C++ code that is compiled in R for making faster calculations. The code in Rcpp is intended to calculate in a recursive way the likelihood function for an Hidden Markov Model, the likelihood function in this case is Like_Fun_acoustic_FAST. First I provide the code in Rcpp
#include <RcppArmadilloExtensions/sample.h>
#include <omp.h>
#include <random>
#include <iostream>
#include <cmath>
#include <vector>
#include <numeric>
#include <algorithm>
#include <stdio.h>
#include <math.h>
#include<Rmath.h>
using namespace Rcpp;
// [[Rcpp::export]]
arma::vec log_sum_exp2_cpp_apply(arma::mat x){
int n = x.n_rows;
arma::vec res(n);
double M;
for(int j=0; j<n; ++j){
M = max(x.row(j));
res[j] = M + log(sum(exp(x.row(j) - M)));
}
return res;
}
// [[Rcpp::export]]
arma::mat SummarizeLastCol(arma::cube Q){
int n = size(Q)[0];
int k = size(Q)[2];
int t = size(Q)[1];
arma::mat cd(n,k);
for(int j=0; j<k; ++j){
cd.col(j) = Q.slice(j).tail_cols(1);
}
return cd;
}
void inplace_tri_mat_mult(arma::rowvec &x, arma::mat const &trimat){
arma::uword const n = trimat.n_cols;
for(unsigned j = n; j-- > 0;){
double tmp(0.);
for(unsigned i = 0; i <= j; ++i)
tmp += trimat.at(i, j) * x[i];
x[j] = tmp;
}
} | {
"domain": "codereview.stackexchange",
"id": 45374,
"lm_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, r, rcpp",
"url": null
} |
c++, performance, r, rcpp
// [[Rcpp::export]]
arma::vec dmvnrm_arma_mc(arma::mat const &x,
arma::rowvec const &mean,
arma::mat const &sigma,
bool const logd = false,
int const cores = 1) {
using arma::uword;
omp_set_num_threads(cores);
uword const n = x.n_rows,
xdim = x.n_cols;
arma::vec out(n);
arma::mat const rooti = arma::inv(trimatu(arma::chol(sigma)));
double const rootisum = arma::sum(log(rooti.diag())),
constants = -(double)xdim/2.0 * log2pi,
other_terms = rootisum + constants;
arma::rowvec z;
#pragma omp parallel for schedule(static) private(z)
for (uword i = 0; i < n; i++) {
z = (x.row(i) - mean);
inplace_tri_mat_mult(z, rooti);
out(i) = other_terms - 0.5 * arma::dot(z, z);
}
if (logd)
return out;
return exp(out);
}
// [[Rcpp::export]]
double Like_Fun_acoustic_FAST( int n, int TT, int k, List Data, arma::mat mu, arma::cube Sigma,
arma::vec pi, arma::mat PI, int num_feat){
arma::mat cb(n,2);
arma::cube q(n,TT,k);
arma::vec res(n);
//time point 1
for(int j=0; j<k; ++j){
q.slice(j).col(0) = dmvnrm_arma_mc(as<arma::mat>(Data[0]), mu.row(j),
Sigma.slice(j), true,4) + log(pi[j]);
}
// //late time points
for(int t=1; t<TT; ++t){
for(int j=0; j<k; ++j){
if(k>0){
q.slice(j).col(t) = q.slice(0).col(t-1) + log(PI(0,j));
for(int d=1; d<k; ++d){
cb.col(0) = q.slice(j).col(t);
cb.col(1) = q.slice(d).col(t-1)+log(PI(d,j));
(q.slice(j)).col(t) = log_sum_exp2_cpp_apply(cb);
}
q.slice(j).col(t) +=
dmvnrm_arma_mc(as<arma::mat>(Data[t]), mu.row(j),
Sigma.slice(j), true,4); | {
"domain": "codereview.stackexchange",
"id": 45374,
"lm_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, r, rcpp",
"url": null
} |
c++, performance, r, rcpp
}
if(k==1){
q.slice(j).submat(0,t,n-1,t) = q.slice(0).submat(0,t-1,n-1,t-1) + log(PI(0,j)) +
dmvnrm_arma_mc(as<arma::mat>(Data[t]), mu.submat(j,0,j,num_feat-1),
Sigma.slice(j), true,4);
}
}
}
if(k>1){
cb = SummarizeLastCol(q);
res = log_sum_exp2_cpp_apply(cb);
return accu(res);
}
if(k==1){
return accu(q.slice(0).submat(0,TT-1,n-1,TT-1));
}
} | {
"domain": "codereview.stackexchange",
"id": 45374,
"lm_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, r, rcpp",
"url": null
} |
c++, performance, r, rcpp
I tried to optimize all the functions shown by avoiding using any cumbersome functions, however, the time needed for the function Like_Fun_acoustic_FAST to run is still too much. The first function log_sum_exp2_cpp_apply takes as input a matrix and calculates the log sum for each row. The function SummarizeLastCol takes a cube and a creates a matrix whose columns are the last column for matrix component of the cube. The dmvnrm_arma_mc calculates the multivariate normal density based on parallelization.
The likelihood function Like_Fun_acoustic_FAST recursively integrates out the latent states of a hidden markov chain. It does that with the use of the cube q which stores K latent components corresponding to K latent states, and for each latent state we have a matrix of size n row and TT columns corresponding to observations and time respectively. In particular, we have a time series of TT points, and on each point we calculate the multivariate normal density conditional on all the possible latent states.
For the number of cores used for the parallelization I used the optimal number, based on which number of cores gives me the fastest calculations.
So, I try to find any possible way to make the algorithms faster, because in my eyes all functions are written in the most neat way in terms of time complexity.
I give inputs if someone wants to reproduce the example in R.
library(MASS)
library(extraDistr)
n_dim = 10
TT = 15
n_feat = 3
K = 3
m = matrix(NA,K,n_feat)
for(i in 1:K){
m[i,] = rnorm(n_feat,0,1)
}
Sigma = array(NA,c(n_feat,n_feat,K))
for(i in 1:K){
Sigma[,,i] = rwishart(3,diag(1,n_feat))
}
data = list()
for(i in 1:TT){
data[[i]] = mvrnorm(n_dim, m[1,], Sigma[,,1])
}
prob_pi = rdirichlet(1,rep(1,K))
prob_P = matrix(NA,K,K)
for(i in 1:K){
prob_P[i,] = rdirichlet(1,rep(1,K))
}
Like_Fun_acoustic_FAST( n_dim, TT, K, data, m, Sigma,
prob_pi,
prob_P, n_feat) | {
"domain": "codereview.stackexchange",
"id": 45374,
"lm_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, r, rcpp",
"url": null
} |
c++, performance, r, rcpp
Answer: I tried to look for performance issues, but unfortunately I can't, because your code has a major problem:
Naming things
Your code is very hard to read because of the inconsistent way you are naming things. Also, while you are apparently not afraid to use long names for certain things, in most cases you are unnecessarily abbreviating things.
Let's begin with Like_Fun_acoustic_FAST(). I also like fun! But I wouldn't have known it was a "likelihood function" if it wasn't for your description in the question. It's not mentioned anywhere in the code. But "likelihood" is just a value that you want to calculate, there is no "likelihood function" in the mathematical problem. Sure, you wrote a C++ function to calculate it, but why put Fun in this function's name? You didn't do that for the other functions. Why are Like and Fun capitalized, but not acoustic? Why is FAST in all caps? That makes it either look like it's an acronym, or that you are shouting.
Why did you add _FAST to the function name? Sure you want this to go fast, but typically you want all your functions to run fast. It might make sense to add this to the function if there is also a _SLOW, or perhaps an _ACCURATE if you have a trade-off between speed and accuracy. Otherwise, just leave it off.
What does acoustic mean here? Is there something like an "acoustic likelihood"? That doesn't sound very likely to me. Maybe the problem involves sound waves, but what exactly is it you want to calculate the likelihood of? If you are trying to detect the presence of some feature in a sound signal, and want to know the likelihood of it actually being there, then I would name this function calculate_likelihood_of_feature(), where feature is replaced by the actual name of the feature. | {
"domain": "codereview.stackexchange",
"id": 45374,
"lm_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, r, rcpp",
"url": null
} |
c++, performance, r, rcpp
Go over all the function names, make sure they use the same style of naming (I recommend using snake_case, as that is the most commonly used style for function and variable names in C++ code), and ensure the name clearly explains what it is doing.
Do the same for variable names: make sure they are consistent, and convey clearly what information they hold.
Some abbreviations are fine, but only if they are widely used ones, and are unambiguous in the context where they are used. For example, i, j and k are often used as loop indices, so that might be fine. However, compare:
for(int j=0; j<n; ++j){ | {
"domain": "codereview.stackexchange",
"id": 45374,
"lm_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, r, rcpp",
"url": null
} |
c++, performance, r, rcpp
With:
for (int row = 0; row < num_rows; ++row) {
Sure, it's a bit more typing, but now I instantly know what is being looped over, whereas with j and n I have to look elsewhere to see what is actually stored in those variables.
Another thing you can do is imagine your are talking with someone about your code, and having to pronounce your variable and function names. Will they understand you if you say "dmvnrm_arma_mc"? What about "pi" and "PI"? Won't they think you are talking about the constant \$\pi\$?
Performance
I don't even know what exactly this code is doing, so I can't tell whether your algorithm can be improved or not. There are a few things that I did notice that you might want to look at:
Do you really need double precision? Often you get a speedup of more than 2 by using float instead.
Avoid unnecessary allocations. dmvnrm_arma_mc() allocates a vector and a matrix each time it is called. Those will have exactly the same size. It might be better to ensure these are allocated once and then reused. | {
"domain": "codereview.stackexchange",
"id": 45374,
"lm_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, r, rcpp",
"url": null
} |
php, database, mysqli
Title: A PHP class for the common database operations?
Question: I'm a CS undergrad, so I don't have much experience. But while coding vanilla PHP projects, I found that I was repeating myself a lot with the CRUD operations. So overtime, I developed a single file called config.php that I use in all the projects where I use PHP as a backend (70% of the time). Basically, the workflow is like this: Get data, put it into an array, get the query, then call a function from config.php which will execute it for you without needing to call the database in the same file. My teammates all praised it for its simplicity. I worked with someone who didn't even know PHP and was able to get along because of the file.
That said, all these praises come from undergrads like myself. If someone can look at my file and give me constructive feedback I'd really appreciate it. I want to know if there are ways to improve it or if it's a really bad idea to do this from the get go.
<?php
class Connection
{
private $conn;
public function __construct()
{
$servername = "localhost";
$username = "root";
$password = "";
$database = "dloc";
$this->conn = new mysqli($servername, $username, $password, $database);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
}
public function getConnection()
{
return $this->conn;
}
public function closeConnection()
{
$this->conn->close();
}
public function executeSelectQuery($query, $params = array())
{
$stmt = $this->prepareStatement($query, $params);
try {
if (!$stmt) {
return array();
}
$stmt->execute();
$result = $stmt->get_result();
if (!$result) {
return array();
} | {
"domain": "codereview.stackexchange",
"id": 45375,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, database, mysqli",
"url": null
} |
php, database, mysqli
if (!$result) {
return array();
}
return $result->fetch_all(MYSQLI_ASSOC);
} finally {
$stmt->close();
}
}
public function executeWriteQuery($query, $params = array())
{
$stmt = $this->prepareStatement($query, $params);
try {
if (!$stmt) {
return false;
}
$result = $stmt->execute();
return $result;
} finally {
$stmt->close();
}
}
public function executeSelectOneRow($query, $params = array())
{
$stmt = $this->prepareStatement($query, $params);
try {
if (!$stmt) {
return null;
}
$stmt->execute();
$result = $stmt->get_result();
if (!$result || $result->num_rows == 0) {
return null;
}
return $result->fetch_assoc();
} finally {
$stmt->close();
}
}
public function executeMultipleWriteQueries(array $queries)
{
$this->conn->begin_transaction();
try {
foreach ($queries as $queryData) {
list($query, $params) = $queryData;
$stmt = $this->prepareStatement($query, $params);
if (!$stmt) {
$query = $queryData['query'];
$params = $queryData['params'];
$stmt = $this->prepareStatement($query, $params);
if(!$stmt){
throw new Exception($stmt->error);
}
}
$stmt->execute();
$stmt->close();
}
$this->conn->commit();
return true;
} catch (Exception $exception) {
error_log("Exception during executeMultipleWriteQueries: " . $exception->getMessage()); | {
"domain": "codereview.stackexchange",
"id": 45375,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, database, mysqli",
"url": null
} |
php, database, mysqli
$this->conn->rollback();
return false;
}
}
private function prepareStatement($query, $params)
{
$stmt = $this->conn->prepare($query);
if (!$stmt) {
return false;
}
if ($params) {
$types = $this->getBindTypes($params);
$stmt->bind_param($types, ...$params);
}
return $stmt;
}
private function getBindTypes($params)
{
$types = '';
foreach ($params as $param) {
if (is_int($param)) {
$types .= 'i'; // integer
} elseif (is_float($param)) {
$types .= 'd'; // double
} elseif (is_string($param)) {
$types .= 's'; // string
} else {
$types .= 'b'; // blob
}
}
return $types;
}
public function __destruct()
{
$this->conn->close();
}
}
?>
And usually I have repository files which will call instantiate this class i.e:
function getSheetById($sheetOneId) {
$query = "SELECT * FROM sheetone WHERE SheetOneId = ?";
$connection = new Connection();
return $connection->executeSelectOneRow($query, array($sheetOneId));
}
function insertSheet($sheetOneId, $material, $lengthAndWidth, $thickness, $quantity, $operator, $dateSent) {
$query = "INSERT INTO sheetone (SheetOneId, Material, LengthAndWidth, Thickness, Quantity, Operator, DateSent) VALUES (?, ?, ?, ?, ?, ?, ?)";
$params = array($sheetOneId, $material, $lengthAndWidth, $thickness, $quantity, $operator, $dateSent);
$connection = new Connection();
return $connection->executeWriteQuery($query, $params);
} | {
"domain": "codereview.stackexchange",
"id": 45375,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, database, mysqli",
"url": null
} |
php, database, mysqli
Answer: Yes of course it's OK to have such a file. However, your Connection class is hardly related to actual CRUD operations. It's more a DAO, a database abstraction object.
Speaking of the code you provided, it's not a bad code for an undergraduate, though it can see a good rewrite. Better yet, just update your PHP version, as since 8.2 PHP has everything that your Connection class does.
So you can leave only the following code in the config file
$servername = "localhost";
$username = "root";
$password = "";
$database = "dloc";
$conn = new mysqli($servername, $username, $password, $database);
and then rewrite following statements
$data = $conn->executeSelectQuery($sql, $params);
// to
$data = $conn->execute_query($sql, $params)->fetch_all(MYSQLI_ASSOC);
$data = $conn->executeWriteQuery($sql, $params);
// to
$data = $conn->execute_query($sql, $params);
$data = $conn->executeSelectOneRow($sql, $params);
// to
$data = $conn->execute_query($sql, $params)->fetch_assoc();
Though executeMultipleWriteQueries indeed warranted to exist, but you can have it as a function. And it needs to be rewritten as well
function executeMultipleWriteQueries(array $queries)
{
try {
$this->conn->begin_transaction();
foreach ($queries as $queryData) {
$this->conn->execute_query(...$queryData);
}
$this->conn->commit();
} catch (Throwable $exception) {
$this->conn->rollback();
throw $e;
}
}
Note that I removed that ambiguous behavior, when $queryData may contain either associative or enumerated array. You should decide on a single format and always use it.
Also, there is a HUGE downside in the way you are using your Connection class. You are creating a new connection every time a query gets executed. It's a BIG NO. A connection has to be created only once. Create it at the beginning of your script and then pass as a parameter to your classes. | {
"domain": "codereview.stackexchange",
"id": 45375,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, database, mysqli",
"url": null
} |
c++, datetime
Title: Getting current time with milliseconds
Question: I am looking for a more efficient or shorter way to achieve the following output using the following code:
timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;
time_t rawtime;
struct tm * timeinfo;
char buffer [80];
time(&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", timeinfo);
char currentTime[84] = "";
sprintf(currentTime, "%s:%d", buffer, milli);
printf("current time: %s \n", currentTime);
Sample output:
current time: 2012-05-16 13:36:56:396
I would prefer not to use any third-party library like Boost.
Answer: When you call gettimeofday it gives you the number of seconds since EPOCH too, so you don't need to call time again. And when you use output of localtime as input of strftime, you may omit the intermediate variable (not a very useful point though). So your code could be written like:
timeval curTime;
gettimeofday(&curTime, NULL);
int milli = curTime.tv_usec / 1000;
char buffer [80];
strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", localtime(&curTime.tv_sec));
char currentTime[84] = "";
sprintf(currentTime, "%s:%03d", buffer, milli);
printf("current time: %s \n", currentTime);
an important note to be considered is that functions like localtime are not thread-safe, and you'd better use localtime_r instead. | {
"domain": "codereview.stackexchange",
"id": 45376,
"lm_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++, datetime",
"url": null
} |
performance, python-3.x, sorting
Title: Average Pair Sorting algorithm
Question: I had to relax a bit, so I wrote this sorting algorithm. By any means it isn't fast, but I really started to get interested in it, since I haven't seen similar approach yet.
Disclaimer
I do not intend to make something revolutionary, but rather find another possible way to sort numbers, this algorithm was made due to my heavy insomnia when I had to relax my brain and I don't want people to comment to use Python native sorting algorithms. Of course these are much more elegant and efficient, I'm just curious about things, see the Questions section for that.
How it works:
The algorithm works as following:
Finding pairs of numbers in incorrect order - any two numbers that are next to each other, are not a member of other pair and are not in correct order are grouped together and the pair gets computed value of an average of the two numbers. If numbers are in correct order, they are treated as a single number into the next step.
Checking the order of the newly simplified array - If such an array has all numbers in correct order and it consists only of the original numbers, the array is sorted, otherwise it gets to step 3
Unpacking pairs - any pair in the array is unpacked in correct order, so if a pair was previously packed as [63, 48], it gets automatically unpacked back into the array as [..., 48, 63, ...] Then the algorithm gets back to step 2
The code [Python]
import random | {
"domain": "codereview.stackexchange",
"id": 45377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, sorting",
"url": null
} |
performance, python-3.x, sorting
The code [Python]
import random
class ValueNode: #ValueNode object storing single number or a pair of values
def __init__(self, numL=None, numR=None, num=None):
if num is None: #Initializing a pair of values
self.numL = numL
self.numR = numR
self.valL = numL.value if isinstance(numL, ValueNode) else numL
self.valR = numR.value if isinstance(numR, ValueNode) else numR
self.value = (self.valL + self.valR) / 2
self.isPair = True
else: #Initializing a single value
self.num = num
self.value = num.value if isinstance(num, ValueNode) else num
self.isPair = False
def __str__(self):
if self.isPair:
return f"({str(self.numL)}|{str(self.numR)})->{self.value}"
else:
return f"{(str(self.num) + '->') if isinstance(self.num, ValueNode) else ''}{self.value}"
def __gt__(self, otherValue): #gt implementation for comparison of the value of ValueNode
return self.value > otherValue.value
def unpack(self): #Unpack logic, either returning the pair of numbers in correct order or a single number
if self.isPair:
return [self.numL, self.numR] if self.numR > self.numL else [self.numR, self.numL]
else:
return [self.num]
def solve(arr): #Algorithm implementation using array as stack
stack = [arr]
sizes = []
while stack:
current_arr = stack.pop()
sizes.append(len(current_arr))
if isSorted(current_arr):
if isComplete(current_arr): | {
"domain": "codereview.stackexchange",
"id": 45377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, sorting",
"url": null
} |
performance, python-3.x, sorting
if isSorted(current_arr):
if isComplete(current_arr):
return current_arr
else:
unpackedArray = []
for i in current_arr:
unpackedArray += i.unpack()
stack.append(unpackedArray)
else:
newArray = []
counter = 0
while counter <= (len(current_arr) - 1):
if counter < (len(current_arr) - 1) and current_arr[counter] > current_arr[counter + 1]:
newArray.append(ValueNode(numL=current_arr[counter], numR=current_arr[counter + 1]))
counter += 1
else:
newArray.append(ValueNode(num=current_arr[counter]))
counter += 1
stack.append(newArray)
def isSorted(arr): #Function to check whether the array is sorted
for i in range(len(arr) - 1):
if arr[i] > arr[i + 1]:
return False
return True
def isComplete(arr): #Function to check whether the array contains all the original numbers
for i in arr:
if i.isPair:
return False
return True
#Generating random array of numbers, converting each of them to ValueNode and sorting them using Pair Average Sorting algorithm
unsorted_numbers = [ValueNode(num=i) for i in [random.randint(0, 10000000) for _ in range(100)]]
for i in solve(unsorted_numbers):
print(i)
Size of arrays through the run
Here is an interesting chart of the size of the arrays, it starts with the initial array of size 1000 in this case and then it starts to merge and average the numbers. You can notice a repetitive pattern that is probably also recursive.
My questions:
Does this sorting algorithm make any sense from the perspective of sorting algorithms in general?
Could the algorithm possibly be optimized for better performance? I'm really interested if the optimization would lead to a better solution, although I mostly bet on it becoming one of the standard algorithm. | {
"domain": "codereview.stackexchange",
"id": 45377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, sorting",
"url": null
} |
performance, python-3.x, sorting
Answer: naming convention
self.numL = numL
self.numR = numR
self.valL = ...
PEP-8
asks that you spell these num_l, val_l, new_array, and so on.
(Also, somehow your defs wound up exdented and in the left margin,
but that must be a stackexchange copy-n-paste issue.)
duck defaulting
... = numL.value if isinstance(numL, ValueNode) else numL
This reads vaguely like java code, rather than duck-typed python code.
Consider using
getattr()
to simplify it:
... = getattr(numL, 'value', numL)
Also, if you're going to mess around with same variable having different types,
it would be a kindness to the Gentle Reader to throw in some type annotations,
including | Union types, so we know what to expect.
The machine doesn't care, but we do.
ctor defines all attributes
A class invariant is a pretty important aspect of a defined class,
and "the set of object attributes" typically will be a stable invariant
of constant size, always the same attributes.
Your constructor always defines
self.value: float = ...
self.isPair: bool = ...
In the False case we also define self.num.
OTOH in the True case we instead define
self.numL = ...
self.numR = ...
self.valL = ...
self.valR = ...
One can certainly do this.
The machine doesn't care.
But a maintenance engineer will.
You should minimally write some comments that motivate this design decision.
More likely, you want to group those four attributes into a
namedtuple,
@dataclass,
or other data structure, setting it to None in the False case.
By convention a pythonista will typically list all possible
attributes in the constructor, assigning None if not yet known,
as a handy list of "things to juggle in your mind" as you read the code.
Not following the convention is possible, but it can
lead to surprises.
total order
You define a partial order over value nodes.
def __gt__( ... | {
"domain": "codereview.stackexchange",
"id": 45377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, sorting",
"url": null
} |
performance, python-3.x, sorting
Now, I understand that this code happens to never ask if one is less than another.
But still, it's odd that you didn't throw in a
@total_ordering
decorator.
It feels like a giant hole in the sidewalk,
just waiting for some hapless maintenance engineer
to fall into.
And at this point, I'm hesitant to even broach the
topic of equality.
tuples for things that aren't lists
def unpack(self):
...
return [self.numL, self.numR] if ...
Prefer to return a 2-tuple here, please.
This is a situation where a C coder would use a struct.
A somewhat subtle aspect of writing pythonic code is
we use tuple for fixed number of items where
position dictates meaning.
For example, in an (x, y) point we wouldn't want
to mix up the two coordinates, as they mean different things.
Similarly a (name, height, weight) record should be a tuple.
In contrast, we use a list for arbitrary number of "same" thing,
such as a list of student names.
When unpacking a pair, we're returning (smaller, larger) numbers,
and we should not confuse the one with the other,
they're not interchangeable.
Different meanings are associated with each one.
re-testing same thing repeatedly
def solve( ...
while stack:
...
if isSorted(current_arr):
Wow, that looks pretty expensive, given that it's a O(N) linear predicate.
Some sort algorithms would do a bit of bookkeeping with an index or two,
keeping track of "sorted up to here", invalidating it when needed,
in order to avoid the expense of repeated linear scans.
The body of solve is straightforward enough, no complaints.
But it would really benefit from a few comments or asserts
that explain relevant loop variants ("are we closer to finished?")
and invariants ("everything in this range is definitely sorted!").
numeric conversions
unsorted_numbers = ...
This use case suggests that it would be handy to have a utility
function that converts an Iterable of floats into a bunch
of value nodes.
questions
make sense? | {
"domain": "codereview.stackexchange",
"id": 45377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, sorting",
"url": null
} |
performance, python-3.x, sorting
make sense?
Yes, sure, given that it eventually puts the inputs into proper order.
I assume you have an automated
test suite
that compares results with what sorted() says.
Given the ready availability of such an oracle,
consider letting the
hypothesis
package torture test this algorithm for correctness.
optimized?
Well, caching an index or two so we do fewer full linear scans
is one idea that leapt off the page.
I didn't hear you mention whether
stability
is a requirement.
It can make a difference to implementations,
given that it's a constraint on what your algorithm is permitted to do.
You didn't mention any particular use case,
so I'm going to assume you're shooting for "general sort".
In which case there are some obvious edge cases to verify:
given the best case, already sorted input, return "quickly"
given mostly sorted input, return somewhat quickly
does perfectly reverse sorted input take "too long"?
does large number of duplicate values impact the sorting time? (likely not, but test it!)
All of which leads us to ask
Is expected running time O(N × log N) ?
What is a worst case input?
Given the averaging behavior, are some input distributions harder to sort than others? | {
"domain": "codereview.stackexchange",
"id": 45377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, sorting",
"url": null
} |
performance, python-3.x, sorting
As a separate matter, I have seen the standard library array
(or equivalently, np.array) make code run 3x faster
than a naïve list of numbers.
How does that work?
Part of it is due to being cache-friendly.
For N numbers we don't need to do random reads via N 64-bit pointers.
In your case, you really do need two kinds of object.
And you do lots of allocates and deallocates.
Maybe two arrays, one for each of the is_pair() cases?
type stability
If I pass in a bunch of floats, I won't be disappointed,
I will get ordered floats back.
If I pass in a bunch of ints, is there the risk of
any being converted to the corresponding float by unpack ?
Should we document such behavior?
Should we just unconditionally map(float, arr) to properly set expectations?
Notice that an int can be as big as 2 ** 53,
and still be properly represented by a double float.
Increment by just + 1 and we will see that float(n) == n turns False.
numeric precision
Don't worry about this, but I will note in passing that there's a bigger
literature on the topic of "computing a midpoint" than one might expect.
... = (self.valL + self.valR) / 2
You don't specify bounds on the input values, for example "less than 2 ** 52".
Even if both values are int, this returns a float average,
with opportunity for overflow.
Standard bit of paranoia for code that cares about such details is to compute
assert self.valL <= self.valR
... = self.valL + (self.valR - self.valL) / 2
If you wrote this in C++20 you could rely on
std::midpoint
to avoid overflow. | {
"domain": "codereview.stackexchange",
"id": 45377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, python-3.x, sorting",
"url": null
} |
python-3.x, console
Title: Python3 Unix command_line_interface task organizer application using argparse
Question: Greetings.
Lately I've tried to use a branch of text_formatting rules to enhance my productivity while working with different integration tools such as Git, but this formatting convention went so
deep into my life that I thought that writing my To-Do list while adhering to it would be
a good idea.
Since the element organizing section took me a lot of time everyday, I decided to write a simple organizer CLI application, while preventing object-oriented programming as much as possible ( Since I think that would add too much complexity for a simple application like this ) using Python argparse.
I would kindly accept feedback on:
Design patterns.
organo.py
#!/usr/bin/env python3
"""
KhodeNima's task organizer script.
"""
from sys import argv as cli_arguments
from os import system as cmd_input
from pathlib import Path
from time import sleep
import webbrowser
import argparse
import sys
argument_parser = argparse.ArgumentParser(prog="Organo", usage="organize_tasks --elements [] --filename Path | organize_tasks [--help, -h, -?]", add_help=True)
command_line_arguments = cli_arguments[1:cli_arguments.index(cli_arguments[-1])+1]
command_line_argument_amount = len(command_line_arguments)
color_red = "\33[31m"
color_default = "\33[0m"
def handle_help_argument_action() -> None:
if command_line_argument_amount == 2 and "-help" in command_line_arguments:
argument_parser.print_help()
sys.exit()
if command_line_argument_amount == 2 and "-?" in command_line_arguments:
argument_parser.print_help()
sys.exit()
def setup_help_arguments() -> None:
argument_parser.add_argument("-?", help="Same as --help.", action="help")
def setup_element_arguments() -> None:
argument_parser.add_argument("--elements", help="The elements to organize.", required=True, nargs="+", action="append") | {
"domain": "codereview.stackexchange",
"id": 45378,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, console",
"url": null
} |
python-3.x, console
def handle_filename_argument_action() -> str:
filename_signature = "--filename"
filename = ''.join([argument for argument in command_line_arguments if command_line_arguments[command_line_arguments.index(filename_signature) + 1] == argument])
return filename
def setup_filename_argument() -> None:
argument_parser.add_argument("--filename", help="The filename or path you want to write to ( relative to current ).", action="store", required=True)
def main() -> None:
cmd_input("clear")
file_name = handle_filename_argument_action()
try:
with open(f"{Path.cwd()}/{file_name}", "w"):
pass
except PermissionError:
print(f"{color_red} Invalid permission for writing to file, run the command as root.")
sys.exit()
header_title = str(input("Please enter your desired header title: "))
todo_text = f"---- {header_title} ----\n\n\n"
elements = []
for element in command_line_arguments:
if element.startswith("--") or element.startswith("-") or element == "--elements":
continue
if command_line_arguments.index(element) < command_line_arguments.index("--elements"):
continue
elements.append(element)
for task_id, task_title in enumerate(elements):
task_id += 1
organized_task = f" {task_id}. {task_title}. \n\n"
todo_text += organized_task
if task_title == cli_arguments[-1]:
todo_text += "\n ---- END ----"
saved_file_path = f"{Path.cwd()}/{file_name}"
with open(saved_file_path, "w") as todo_file:
todo_file.write(todo_text)
cmd_input(f"touch {Path.cwd()}/{file_name}")
cmd_input(f"chmod 700 {Path.cwd()}/{file_name}")
color_syntax = "\33[32m"
cmd_input("clear")
print(f"{color_syntax}DONE.\33[0m")
sleep(2)
cmd_input("clear") | {
"domain": "codereview.stackexchange",
"id": 45378,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, console",
"url": null
} |
python-3.x, console
cmd_input("clear")
should_open_file = input("Do you want to open the file? ( Y OR N )?: ")
if should_open_file.lower() == "yes" or should_open_file.lower() == "y":
webbrowser.open(saved_file_path)
if __name__ == "__main__":
setup_help_arguments()
setup_element_arguments()
setup_filename_argument()
argument_parser.parse_args()
handle_help_argument_action()
main()
```
Answer: Bonus points for that optional module docstring.
(Though I suspect possibly pylint "made" you do it.
I recommend preferring ruff, which doesn't get in your way,
over pylint, which by default is much too picky and counter-productive.)
sort the imports
Your imports are weirdly organized, and not
pep8 compliant.
Don't give them a moment's thought.
Just run isort
and be done with it, move on to more interesting things.
globals
You define a bunch of global symbols.
argument_parser = ...
command_line_arguments = ...
command_line_argument_amount = ...
color_red = ...
color_default = ...
Maybe this is good?
(Well, not that middle one, calling len() is too trivial to warrant defining it.)
Maybe you really need these, and didn't want to bury them within a class?
Ok, fair enough.
But at least mark them _private, e.g. _command_line_arguments.
As written, you are inviting folks to import them into other modules,
which does not appear to be your intent.
We make an effort to keep the namespace somewhat clean,
and scope things down within a smaller scope where feasible.
That way there's less
coupling,
fewer things for the Gentle Reader to juggle in their head.
I will note in passing that pypi offers more than one
library that will help with ANSI escape sequences,
if you're willing to take an external dependency.
prefer Path
def handle_filename_argument_action() -> str: | {
"domain": "codereview.stackexchange",
"id": 45378,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, console",
"url": null
} |
python-3.x, console
Thank you for the type annotation.
Prefer Path over str here.
It is more specific, so it more clearly communicates Author's Intent.
And there are lots of nice convenience methods hanging off of each Path object.
filename = ...
Yeah, you wrote some code there.
It extends way, waayyy beyond an 80-char horizontal scroll limit.
I didn't read it.
If you want others to read what you wrote, write it legibly.
You may find black helpful.
As written, Author is essentially telling folks "don't read this!".
"Handle" is a rather vague verb.
If this function is a getter, then prefer get_ in its name.
coupling
def setup_help_arguments() -> None:
...
def setup_element_arguments() -> None:
...
def setup_filename_argument() -> None:
These functions don't take any formal parameters.
Yet we are passing argument_parser to them,
implicitly, via the module namespace.
Don't do that.
Prefer to explicitly name the arg parser in the signature,
so the reader will quickly understand that we are
evaluating the function for side effects on that object.
Consider consolidating these rather small functions into a single function.
Re-evaluate your decision to not define a class.
When a bunch of functions accept similar argument,
via signature or via the module namespace,
that's the classic code smell that your functions
are asking to be grouped together in a class,
so they can share self.arg_parser.
DRY
Please DRY up
handle_help_argument_action.
For example you might choose to iterate in this way:
for option in ['-?', '-help']:
if ... | {
"domain": "codereview.stackexchange",
"id": 45378,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, console",
"url": null
} |
python-3.x, console
long function
I count 64 lines in main().
That's starting to get too long --
we need to vertically scroll in order to visually take it all in.
Consider breaking out one or more sections as
(individually testable!) helper functions.
Often for loops will be likely candidates.
Calling it main is not a terrible name.
But it is a bit vague,
and you neglected to offer a """docstring"""
explaining what it does, its
single responsibility.
unusual alias
from os import system as cmd_input
I recommend you just invoke the function as os.system(...).
Giving it an unfamiliar name isn't helping others to understand what your code does.
The os.system()
documentation is telling you that, instead of this ancient call,
you should prefer the newer
subprocess.check_call(),
which does a better job of conveniently accomplishing what you wish here.
And, oh look! You turned the usual sys.argv into cli_arguments.
Less mysterious when someone reads it, but still, unnecessary.
Also, you defined ANSI escape codes for the color red,
but not for clear screen?!?
You'd rather the expense of forking off a /usr/bin/clear child?
Ok, I mean it works.
You might want to consider
alternatives.
redundant type conversion
... = str(input( ... ))
We always get a str back from input(),
so there's no need to stringify an existing string here.
Notice that if user hits CTRL/C here we leave behind a turd file,
leftover from the write permission check.
So consider deleting that file prior to soliciting input.
nested loops
for element in command_line_arguments:
...
if command_line_arguments.index(element) < command_line_arguments.index("--elements"): | {
"domain": "codereview.stackexchange",
"id": 45378,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, console",
"url": null
} |
python-3.x, console
That's a little weird.
Typical idiom would be to set a bool flag when we
encounter "--elements", and then just test the flag.
(And for the number on the left that we're comparing,
a for loop using enumerate would give you that index directly.)
As written, cost of scanning N arguments is O(N²) quadratic.
We loop over N args, and for each arg we make linear scan of N args
Idioms like find . | xargs cmd... make "lots of args"
a more common occurrence than you might at first think.
post-loop logic belongs after the loop
if task_title == cli_arguments[-1]:
todo_text += "\n ---- END ----"
That's just odd.
Elide the if, and exdent the assignment
so it executes unconditionally.
If you're concerned about the "no elements" case,
say so explicitly with an if elements: guard for
the whole thing.
Path.resolve()
saved_file_path = f"{Path.cwd()}/{file_name}"
Ok, I let it go the first time, but we keep seeing this idiom.
The type of file_name should be Path.
And then we should be assigning ... = file_name.resolve().
Or rather, up above we should have ensured that file_name
is already fully resolved.
This is robust to things like a user entering a ../dir/file prefix,
or entering a fully qualified pathname, common when pasting it in.
useless forks
cmd_input(f"touch {Path.cwd()}/{file_name}")
cmd_input(f"chmod 700 {Path.cwd()}/{file_name}") | {
"domain": "codereview.stackexchange",
"id": 45378,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, console",
"url": null
} |
python-3.x, console
I can't imagine what helpful effect that first one has,
given that our previous action was to write to that same file.
Elide it.
The chmod suffers from a
TOCTTOU
race bug.
We could accomplish this more quickly with
file_name.chmod(mode),
but that would still suffer from the race condition.
If you want to prohibit access for group+other,
you need to do that in the open, which accepts
an optional ..., mode= parameter.
And then doing a chmod afterwards would be a
harmless belt-and-suspenders operation,
just in case the file already existed with wrong permission.
The permissions check should similarly be careful with the mode parameter.
YORN
if should_open_file.lower() == "yes" or should_open_file.lower() == "y":
You can DRY that up a little:
if should_open_file.lower() in ["y", "yes"]: | {
"domain": "codereview.stackexchange",
"id": 45378,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, console",
"url": null
} |
python, python-3.x, strings
Title: A simple search-and-replace algorithm
Question: In recent times, I've been using the following algorithm repeatedly in different languages (Java, Python, ...) to search and replace strings. I don't like this implementation very much, it's very procedural and not very descriptive, but I have yet to come up with a better one. How could the implementation be improved?
from typing import Callable
import re
def find_and_replace(pattern: str, text: str, replace: Callable[[re.Match], str]) -> str:
last_end = 0
output = []
for match in pattern.finditer(text):
text_before = text[last_end:match.start()]
if text_before:
output.append(text_before)
replacement = replace(match)
output.append(replacement)
last_end = end
text_remaining = text[last_end:]
if text_remaining:
output.append(text_remaining)
return ''.join(output)
Answer: wrong signature
def find_and_replace(pattern: str, ...
You intended pattern: re.Pattern,
Recommend you routinely use mypy or similar type checker
if you choose to add optional type annotations.
It is common knowledge that "Comments lie!".
Often they're initially accurate,
and then the code evolves with edits
while the comments remain mired in the past, out of sync.
So at best we will "mostly believe" the comments that appear.
A type signature offers stronger promises, since we expect
that lint nonsense was cleaned up during routine edit-debug
and CI/CD cycles. Posting code for review which doesn't meet that
expectation is problematic.
wrong code
last_end = end | {
"domain": "codereview.stackexchange",
"id": 45379,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, strings",
"url": null
} |
python, python-3.x, strings
You intended to assign ... = match.end().
I cannot imagine how one could "test" this source code
without noticing a fatal NameError.
missing documentation
The review context merely mentioned that this will "search and replace strings",
similar to what the identifier promises.
It's unclear how the proposed functionality would differ from what the
str or
re
libraries offer, though the signature does offer a hint.
The hint is not enough, and we are not even offered so
much as a motivating example of the kinds of Turing machines
we might usefully pass in.
missing test suite
This submission contained no doctest, no automated tests of any kind.
One reason we write tests is to exercise the code,
for example to discover a NameError.
Another reason is to educate engineers who might want
to call into this library routine.
Here is a test that might usefully have been included in the OP.
import unittest
class FindAndReplaceTest(unittest.TestCase):
def test_find_and_replace(self) -> None:
pattern = re.compile(r"\w+")
text = "... Hello, world!"
def replace(match: re.Match) -> str:
return "<" + str(match.group(0).upper()) + ">"
self.assertEqual(
"... <HELLO>, <WORLD>!",
find_and_replace(pattern, text, replace),
)
superfluous tests
if text_before:
output.append(text_before)
...
if text_remaining:
output.append(text_remaining)
There's no need to test for non-empty,
as empty string is the additive identity when catenating.
The ''.join(output) result won't be altered in the
slightest if we tack on a hundred empty entries with:
output += [""] * 100
So as a minor cleanup, simply elide the ifs. | {
"domain": "codereview.stackexchange",
"id": 45379,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, strings",
"url": null
} |
java
Title: Read a list of value display it depends on pagesize and current page
Question:
code feature: read a list of value display it depends on pagesize and current page
original code:
public static <T> List<T> pageBySubList(List<T> list, int pagesize, int currentPage) {
int totalcount = list.size();
if (totalcount == 0) {
return new ArrayList<>();
}
int pagecount = 0;
List<T> subList;
int m = totalcount % pagesize;
if (m > 0) {
pagecount = totalcount / pagesize + 1;
} else {
pagecount = totalcount / pagesize;
}
if (m == 0) {
subList = list.subList((currentPage - 1) * pagesize, pagesize * (currentPage));
} else {
if (currentPage == pagecount) {
subList = list.subList((currentPage - 1) * pagesize, totalcount);
} else {
subList = list.subList((currentPage - 1) * pagesize, pagesize * (currentPage));
}
}
return subList;
}
first try:
public static <T> List<T> pageBySubList(List<T> list, int pageSize, int currentPage) {
if (list.isEmpty()) {
return new ArrayList<>();
}
int pageCount = list.size() / pageSize + list.size() % pageSize > 0 ? 1 : 0;
boolean isLastPage = list.size() % pageSize != 0 && currentPage == pageCount;
return list.subList((currentPage - 1) * pageSize, isLastPage ? list.size() : pageSize * (currentPage));
}
second try: | {
"domain": "codereview.stackexchange",
"id": 45380,
"lm_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",
"url": null
} |
java
second try:
public static <T> List<T> pageBySubList(List<T> list, int pageSize, int currentPage) {
if (list.isEmpty()) {
return new ArrayList<>();
}
int pageCount = list.size() / pageSize + list.size() % pageSize > 0 ? 1 : 0;
boolean isLastPage = list.size() % pageSize != 0 && currentPage == pageCount;
int pageStartLine = (currentPage - 1) * pageSize;
int pageLastLine = isLastPage ? list.size() : pageSize * (currentPage);
return list.subList(pageStartLine, pageLastLine);
}
one-line try, I think this one is the worst one which is worse than original one:
public static <T> List<T> pageBySubList(List<T> list, int pageSize, int currentPage) {
return list.isEmpty() ? new ArrayList<>() : list.subList((currentPage - 1) * pageSize, (list.size() % pageSize != 0 && currentPage == (list.size() / pageSize + list.size() % pageSize > 0 ? 1 : 0)) ? list.size() : pageSize * (currentPage));
}
question:
Which one is better in maintainability and readability? In short, Temporary variables amount vs Readability
Any better way to achieve it?
Answer: meaningful identifier
public ... pageBySubList(List<T> list, ...) { | {
"domain": "codereview.stackexchange",
"id": 45380,
"lm_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",
"url": null
} |
java
Answer: meaningful identifier
public ... pageBySubList(List<T> list, ...) {
That final identifier there, list, is just terrible.
Tell me what's in the list, tell me about its content.
From reading the signature I already know that list is a List,
so the name isn't being helpful.
OTOH isLastPage is a terrific identifier, very helpful.
The pageStartLine and pageLastLine names are nice, also.
documentation
This function
promises
to do something.
But you don't spell out what that is,
you don't tell us about the post-condition.
There's no /** javadoc */,
and the English phrase "page by sub-list" is not sufficiently descriptive.
Let's put it this way.
Suppose I gave you specs for the three input parameters,
and an hour to write some code,
and I asked you to "please write a page by sub-list function",
which I'm going to examine for correctness and run tests against.
Would that be enough of a specification for you to code it up,
and be confident it would pass my functional tests?
We're looking for a sentence of javadoc which would allow you
to successfully accomplish that task.
parallel structure
int pageStartLine = (currentPage - 1) * pageSize;
int pageLastLine = isLastPage ? list.size() : pageSize * (currentPage);
nit: Please use the same order for factors in both assignments, with pageSize appearing first.
Yes, I know, multiplication commutes, and the machine doesn't care.
But people do.
You want to emphasize the similarity between what is being computed.
level of abstraction
I agree with you that first and second try are definitely better than the original,
and that the one-liner is a non-starter.
It's a bit of a toss-up between the two, as either version would
make it past PR code review and get merged down to main.
I'm going to vote for the second try.
It introduces a pair of temp vars,
that is, it names intermediate expressions,
and in doing that it reveals higher level business concepts,
reveals what those expressions mean.
Ship it! | {
"domain": "codereview.stackexchange",
"id": 45380,
"lm_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",
"url": null
} |
c++, number-guessing-game
Title: Number Guessing Game in C++
Question: I am very new to C++ and I've tried to write a simple number guessing game. I know it is a basic task but I'd really appreciate any feedback that could help me improve my writing. Thanks!
#include <iostream>
#include<cstdlib>
int main(){
//This is a number guessing game.
std::cout << "Welcome to the number guessing game!" <<std::endl;
int num; //is the random number.
int g; //guess
int count; //attempt count(max 5)
//generate random number between 1-100
srand((unsigned) time(NULL));
num = 1+(rand()%100);
//ask for player's guess
while (num != g){
std::cout << "Enter your guess (1-100):" <<std::endl;
std::cin >> g;
if (g>num){
std::cout << "Too high! Try again." <<std::endl;
}
if(g<num){
std::cout << "Too low! Try again." <<std::endl;
}
count++;
}
std::cout << "Correct! You found the correct number in " << count <<" tries." <<std::endl;
return 0;
}
Answer: A couple of things to think about:
Don’t use std::endl, just output \n instead. See here.
srand and rand are also in the std:: namespace, don’t forget to add that. But these functions are outdated, the random number generator used is really bad (though that doesn’t matter in this case). Get used to using the more modern facilities.
Try to use consistent spacing. Using a good IDE that formats your code for you helps with this. It makes the code easier to read and gives a less disorganized impression. For some people in this profession, the dissonance of inconsistent spacing can be highly jarring.
There are two bugs in your code: you use g and count before you assign anything to them (they’re uninitialized). You could initialize g with something outside the range of num (e.g. zero). count must be initialized to zero.
Always enable all warnings in your compiler, and pay attention to them. This bug would have been caught by the compiler.
Now this,
int g; //guess
is silly. Why not
int guess; | {
"domain": "codereview.stackexchange",
"id": 45381,
"lm_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++, number-guessing-game",
"url": null
} |
c++, number-guessing-game
Now this,
int g; //guess
is silly. Why not
int guess;
If you use proper variable names you’ll need fewer comments. Also it makes the rest of the code easier to read, as you won’t have to refer to the earlier comment. This becomes increasingly important as the size and complexity of the program grows.
In C++ you don’t need to declare variables at the top of a scope. It is always best to declare them where you can immediately initialize them. So instead of
int num; //is the random number.
// …
num = 1+(rand()%100);
do
// …
int num = 1+(rand()%100);
At the end of main(), return 0 is implied. You don’t need to return explicitly. | {
"domain": "codereview.stackexchange",
"id": 45381,
"lm_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++, number-guessing-game",
"url": null
} |
java, algorithm, generics, library, dijkstra
Title: Fully generic, very efficient bidirectional Dijkstra's algorithm in Java
Question: After finding out that my previous implementations are incorrect, I decided to give it another try. I relied on this post.
(The entire project resides in this GitHub repository. Contains some unit tests that are not included in this post.)
Code
com.github.coderodde.pathfinding.BidirectionalDijkstrasAlgorithm.java:
package com.github.coderodde.pathfinding;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set; | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
/**
* This class implements a bidirectional Dijkstra's algorithm.
*
* @param <N> the actual graph node type.
* @param <W> the value type of arc weights.
*/
public final class BidirectionalDijkstrasAlgorithm<N, W> {
/**
* Searches for a shortest {@code source/target} path. Throws an
* {@link IllegalStateException} if the target node is not reachable from
* the source node.
*
* @param source the source node.
* @param target the target node.
* @param childrenExpander the node expander generating child nodes.
* @param parentsExpander the node expander generating parent nodes.
* @param weightFunction the weight function of the graph.
* @param scoreComparator the comparator for comparing weights/node
* g-scores.
*
* @return the shortest path.
*/
public List<N> findShortestPath(N source,
N target,
NodeExpander<N> childrenExpander,
NodeExpander<N> parentsExpander,
WeightFunction<N, W> weightFunction,
Comparator<W> scoreComparator) {
if (source.equals(target)) {
// We need to handle this special case, since the actual algorithm
// cannot deal with it.
return Arrays.asList(target);
}
Queue<HeapNodeWrapper<N, W>> queueF = new PriorityQueue<>();
Queue<HeapNodeWrapper<N, W>> queueB = new PriorityQueue<>();
Map<N, W> distancesF = new HashMap<>();
Map<N, W> distancesB = new HashMap<>();
Map<N, N> parentsF = new HashMap<>();
Map<N, N> parentsB = new HashMap<>();
Set<N> settledF = new HashSet<>();
Set<N> settledB = new HashSet<>();
queueF.add(new HeapNodeWrapper<>(
weightFunction.getZero(), | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
queueF.add(new HeapNodeWrapper<>(
weightFunction.getZero(),
source,
scoreComparator));
queueB.add(new HeapNodeWrapper<>(
weightFunction.getZero(),
target,
scoreComparator));
distancesF.put(source, weightFunction.getZero());
distancesB.put(target, weightFunction.getZero());
parentsF.put(source, null);
parentsB.put(target, null);
W mu = weightFunction.getInfinity();
N touchNodeF = null;
N touchNodeB = null;
while (!queueF.isEmpty() && !queueB.isEmpty()) {
N currentNodeF = queueF.remove().getNode();
N currentNodeB = queueB.remove().getNode();
settledF.add(currentNodeF);
settledB.add(currentNodeB);
for (N childNode : childrenExpander.expand(currentNodeF)) {
if (settledF.contains(childNode)) {
continue;
}
if (!distancesF.containsKey(childNode) ||
scoreComparator.compare(
distancesF.get(childNode),
weightFunction.sum(
distancesF.get(currentNodeF),
weightFunction.getWeight(currentNodeF,
childNode))) > 0) {
W tentativeDistance =
weightFunction.sum(
distancesF.get(currentNodeF),
weightFunction.getWeight(currentNodeF,
childNode));
distancesF.put(childNode, tentativeDistance);
parentsF.put(childNode, currentNodeF); | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
parentsF.put(childNode, currentNodeF);
queueF.add(new HeapNodeWrapper<>(tentativeDistance,
childNode,
scoreComparator));
}
if (settledB.contains(childNode)) {
W shortestPathUpperBound =
weightFunction.sum(
distancesF.get(currentNodeF),
weightFunction.getWeight(currentNodeF,
childNode),
distancesB.get(childNode));
if (scoreComparator.compare(mu,
shortestPathUpperBound) > 0) {
mu = shortestPathUpperBound;
touchNodeF = currentNodeF;
touchNodeB = childNode;
}
}
}
for (N parentNode : parentsExpander.expand(currentNodeB)) {
if (settledB.contains(parentNode)) {
continue;
}
if (!distancesB.containsKey(parentNode) ||
scoreComparator.compare(
distancesB.get(parentNode),
weightFunction.sum(
distancesB.get(currentNodeB),
weightFunction.getWeight(parentNode,
currentNodeB))) > 0) {
W tentativeDistance =
weightFunction.sum(
distancesB.get(currentNodeB),
weightFunction.getWeight(parentNode, | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
weightFunction.getWeight(parentNode,
currentNodeB));
distancesB.put(parentNode, tentativeDistance);
parentsB.put(parentNode, currentNodeB);
queueB.add(new HeapNodeWrapper<>(tentativeDistance,
parentNode,
scoreComparator));
}
if (settledF.contains(parentNode)) {
W shortestPathUpperBound =
weightFunction.sum(
distancesF.get(parentNode),
weightFunction.getWeight(parentNode,
currentNodeB),
distancesB.get(currentNodeB));
if (scoreComparator.compare(mu,
shortestPathUpperBound) > 0) {
mu = shortestPathUpperBound;
touchNodeF = parentNode;
touchNodeB = currentNodeB;
}
}
}
if (distancesF.containsKey(currentNodeF) &&
distancesB.containsKey(currentNodeB) &&
scoreComparator.compare(
weightFunction.sum(
distancesF.get(currentNodeF),
distancesB.get(currentNodeB)),
mu) > 0) {
return tracebackPath(touchNodeF,
touchNodeB,
parentsF,
parentsB);
}
} | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
parentsB);
}
}
throw new IllegalStateException(
"The target node is not reachable from the source node.");
}
private static <N> List<N> tracebackPath(N touchNodeF,
N touchNodeB,
Map<N, N> parentsF,
Map<N, N> parentsB) {
List<N> path = new ArrayList<>();
N node = touchNodeF;
while (node != null) {
path.add(node);
node = parentsF.get(node);
}
Collections.reverse(path);
node = touchNodeB;
while (node != null) {
path.add(node);
node = parentsB.get(node);
}
return path;
}
} | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
com.github.coderodde.pathfinding.DijkstrasAlgorithm.java:
package com.github.coderodde.pathfinding;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
/**
* This class implements the (unidirectional) Dijkstra's algorithm.
*
* @param <N> the actual graph node type.
* @param <W> the weight value type.
*/
public final class DijkstrasAlgorithm<N, W> { | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
/**
* Finds the shortest {@code source/target} path or throws an
* {@link IllegalStateException} if the target node is not reachable from
* the source node.
*
* @param source the source node.
* @param target the target node.
* @param childrenExpander the children expander.
* @param weightFunction the graph weight function.
* @param scoreComparator the score comparator.
*
* @return the shortest path, if any exist.
*/
public List<N> findShortestPath(N source,
N target,
NodeExpander<N> childrenExpander,
WeightFunction<N, W> weightFunction,
Comparator<W> scoreComparator) {
Queue<HeapNodeWrapper<N, W>> open = new PriorityQueue<>();
Map<N, W> distanceMap = new HashMap<>();
Map<N, N> parentMap = new HashMap<>();
Set<N> closed = new HashSet<>();
open.add(new HeapNodeWrapper<>(
weightFunction.getZero(),
source,
scoreComparator));
distanceMap.put(source, weightFunction.getZero());
parentMap.put(source, null);
while (!open.isEmpty()) {
N currentNode = open.remove().getNode();
if (currentNode.equals(target)) {
return tracebackSolution(target, parentMap);
}
closed.add(currentNode);
for (N childNode : childrenExpander.expand(currentNode)) {
if (closed.contains(childNode)) {
continue;
}
if (!distanceMap.containsKey(childNode)) {
W tentativeDistance =
weightFunction.sum( | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
W tentativeDistance =
weightFunction.sum(
distanceMap.get(currentNode),
weightFunction.getWeight(currentNode,
childNode));
distanceMap.put(childNode, tentativeDistance);
parentMap.put(childNode, currentNode);
open.add(new HeapNodeWrapper<>(tentativeDistance,
childNode,
scoreComparator));
} else {
W tentativeDistance =
weightFunction.sum(
distanceMap.get(currentNode),
weightFunction.getWeight(currentNode,
childNode)); | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
if (scoreComparator.compare(distanceMap.get(childNode), tentativeDistance) > 0) {
distanceMap.put(childNode, tentativeDistance);
parentMap.put(childNode, currentNode);
open.add(new HeapNodeWrapper<>(tentativeDistance,
childNode,
scoreComparator));
}
}
}
}
throw new IllegalStateException(
"Target not reachable from the source.");
}
private static <N> List<N> tracebackSolution(N target, Map<N, N> parentMap) {
List<N> path = new ArrayList<>();
N node = target;
while (node != null) {
path.add(node);
node = parentMap.get(node);
}
Collections.reverse(path);
return path;
}
}
com.github.coderodde.pathfinding.HeapNodeWrapper.java:
package com.github.coderodde.pathfinding;
import java.util.Comparator;
final class HeapNodeWrapper<N, W> implements Comparable<HeapNodeWrapper<N, W>> {
private final W score;
private final N node;
private final Comparator<W> scoreComparator;
HeapNodeWrapper(W score,
N node,
Comparator<W> scoreComparator) {
this.score = score;
this.node = node;
this.scoreComparator = scoreComparator;
}
N getNode() {
return node;
}
@Override
public int compareTo(HeapNodeWrapper<N, W> o) {
return scoreComparator.compare(this.score, o.score);
}
}
com.github.coderodde.pathfinding.NodeExpander.java:
package com.github.coderodde.pathfinding;
import java.util.Collection; | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
import java.util.Collection;
/**
* This interface defines the API for all the node expanders.
*
* @param <N> the actual type of the nodes.
*/
public interface NodeExpander<N> {
/**
* Returns the expansion view of the input node.
*
* @param node the node to expand.
* @return the collection of "next" nodes to consider in search.
*/
Collection<N> expand(N node);
}
com.github.coderodde.pathfinding.WeightFunction.java:
package com.github.coderodde.pathfinding;
/**
* This interface defines the API for graph weight functions.
*
* @param <N> the actual graph node type.
* @param <W> the type of the weight values.
*/
public interface WeightFunction<N, W> {
/**
* Returns the weight of the arc {@code (tail, head)}.
*
* @param tail the starting node of the arc.
* @param head the ending node of the arc.
* @return the weight of the input arc.
*/
W getWeight(N tail, N head);
/**
* Returns the value of type {@code W} representing zero.
*
* @return the zero value.
*/
W getZero();
/**
* Returns the largest representable weight.
*
* @return the largest weight.
*/
W getInfinity();
/**
* Returns the sum of {@code w1} and {@code w2}.
*
* @param w1 the first weight value.
* @param w2 the second weight value.
*
* @return the sum of the two input weights.
*/
W sum(W w1, W w2);
/**
* Returns the sum of three input weights. We need this method primarily for
* bidirectional Dijkstra's algorithm.
*
* @param w1 the first weight.
* @param w2 the second weight.
* @param w3 the third weight.
* @return the sum of the three input weights.
*/
default W sum(W w1, W w2, W w3) {
return sum(w1, sum(w2, w3));
}
}
com.github.coderodde.pathfinding.benchmark.Benchmark.java:
package com.github.coderodde.pathfinding.benchmark; | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
import com.github.coderodde.pathfinding.BidirectionalDijkstrasAlgorithm;
import com.github.coderodde.pathfinding.DijkstrasAlgorithm;
import com.github.coderodde.pathfinding.NodeExpander;
import com.github.coderodde.pathfinding.WeightFunction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.Set; | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
final class Benchmark {
private static final int NUMBER_OF_NODES = 100_000;
private static final int NUMBER_OF_ARCS = 1_000_000;
public static void main(String[] args) {
long seed = parseSeed(args);
System.out.println("Seed = " + seed);
Random random = new Random(seed);
long startTime = System.currentTimeMillis();
GraphData graphData = getRandomGraph(NUMBER_OF_NODES,
NUMBER_OF_ARCS,
random);
System.out.printf("Built the graph in %d milliseconds.\n",
System.currentTimeMillis() - startTime);
DirectedGraphNode source = graphData.getRandonNode(random);
DirectedGraphNode target = graphData.getRandonNode(random);
System.out.printf("Source node: %s\n", source);
System.out.printf("Target node: %s\n", target);
DijkstrasAlgorithm<DirectedGraphNode, Float> pathfinderDijkstra =
new DijkstrasAlgorithm<>();
BidirectionalDijkstrasAlgorithm<DirectedGraphNode, Float>
pathfinderBidirectionalDijkstra =
new BidirectionalDijkstrasAlgorithm<>();
NodeExpander<DirectedGraphNode> childNodeExpander =
new DirectedGraphNodeChildrenExpander();
NodeExpander<DirectedGraphNode> parentNodeExpander =
new DirectedGraphNodeParentsExpander();
DirectedGraphWeightFunction weightFunction =
new DirectedGraphWeightFunction();
startTime = System.currentTimeMillis();
List<DirectedGraphNode> pathDijkstra =
pathfinderDijkstra.findShortestPath(
source,
target,
childNodeExpander,
weightFunction,
Float::compare); | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
weightFunction,
Float::compare);
System.out.printf("Dijkstra's algorithm in %d milliseconds.\n",
System.currentTimeMillis() - startTime);
startTime = System.currentTimeMillis();
List<DirectedGraphNode> pathBidirectionalDijkstra =
pathfinderBidirectionalDijkstra.findShortestPath(
source,
target,
childNodeExpander,
parentNodeExpander,
weightFunction,
Float::compare);
System.out.printf(
"Bidirectional Dijkstra's algorithm in %d milliseconds.\n",
System.currentTimeMillis() - startTime);
boolean pathsAreEqual = pathDijkstra.equals(pathBidirectionalDijkstra);
if (pathsAreEqual) {
System.out.println("Paths agree:");
for (DirectedGraphNode node : pathDijkstra) {
System.out.println(node);
}
System.out.printf(
"Path cost: %.3f\n",
computePathCost(pathDijkstra, weightFunction));
} else {
System.out.println("Paths diagree!");
System.out.println("Dijkstra's algorithm's path:");
for (DirectedGraphNode node : pathDijkstra) {
System.out.println(node);
}
System.out.printf("Dijkstra's path cost: %.3f\n",
computePathCost(pathDijkstra, weightFunction));
System.out.println("Bidirectional Dijkstra's algorithm's path:");
for (DirectedGraphNode node : pathBidirectionalDijkstra) {
System.out.println(node);
} | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
System.out.println(node);
}
System.out.printf("Bidirectional Dijkstra's path cost: %.3f\n",
computePathCost(pathBidirectionalDijkstra,
weightFunction));
}
}
private static long parseSeed(String[] args) {
if (args.length == 0) {
return System.currentTimeMillis();
}
try {
return Long.parseLong(args[0]);
} catch (NumberFormatException ex) {
System.err.printf("WARNING: Could not parse %s as a long value.",
args[0]);
return System.currentTimeMillis();
}
}
private static float computePathCost(
List<DirectedGraphNode> path,
DirectedGraphWeightFunction weightFunction) {
float cost = 0.0f;
for (int i = 0; i < path.size() - 1; i++) {
DirectedGraphNode tail = path.get(i);
DirectedGraphNode head = path.get(i + 1);
float arcWeight = weightFunction.getWeight(tail, head);
cost += arcWeight;
}
return cost;
}
private static final class GraphData {
private final List<DirectedGraphNode> graphNodes;
private final DirectedGraphWeightFunction weightFunction;
GraphData(List<DirectedGraphNode> graphNodes,
DirectedGraphWeightFunction weightFunction) {
this.graphNodes = graphNodes;
this.weightFunction = weightFunction;
}
DirectedGraphNode getRandonNode(Random random) {
return choose(graphNodes, random);
}
}
private static final GraphData
getRandomGraph(int nodes, int edges, Random random) {
List<DirectedGraphNode> graph = new ArrayList<>(nodes);
Set<Arc> arcs = new HashSet<>(edges); | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
Set<Arc> arcs = new HashSet<>(edges);
for (int i = 0; i < nodes; i++) {
graph.add(new DirectedGraphNode());
}
while (arcs.size() < edges) {
DirectedGraphNode tail = choose(graph, random);
DirectedGraphNode head = choose(graph, random);
Arc arc = new Arc(tail, head);
arcs.add(arc);
}
DirectedGraphWeightFunction weightFunction =
new DirectedGraphWeightFunction();
for (Arc arc : arcs) {
DirectedGraphNode tail = arc.getTail();
DirectedGraphNode head = arc.getHead();
float weight = 100.0f * random.nextFloat();
tail.addChild(head, weight);
}
return new GraphData(graph, weightFunction);
}
private static <T> T choose(List<T> list, Random random) {
return list.get(random.nextInt(list.size()));
}
private static final class Arc {
private final DirectedGraphNode tail;
private final DirectedGraphNode head;
Arc(DirectedGraphNode tail, DirectedGraphNode head) {
this.tail = tail;
this.head = head;
}
DirectedGraphNode getTail() {
return tail;
}
DirectedGraphNode getHead() {
return head;
}
@Override
public int hashCode() {
return Objects.hash(tail, head);
}
@Override
public boolean equals(Object o) {
Arc arc = (Arc) o;
return tail.equals(arc.tail) &&
head.equals(arc.head);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
final class DirectedGraphNode {
private static int nodeIdCounter = 0;
private final int id;
private final Map<DirectedGraphNode, Float> outgoingArcs =
new HashMap<>();
private final Map<DirectedGraphNode, Float> incomingArcs =
new HashMap<>();
DirectedGraphNode() {
this.id = nodeIdCounter++;
}
void addChild(DirectedGraphNode child, Float weight) {
outgoingArcs.put(child, weight);
child.incomingArcs.put(this, weight);
}
List<DirectedGraphNode> getChildren() {
return new ArrayList<>(outgoingArcs.keySet());
}
List<DirectedGraphNode> getParents() {
return new ArrayList<>(incomingArcs.keySet());
}
Float getWeightTo(DirectedGraphNode headNode) {
return outgoingArcs.get(headNode);
}
@Override
public String toString() {
return String.format("[DirectedGraphNode id = %d]", id);
}
@Override
public int hashCode() {
return id;
}
@Override
public boolean equals(Object obj) {
DirectedGraphNode other = (DirectedGraphNode) obj;
return this.id == other.id;
}
}
class DirectedGraphWeightFunction
implements WeightFunction<DirectedGraphNode, Float> {
@Override
public Float getWeight(DirectedGraphNode tail, DirectedGraphNode head) {
return tail.getWeightTo(head);
}
@Override
public Float getZero() {
return 0.0f;
}
@Override
public Float getInfinity() {
return Float.POSITIVE_INFINITY;
}
@Override
public Float sum(Float w1, Float w2) {
return w1 + w2;
}
}
class DirectedGraphNodeChildrenExpander
implements NodeExpander<DirectedGraphNode> {
@Override
public List<DirectedGraphNode> expand(DirectedGraphNode node) {
return node.getChildren();
}
} | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
class DirectedGraphNodeParentsExpander
implements NodeExpander<DirectedGraphNode> {
@Override
public List<DirectedGraphNode> expand(DirectedGraphNode node) {
return node.getParents();
}
}
Typical output
Seed = 1705171998017
Built the graph in 1768 milliseconds.
Source node: [DirectedGraphNode id = 80226]
Target node: [DirectedGraphNode id = 33520]
Dijkstra's algorithm in 1056 milliseconds.
Bidirectional Dijkstra's algorithm in 31 milliseconds.
Paths agree:
[DirectedGraphNode id = 80226]
[DirectedGraphNode id = 35320]
[DirectedGraphNode id = 77598]
[DirectedGraphNode id = 93003]
[DirectedGraphNode id = 34031]
[DirectedGraphNode id = 32260]
[DirectedGraphNode id = 53773]
[DirectedGraphNode id = 53078]
[DirectedGraphNode id = 35871]
[DirectedGraphNode id = 15879]
[DirectedGraphNode id = 79948]
[DirectedGraphNode id = 31828]
[DirectedGraphNode id = 10811]
[DirectedGraphNode id = 44856]
[DirectedGraphNode id = 33520]
Path cost: 123,482
Critique request
As always, I would like to hear whatever comes to mind. | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
Critique request
As always, I would like to hear whatever comes to mind.
Answer: (Not a full review)
A lot of things feel done right - doc comments, use of interfaces, visibility…
One alternative to keeping a set of closed nodes should be to keep open as a "PrioritySet": higher priority offers replacing a node kept, equal or lower ignored.
It doesn't feel quite right to keep a/the Comparator with every NodeWrapper.
What if one extended the priority datastructure to keep it, and made the NodeWrapper a nested class? (Is the design any cleaner? The implicit reference to the enclosing priority DS instance should take as much space an explicit reference to a Comparator.)
Some code in DijkstrasAlgorithm.findShortestPath()'s inner loop looks duplicated.
It would seem it might look
for (N childNode : childrenExpander.expand(currentNode)) {
if (closed.contains(childNode)) {
continue;
}
W tentativeDistance = weightFunction.sum(
distanceMap.get(currentNode),
weightFunction.getWeight(currentNode, childNode));
if (!distanceMap.containsKey(childNode)
|| scoreComparator.compare(distanceMap.get(childNode),
tentativeDistance) > 0) {
distanceMap.put(childNode, tentativeDistance);
parentMap.put(childNode, currentNode);
open.add(new HeapNodeWrapper<>(tentativeDistance,
childNode,
scoreComparator));
}
} | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
java, algorithm, generics, library, dijkstra
In BidirectionalDijkstrasAlgorithm.findShortestPath(), I think the declarations "qualified" by F&B a code smell.
If there was a class subsuming these, it should be possible to remove most code duplication.
class ExplorationState {
Queue<HeapNodeWrapper<N, W>> queue = new PriorityQueue<>();
Map<N, W> distances = new HashMap<>();
Map<N, N> parents = new HashMap<>();
Set<N> settled = new HashSet<>();
N touchNode;
ExplorationState(N start, WeightFunction<N, W> weightFunction,
Comparator<W> scoreComparator) {
queue.add(new HeapNodeWrapper<>(weightFunction.getZero(),
start,
scoreComparator));
distances.put(start, weightFunction.getZero());
parents.put(start, null);
}
} | {
"domain": "codereview.stackexchange",
"id": 45382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, algorithm, generics, library, dijkstra",
"url": null
} |
c++, converting
Title: library for converting numbers to HEX
Question: This is library for fast converting "HEX strings" to unsigned numbers and vice versa.
The result is not defined, if input is incorrect, e.g. string "ZZZ1" will be converted to number 1.
Special attention is made the conversion to string to work inside existing buffer (see ">>>:0000:<<<"). In this case the programmer is responsible to provide enough space in the buffer.
#include <cstdint>
#include <type_traits>
#include <array>
#include <string_view>
namespace hex_convert{
namespace options{
constexpr uint8_t nonterminate = 0b0000;
constexpr uint8_t terminate = 0b0001;
constexpr uint8_t lowercase = 0b0000;
constexpr uint8_t uppercase = 0b0010;
constexpr uint8_t defaults = terminate | uppercase;
}
template <typename T, uint8_t opt = options::defaults>
std::string_view toHex(T const number, char *buffer){
static_assert(
std::is_same_v<T, uint8_t > ||
std::is_same_v<T, uint16_t> ||
std::is_same_v<T, uint32_t> ||
std::is_same_v<T, uint64_t>
);
constexpr const char *digits = [](){
if constexpr(opt & options::uppercase)
return "0123456789ABCDEF";
else
return "0123456789abcdef";
}();
constexpr std::size_t size = sizeof(T) * 2;
if constexpr(opt & options::terminate)
buffer[size] = '\0';
for (std::size_t i = 0; i < size; ++i){
auto const index = (number >> (4 * i)) & 0xF;
buffer[size - 1 - i] = digits[index];
}
return { buffer, size };
} | {
"domain": "codereview.stackexchange",
"id": 45383,
"lm_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++, converting",
"url": null
} |
c++, converting
return { buffer, size };
}
template <typename T, uint8_t opt = options::defaults, size_t N>
std::string_view toHex(T const number, std::array<char, N> &buffer){
static_assert(
std::is_same_v<T, uint8_t > ||
std::is_same_v<T, uint16_t> ||
std::is_same_v<T, uint32_t> ||
std::is_same_v<T, uint64_t>
);
static_assert(N > sizeof(T) + (opt & options::terminate ? 1 : 0));
return toHex<T, opt>(number, buffer.data());
}
template <typename T>
auto fromHex(std::string_view const hex){
static_assert(
std::is_same_v<T, uint8_t > ||
std::is_same_v<T, uint16_t> ||
std::is_same_v<T, uint32_t> ||
std::is_same_v<T, uint64_t>
);
auto _ = [](char c) -> T{
switch(c){
default:
case '0': return 0;
case '1': return 1;
case '2': return 2;
case '3': return 3;
case '4': return 4;
case '5': return 5;
case '6': return 6;
case '7': return 7;
case '8': return 8;
case '9': return 9;
case 'A': case 'a': return 10;
case 'B': case 'b': return 11;
case 'C': case 'c': return 12;
case 'D': case 'd': return 13;
case 'E': case 'e': return 14;
case 'F': case 'f': return 15;
}
};
T val = 0;
for(auto const &c : hex){
T const nibble = _(c);
val = (val << 4) | nibble;
}
return val;
}
}
#include <iostream>
constexpr size_t to_string_buffer_t_size = 32; // largest uint64_t is 20 digits.
using to_string_buffer_t = std::array<char, to_string_buffer_t_size>;
int main(){
namespace о = hex_convert::options;
if constexpr(1){
to_string_buffer_t buffer; | {
"domain": "codereview.stackexchange",
"id": 45383,
"lm_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++, converting",
"url": null
} |
c++, converting
if constexpr(1){
to_string_buffer_t buffer;
printf("%s\n", hex_convert::toHex<uint64_t, о::terminate | о::lowercase>(0x00DEADBEEF, buffer).data());
printf("%s\n", hex_convert::toHex<uint64_t, о::terminate | о::uppercase>(0x00DEADBEEF, buffer).data());
printf("%s\n", hex_convert::toHex<uint32_t, о::terminate | о::lowercase>(0x00DEADBEEF, buffer).data());
printf("%s\n", hex_convert::toHex<uint32_t, о::terminate | о::uppercase>(0x00DEADBEEF, buffer).data());
}
if constexpr(1){
char x[200] = { ">>>:0000:<<<" };
hex_convert::toHex<uint16_t, о::nonterminate | о::lowercase>(0xABBA, x + 4);
printf("%s\n", x);
hex_convert::toHex<uint16_t, о::nonterminate | о::uppercase>(0xABBA, x + 4);
printf("%s\n", x);
}
if constexpr(1){
printf("0x%16X\n", hex_convert::fromHex<uint8_t >("F1"));
printf("0x%16X\n", hex_convert::fromHex<uint16_t>("ABBA"));
printf("0x%16X\n", hex_convert::fromHex<uint32_t>("DEADBEEF"));
printf("0x%16lX\n", hex_convert::fromHex<uint64_t>("1122334455667788"));
}
}
Answer: The identifiers from <cstdint> are used without their namespace qualifiers. While your implementation is allowed to define global-namespace equivalents, that's not required, so portable code cannot rely on it.
Why are options passed as a std::uint8_t? I'd expect an enum for that - and if specifying the underlying representation type, use a portable one such as std::uint_fast8_t.
There's no option for zero-padding; the value seems to be zero-extended always. Users probably want to be able to choose between behaviours here.
Consider allowing callers to pass options at runtime, rather than requiring them to be fixed at compile time (at least for the uppercase and zero-fill option - nul-terminating is part of program logic and wouldn't be expected to change at runtime). | {
"domain": "codereview.stackexchange",
"id": 45383,
"lm_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++, converting",
"url": null
} |
c++, converting
The char* version of toHex() requires the caller to know the required buffer size in advance and provide a suitable pointer. That's risky. I'd prefer a version that creates a std::string.
The std::array version of toHex() only asserts that the buffer has enough space for 1 character per input octet, but we know that two characters are required. In both cases, it seems there's an implicit assumption that CHAR_BIT is 8, but that's just the minimum that C++ requires, so we should multiply the size by CHAR_BIT and ceil-divide by 4 to get the true output requirement.
Instead of using static_assert that T is one of a few types, why not use a requires to allow all unsigned types? We could simply use the std::unsigned_integral concept for this: std::string_view toHex(std::unsigned_integral auto number, char *buffer)
Instead of sizeof(T), it's clearer to write sizeof number, since that's the value we're converting.
fromHex() is completely lacking any validation of input. Consider throwing an exception if input contains invalid characters.
The identifier _ is conventionally used as a "discard" variable (signifying that we don't intend to use its value) and there's a proposal for C++ to make it magic (re-declarable, etc). Prefer to use an alphabetic name for the lambda function, so readers know it's to be used.
The demonstration program could easily be turned into a unit test, if it confirmed the results and exited with success or failure value appropriately.
We should probably be testing more edge cases. | {
"domain": "codereview.stackexchange",
"id": 45383,
"lm_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++, converting",
"url": null
} |
javascript, typescript, user-interface, vue.js
Title: Virtual scroller Vue component
Question: Problem
The scrolling looks smooth on Windows, but very laggy on Linux (Webkit webview and Webkit browsers).
Any thoughts on what could be optimized or what's obviously broken?
Demo playground:
https://stackblitz.com/edit/sigma-scrollkit-demo?file=README.md
Code
Full source code
The main logic is happening in this component:
<script setup lang="ts">
import uniqueId from '@/utils/uniqueId';
import {
ref,
computed,
nextTick,
watch,
onMounted,
onBeforeUnmount
} from 'vue';
import type {Ref} from 'vue';
import type {VirtualEntryItem, VirtualEntry} from 'types/shared';
type ElementResizeCallback = (entry: ResizeObserverEntry) => void;
interface ScrollEmitValue {
event: UIEvent;
scrollOffsetY: number;
scrollDelta: number;
scrollDirection: 'up' | 'down';
scrollSpeed: number;
}
interface Props {
virtualEntries: VirtualEntry[];
scrollerId: string;
layoutType: 'list' | 'grid';
minColumnWidth?: number;
bufferItemCount?: number;
calcExtraInfo?: boolean;
topOffsetTrigger?: number;
bottomOffsetTrigger?: number;
}
interface Emits {
(
event: 'viewport-mounted',
value: { viewport: Ref<HTMLElement | null>; selector: string }
): void;
(event: 'scroll', value: ScrollEmitValue): void;
(event: 'scrolling', value: boolean): void;
(event: 'is-scrollable', value: boolean): void;
(event: 'top-reached', value: boolean): void;
(event: 'bottom-reached', value: boolean): void;
(event: 'top-offset-trigger', value: boolean): void;
(event: 'bottom-offset-trigger', value: boolean): void;
}
const props = withDefaults(defineProps<Props>(), {
virtualEntries: () => [],
bufferItemCount: 2,
minColumnWidth: 200,
calcExtraInfo: false,
topOffsetTrigger: 0,
bottomOffsetTrigger: 0
});
const emit = defineEmits<Emits>();
defineExpose({scrollTop, scrollToItem, scrollToIndex}); | {
"domain": "codereview.stackexchange",
"id": 45384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, user-interface, vue.js",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.