text stringlengths 1 2.12k | source dict |
|---|---|
python, performance, python-3.x, numpy, image
if __name__ == "__main__":
import cv2
shape = (36, 64, 3)
zeros = np.zeros(shape)
assert np.array_equal(BGR_to_HSL(zeros), zeros)
assert np.array_equal(HSL_to_BGR(zeros), zeros)
ones = np.ones(shape)
assert np.array_equal(HSL_to_BGR(BGR_to_HSL(ones)), ones)
for _ in range(256):
bools = np.random.choice((0.0, 1.0), size=shape)
assert np.isclose(HSL_to_BGR(BGR_to_HSL(bools)), bools).all()
grey = np.random.random(size=shape[:2])
grey = np.dstack([grey] * 3)
assert np.isclose(HSL_to_BGR(BGR_to_HSL(grey)), grey).all()
img = np.random.random(size=shape)
assert np.isclose(HSL_to_BGR(BGR_to_HSL(img)), img).all()
intimg = (img * 255).astype(np.uint8)
diff = cv2.absdiff(
cv2.cvtColor(intimg, cv2.COLOR_BGR2HLS_FULL),
(BGR_to_HSL(img) * 255).astype(np.uint8)[..., (0, 2, 1)],
)
assert (diff > 16).sum() < 24
assert not (diff[..., 1:] > 128).any()
Because I use floats, there is inherent impression, and there is so much conversion going on, the output is different from that obtained from cv2.cvtColor, but mostly the difference is small, but cv2.absdiff values can be over 250, I think it must be from the hue component but I am not sure.
My code converts from BGR color space to HSL color space, to get the same order as HLS you need to do hsl[..., (0, 2, 1)].
My code works for all inputs, and it is verified to be correct. How can I make it more efficient, and how can I make the output closer to that from cv2 (that is, when converted like this: (hsl * 255).astype(np.uint8)[..., (0, 2, 1)], the result of cv2.absdiff of the converted output and that from cv2.cvtColor(img, cv2.COLOR_BGR2HLS_FULL) would be less than the current value)? | {
"domain": "codereview.stackexchange",
"id": 45033,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy, image",
"url": null
} |
python, performance, python-3.x, numpy, image
I just added a new check and I have confirmed that the discrepancy of about 254 for some values is indeed from the hue channel, which is not a big problem, because the hue goes from red to yellow and then green then cyan, blue, magenta and finally back to red, it rotates and will always go back. The value wraps around and so a difference of 254 is just -2, nevertheless it is something to be fixed.
Edit
I just found out there are some huge discrepancies because the input values are invalid, the values inside the result of np.random.random(size=shape) would be very likely not be an integer between 0 and 255 when multiplied by 255.
If the values are fractions n / 255 where n is an integer between 0 and 255, my code gives the correct output, I tested with this:
byte = range(256)
colors = np.array(np.meshgrid(byte, byte, byte), dtype=np.uint8).T.reshape(-1, 3)
img = colors.reshape((4096, 4096, 3))
assert not (
cv2.absdiff(
cv2.cvtColor(img, cv2.COLOR_BGR2HLS_FULL),
(BGR_to_HSL(img / 255) * 255).astype(np.uint8)[..., (0, 2, 1)],
)
> 1
).any()
I have converted all 16777216 colors and the absolute difference is never greater than 1.
So there wasn't actually a problem.
Answer: I find the code easy to read; there are no legibility issues (within the context that you need to understand Numpy).
It's a good idea that you're doing division safety checks, but you should simplify them. For instance, this:
safe = (mina != 0) | (maxa != 0)
quotient[safe] = delta[safe] / (mina[safe] + maxa[safe])
should really just be
denominator = mina + maxa
safe = denominator != 0
quotient[safe] = delta[safe] / denominator[safe] | {
"domain": "codereview.stackexchange",
"id": 45033,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy, image",
"url": null
} |
python, performance, python-3.x, numpy, image
This also better handles the case where mina and maxa are safe individually but their sum is not.
There are many argument names that appear to be errors. For any BGR_to_HSL function, I would expect an argument name of bgr and not hsl.
Where possible, convert module calls to instance calls, e.g. np.clip(quotient) becomes quotient.clip().
From this expression:
((maxa[safe, np.newaxis] - img[safe]) / 6 + delta / 2) / delta
You can divide out delta from the last term and just + 0.5.
%= 1 is fine, but you might see a performance difference if you switch to a non-division method such as subtracting the result of np.fix().
Your functions could use """ docstrings.
Everything under your __main__ guard is still in the global scope. Put it in a function.
np.isclose().all() is just np.allclose(). | {
"domain": "codereview.stackexchange",
"id": 45033,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy, image",
"url": null
} |
python, beginner, object-oriented, cellular-automata
Title: Cellular Automata Python Class
Question: I've been working on creating a simple Class for a Cellular Automata. It generates a grid of NxM dimensions populated by Cell objects - Pretty straightforward class to save the state of the cell-. It allows to update the world grid using two sets of rules a the moment: solidification rules and Conway's game of life rules, I will implement a way of using custom rules in the future. It also has the capability of printing the world grid current state or saving it as an image file. I'm no expert when it comes to writing code. I would like the code to be as clear and maintainable as possible, while following good practices. I'm not interested at the moment in optimizing it. I just want to make great Python code so I can use it, extend it or publish it in the future.
"""
File: CA.py
Project: Cellular_automata
File Created: Wednesday, 30th August 2023 10:20:17 am
Author: Athansya
-----
License: MIT License
-----
Description: Simple cellular automata class.
"""
from copy import deepcopy
from dataclasses import dataclass, field
import matplotlib.pyplot as plt
from numpy import array, ndarray
@dataclass()
class Cell:
"""Class for storing the state of a cell
Args:
state (int): state of the cell. Default 0.
"""
state: int = 0
def __add__(self, other) -> int:
return self.state + other.state
def __repr__(self) -> str:
return str(self.state)
@dataclass
class CA:
"""Class for creating a cellular automata
Args:
world_dim (tuple[int, int]): Dimensions MxN of the world grid.
states (dict[str, int]): Valid states for the cell
"""
world_dim: tuple[int, int]
states: dict[str, int] = field(default_factory=lambda: {"0": 0, "1": 1})
gen: int = field(init=False, default=0) | {
"domain": "codereview.stackexchange",
"id": 45034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, cellular-automata",
"url": null
} |
python, beginner, object-oriented, cellular-automata
def __post_init__(self):
self.world = [
[Cell() for _ in range(self.world_dim[1] + 1)]
for _ in range(self.world_dim[0] + 1)
]
self.new_world = deepcopy(self.world)
def set_cell_value(self, row_index: int, col_index: int, value: int):
"""Sets the state of a cell.
Args:
row_index (int): row position of cell in world grid.
col_index (int): column position of cell in world grid.
value (int): new state value.
"""
self.world[row_index][col_index].state = value
def show_world(self):
"""Prints the world grid"""
for row in self.world:
print(*row)
def show_world_pretty(self):
"""Pretty print of world grid"""
state_to_char = {
0: " ",
1: "#"
}
for row in self.world:
print(*[state_to_char[cell.state] for cell in row])
def apply_rules(self, row_index: int, col_index: int) -> int:
"""Applies solidification rules for a 2D cellular automata.
Args:
row_index (int): row position in world grid.
col_index (int): col position in world grid. | {
"domain": "codereview.stackexchange",
"id": 45034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, cellular-automata",
"url": null
} |
python, beginner, object-oriented, cellular-automata
Returns:
int: new cell's state.
"""
# Solidification rules
# Case 1. State == 1 -> 1
if self.world[row_index][col_index].state == self.states["1"]:
return 1
# Case 2. State == 0 and && neighorhood sum == 1 or 2 -> 1
# Init sum without taking central into account
neighborhood_sum = 0 - self.world[row_index][col_index].state
# Walk through Von Newmann Neighborhood
for row in self.world[row_index - 1 : row_index + 2]:
neighborhood_sum += sum(
cell.state for cell in row[col_index - 1 : col_index + 2]
)
if neighborhood_sum == 1 or neighborhood_sum == 2:
return self.states["1"]
else:
return self.states["0"]
def game_of_life_rules(self, row_index: int, col_index: int) -> int:
"""Applies Conway's game of life rules for 2D cellular automata.
Args:
row_index (int): _description_
col_index (int): _description_
Returns:
int: _description_
"""
# Conway's rules
# 1 with 2 or 3 -> 1 else -> 0
# 0 with 3 -> 1 else 0 | {
"domain": "codereview.stackexchange",
"id": 45034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, cellular-automata",
"url": null
} |
python, beginner, object-oriented, cellular-automata
neighborhood_sum = 0 - self.world[row_index][col_index].state
# Live cell
if self.world[row_index][col_index].state == self.states['1']:
for row in self.world[row_index - 1 : row_index + 2]:
neighborhood_sum += sum(
cell.state for cell in row[col_index - 1 : col_index + 2]
)
if neighborhood_sum == 2 or neighborhood_sum == 3:
# Keeps living
return self.states["1"]
else:
# Dies
return self.states["0"]
else: # Dead cell
for row in self.world[row_index - 1 : row_index + 2]:
neighborhood_sum += sum(
cell.state for cell in row[col_index - 1 : col_index + 2]
)
if neighborhood_sum == 3:
# Revives
return self.states["1"]
else:
# Still dead
return self.states["0"]
def update_world(self, generations: int = 10):
"""Updates world grid using a set of rules
Args:
generations (int, optional): Number of generations. Defaults to 10.
"""
for _ in range(1, generations + 1):
for row_index in range(1, self.world_dim[0]):
for col_index in range(1, self.world_dim[1]):
# Solidification rules
self.new_world[row_index][col_index].state = self.apply_rules(
row_index, col_index
)
# Game of life rules
# self.new_world[row_index][col_index].state = self.game_of_life_rules(
# row_index, col_index
# )
# Update worlds!
self.world = deepcopy(self.new_world)
self.gen += 1 # Update gen counter
def world_to_numpy(self) -> ndarray:
"""Converts world grid to numpy array. | {
"domain": "codereview.stackexchange",
"id": 45034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, cellular-automata",
"url": null
} |
python, beginner, object-oriented, cellular-automata
def world_to_numpy(self) -> ndarray:
"""Converts world grid to numpy array.
Returns:
ndarray: converted world grid.
"""
return array([[cell.state for cell in row] for row in self.world])
def save_world_to_image(self, title: str = None, filename: str = None):
"""Saves the world state as 'png' image.
Args:
title (str, optional): Image title. Defaults to None.
filename (str, optional): file name. Defaults to None.
"""
img = self.world_to_numpy()
plt.imshow(img, cmap="binary")
plt.axis("off")
if title is not None:
plt.title(f"{title}")
else:
plt.title(f"Cellular Automata - Gen {self.gen}")
if filename is not None:
plt.savefig(f"{filename}.png")
else:
plt.savefig(f"ca_{self.gen}.png")
if __name__ == "__main__":
# CA init
ROWS, COLS = 101, 101
ca = CA(world_dim=(ROWS, COLS))
ca.set_cell_value(ROWS // 2, COLS // 2, 1)
# Updates CA and saves images
for _ in range(8):
ca.update_world()
ca.save_world_to_image(filename=f"ca_solification_rules_gen_{ca.gen}.png")
Here are some sample outputs following the solidification rules: | {
"domain": "codereview.stackexchange",
"id": 45034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, cellular-automata",
"url": null
} |
python, beginner, object-oriented, cellular-automata
Here are some sample outputs following the solidification rules:
Answer: It's important that when you use dataclass, you almost always pass slots=True. Other than having performance benefits, it catches type consistency errors. Your world and new_world are missing declarations in CA.
You should refactor your code so that Cell is immutable and its dataclass attribute accepts frozen=True.
It's a strange contract indeed for Cell.__add__ to accept another Cell but produce an integer. Why shouldn't this just return a new Cell whose state is the sum?
You're missing some type hints, e.g. __post_init__(self) -> None.
Don't from numpy import array, ndarray; do the standard import numpy as np and then refer to np.array.
Since state_to_char has keys of contiguous, zero-based integers, just write it as a tuple - or even a string, ' #'.
update_world should accept a method reference, or at least a boolean, to switch between Conway and Solidification modes; you shouldn't have to change the commenting.
title: str = None, filename: str = None is incorrect. Either use title: str | None = None, filename: str | None = None or invoke Optional.
Everything in your __main__ guard is still in global scope, so move it into a main function.
I'm not interested at the moment in optimizing it. I just want to make great Python code
OK, but... Great code that's extremely slow even for the trivial cases isn't great code. It's good that you have a proof of concept, but you should now restart and write a vectorised implementation. | {
"domain": "codereview.stackexchange",
"id": 45034,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, object-oriented, cellular-automata",
"url": null
} |
python
Title: File Organiser in Python
Question: main.py
The "main.py" script is a Python program designed to organize files within a specified directory based on their file extensions. It enhances file organization and grouping for better management by moving files into subdirectories that correspond to specific categories, such as programming languages, file types, and data formats. This script provides a way to efficiently organize and categorize files in a given folder, making it easier to find and manage files of different types.
Notes on main.py
The script uses constants defined in "constants.py" to categorize files into different groups.
It provides a clear structure for adding new categories or modifying existing ones.
The "constants.py" file allows customization of file extensions and categories.
Code
"""_File Organizer_
@date:
August 28, 2023
@version:
1.0
@license:
This code is licensed under the MIT License.
@file:
main.py
@description:
This script is a Python program designed to organize files
within a specified directory into different categories
based on their file extensions. It aims to enhance file
organization and grouping for better management. The script
achieves this by moving files into subdirectories that correspond
to specific categories such as programming languages, file types, and data formats.
@usage:
Run this script with the necessary dependencies installed and provide the name of the folder
you would like to organized. The script will organize the files in that folder.
@example:
$ python main.py
"""
"""_imports_"""
import os
import shutil
import sys
from typing import List
from tqdm import tqdm
from constants import *
#---
# Imported for testing purposes only
#---
from test import run_test, delete_dir
"""_summary_
_desc_: returns the extension of a file name.
_param_: file_name (str): The name of the file. | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
_param_: file_name (str): The name of the file.
_returns_: str: The extension of the file name.
"""
def get_extension(file_name: str) -> str:
return "." + file_name.split(".")[-1].lower()
def move_file(subcategory_dir: str, file: str) -> None:
if not os.path.exists(os.path.join(TARGET_DIR_, subcategory_dir)):
os.makedirs(os.path.join(TARGET_DIR_, subcategory_dir))
source_path = os.path.join(TARGET_DIR_, file)
destination_path = os.path.join(TARGET_DIR_, subcategory_dir, os.path.basename(file))
shutil.move(source_path, destination_path)
"""_summary_
_desc_: organizes files into different categories based on their file extensions. | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
_param_: files (List[str]): A list of file paths.
_returns_: None: This function does not return anything.
"""
def organize_files(files: List[str]) -> None:
#for file in files:
for file in tqdm(files, desc="\n[organizing files]", unit="file"):
if file.lower() != MAKEFILE_:
extension = get_extension(file)
else:
extension = "Makefile"
for extensions, category in file_extensions.items():
if extension in extensions:
category_dir = category
if extension in [".cpp", ".hpp", ".asm", "Makefile"]:
subdir_name = "Cpp"
elif extension in [".c", ".h", ".pch", ".o", ".a"]:
subdir_name = "C"
elif extension in [".java"]:
subdir_name = "Java"
elif extension in [".py", ".pyw", ".ipynb"]:
subdir_name = "Python"
elif extension in [".js", ".html", ".css", ".scss", ".sass", ".php", ".ts"]:
subdir_name = "Web"
elif extension in [".rb"]:
subdir_name = "Ruby"
elif extension in [".cs", ".vs"]:
subdir_name = "CSharp"
elif extension in [".rs"]:
subdir_name = "Rust"
elif extension in [".xlsx", ".xls"]:
subdir_name = "Spreadsheets"
elif extension in [".pptx", ".ppt"]:
subdir_name = "Presentations"
elif extension in [".csv", ".dat", ".db", ".dbf", ".log", ".mdb", ".sav", ".sql", ".json", ".xml"]:
subdir_name = "Data-Sets"
elif extension in [".git"]:
subdir_name = "Git"
elif extension in [".exe"]:
subdir_name = "Executables"
else:
#check if no subdirs are present | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
else:
#check if no subdirs are present
subdir_name = OTHER_STR_
move_file(os.path.join(category_dir, subdir_name), file)
break
else:
move_file(os.path.join(OTHER_STR_), file) | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
"""_summary_
_desc_: exits the program.
_returns_: None
_param_: exit_code: int corresponding to the exit code
"""
def quit(exit_code: int) -> None:
sys.exit(exit_code)
"""_summary_
_desc_: establishes the current directory and returns a list of files in the directory.
_returns_: List[str]: A list of file names in the current directory.
_raises_: FileNotFoundError: If the target directory is not found.
"""
def establish_current_dir() -> List[str]:
try:
with os.scandir(TARGET_DIR_) as entries:
files = [entry.name for entry in entries] # if entry.is_file()
return files
except FileNotFoundError:
print(ERROR_MSG_)
quit(exit_code=1)
def main() -> None:
run_test()
files = establish_current_dir()
organize_files(files)
input("\nPress [Enter] to continue...")
delete_dir()
if __name__ == "__main__":
main()
constants.py
The "constants.py" file contains constants used throughout the program to categorize files into different groups. It defines file extensions and their corresponding categories, making it easy to maintain and expand the categorization system. You can customize the values in this file to fit your specific needs.
Code
"""_File Organizer_
@date:
August 28, 2023
@version:
1.0
@license:
This code is licensed under the MIT License.
@file:
constants.py
@description:
This file contains the constants used throughout the program
@usage:
Change the value of the TARGET_DIR_ variable to the folder you would like organized.
"""
'''_Could be changed to "Desktop" or any folder you would like organized_'''
TARGET_DIR_ = "__TEST__"
'''_List is unhashable, using tuples instead_'''
IMAGES_ = (".jpeg", ".png", ".jpg", ".gif",
".bmp", ".svg", ".tiff", ".heic", ".webp")
TEXT_ = (".txt", ".rtf", ".md")
VIDEO_ = (".mp4", ".mkv", ".avi", ".mov",
".wmv", ".flv", ".ogg", ".webm") | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
VIDEO_ = (".mp4", ".mkv", ".avi", ".mov",
".wmv", ".flv", ".ogg", ".webm")
AUDIO_ = (".mp3", ".wav", ".m4a", ".flac")
APPLICATIONS_ = (".exe", ".lnk", ".msi", ".app")
CODE_ = (".cpp", ".hpp", ".asm", ".js", ".html", ".css", ".scss",
".sass", ".php", ".ts", ".c", ".h", ".pch", ".o", ".a",
".java", ".rb", ".rs", ".py", ".pyw", ".ipynb", ".cs", ".vs"
".xcodeproj")
INSTALL_ = (".dmg", ".pkg", ".deb", ".rpm")
COMPRESSED_ = (".zip", ".rar", ".tar", ".gz", ".7z")
DOCUMENTS_ = (".doc", ".pdf", ".docx", ".ppt", ".pptx", ".odt", ".ods",
".xls", ".xlsx", ".csv", ".dat", ".db", ".dbf", ".log",
".mdb", ".sav", ".sql", ".json", ".xml")
OTHER_ = ("",)
'''_file categories used in organize_files()_'''
file_extensions = {
IMAGES_: "Images",
TEXT_: "Text",
VIDEO_: "Video",
AUDIO_: "Audio",
APPLICATIONS_: "Applications",
CODE_: "Code",
INSTALL_: "Install",
COMPRESSED_: "Compressed",
DOCUMENTS_: "Documents",
OTHER_: "Other"
}
'''_other constants defined for clarity_'''
MAKEFILE_ = "makefile"
OTHER_STR_ = "Other"
ERROR_MSG_ = f"[{TARGET_DIR_} directory not found]\n"
test.py
The "test.py" script provides a testing environment for the file organizer program. It includes functions to create random files with different extensions in a target directory. This allows you to test the file organizer's functionality without affecting your actual files.
Notes on test.py
The script uses random file extensions to simulate a variety of file types for testing purposes.
It ensures that the target directory is created before running tests.
This testing script is separate from the main program and is useful for verifying the file organizer's functionality.
Use the run_test() function to create a set of random files in the specified target directory.
Use the delete_dir() function to remove the target directory and its contents after testing. | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Use the delete_dir() function to remove the target directory and its contents after testing.
Code
"""_File Organizer_
@date:
August 28, 2023
@version:
1.0
@license:
This code is licensed under the MIT License.
@file:
contants.py
@description:
This file contains the constants used throughout the program
@usage:
Chnage the value of the TARGET_DIR_ variable to the folder you would like organized.
"""
"""_imports_"""
import os
import shutil
from typing import List
import random
import string
from constants import *
_MAX_ = 100
"""_summary_
_desc_: creates a new directory and moves a randomly generated file into it.
_param_: None
_returns_: None
"""
def make_dir() -> None:
random_sequence = ''.join(random.choice(string.ascii_lowercase) for _ in range(4))
all_extensions = (
IMAGES_ + TEXT_ + VIDEO_ + AUDIO_ + APPLICATIONS_ + CODE_ +
INSTALL_ + COMPRESSED_ + DOCUMENTS_ + OTHER_
)
random_extension = random.choice(all_extensions)
file_name = random_sequence + random_extension
with open(file_name, "w") as f:
pass
shutil.move(file_name, os.path.join(TARGET_DIR_, file_name))
"""_summary_
_desc_: create a directory if it doesn't exist.
_param_: None
_returns_: None
"""
def establish() -> None:
if not os.path.exists(TARGET_DIR_):
os.makedirs(TARGET_DIR_)
"""_summary_
_desc_: deletes the directory specified by the constant TARGET_DIR_.
_param_: None
_returns_: None
"""
def delete_dir() -> None:
shutil.rmtree(TARGET_DIR_)
"""_summary_
_desc_: run the test by establishing a connection and creating directories.
_param_: None
_returns_:
None
"""
def run_test() -> None:
establish()
for i in range(_MAX_):
make_dir()
Things on the TODO list:
Command line Args -> e.g:
pyhton3 main.py "Downloads"
Using .aksdirectory() from the Tkinter library
Eventually, make a GUI | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
pyhton3 main.py "Downloads"
Using .aksdirectory() from the Tkinter library
Eventually, make a GUI
Note
I got the C++ disease in my freshman year and it's still sort of going on. I am sorry in advance if I insulted anyone with the use of unnecessary underscores, Doxygen style documentation, documenting my functions above the prototype and not inside the body, and defining a separate file for my constants (sort of like a .h file).
Answer: isort
Pep-8
asks that you organize imports into three sections.
As author there's no need to devote a moment's thought to that;
just "$ isort ." every
now and again, and you're done.
from constants import *
The * star makes the meaning of this source code
less obvious to the Gentle Reader;
it slightly obscures it.
Prefer from constants import TARGET_DIR_.
Also, wazzup with that trailing _ underscore?
Typically we follow that convention for local
variables like dir_ or map_,
when we want to avoid shadowing a builtin.
That's not what happening here.
Plus, the identifier is part of your Public API, so
spelling
matters, more than for a local variable.
docstrings
"""_summary_
_desc_: returns the extension of a file name.
_param_: file_name (str): The name of the file.
_returns_: str: The extension of the file name.
"""
I didn't understand that module-level docstring at all;
it's not helping me.
OIC, you meant to write a function docstring:
def get_extension(file_name: str) -> str:
"""_summary_ ...
"""
return "." + file_name.split(".")[-1].lower() | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Nuke the _summary_ tag, it isn't helpful.
Or cite the URL reference of the coding standard you're trying to conform to.
The _desc_ is obvious from the well-chosen function name -- elide it.
Similarly for _param_ and _returns_,
but they additionally have
redundant
type annotations, which I fear can get out of sync with the signature's annotations.
Recommend you specify type in just one place: the function signature.
That way the
mypy
linter (type checker) can offer you automated assistance.
def get_extension(file_name: str) -> str:
This is a perfectly clear and lovely signature that you can keep as-is.
But consider being even more clear by asking caller to pass in a
Path.
The implementation is perfectly nice.
I will note in passing that you chose to pass up
both of these standard methods:
splitext and
suffix.
Maintenance engineers will already be familiar with those,
yet you're asking them to learn a new related API
which has similar but subtly different behavior.
This increases cognitive load and
makes code defect injection during maintenance more likely.
sphinx
OIC, way at the end you offered a Note about conforming to Doxygen format.
Hmmmm. Recommend you adopt
sphinx,
along with standard """docstrings""" between signature and function body.
And as far as choosing names goes, it is pretty important to use
pep-8
conventions if you want to productively collaborate with folks
in the python community.
C++ names are very nice, in that environment,
but they don't work well in other environments like Scheme, Forth, or others.
Learning a new language is about much more than keyword syntax details.
document parameters
def move_file(subcategory_dir: str, file: str) -> None: | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
document parameters
def move_file(subcategory_dir: str, file: str) -> None:
That is a perfectly nice signature, with well-named parameters.
But it needs a """docstring""" that spells out we want
a relative directory spec.
Equivalently you might choose to assert or otherwise
raise an error if that parameter starts with a slash.
if not os.path.exists(os.path.join(TARGET_DIR_, subcategory_dir)): ...
Recall that
makedirs and
mkdir
accept an exist_ok flag.
carefully choose what your Public API returns
_returns_: None: This function does not return anything.
"""
def organize_files(files: List[str]) -> None:
#for file in files:
Keep comments informative.
After i += 1 we don't write "increments the integer index i by exactly one",
and after a return of None we don't write
"This function does not return anything."
The code gives the details;
the comments describe the motivation ("how" vs "why").
The commented for loop was fine during debugging.
But now you're ready to tidy things up and merge down to main
so other project members can interact with and maintain this code.
That's when it is time to delete commented code, prior to requesting review.
if file.lower() != MAKEFILE_:
extension = get_extension(file)
else:
extension = "Makefile" | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Ok, that's just crazy.
Clearly there are "LICENSE" files and many others
which lack a dot suffix.
Special casing each of them as trouble arises won't scale.
Above I mentioned "subtly different" behavior for your helper
plus a pair of standard helpers.
Now we're seeing the chickens come home to roost.
You implemented in a particular way down in the helper,
and at this point you're telling the caller to "lump it!",
that's just the way it is.
The behavior the caller wants here is to receive "" empty string,
rather than ".Makefile".
Design each helper with the caller(s) in mind.
Calling code should be simple, operating at a higher level,
closer to your business goal than to the bits and bytes.
Implementing the helper as you did was fine.
But when you noticed this awkward edge case,
that's when it would have made sense to go refactor the helper.
Messing around with upper M vs lower m in Makefile
is not well-motivated here (no explanatory comment)
and is likely to lead to bugs.
nesting
for file in tqdm(files, desc="\n[organizing files]", unit="file"):
...
for extensions, category in file_extensions.items():
if extension in extensions:
...
if extension in [".cpp", ".hpp", ".asm", "Makefile"]:
subdir_name = "Cpp"
elif extension in [".c", ".h", ".pch", ".o", ".a"]:
subdir_name = "C"
elif ... | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Wow, that's a lot of nesting, there.
I bet you could have identified one or two business concepts within that,
suggesting a function name for an Extract Helper refactor.
The elif chain is not the end of the world.
Consider replacing with
match.
And you should especially consider replacing with a dict.
Whatever you do, bury it down in some helper function.
The move_file() / break / move_file() special casing is awkward.
It appears that Constants.py (unclear why that should be
captilized)
was originally intended to shoulder some responsibility for categorizing,
but that was subsequently abandoned.
DRY --
keep e.g. the CODE list in just one place,
and don't invent synonymous names like WEB.
Downcasing "Makefile" seems odd.
More generally your docstrings should be explaining
what case-insensitive behavior caller should expect, if any.
In establish_current_dir() you
os.scandir(TARGET_DIR_)
which is fine. Apparently a single level of directory nesting
suffices for your use case.
If you ever need more flexibility, remember that
os.walk()
is always ready to recurse for you, and
glob("**/*.txt")
can recurse with a little less effort.
If you retain scandir, I recommend that you process sorted(os.scandir(...))
so the progress report happens in a consistent and human-meaningful way.
test.py
This is not a terrific module name to use for your code.
It regrettably is already defined as a standard part of python --
any SO contributor can successfully run $ python -c 'import test'
Your PYTHONPATH env var disambiguate which one gets used,
either standard or your custom code.
Depending on env var directory order is a recipe for
confusion and higher maintenance costs.
Choose another name, even if only to call it "test1.py".
use unit tests
Use the run_test() function to create a set of random files in the specified target directory.
Use the delete_dir() function to remove the target directory and its contents after testing. | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
python
Those are needlessly complicated instructions.
Consider adding a $ make test target which implements them.
That gives you an opportunity to add an rm -r line
which makes the cleanup crystal clear.
And especially consider inheriting from
unittest.TestCase
in the standard way,
so $ python -m unittest *.py, or $ pytest,
will run the tests.
An automated test is "self evaluating",
it "knows the right answer",
often modeled with an assertEquals(a, b) statement.
Your current test code looks for "correctness"
in the sense of "we didn't crash!"
There's an opportunity to probe the return value of
smaller units like helpers, especially after you've broken out
a couple of helper functions. | {
"domain": "codereview.stackexchange",
"id": 45035,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python",
"url": null
} |
java, mathematics, composition
Title: Mapping composition in Java
Question: (See also the continuation of this post.)
This time, I have a mapping type:
com.github.coderodde.mapping.Mapping.java:
package com.github.coderodde.mapping;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* This class implements a mapping from a domain set to a range set.
*
* @param <D> the domain element type.
* @param <R> the range element type.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Sep 3, 2023)
* @since 1.6 (Sep 3, 2023)
*/
public final class Mapping<D, R> { | {
"domain": "codereview.stackexchange",
"id": 45036,
"lm_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, mathematics, composition",
"url": null
} |
java, mathematics, composition
final Map<D, R> data = new HashMap<>();
public void map(D domainValue, R rangeValue) {
checkDomainValueNotYetMapped(domainValue);
data.put(domainValue, rangeValue);
}
public boolean isMapped(D domainValue) {
return data.containsKey(
Objects.requireNonNull(
domainValue,
"The input domain value is null."));
}
public R map(D domainValue) {
checkDomainValueIsMapped(domainValue);
return data.get(domainValue);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean first = true;
for (Map.Entry<D, R> entry : data.entrySet()) {
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append("(")
.append(entry.getKey())
.append(", ")
.append(entry.getValue())
.append(")");
}
sb.append("]");
return sb.toString();
}
private void checkDomainValueNotYetMapped(D domainValue) {
if (data.containsKey(
Objects.requireNonNull(domainValue, "Domain value is null."))) {
throw new DuplicateDomainValueException(
"Trying to map a domain value ["
+ domainValue
+ "] twice.");
}
}
private void checkDomainValueIsMapped(D domainValue) {
if (!data.containsKey(domainValue)) {
throw new DomainValueIsNotMappedException(
"Domain value [" + domainValue + "] is not mapped.");
}
}
}
Also, I can compose mappings:
com.github.coderodde.mapping.MappingComposition.java:
package com.github.coderodde.mapping;
import java.util.Map; | {
"domain": "codereview.stackexchange",
"id": 45036,
"lm_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, mathematics, composition",
"url": null
} |
java, mathematics, composition
import java.util.Map;
/**
* This class provides facilities for composing mappings.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Sep 3, 2023)
* @since 1.6 (Sep 3, 2023)
*/
public final class MappingComposition {
/**
* Composes two functions together. For example, if
* {@code mapping1 = [(1, 'a'], (2, 'b'), (3, 'c')]} and
* {@code mapping2 = [('a', "Alice"), ('c', "Clarice")]}, then the composed
* mapping is {@code [(1, "Alice"), (3, "Clarice")]}.
*
* @param <D> the domain value type of the first mapping.
* @param <T> the domain value type of the second mapping. This is the same
* as the range value type of the first mapping.
* @param <R> the range value type of the second mapping.
* @param mapping1 the first mapping.
* @param mapping2 the second mapping.
* @return a composed function.
*/
public static <D, T, R> Mapping<D, R> compose(Mapping<D, T> mapping1,
Mapping<T, R> mapping2) {
Mapping<D, R> result = new Mapping<>();
for (Map.Entry<D, T> entry1 : mapping1.data.entrySet()) {
D domainValue = entry1.getKey();
T temporaryValue = entry1.getValue();
if (mapping2.isMapped(temporaryValue)) {
R rangeValue = mapping2.map(temporaryValue);
result.map(domainValue, rangeValue);
}
}
return result;
}
}
... I need some exception definitions:
package com.github.coderodde.mapping; | {
"domain": "codereview.stackexchange",
"id": 45036,
"lm_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, mathematics, composition",
"url": null
} |
java, mathematics, composition
... I need some exception definitions:
package com.github.coderodde.mapping;
/**
* Instances of this class are thrown on occasions where the domain value is not
* yet mapped to a range value.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Sep 3, 2023)
* @since 1.6 (Sep 3, 2023)
*/
public final class DomainValueIsNotMappedException extends RuntimeException {
public DomainValueIsNotMappedException(String exceptionMessage) {
super(exceptionMessage);
}
}
package com.github.coderodde.mapping;
/**
* Instances of this class are thrown on occasions where the domain value is
* already mapped and we are trying to map it to a second range value.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Sep 3, 2023)
* @since 1.6 (Sep 3, 2023)
*/
public final class DuplicateDomainValueException extends RuntimeException {
public DuplicateDomainValueException(String exceptionMessage) {
super(exceptionMessage);
}
}
Finally, the demonstration program follows:
package com.github.coderodde.mapping;
class MappingCompositionDemo { | {
"domain": "codereview.stackexchange",
"id": 45036,
"lm_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, mathematics, composition",
"url": null
} |
java, mathematics, composition
class MappingCompositionDemo {
public static void main(String[] args) {
mapDual();
mapFour();
}
private static void mapDual() {
Mapping<Character, Integer> mapping1 = new Mapping<>();
Mapping<Integer, String> mapping2 = new Mapping<>();
mapping1.map('a', 1);
mapping1.map('b', 2);
mapping1.map('c', 3);
mapping2.map(1, "Alice");
mapping2.map(2, "Clarice");
System.out.println(MappingComposition.compose(mapping1, mapping2));
}
private static void mapFour() {
Mapping<Character, Integer> mapping1 = new Mapping<>();
Mapping<Integer, String> mapping2 = new Mapping<>();
Mapping<String, Long> mapping3 = new Mapping<>();
Mapping<Long, Float> mapping4 = new Mapping<>();
mapping1.map('a', 1);
mapping1.map('b', 2);
mapping1.map('c', 3);
mapping2.map(1, "Alice");
mapping2.map(3, "Clarice");
mapping3.map("Alice", 11L);
mapping3.map("Bob", 12L);
mapping3.map("Clarice", 13L);
mapping4.map(11L, 11.0f);
mapping4.map(12L, 12.0f);
mapping4.map(13L, 13.0f);
System.out.println(
MappingComposition.compose(
MappingComposition.compose(mapping1, mapping2),
MappingComposition.compose(mapping3, mapping4)));
}
}
Demo output
[(a, Alice), (b, Clarice)]
[(a, 11.0), (c, 13.0)]
Critique request
As always, I would like to hear whatever comes to mind. | {
"domain": "codereview.stackexchange",
"id": 45036,
"lm_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, mathematics, composition",
"url": null
} |
java, mathematics, composition
Critique request
As always, I would like to hear whatever comes to mind.
Answer: Since Mapping's domainValue method's parameters represent keys in data map might worth calling them differently closer to their purpose. Probably they are called domainValue since while calling the methods values of other Mappings are passed in.
With exceptions interrupting the flow the MappingCompositionDemo is an example of either all succeed either all fail, if this isn't the intended behaviour the code gets cluttered with try/catch blocks when other scenarios are implemented.
Mapping#toString method's complexity could be improved by appending separator string , after each entry string and deleting the last separator string occurrence before other further appends.
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
for (Map.Entry<D, R> entry : data.entrySet()) {
sb.append("(")
.append(entry.getKey())
.append(", ")
.append(entry.getValue())
.append("), ");
}
sb.delete(sb.length() - 2, sb.length());
sb.append("]");
return sb.toString();
} | {
"domain": "codereview.stackexchange",
"id": 45036,
"lm_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, mathematics, composition",
"url": null
} |
java, algorithm, reinventing-the-wheel, graph
Title: Non-recursive topological ordering, starting from given nodes, for Guava graphs
Question: This method returns the topological ordering of a Guava graph starting from a given set of nodes. It's from my personal project github.com/jbduncan/guava-graph-utils, where I'm exploring utilities for Guava graphs. I'm aware of JGraphT, which has a topological ordering iterator that can be used with Guava graphs, but I'm reinventing the wheel purely for fun.
I'm open to any feedback, but I'm particularly keen for feedback on the inner DeepRecursion class. It was inspired by Iteration from github.com/google/mug and Kotlin's DeepRecursiveFunction, and it turns the underlying depth-first-search-based algorithm from a recursive one to an iterative one to let it run on large inputs. However, I wonder if there's a simpler, easier to read solution, or even a faster one.
Note: this is a stripped-down version of the file with just the relevant method; the Javadoc refers to other methods in the same file, so refer to it if you're interested.
package com.github.jbduncan.guavagraphutils;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.ImmutableList.toImmutableList;
import com.google.common.collect.ImmutableList;
import com.google.common.graph.Graph;
import com.google.common.graph.SuccessorsFunction;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Stream;
import org.checkerframework.checker.nullness.qual.Nullable;
// This class purposefully expands upon an unstable Guava API
@SuppressWarnings("UnstableApiUsage")
public final class MoreGraphs {
private static final String SUCCESSORS_FUNCTION_HAS_AT_LEAST_ONE_CYCLE =
"successors function has at least one cycle"; | {
"domain": "codereview.stackexchange",
"id": 45037,
"lm_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, reinventing-the-wheel, graph",
"url": null
} |
java, algorithm, reinventing-the-wheel, graph
/**
* Returns an immutable list representing the topological ordering of the graph, specifically the
* subgraph that is {@linkplain com.google.common.graph.Graphs#reachableNodes(Graph, Object)
* reachable} from the given starting nodes. A topological ordering is a traversal of the subgraph
* in which each node is visited only after all its {@linkplain Graph#predecessors(Object)
* predecessors} and other ancestors have been visited.
*
* <p>This method is preferable to {@link MoreGraphs#lazyTopologicalOrdering(Graph)
* lazyTopologicalOrdering} and {@link MoreGraphs#topologicalOrdering(Graph) topologicalOrdering}
* when the graph can only be represented as a successors function or when only the subgraph
* reachable from the starting nodes is needed.
*
* <p>The given starting nodes iterable, its elements, and the graph must all be non-null,
* otherwise a {@code NullPointerException} will be thrown.
*
* <p>The given graph may have multiple valid topological orderings. This method does not
* guarantee which topological ordering is returned, even on subsequent calls.
*
* <p>For example, given this graph and starting node {@code a}...
*
* <pre>{@code
* b <--- a ---> d g ---> h
* | | |
* v v v
* e ---> c ---> f i
* }</pre>
*
* <p>...the topological ordering returned can be any of:
*
* <ul>
* <li>{@code [a, b, d, e, c, f]}
* <li>{@code [a, b, e, c, d, f]}
* <li>{@code [a, b, e, d, c, f]}
* <li>{@code [a, b, e, c, f, d]}
* <li>{@code [a, d, b, e, c, f]}
* </ul>
*
* <p>Note that the subgraph {@code {g, h, i}} is not reachable from node {@code a}. Thus, its
* nodes are not included in the topological ordering.
*
* <p>This method only works on directed acyclic graphs. If a cycle is discovered when traversing
* the graph, an {@code IllegalArgumentException} will be thrown.
* | {
"domain": "codereview.stackexchange",
"id": 45037,
"lm_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, reinventing-the-wheel, graph",
"url": null
} |
java, algorithm, reinventing-the-wheel, graph
* the graph, an {@code IllegalArgumentException} will be thrown.
*
* <p>This method runs in linear time, specifically {@code O(N + E)}, where {@code N} is the
* number of nodes in the graph and {@code E} is the number of edges.
*
* @param startingNodes the nodes to start traversing the graph from; the iterable and the nodes
* themselves must not be null
* @param successorsFunction the graph to return a topological ordering for; must not be null
* @param <N> the node type; must have {@link #equals(Object) equals()} and {@link #hashCode()
* hashCode()} implementations as described in "<a
* href='https://github.com/google/guava/wiki/GraphsExplained#graph-elements-nodes-and-edges'>
* Graphs Explained</a>".
* @return an immutable list representing a topological ordering of the graph
* @throws IllegalArgumentException if the graph has a cycle
* @see <a href='https://en.wikipedia.org/wiki/Topological_sorting'>Wikipedia, "Topological
* sorting"</a>
* @see <a href='https://github.com/google/guava/wiki/GraphsExplained'>Graphs Explained</a>
*/
public static <N> ImmutableList<N> topologicalOrderingStartingFrom(
Iterable<N> startingNodes, SuccessorsFunction<N> successorsFunction) {
checkNotNull(startingNodes, "startingNodes");
for (N startingNode : startingNodes) {
checkNotNull(startingNode, "startingNodes has at least one null node");
}
checkNotNull(successorsFunction, "successorsFunction"); | {
"domain": "codereview.stackexchange",
"id": 45037,
"lm_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, reinventing-the-wheel, graph",
"url": null
} |
java, algorithm, reinventing-the-wheel, graph
/*
* Depth-first-search-based algorithm. Derived from [1], in turn derived from Introduction to Algorithms (2nd ed.)
* by Cormen et al.
*
* The original algorithm by Cormen et al. is recursive, which may throw StackOverflowErrors on large inputs, so
* this algorithm uses an iterative "deep recursion" technique to simulate the stack and avoid SOEs.
*
* [1] https://web.archive.org/web/20230225053309/https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
*/
abstract class DeepRecursion<T> {
@FunctionalInterface
interface Closure {
void run();
}
private final Deque<Object> intermediateStack = new ArrayDeque<>();
private final Deque<Object> frameStack = new ArrayDeque<>();
void yieldClosure(Closure closure) {
intermediateStack.push(closure);
}
void yieldValue(T value) {
intermediateStack.push(value);
}
ImmutableList<T> recurse() {
return Stream.generate(this::next)
.takeWhile(Objects::nonNull) // null signals end of data
.collect(toImmutableList())
.reverse();
}
private @Nullable T next() {
while (true) {
while (!intermediateStack.isEmpty()) {
frameStack.push(intermediateStack.pop());
}
if (!frameStack.isEmpty()) {
var next = frameStack.pop();
if (next instanceof Closure closure) {
closure.run();
} else {
// frameStack only contains Ns and Closures, so the type is
// guaranteed to be N here.
@SuppressWarnings("unchecked")
T result = (T) next;
return result;
}
}
if (intermediateStack.isEmpty() && frameStack.isEmpty()) {
return null; // end of data
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45037,
"lm_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, reinventing-the-wheel, graph",
"url": null
} |
java, algorithm, reinventing-the-wheel, graph
class DeepRecursiveTopo extends DeepRecursion<N> {
private enum VisitState {
PARTIALLY_VISITED,
FULLY_VISITED
}
DeepRecursiveTopo() {
var nodeToVisitState = new HashMap<N, VisitState>();
for (N startingNode : startingNodes) {
yieldClosure(() -> visit(startingNode, successorsFunction, nodeToVisitState));
}
}
private void visit(
N node, SuccessorsFunction<N> successorsFunction, Map<N, VisitState> nodeToVisitState) {
var visitState = nodeToVisitState.get(node);
if (visitState == VisitState.FULLY_VISITED) {
return;
}
if (visitState == VisitState.PARTIALLY_VISITED) {
throw new IllegalArgumentException(SUCCESSORS_FUNCTION_HAS_AT_LEAST_ONE_CYCLE);
}
nodeToVisitState.put(node, VisitState.PARTIALLY_VISITED);
for (N successor : successorsFunction.successors(node)) {
yieldClosure(() -> visit(successor, successorsFunction, nodeToVisitState));
}
yieldClosure(() -> nodeToVisitState.put(node, VisitState.FULLY_VISITED));
yieldValue(node);
}
}
return new DeepRecursiveTopo().recurse();
}
private MoreGraphs() {}
}
Answer: Answering my own question, the only things I can think of are:
Remove the successorsFunction and nodeToVisitState parameters from DeepRecursiveTopo.visit(), which either aren't needed or can be fields.
Make DeepRecursion and DeepRecursiveTopo non-local classes to reduce clutter.
Research how others have done iterative depth-first-search-based topological ordering. (Or ask a LLM and thoroughly test it.)
But I'm actually quite fond of the deep recursion technique, so this would be a last resort. | {
"domain": "codereview.stackexchange",
"id": 45037,
"lm_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, reinventing-the-wheel, graph",
"url": null
} |
c++, array, memory-management, pointers, type-safety
Title: Reusable storage for array of objects V2
Question: Here is a follow up on Reusable storage for array of objects, taking into account the provided answers.
The following code should be compliant at least with gcc, clang, msvc and for C++14 and beyond.
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#include <new>
#include <type_traits>
template <typename T>
constexpr T* Launder(T* Ptr) {
#if __cplusplus < 201703L
// Launder in C++<17
return Ptr;
#else
// Launder in C++>=17
return std::launder(Ptr);
#endif
}
// Object constructible from a double
// forcing alignment
struct alignas(16) SFloat {
float val = 0.f;
SFloat() { std::cout << "Constructing a SFloat with default value\n"; };
SFloat(const double v) : val(static_cast<float>(v)) {
std::cout << "Constructing a SFloat from " << v << '\n';
};
SFloat& operator=(SFloat&& f) {
val = f.val;
std::cout << "Move-assigning from a SFloat " << f.val << '\n';
return *this;
}
~SFloat() { std::cout << "Destructing a SFloat holding " << val << '\n'; }
};
// Serialization of Float objects
std::ostream& operator<<(std::ostream& o, SFloat const& f) {
return o << f.val;
} | {
"domain": "codereview.stackexchange",
"id": 45038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
c++, array, memory-management, pointers, type-safety
// type-punning reusable buffer
// holds a non-typed buffer (actually a char*) that can be used to store any
// types, according to user needs
class Buffer {
private:
// destructing functor storage
// required to call the correct object destructors
// using std::function to store a copy of the lambda used
// @1 is there a way to avoid std::function? a mere function pointer could
// be used but it does not compile with msvc/C++14
// @2 std::function does not support noexcept properly how to do better?
std::function<void(Buffer*)> Destructors = [](Buffer*) noexcept {};
// buffer address
unsigned char* Storage = nullptr;
// aligned buffer address
unsigned char* AlignedStorage = nullptr;
// number of stored elements
std::size_t CountOfStoredObjects = 0;
// buffer size in bytes
std::size_t StorageSizeInBytes = 0;
// computes the smallest positive offset in bytes that must be applied to
// Storage in order to have alignment a Alignment is supposed to be a valid
// alignment
std::size_t OffsetForAlignment(unsigned char const* const Ptr,
std::size_t Alignment) noexcept {
std::size_t Res = static_cast<std::size_t>(
reinterpret_cast<std::uintptr_t>(Ptr) % Alignment);
if (Res) {
return Alignment - Res;
} else {
return 0;
}
} | {
"domain": "codereview.stackexchange",
"id": 45038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
c++, array, memory-management, pointers, type-safety
public:
// allocates a char buffer large enough for Counts object of type T and
// default-construct them
template <typename T>
T* DefaultAllocate(const std::size_t Count) {
// Destroy previously stored objects, supposedly ends lifetime of the
// array object that contains them
Destructors(this);
std::size_t RequiredSize = sizeof(T) * Count + alignof(T);
if (StorageSizeInBytes < RequiredSize) {
std::cout << "Requiring " << RequiredSize << " bytes of storage\n";
// @3 creating a storage of RequiredSize bytes
// what would be the C++17+ way of do that? std::aligned_alloc?
Storage = reinterpret_cast<unsigned char*>(
std::realloc(Storage, RequiredSize));
if (Storage == nullptr) {
throw(std::bad_alloc());
}
StorageSizeInBytes = RequiredSize;
// here should do something for the case where Storage is nullptr
}
AlignedStorage = Storage + OffsetForAlignment(Storage, alignof(T));
// @4 Form1 placement array new default construction: ill-defined in
// C++14?
// expecting starting an array object lifetime and the lifetime of
// contained objects
// expecting pointer arithmetic to be valid on tmp T*
// Is the use of Launder correct?
T* tmp = Launder(new (Storage) T[Count]);
// @5 Form2 individually creating packed object in storage
// expecting starting an array object lifetime and the lifetime of
// contained objects
// expecting pointer arithmetic to be valid on tmp T*
// Is the use of Launder correct?
// unsigned char* pos = AlignedStorage;
// T* tmp = Launder(reinterpret_cast<T*>(AlignedStorage));
// for (std::size_t i = 0; i < Count; ++i) {
// new (pos) T();
// pos += sizeof(T);
// } | {
"domain": "codereview.stackexchange",
"id": 45038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
c++, array, memory-management, pointers, type-safety
// update nb of objects
CountOfStoredObjects = Count;
// create destructors functor
// @6 supposedly ends the lifetime of the array object and of the
// contained objects
Destructors = [](Buffer* pobj) noexcept {
T* ToDestruct = reinterpret_cast<T*>(pobj->AlignedStorage);
// Delete elements in reverse order of creation
while (pobj->CountOfStoredObjects > 0) {
--(pobj->CountOfStoredObjects);
// should be std::Destroy(ToDestruct[CountOfStoredObjects]) in
// C++17 I should provide my own implementation in C++14 in
// order to distinguish between fundamental types and other ones
// @ how to formally en the lifetime of a fundamental objects?
// merely rewrite on its memory location?
ToDestruct[(pobj->CountOfStoredObjects)].~T();
}
// @7 How to formally end the array object lifetime?
};
return tmp;
}
// deallocate objects in buffer but not the buffer itself
// actually useless
// template <typename T>
// void Deallocate() {
// Destructors(this);
// }
~Buffer() noexcept {
// Ending objects lifetime
// @8 Actually not throwing and compilers are not complaining
// should I wrap it anyway into a try-catch block?
Destructors(this);
// Releasing storage
std::free(Storage);
}
}; | {
"domain": "codereview.stackexchange",
"id": 45038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
c++, array, memory-management, pointers, type-safety
int main() {
#if (__cplusplus >= 201703L)
std::cout << "C++17\n";
#else
std::cout << "C++14\n";
#endif
constexpr std::size_t N0 = 7;
constexpr std::size_t N1 = 3;
Buffer B;
std::cout << "Test on SomeClass\n";
SFloat* PSFloat = B.DefaultAllocate<SFloat>(N0);
PSFloat[0] = 3.14;
*(PSFloat + 1) = 31.4;
PSFloat[2] = 314.;
std::cout << PSFloat[0] << '\n';
std::cout << PSFloat[1] << '\n';
std::cout << *(PSFloat + 2) << '\n';
std::cout << "Test on float\n";
// reallocating, possibly using existing storage, for a different type and
// size
float* PFloat = B.DefaultAllocate<float>(N1);
PFloat[0] = 3.14f;
*(PFloat + 1) = 31.4f;
PFloat[2] = 314.f;
std::cout << PFloat[0] << '\n';
std::cout << PFloat[1] << '\n';
std::cout << *(PFloat + 2) << '\n';
return 0;
}
Live
Answer: Consider using or reimplementing std::any
// holds a non-typed buffer (actually a char*) that can be used to store any
// types, according to user needs
This is exactly what std::any does, which was added in C++17. I would strongly recommend you use that, or if you need something like this in C++14 projects, then consider making your Buffer a drop-in replacement for std::any, and copy its interface.
Answers to the questions in the code
// @1 is there a way to avoid std::function? a mere function pointer could
// be used but it does not compile with msvc/C++14
A mere function pointer works fine as far as I can tell:
void (*Destructors)(Buffer*) = [](Buffer*) noexcept {};
// @2 std::function does not support noexcept properly how to do better?
I would not worry about it. I don't think it has any impact on runtime performance as long as nothing actually throws. You can still make ~Buffer() noexcept.
// @3 creating a storage of RequiredSize bytes
// what would be the C++17+ way of do that? std::aligned_alloc? | {
"domain": "codereview.stackexchange",
"id": 45038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
c++, array, memory-management, pointers, type-safety
Yes. Or from C++11 up to C++23 there is std::aligned_storage, but this might not deal properly with over-aligned types. Note also that you can use new char[RequiredSize] and delete[] to allocate the uninitialized storage, there is no need to use C's std::malloc()/std::free().
// @4 Form1 placement array new default construction: ill-defined in C++14?
I don't know why this would be ill-defined, unless T has no default constructor.
// Is the use of Launder correct?
T* tmp = Launder(new (Storage) T[Count]);
It's unnecessary to use std::launder() here: the return value of placement-new is already a valid pointer to live objects of type T. The code that is commented out under question @5 uses std::launder() for a good reason.
// @ how to formally en the lifetime of a fundamental objects?
// merely rewrite on its memory location?
ToDestruct[(pobj->CountOfStoredObjects)].~T();
That's perfectly fine for all types of objects, there is no need to use any other code for fundamental objects. The fundamental types have destructors that just do nothing.
// @7 How to formally end the array object lifetime?
Technically, I think you should call the non-allocating placement deallocation variant of operator delete[]. This is what placement-new calls when a constructor throws. However, by default this does absolutely nothing. It's only if the program provides a custom implementation of operator delete[] that you need to worry about this.
// @8 Actually not throwing and compilers are not complaining
// should I wrap it anyway into a try-catch block?
No. If the call to Destructors() throws and you don't catch it, then because your function is noexcept, the exception won't be passed to the caller, but instead std::terminate() will be called.
Possible integer overflow
In this line:
std::size_t RequiredSize = sizeof(T) * Count + alignof(T); | {
"domain": "codereview.stackexchange",
"id": 45038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
c++, array, memory-management, pointers, type-safety
You can have an integer overflow if the result of the calculation is larger than a std::size_t can hold. You should check for this in a safe way:
if (Count > (SIZE_MAX - alignof(T)) / sizeof(T)) {
throw std::bad_alloc("…");
}
Incorrect handling of reallocation failure
In the previous iteration of your code, Toby Speight already pointed out that you are not handling std::realloc() returning nullptr correctly. Your fix is incorrect, and makes the problem even worse. First, if it fails, the original allocation is still valid, but you've thrown away the pointer to it, causing a memory leak. But by throwing, you now also left Destructors to point to the old destructor function which you have already used. So when your Buffer is then destructed, it will be called again, which is incorrect. Carefully reread Toby's answer for the correct way to handle this. | {
"domain": "codereview.stackexchange",
"id": 45038,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
java, unit-testing, file-system
Title: Finding duplicates in given list of files
Question: I implemented a simple tool to find duplicate files, by applying the following strategy:
Take a list of files and return the sets of duplicates (set of sets)
Implement a custom Comparator<File> to compare files by content
Implement another comparator that calls the first one, and when two files are equal, mark them as duplicates, using a "duplicate tracker" helper class
Pass the list of files to Collections.sort, using the custom comparator with the duplicate tracker. The goal of sort algorithms is to reduce the number of comparisons, which seems to suit well for my purpose too.
The main method calling the other pieces:
public class DuplicateFileFinder {
/**
* Find duplicates in given list of files, ignoring I/O errors
*
* @param files the list of files to check
* @return sets of duplicate files
*/
public Set<Set<File>> findDuplicates(List<File> files) {
DuplicateTracker<File> tracker = new DuplicateTracker<>();
Comparator<File> comparator = new FileContentComparator();
Collections.sort(files, (file1, file2) -> {
int cmp = comparator.compare(file1, file2);
if (cmp == 0) {
tracker.add(file1, file2);
}
return cmp;
});
return tracker.getDuplicates();
}
}
The Comparator<File> to compare files by content, ignoring I/O errors:
/**
* A comparator to compare two files by content.
* In case of I/O errors, fall back to default comparator of File.
*/
public class FileContentComparator implements Comparator<File> {
private static final int DEFAULT_BUFSIZE = 1024 * 1024;
private final int bufSize;
public FileContentComparator() {
bufSize = DEFAULT_BUFSIZE;
}
public FileContentComparator(int bufSize) {
this.bufSize = bufSize;
} | {
"domain": "codereview.stackexchange",
"id": 45039,
"lm_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, unit-testing, file-system",
"url": null
} |
java, unit-testing, file-system
public FileContentComparator(int bufSize) {
this.bufSize = bufSize;
}
@Override
public int compare(File file1, File file2) {
int cmpFileSize = Long.compare(file1.length(), file2.length());
if (cmpFileSize != 0) {
return cmpFileSize;
}
if (file1.length() == 0) {
return 0;
}
byte[] buffer1 = new byte[bufSize];
byte[] buffer2 = new byte[bufSize];
try (BufferedInputStream stream1 = new BufferedInputStream(new FileInputStream(file1));
BufferedInputStream stream2 = new BufferedInputStream(new FileInputStream(file2))) {
int bytesRead1;
int bytesRead2;
while (true) {
bytesRead1 = stream1.read(buffer1);
bytesRead2 = stream2.read(buffer2);
assert bytesRead1 == bytesRead2;
if (bytesRead1 == -1) {
break;
}
int cmpBuffers = compareBuffers(buffer1, buffer2, bytesRead1);
if (cmpBuffers != 0) {
return cmpBuffers;
}
}
} catch (IOException e) {
// ignore I/O errors, fall back to default comparison logic
return file1.compareTo(file2);
}
return 0;
}
private int compareBuffers(byte[] buffer1, byte[] buffer2, int size) {
for (int i = 0; i < size; ++i) {
int cmp = Byte.compare(buffer1[i], buffer2[i]);
if (cmp != 0) {
return cmp;
}
}
return 0;
}
}
The class to track duplicates:
/**
* Track objects that are considered duplicates.
* (Completely unrelated to logical equality by .equals, or identity by ==)
*
* @param <T>
*/
public class DuplicateTracker<T> {
private final Map<T, Set<T>> pools = new HashMap<>(); | {
"domain": "codereview.stackexchange",
"id": 45039,
"lm_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, unit-testing, file-system",
"url": null
} |
java, unit-testing, file-system
private final Map<T, Set<T>> pools = new HashMap<>();
public void add(T item1, T item2) {
Set<T> pool1 = pools.get(item1);
Set<T> pool2 = pools.get(item2);
if (pool1 == null && pool2 == null) {
pool1 = new HashSet<>();
pool1.add(item1);
pool1.add(item2);
pools.put(item1, pool1);
pools.put(item2, pool1);
} else if (pool1 == null) {
pool2.add(item1);
pools.put(item1, pool2);
} else if (pool2 == null) {
pool1.add(item2);
pools.put(item2, pool1);
} else if (pool1 != pool2) {
pool1.addAll(pool2);
for (T item : pool2) {
pools.put(item, pool1);
}
pool2.clear();
}
}
public Set<Set<T>> getDuplicates() {
Set<Set<T>> duplicates = new HashSet<>();
duplicates.addAll(pools.values());
return duplicates;
}
}
Unit tests for the duplicate finder:
public class DuplicateFileFinderTest {
private final DuplicateFileFinder duplicateFileFinder = new DuplicateFileFinder();
@Rule
public TemporaryFolder tmpDir = new TemporaryFolder();
private File createTempFileWithContent(String content) throws IOException {
File file = tmpDir.newFile();
FileWriter writer = new FileWriter(file);
writer.append(content);
writer.close();
return file;
}
private Set<File> toSet(File... files) {
Set<File> set = new HashSet<>();
set.addAll(Arrays.asList(files));
return set;
}
@Test
public void should_find_no_duplicates() throws IOException {
File file1 = createTempFileWithContent("foo");
File file2 = createTempFileWithContent("bar");
List<File> files = Arrays.asList(file1, file2);
assertEquals(0, duplicateFileFinder.findDuplicates(files).size());
} | {
"domain": "codereview.stackexchange",
"id": 45039,
"lm_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, unit-testing, file-system",
"url": null
} |
java, unit-testing, file-system
assertEquals(0, duplicateFileFinder.findDuplicates(files).size());
}
@Test
public void should_find_2_of_2_duplicates() throws IOException {
String content = "blah";
File file1 = createTempFileWithContent(content);
File file2 = createTempFileWithContent(content);
List<File> files = Arrays.asList(file1, file2);
Set<Set<File>> duplicates = Collections.singleton(toSet(file1, file2));
assertEquals(duplicates, duplicateFileFinder.findDuplicates(files));
}
@Test
public void should_find_5_of_5_duplicates() throws IOException {
String content = "blah";
File file1 = createTempFileWithContent(content);
File file2 = createTempFileWithContent(content);
File file3 = createTempFileWithContent(content);
File file4 = createTempFileWithContent(content);
File file5 = createTempFileWithContent(content);
List<File> files = Arrays.asList(file1, file2, file3, file4, file5);
Set<Set<File>> duplicates = Collections.singleton(toSet(file1, file2, file3, file4, file5));
assertEquals(duplicates, duplicateFileFinder.findDuplicates(files));
}
@Test
public void should_find_2_of_3_duplicates() throws IOException {
String content = "blah";
String differentContent = "balm";
File file1 = createTempFileWithContent(content);
File file2 = createTempFileWithContent(content);
File file3 = createTempFileWithContent(differentContent);
List<File> files = Arrays.asList(file1, file2, file3);
Set<Set<File>> duplicates = Collections.singleton(toSet(file1, file2));
assertEquals(duplicates, duplicateFileFinder.findDuplicates(files));
}
@Test
public void should_find_2_sets_of_duplicates_among_5() throws IOException {
String content = "blah";
String anotherContent = "balm";
String yetAnotherContent = "bulk"; | {
"domain": "codereview.stackexchange",
"id": 45039,
"lm_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, unit-testing, file-system",
"url": null
} |
java, unit-testing, file-system
File file1 = createTempFileWithContent(content);
File file2 = createTempFileWithContent(content);
File file3 = createTempFileWithContent(anotherContent);
File file4 = createTempFileWithContent(anotherContent);
File file5 = createTempFileWithContent(yetAnotherContent);
List<File> files = Arrays.asList(file1, file2, file3, file4, file5);
Set<Set<File>> duplicates = new HashSet<>(Arrays.asList(
toSet(file1, file2),
toSet(file3, file4)
));
assertEquals(duplicates, duplicateFileFinder.findDuplicates(files));
}
}
Unit tests for the duplicate tracker:
public class DuplicateTrackerTest {
static class Item {
// Inherits default .equals and .hashCode
// -> instances will not be equal, with distinct hash code
}
private DuplicateTracker<Item> newTracker() {
return new DuplicateTracker<>();
}
@Test
public void should_create_common_pool_for_2_items() {
DuplicateTracker<Item> tracker = newTracker();
tracker.add(new Item(), new Item());
Set<Set<Item>> duplicates = tracker.getDuplicates();
assertEquals(1, duplicates.size());
assertEquals(2, duplicates.iterator().next().size());
}
@Test
public void should_create_common_pool_for_3_items() {
DuplicateTracker<Item> tracker = newTracker();
Item item = new Item();
tracker.add(item, new Item());
tracker.add(item, new Item());
Set<Set<Item>> duplicates = tracker.getDuplicates();
assertEquals(1, duplicates.size());
assertEquals(3, duplicates.iterator().next().size());
}
@Test
public void should_find_pool_of_second_when_exists() {
DuplicateTracker<Item> tracker = newTracker();
Item item = new Item();
tracker.add(item, new Item());
tracker.add(new Item(), item); | {
"domain": "codereview.stackexchange",
"id": 45039,
"lm_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, unit-testing, file-system",
"url": null
} |
java, unit-testing, file-system
Set<Set<Item>> duplicates = tracker.getDuplicates();
assertEquals(1, duplicates.size());
assertEquals(3, duplicates.iterator().next().size());
}
@Test
public void should_create_distinct_pools_for_2_pairs_of_items() {
DuplicateTracker<Item> tracker = newTracker();
tracker.add(new Item(), new Item());
tracker.add(new Item(), new Item());
Set<Set<Item>> duplicates = tracker.getDuplicates();
assertEquals(2, duplicates.size());
Iterator<Set<Item>> iterator = duplicates.iterator();
assertEquals(2, iterator.next().size());
assertEquals(2, iterator.next().size());
}
@Test
public void should_merge_pools() {
DuplicateTracker<Item> tracker = newTracker();
Item ofPool1 = new Item();
Item ofPool2 = new Item();
tracker.add(ofPool1, new Item());
tracker.add(ofPool2, new Item());
tracker.add(ofPool1, ofPool2);
Set<Set<Item>> duplicates = tracker.getDuplicates();
assertEquals(1, duplicates.size());
assertEquals(4, duplicates.iterator().next().size());
}
}
I'm looking for any and all suggestions to do this better, including testing.
A command line client is in the works, but not ready yet. The project is on GitHub. | {
"domain": "codereview.stackexchange",
"id": 45039,
"lm_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, unit-testing, file-system",
"url": null
} |
java, unit-testing, file-system
Answer: The default comparison logic is File.compareTo, which compares
pathnames. That doesn't seem too useful when comparing file contents.
I guess the assert is fine if you disregard the race condition between
looking at the file size and reading the file; then again, the
stacktrace in that case wouldn't be too user friendly.
For the compareBuffers function I'd look for some function that
operates on more than a single byte per iteration. Possibly only
comparing for equality till a mismatch occurs and only then checking
with Byte.compare.
The HashSet in getDuplicates could be constructed by passing the
values directly into the constructor, same for the toSet method.
That said I agree with computing some checksum to improve performance. | {
"domain": "codereview.stackexchange",
"id": 45039,
"lm_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, unit-testing, file-system",
"url": null
} |
javascript, html5, canvas, plugin
Title: An extended JavaScript plugin for rendering radial pie charts
Question: (This post is the continuation of A JavaScript plugin for rendering radial pie charts.)
(See the continuation of this post.)
Now, you can mark up the radial pie charts via XML:
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Radial pie chart demo</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="rodde-radial-pie-chart.js" defer></script>
</head>
<body>
<h3>Introduction</h3>
<rodde-radial-pie-chart start-angle="30"
maximum-radius="200"
empty-pie-chart-color="grey"
canvas-background-color="#333">
<entry value="100" color="black"></entry>
<entry value="80" color="#faa"></entry>
<entry value="50" color="#a12bc3"></entry>
</rodde-radial-pie-chart>
<p>Some text here.</p>
<rodde-radial-pie-chart>
<entry value="100" color="black"></entry>
<entry value="80" color="red"></entry>
<entry value="50" color="blue"></entry>
<entry value="70" color="orange"></entry>
</rodde-radial-pie-chart>
</body>
</html>
rodde-radial-pie-chart.js:
class RadialPieChart {
#canvas_id;
#entries = [];
#maximum_radius;
#start_angle;
#empty_pie_chart_color;
#canvas_background_color;
constructor(canvas_id,
maximum_radius = 100,
start_angle = 0.0,
empty_pie_chart_color = "#000",
canvas_background_color = "#fff") {
this.#canvas_id = canvas_id;
this.#maximum_radius =
RadialPieChart.#validateMaximumRadius(maximum_radius);
start_angle %= 360.0;
if (start_angle < 0.0) {
start_angle += 360.0;
} | {
"domain": "codereview.stackexchange",
"id": 45040,
"lm_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, html5, canvas, plugin",
"url": null
} |
javascript, html5, canvas, plugin
if (start_angle < 0.0) {
start_angle += 360.0;
}
this.#start_angle = start_angle;
this.#empty_pie_chart_color = empty_pie_chart_color;
this.#canvas_background_color = canvas_background_color;
}
addEntry(value, color) {
const entry = {
"value": RadialPieChart.#validateValue(value),
"color": color
};
this.#entries.push(entry);
}
getMaximumRadius() {
return this.#maximum_radius;
}
getStartAngle() {
return this.#start_angle;
}
getValueAt(index) {
this.#checkIndex(index);
return this.#entries[index]["value"];
}
getColorAt(index) {
this.#checkIndex(index);
return this.#entries[index]["color"];
}
setStartAngle(start_angle) {
this.#start_angle = start_angle;
this.#start_angle %= 360.0;
if (this.#start_angle < 0.0) {
this.#start_angle += 360.0;
}
}
setMaximumRadius(new_maximum_radius) {
this.#validateValue(new_maximum_radius);
this.#maximum_radius = new_maximum_radius;
}
setValueAt(index, new_value) {
this.#checkIndex(index);
this.#entries[index]["value"] = this.#validateValue(new_value);
}
setColorAt(index, new_color) {
this.#checkIndex(index);
this.#entries[index]["color"] = new_color;
}
removeEntry(index) {
if (this.#entries.length === 0) {
throw "Removing from an empty list.";
}
this.#checkIndex(index);
this.#entries.splice(index, 1);
}
render() {
const canvas = document.getElementById(this.#canvas_id);
const ctx = canvas.getContext("2d");
ctx.canvas.width = this.#maximum_radius * 2;
ctx.canvas.height = this.#maximum_radius * 2; | {
"domain": "codereview.stackexchange",
"id": 45040,
"lm_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, html5, canvas, plugin",
"url": null
} |
javascript, html5, canvas, plugin
// Fill the entire chart background:
ctx.fillStyle = this.#canvas_background_color;
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
if (this.#entries.length === 0) {
// Once here, there is no entries in the list.
// Just fill the circle with empty_pie_chart_color:
this.#fillEmptyCircle(ctx);
} else {
this.#renderEntries(ctx);
}
}
static #validateValue(value) {
if (value < 0) {
throw "Value (" + value + ") can not be negative.";
}
return value;
}
static #validateMaximumRadius(maximum_radius) {
if (maximum_radius <= 0) {
throw "Maximum radius (" + maximum_radius + ") is not positive.";
}
return maximum_radius;
}
#checkIndex(index) {
if (this.#entries.length === 0) {
throw "Indexing an empty list.";
}
if (index < 0) {
throw "Index (" + index + ") cannot be negative.";
}
if (index >= this.#entries.length) {
throw "Index (" + index + ") is too large. Must be at most "
+ this.#entries.length + ".";
}
}
#fillEmptyCircle(ctx) {
const width = ctx.canvas.width;
const height = ctx.canvas.height;
const centerX = width / 2;
const centerY = height / 2;
const radius = width / 2;
ctx.beginPath();
ctx.arc(centerX,
centerY,
radius,
0.0,
2 * Math.PI,
false);
ctx.fillStyle = this.#empty_pie_chart_color;
ctx.fill();
}
#renderEntries(ctx) {
const angle_per_entry = 360.0 / this.#entries.length; | {
"domain": "codereview.stackexchange",
"id": 45040,
"lm_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, html5, canvas, plugin",
"url": null
} |
javascript, html5, canvas, plugin
#renderEntries(ctx) {
const angle_per_entry = 360.0 / this.#entries.length;
for (var i = 0, n = this.#entries.length; i !== n; i++) {
var entry_start_angle = -90.0 + this.#start_angle + angle_per_entry * i;
var entry_end_angle = entry_start_angle + angle_per_entry;
this.#drawEntry(ctx,
entry_start_angle,
entry_end_angle,
this.#entries[i]["value"],
this.#entries[i]["color"]);
}
}
#drawEntry(ctx, start_angle, end_angle, value, color) {
const centerX = this.#maximum_radius;
const centerY = this.#maximum_radius;
const maximum_value = this.#findMaximumValue();
const radius = this.#maximum_radius * (value / maximum_value);
ctx.beginPath();
ctx.arc(centerX,
centerY,
radius,
(start_angle / 180.0) * Math.PI,
(end_angle / 180.0) * Math.PI);
ctx.lineTo(centerX, centerY);
ctx.fillStyle = color;
ctx.fill();
}
#findMaximumValue() {
var maximum_value = 0;
for (var i = 0, n = this.#entries.length; i !== n; i++) {
const tentative_maximum_value = this.#entries[i]["value"];
maximum_value = Math.max(maximum_value, tentative_maximum_value);
}
return maximum_value;
}
}
function populatePieChartWithEntries(rpc, pie_chart) {
const entries = pie_chart.getElementsByTagName("entry");
for (var i = 0, n = entries.length; i !== n; i++) {
const entry = entries[i];
const value = entry.getAttribute("value");
const color = entry.getAttribute("color");
rpc.addEntry(value, color);
}
}
function getRadialPieChartCanvasID(number) {
return "radial-pie-chart-canvas-id-" + number;
} | {
"domain": "codereview.stackexchange",
"id": 45040,
"lm_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, html5, canvas, plugin",
"url": null
} |
javascript, html5, canvas, plugin
function getRadialPieChartCanvasID(number) {
return "radial-pie-chart-canvas-id-" + number;
}
function typesetSinglePieChart(pie_chart, number) {
const canvas = document.createElement("canvas");
canvas.id = getRadialPieChartCanvasID(number);
pie_chart.appendChild(canvas);
const start_angle = pie_chart.getAttribute("start-angle") || 0;
const maximum_radius = pie_chart.getAttribute("maximum-radius") || 100;
canvas.width = maximum_radius * 2;
canvas.height = maximum_radius * 2;
const empty_pie_chart_color =
pie_chart.getAttribute("empty-pie-chart-color") || "#000";
const canvas_background_color =
pie_chart.getAttribute("canvas-background-color") || "#fff";
const rpc = new RadialPieChart(canvas.id,
maximum_radius,
start_angle,
empty_pie_chart_color,
canvas_background_color);
populatePieChartWithEntries(rpc, pie_chart);
rpc.render();
}
function typesetAllPieCharts() {
const pie_charts = document.getElementsByTagName("rodde-radial-pie-chart");
var number = 1;
for (var i = 0, n = pie_charts.length; i !== n; i++) {
typesetSinglePieChart(pie_charts[i], number++);
}
}
typesetAllPieCharts();
Critique request
As always, please tell me anything that comes to mind.
Demo output
You can see the result of the above here.
Answer: First off, that isn't "XML". Those are custom HTML elements.
Most of the code in typesetSinglePieChart belongs in the constructor.
You don't need the default values there, because you already have them on the constructor parameters.
Creating, attaching and sizing the canvas can be done there.
populatePieChartWithEntries belongs inside the constructor, too. | {
"domain": "codereview.stackexchange",
"id": 45040,
"lm_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, html5, canvas, plugin",
"url": null
} |
javascript, html5, canvas, plugin
You don't need to assign an ID to the canvas. Store the reference to the canvas directly instead of its ID in the class.
Instead of attaching your class to the custom HTML elements yourself, consider creating a web component.
It is convention to use camelCase for variables instead of snake_case, e.g. emptyPieChartColor. | {
"domain": "codereview.stackexchange",
"id": 45040,
"lm_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, html5, canvas, plugin",
"url": null
} |
javascript, node.js, authorization
Title: Permissions system in MERN app
Question: I am working on a MERN stack app that is a CRM with a couple of modules. Now when the user sends x request to the server to do a supposed action (such as delete something), the server first checks if the user has access by checking the MongoDB database users' collection's permissions property for an array of "permissions" that looks something like this:
[
{ name: "Leads", level: 1 },
{ name: "Conversations", level: 1 },
{ name: "Salesbot", level: 0 },
{ name: "Reporting", level: 1 },
{ name: "Contacts", level: 4 },
]
This states the level of permission this user has for each module. There are 5 possible levels conveying different amounts of access, these are:
None
Accepted only
Read
Write
All
Each level automatically grants access to the levels that would be before it. So if the user has write permission, he would logically, also have read permission as well.
I wrote a function that I call every time to check if the user has X relevant permission before doing something on the server.
The function is as follows:
const checkPermission = (permissions, checkFor) => {
for (let i = 0; i < permissions.length; i++) {
const permission = permissions[i];
if (
permission.name === checkFor.name &&
permission.level >= checkFor.level
) {
return true;
}
}
return false;
};
and then I call it this way:
checkPermission(
[
{ name: "Leads", level: 1 },
{ name: "Conversations", level: 1 },
{ name: "Salesbot", level: 0 },
{ name: "Reporting", level: 1 },
{ name: "Contacts", level: 4 },
],
{ name: "Contacts", level: 3 }
); | {
"domain": "codereview.stackexchange",
"id": 45041,
"lm_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, node.js, authorization",
"url": null
} |
javascript, node.js, authorization
So this function call checks to see if the user has write access in the contacts module, and if they do, then it returns true, if they don't, then false.
I welcome any sort of improvements to the code, but most importantly, I would welcome improvements to the logic of permissions if there are any. I came up with this permissions levels system on my own without much research, so there could be many things in this that I would be neglecting unknowingly that you guys can point out. Perhaps an entirely new way of handling permissions or whatever, I welcome any sort of improvements.
Answer: The best approach will depend on how scalable / flexible you want your approach to be. If your app works perfectly as-is and you never intend to make any changes, the current permissions system may be sufficient. But let's pretend you have a client and they ask some questions.
What if I have millions of users?
Could we work with permissions that can't be ordered?
An example might be Append and Delete for some queue of requests: clients might only be allowed to Append new requests, while some processing server might only be allowed to Delete requests as they are finished.
Can your solution scale with a large number of permissions?
What if I want to set one permission without considering the other permissions? | {
"domain": "codereview.stackexchange",
"id": 45041,
"lm_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, node.js, authorization",
"url": null
} |
javascript, node.js, authorization
The current approach might have a tough time on these questions. To solve (1), you can make permissions an unordered map (dictionary with keys) from each user string to each user level. Unordered maps have O(1) search, insertion, and deletion time on average. To solve the next 3 questions, you could replace level with a more sophisticated policy object. Your policy could be an unordered map from actions (strings) to whether they are allowed (true or false). This would allow users to easily share a commonly used policy. Since nonexistent object members are undefined in JavaScript, this has the added bonus of instantly rejecting requests where actions not in the policy (invalid or unspecified) are requested. If we deny all requests by default, this has the added advantage of making it easy to allow a single action or a small group of actions, knowing that all other actions will be rejected by default. I would suggest user instead of name since that is what Passport uses. You can also use TypeScript for more readability and automated checking:
// checking policies, permissions, requests
type policy = {
[action: string]: boolean;
};
const checkPolicy = (policy: policy, action: string) => {
return policy[action] === true;
};
type permissions = {
[user: string]: policy;
};
type request = {
user: string;
action: string;
};
const checkPermission = (permissions: permissions, request: request) => {
const user = request.user;
if (permissions.hasOwnProperty(user))
return checkPolicy(permissions[user], request.action);
return false;
};
// testing
const testPerms = {
Leads: {
accepted: true,
},
Conversations: {
accepted: true,
},
Salesbot: {},
Reporting: {
accepted: true,
},
Contacts: {
accepted: true,
read: true,
write: true,
all: true,
},
Unordered: {
accepted: true,
read: false,
write: true,
all: false,
},
}; | {
"domain": "codereview.stackexchange",
"id": 45041,
"lm_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, node.js, authorization",
"url": null
} |
javascript, node.js, authorization
let test1 = checkPermission(testPerms, { user: 'Contacts', action: 'write' });
let test2 = checkPermission(testPerms, { user: 'Contacts', action: '?' });
let test3 = checkPermission(testPerms, { user: 'Salesbot', action: 'write' });
let test4 = checkPermission(testPerms, { user: 'Unordered', action: 'read' });
let test5 = checkPermission(testPerms, { user: 'Unordered', action: 'write' });
In my opinion, this adjusted approach is also more readable / explicit. I put together a small app in StackBlitz to demonstrate the results. Let's think of some other potential client questions:
Can requests be subjected to multiple contextual policies?
Can policies correspond to particular databases / resources, perhaps using regular expression matching?
Can we add blacklists (deny) in addition to whitelists (allow)?
At that point, you might as well use the Amazon Web Services (AWS) Identity and Access Management (IAM) system, with its policy elements and complex evaluation logic. I lifted the request / policy / action terminology from AWS IAM, as it is a highly sophisticated and widely used permissions system. | {
"domain": "codereview.stackexchange",
"id": 45041,
"lm_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, node.js, authorization",
"url": null
} |
java, recursion
Title: Ackermann Function of (4,2)
Question: How efficient is this program? How could I make it more efficient?
package main;
import java.math.BigInteger;
public class Ackermann {
public static void main(String[] args) {
System.out.println(ack(BigInteger.valueOf(4),BigInteger.valueOf(2)));
}
public static BigInteger ack(BigInteger a, BigInteger b) {
BigInteger ans;
if (a.equals(BigInteger.ZERO)) ans = b.add(BigInteger.ONE);
else if (b.equals(BigInteger.ZERO)) ans = ack(a.subtract(BigInteger.ONE),BigInteger.valueOf(1));
else ans = ack(a.subtract(BigInteger.ONE), ack(a,b.subtract(BigInteger.ONE)));
return (ans);
}
}
Answer: The Ackermann function is not designed to be efficient... ;-) It is designed to be a counter-proof to a theoretical construct.
But, the reality is that the BigInteger is required. The conditions are required.
About the only things I can suggest are:
use better names
return-early logic
the ans variable is unnecessary
always use braces for conditional blocks.
BigInteger.ONE is already defined, you have used it in some places already, no need for BigInteger.valueOf(1)
call it ackermann not ack
I would have:
public static BigInteger ackermann(BigInteger a, BigInteger b) {
if (a.equals(BigInteger.ZERO)) {
return b.add(BigInteger.ONE);
}
if (b.equals(BigInteger.ZERO)) {
return ackermann(a.subtract(BigInteger.ONE),BigInteger.ONE);
}
return ackermann(a.subtract(BigInteger.ONE), ackermann(a, b.subtract(BigInteger.ONE)));
} | {
"domain": "codereview.stackexchange",
"id": 45042,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, recursion",
"url": null
} |
bash, shell, automation, jq, vscode
Title: VSCode-Portable Updater (MSYS2)
Question: VSCode's portable mode doesn't support auto-updates, unlike its normal installer-based versions. I happen to use MSYS2's UCRT64 environment which makes the Linux tools I like play nice with the Windows environment I need, so I wrote a script to do the updating for me.
I prefer zsh, but shellcheck doesn't support zsh or the #!/bin/env $SHELL construct, so I had to use #!/bin/bash to get it to check my script. It also choked on one of my comments which started with # shellcheck, which it interpreted as meaning something, so I had to remove that. Nevertheless, here is the script as I wrote it originally (not getting shellcheck to run on it):
#!/bin/env bash
DEBUG=0
if [[ "$1" == "--debug" ]]; then
DEBUG=1
fi
instdir="/c/Users/User/Applications/vscode"
# code --version doesn't like sed, so we do it the janky way
lver=$(code --version | head -n 2 | tail -n 1)
lnam=$(code --version | head -n 1)
echo "Checking for updates..."
checkdir="$HOME/tmp-vsc-upd"
checkres="$checkdir/tmp-vsc-checkres"
mkdir -p "$checkdir"
curl -s "https://update.code.visualstudio.com/api/update/win32-x64-archive/stable/$lver" -o "$checkres"
if [[ $(wc -l "$checkres") = 0 ]]; then
[[ "$DEBUG" -ne 0 ]] && rm -r "$checkdir"
echo "No updates found."
exit 0
fi
uver=$(jq .version "$checkres" | cut -c 2- | rev | cut -c 3- | rev)
unam=$(jq .name "$checkres" | cut -c 2- | rev | cut -c 3- | rev)
echo "Local version: $lnam ($lver)"
echo "Upstream version: $unam ($uver)"
# shellcheck suggests pgrep, but MSYS2's pgrep can't see Windows processes
if [[ $(ps -eW | grep -c "Code.exe") -gt 0 ]]; then
[[ "$DEBUG" -ne 0 ]] && rm -r "$checkdir"
echo "Close VSCode before updating."
exit 0
fi
read -r -n 1 -p "Replace local version with upstream version? (y/N) " action
if [[ -z "$action" ]]; then
action="n"
else
echo ""
fi | {
"domain": "codereview.stackexchange",
"id": 45043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, shell, automation, jq, vscode",
"url": null
} |
bash, shell, automation, jq, vscode
case "$action" in
y|Y )
echo "Downloading new version..."
src=$(jq .url "$checkres" | cut -c 2- | rev | cut -c 3- | rev)
out="$checkdir/VSCode-win32-x64-$unam.zip"
curl -o "$out" "$src"
echo "Checking file integrity..."
upsum=$(jq .sha256hash "$checkres" | cut -c 2- | rev | cut -c 3- | rev)
acsum=$(sha256sum "$out" | cut -d ' ' -f 1)
if [[ "$upsum" == "$acsum" ]]; then
echo "File OK."
else
[[ "$DEBUG" -ne 0 ]] && rm -r "$checkdir"
echo "File may be corrupted:"
echo " Expected: $upsum"
echo " Received: $acsum"
echo "Aborting."
exit 0
fi
echo "Extracting files..."
unzip -u -o -qq "$out" -d "$instdir"
echo "Finished extracting."
echo ""
[[ "$DEBUG" -ne 0 ]] && rm -r "$checkdir"
echo "Finished updating."
exit 0
;;
* )
[[ "$DEBUG" -ne 0 ]] && rm -r "$checkdir"
echo "Aborting."
exit 0
;;
esac
I would have to download multiple versions of VSCode to properly test this out, so I didn't do that. But it did automate my 6 minute task in 6 hours once.
shellcheck is happy with my little script, but there are probably more improvements to be made that it can't see / wasn't designed to see.
Answer: It's a pretty nice script, I like it. Special thanks for checking the script with shellcheck!
Check for requirements early
The program depends on some non-standard tools such as jq.
It's good to check early in the script if the required tools actually exist and fail early with a clear message, rather letting the program crash later due to the missing tool, and without a helpful message.
Check if a file is empty using [[ -s path/to/file ]]
I don't have MSYS at hand to verify, but this should not work:
if [[ $(wc -l "$checkres") = 0 ]]; then | {
"domain": "codereview.stackexchange",
"id": 45043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, shell, automation, jq, vscode",
"url": null
} |
bash, shell, automation, jq, vscode
if [[ $(wc -l "$checkres") = 0 ]]; then
The issue is that when invoked as wc -l path/to/file, the output is formatted as " <path/to/file>", so the condition will never be true.
To get just the count from wc without the path, you could invoke it as wc -l < path/to/file (notice the input redirection):
if [[ $(wc -l < "$checkres") = 0 ]]; then
But since you don't actually need to count lines, you just want to know if the file is empty or not, you could use the test -s builtin:
if ! [[ -s "$checkres" ]]; then
Use the exit code of grep to check if match was found
Instead of Command Substitution with $(...), counting lines and a numeric comparison like this:
if [[ $(ps -eW | grep -c "Code.exe") -gt 0 ]]; then
It's better to use the exit code of grep to check if a match was found or not:
if ps -eW | grep -q "Code.exe"; then
Note that this is especially useful in combination with the -q flag of grep, which makes it stop searching in the input as soon as it found a match.
An aside, in many systems this command would also match the grep command itself. A common workaround is to make the expression to match a pattern:
if ps -eW | grep -q "[C]ode.exe"; then
Get raw values from jq output using -r
This is hacky and inefficient way to strip the enclosing double-quotes from values in the output of jq, using multiple processes:
uver=$(jq .version "$checkres" | cut -c 2- | rev | cut -c 3- | rev)
A much simpler solution is possible thanks to the -r or --raw-output flag:
uver=$(jq -r .version "$checkres")
Use better variable names
I find the script hard to read because the variable names are a bit cryptic.
I recommend to rename them so they describe better their purpose, for example:
lnam -> current_version_name
lver -> current_version_hash
unam, uver -> like lnam, lver
upsum -> expected_checksum
acsum -> actual_checksum
... really, all the variables...
A simpler way to read the first two lines from a command
Instead of: | {
"domain": "codereview.stackexchange",
"id": 45043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, shell, automation, jq, vscode",
"url": null
} |
bash, shell, automation, jq, vscode
A simpler way to read the first two lines from a command
Instead of:
lver=$(code --version | head -n 2 | tail -n 1)
lnam=$(code --version | head -n 1)
You could use read:
{ read -r lnam; read -r lver; } < <(code --version)
Alternatively, using an array:
version_info=($(code --version))
lnam=${version_info[0]}
lver=${version_info[1]}
Exit with non-zero code in case of failures
The script does exit 0 at multiple places when it detects that something is off.
The recommended practice is to exit with a non-zero code to signal that the execution was a failure.
Using exit 1 is fine solution.
Use set -euo pipefail to fail fast on errors
A common mistake in scripts is forgetting to check that some important command runs successfully, and by default Bash will continue running the rest of the script, which may cause severe harm.
A good simple safeguard is to include set -euo pipefail at the top of the script, which will make Bash abort on the first failure, and also treat referencing unassigned variables as an error, among other things. For more details see help set and man bash.
Minor nits
echo "" is really the same as echo, no need for the empty string parameter.
In a command like curl -s "long url" -o "short value" I prefer to rearrange the terms as curl -s -o "short value" "long url" to keep the most important part of the command visible without horizontal scrolling. If anything important goes at the far right end of a line, there is a higher risk of overlooking it.
instdir, checkdir, and checkres are constants with static values, therefore it's good to group them together at the top of the script. | {
"domain": "codereview.stackexchange",
"id": 45043,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "bash, shell, automation, jq, vscode",
"url": null
} |
c++, array, memory-management, pointers, type-safety
Title: Reusable storage for array of objects V3
Question: Here is a second follow up on Reusable storage for array of objects and Reusable storage for array of objects V2, taking into account the provided answers.
The following code should be compliant at least with gcc, clang, msvc and for C++14 and beyond.
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#include <limits>
#include <new>
#include <type_traits>
// Object constructible from a double
// forcing alignment
struct alignas(16) SFloat {
float val = 0.f;
SFloat() = default;
SFloat(const double v) : val(static_cast<float>(v)){};
SFloat& operator=(SFloat&& f) {
val = f.val;
return *this;
}
~SFloat() = default;
};
// Serialization of Float objects
std::ostream& operator<<(std::ostream& o, SFloat const& f) {
return o << f.val;
}
// type-punning reusable buffer
// holds a non-typed buffer (actually a char*) that can be used to store any
// types, according to user needs
class Buffer {
private:
// destructing functor storage
// required to call the correct object destructors
std::function<void(Buffer*)> Destructors = [](Buffer*) noexcept {};
// buffer address
unsigned char* Storage = nullptr;
// aligned buffer address
unsigned char* AlignedStorage = nullptr;
// number of stored elements
std::size_t CountOfStoredObjects = 0;
// buffer size in bytes
std::size_t StorageSizeInBytes = 0; | {
"domain": "codereview.stackexchange",
"id": 45044,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
c++, array, memory-management, pointers, type-safety
// computes the smallest positive offset in bytes that must be applied to
// Storage in order to have alignment a Alignment is supposed to be a valid
// alignment
std::size_t OffsetForAlignment(unsigned char const* const Ptr,
std::size_t Alignment) noexcept {
std::size_t Res = static_cast<std::size_t>(
reinterpret_cast<std::uintptr_t>(Ptr) % Alignment);
if (Res) {
return Alignment - Res;
} else {
return 0;
}
}
public:
// allocates a char buffer large enough for Counts object of type T and
// default-construct them
template <typename T>
T* DefaultAllocate(const std::size_t Count) {
if (Count > (std::numeric_limits<std::size_t>::max() - alignof(T)) /
sizeof(T)) {
throw std::bad_alloc();
}
// Destroy previously stored objects
Destructors(this);
std::size_t RequiredSize = sizeof(T) * Count + alignof(T);
if (StorageSizeInBytes < RequiredSize) {
// Creating a storage of RequiredSize bytes
unsigned char* NewStorage = reinterpret_cast<unsigned char*>(
std::realloc(Storage, RequiredSize));
if (NewStorage == nullptr) {
Destructors = [](Buffer*) {};
throw std::bad_alloc();
}
Storage = NewStorage;
StorageSizeInBytes = RequiredSize;
}
AlignedStorage = Storage + OffsetForAlignment(Storage, alignof(T));
// initializing an dynamic array of T on the storage
T* tmp = ::new (Storage) T[Count]; | {
"domain": "codereview.stackexchange",
"id": 45044,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
c++, array, memory-management, pointers, type-safety
// update nb of objects
CountOfStoredObjects = Count;
// create destructors functor
Destructors = [](Buffer* pobj) noexcept {
T* ToDestruct = reinterpret_cast<T*>(pobj->AlignedStorage);
// Delete elements in reverse order of creation
while (pobj->CountOfStoredObjects > 0) {
--(pobj->CountOfStoredObjects);
ToDestruct[(pobj->CountOfStoredObjects)].~T();
}
::operator delete[](ToDestruct, ToDestruct);
};
return tmp;
}
~Buffer() noexcept {
// Ending objects lifetime
Destructors(this);
// Releasing storage
std::free(Storage);
}
};
int main() {
constexpr std::size_t N0 = 7;
constexpr std::size_t N1 = 3;
Buffer B;
std::cout << "Test on SomeClass\n";
SFloat* PSFloat = B.DefaultAllocate<SFloat>(N0);
PSFloat[0] = 3.14;
*(PSFloat + 1) = 31.4;
PSFloat[2] = 314.;
std::cout << PSFloat[0] << '\n';
std::cout << PSFloat[1] << '\n';
std::cout << *(PSFloat + 2) << '\n';
std::cout << "Test on float\n";
// reallocating, possibly using existing storage, for a different type and
// size
float* PFloat = B.DefaultAllocate<float>(N1);
PFloat[0] = 3.14f;
*(PFloat + 1) = 31.4f;
PFloat[2] = 314.f;
std::cout << PFloat[0] << '\n';
std::cout << PFloat[1] << '\n';
std::cout << *(PFloat + 2) << '\n';
return 0;
}
Live | {
"domain": "codereview.stackexchange",
"id": 45044,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
c++, array, memory-management, pointers, type-safety
Live
Answer: Incorrect pointer used to construct objects
You are constructing the objects using the non-aligned pointer.
Use the pointer returned from new to destruct the objects
While you are using the correctly aligned pointer to destruct the objects, this pointer was created before there were any valid objects in the allocated memory. If you want to be pedantic, then this pointer might still not be valid even after new has been called. Instead, you should use a pointer derived from tmp to destruct the objects.
Think about the state of a Buffer object if new throws
You have the same issue as before with reallocation failures, except now you just moved it a bit. You really have to think about what can go wrong in each line of code, and how that can leave a Buffer object in an incorrect state. Consider the value of all the member variables at that point.
This also brings me to:
Write a test suite
Write an extensive test suite to cover all the possible ways your class can be used, all the corner cases (like creating a Buffer but never assigning anything to it), some types with huge alignment restrictions, and also how things can go wrong (replace the memory allocator with something that can fail). Use sanitizers, static analysis tools and code coverage tools to get more confidence in the correctness of your code.
Minor issues
Some small things that were already pointed out in the earlier reviews:
Missing <cstdlib>
Naming: short variable names (val, o, f), inconsistent style (tmp and pobj when everything else is capitalized). | {
"domain": "codereview.stackexchange",
"id": 45044,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, array, memory-management, pointers, type-safety",
"url": null
} |
python, pandas
Title: Use row data from a database to find rows in dataframes that match and use data to generate a separate dataframe
Question: I have a DataFrame (database_df) that contains the general record with the IDs that are the same team in each of the lines, containing these values I need to find in two APIs (api_1_df, api_2_df) that I collect the data if there is a way to find the same home team and the away team on the same line in both APIs.
When found on the same lines, I need to generate a dataframe with the lines in common with the columns that demonstrate the game's identification code (match_id):
import pandas as pd
api_1_id = "pressure_id"
api_2_id = "betfair_id"
api_1_match_id = "pressure_match_id"
api_2_match_id = "betfair_match_id"
database_df = pd.DataFrame({
'pressure_id': [101, 102, 103, 201, 202, 203],
'pressure_name': ["Rangers", "City", "Barcelona FC", "Real Madrid FC", "Liverpool", "Chelsea FC"],
'betfair_id': [1001, 1002, 1003, 2001, 2002, 2003],
'betfair_name': ["Rangers FC", "Manchester City", "Barcelona FC", "Real Madrid", "Liverpool FC", "Chelsea"]
})
api_1_df = pd.DataFrame({
'match_id': [1, 3],
'home_id': [101, 103],
'home_name': ["Rangers", "Barcelona FC"],
'away_id': [201, 203],
'away_name': ["Real Madrid FC", "Chelsea FC"]
})
api_2_df = pd.DataFrame({
'match_id': [123, 456, 789],
'home_id': [1001, 1002, 1003],
'home_name': ["Rangers", "City", "Barcelona FC"],
'away_id': [2001, 2002, 2003],
'away_name': ["Real Madrid", "Liverpool FC", "Chelsea"]
})
def api_1_and_api_2_ids(api_1_df: pd.DataFrame, database_df: pd.DataFrame, api_2_df: pd.DataFrame) -> None:
result = []
for _, row in api_1_df.iterrows():
home_id: pd.DataFrame = database_df.loc[database_df[api_1_id] == row['home_id']]
away_id: pd.DataFrame = database_df.loc[database_df[api_1_id] == row['away_id']]
home_id = home_id[api_2_id].iloc[0]
away_id = away_id[api_2_id].iloc[0] | {
"domain": "codereview.stackexchange",
"id": 45045,
"lm_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, pandas",
"url": null
} |
python, pandas
home_id = home_id[api_2_id].iloc[0]
away_id = away_id[api_2_id].iloc[0]
matched_rows: pd.DataFrame = api_2_df[(api_2_df['home_id'] == home_id) & (api_2_df['away_id'] == away_id)]
if not matched_rows.empty:
result.append({api_1_match_id: row['match_id'], api_2_match_id: matched_rows.iloc[0]['match_id']})
result_df = pd.DataFrame(result, columns=[api_1_match_id, api_2_match_id])
result_df = result_df.sort_values(by=[api_1_match_id])
print(result_df)
Result:
pressure_match_id betfair_match_id
1 123
3 789
I would like to improve this method that I am using because it is slow in a large dataframe and I would also like indications of visual improvement because I am finding it very messy and difficult to understand.
Answer: The loop and iterative concatenation need to go away. This is just a series of merges. You might be able to add some micro-optimizations to make the merges more efficient (making indices, changing the merge order, etc.), but the broad strokes can look like:
import pandas as pd
api_1_id = "pressure_id"
api_2_id = "betfair_id"
api_1_match_id = "pressure_match_id"
api_2_match_id = "betfair_match_id"
def api_1_and_api_2_ids(
api_1_df: pd.DataFrame,
database_df: pd.DataFrame,
api_2_df: pd.DataFrame,
) -> pd.DataFrame:
db_to_1_home = pd.merge(left=api_1_df, right=database_df, left_on='home_id', right_on=api_1_id)
db_to_1_away = pd.merge(left=api_1_df, right=database_df, left_on='away_id', right_on=api_1_id) | {
"domain": "codereview.stackexchange",
"id": 45045,
"lm_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, pandas",
"url": null
} |
python, pandas
db_1_2_home = pd.merge(left=db_to_1_home, right=api_2_df, left_on=api_2_id, right_on='home_id',
suffixes=['_api1', '_api2'])
db_1_2 = pd.merge(left=db_to_1_away, right=db_1_2_home, left_on=api_2_id, right_on='away_id_api2',
suffixes=['_away', '_home'])
result_df = db_1_2[['match_id_api1', 'match_id_api2']].rename(columns={
'match_id_api1': api_1_match_id,
'match_id_api2': api_2_match_id,
})
return result_df
def test() -> None:
database_df = pd.DataFrame({
'pressure_id': [101, 102, 103, 201, 202, 203],
'pressure_name': ["Rangers", "City", "Barcelona FC", "Real Madrid FC", "Liverpool",
"Chelsea FC"],
'betfair_id': [1001, 1002, 1003, 2001, 2002, 2003],
'betfair_name': ["Rangers FC", "Manchester City", "Barcelona FC", "Real Madrid",
"Liverpool FC", "Chelsea"]
})
api_1_df = pd.DataFrame({
'match_id': [1, 3],
'home_id': [101, 103],
'home_name': ["Rangers", "Barcelona FC"],
'away_id': [201, 203],
'away_name': ["Real Madrid FC", "Chelsea FC"]
})
api_2_df = pd.DataFrame({
'match_id': [123, 456, 789],
'home_id': [1001, 1002, 1003],
'home_name': ["Rangers", "City", "Barcelona FC"],
'away_id': [2001, 2002, 2003],
'away_name': ["Real Madrid", "Liverpool FC", "Chelsea"]
})
result_df = api_1_and_api_2_ids(api_1_df, database_df, api_2_df)
print(result_df)
if __name__ == '__main__':
test()
pressure_match_id betfair_match_id
0 1 123
1 3 789 | {
"domain": "codereview.stackexchange",
"id": 45045,
"lm_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, pandas",
"url": null
} |
c++, algorithm, strings, time-limit-exceeded, vectors
Title: O(nlogn) Lexicographically minimal rotation code but tle on this particular case
Question: Based on a small suggestion here , this code tries to find lexicographically minimal rotation (question) by successively comparing two adjacent substrings in the very left , that can potentially give us the answer.
Note : Will refer lexicographically smaller char as smaller char and 0-indexing is used
Ex - "abbaad"
Final answer - "aadabb"
My approach is :-
Find out the indices of all the smallest characters. In the above example, [0,3,4]
Start from two leftmost indices :
First smallest index -> pointed by "left" pointer. Here , 0
Second smallest index -> pointed by "right" pointer. Here , 3
Compare corresponding next characters until you find a mismatch. Which is done inside this loop :-
while(i<n/2){
// code
}
The mismatch in our example is when 'b' at 1 is compared to 'a' at 4.
Update the 'left' and 'right' pointers accordingly. Here,
->left is set to right
->right becomes right + 1 | {
"domain": "codereview.stackexchange",
"id": 45046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, strings, time-limit-exceeded, vectors",
"url": null
} |
c++, algorithm, strings, time-limit-exceeded, vectors
This naive algo will give O(n^2) complexity on the test cases like "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" .
The observation is that while we are in the process of comparing corresponding next characters from 'left' and 'right' pointers , if we touch the 'right' pointer (from behind) , then we can remove all the indices of the smallest chars (that we computed in the first step) that lies within the substring of the 'right' pointer that we have traversed so far.
I'll write here but you can also see the first hyperlink.
Ex - "aaaaaaa" : let's say in mid-way , 'left' is 0 and 'right' is 3 . Then for i = 3 , left + i = 3 which is equal to right .
In the first step , our array that stored smallest char indices would be [0,1,2,3,4,5,6] . Then we would remove [3,4,5] from it.
The 'left' pointer stays at 0. But 'right' is now at 6. Hence, we skipped unnecessary computations that would arise with 'right' having values 4 and 5.
But , my solution is giving me tle on the case where string is char 'a' repeated 10^6 times.
I have tried rechecking a lot and also all possible ways of small optimisations like cin.tie(NULL) and using reserve on vector that stored smallest char indices.
#include <bits/stdc++.h>
using namespace std;
#define std_modulo 1000000007
void minimal_rotation()
{
string s;
cin >> s;
if (s.size() == 1)
{
cout << s;
return;
}
// Just some code to extract smallest indices
vector<int> v;
v.reserve(1000000);
for (int i = 0; i < s.size(); i++)
{
if (v.empty())
{
v.push_back(i);
}
else
{
if (s[i] - 'a' <= s[v.back()] - 'a')
{
v.push_back(i);
}
}
}
vector<int> small_indices; // vector of smallest char indices
small_indices.reserve(1000000);
small_indices.push_back(v.back()); | {
"domain": "codereview.stackexchange",
"id": 45046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, strings, time-limit-exceeded, vectors",
"url": null
} |
c++, algorithm, strings, time-limit-exceeded, vectors
for (int i = v.size() - 2; i >= 0; i--)
{
if (s[v[i]] == s[v[i + 1]])
{
small_indices.push_back(v[i]);
}
else
{
break;
}
}
reverse(small_indices.begin(), small_indices.end());
// vector of smallest indices ready
// actual algo begins now
s = s + s;
int n = s.size();
if (small_indices.size() == 1)
{
for (int i = *small_indices.begin(); i < n / 2; i++)
{
cout << s[i];
}
for (int i = 0; i < *small_indices.begin(); i++)
{
cout << s[i];
}
return;
}
// if more than 1 smallest indices
int left = 0;
int right = 1;
while (right < small_indices.size())
{
int i = 0;
while (i < n / 2)
{
// If we touched 'right' pointer from behind
if (small_indices[left] + i == small_indices[right])
{
int removing_range = small_indices[right] + i;
while (right < small_indices.size() && small_indices[right] < removing_range)
{
right++;
}
break;
}
else
{
if (s[small_indices[left] + i] < s[small_indices[right] + i])
{
right++;
break;
}
else if (s[small_indices[left] + i] > s[small_indices[right] + i])
{
left = right;
right = left + 1;
break;
}
else
{
i++;
}
}
}
}
cout << s.substr(small_indices[left], n / 2);
}
int main()
{
minimal_rotation();
} | {
"domain": "codereview.stackexchange",
"id": 45046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, strings, time-limit-exceeded, vectors",
"url": null
} |
c++, algorithm, strings, time-limit-exceeded, vectors
Answer: After much scrutinization , I have found another optimization. And the solution got accepted . I don't know about Code Review's policy but it would be really helpful for all if this question stays here.
The optimisation :-
For the case , where the character mismatches and the right-er charachter is bigger , then in the above code we were just incrementing the 'right' pointer .
The answer is that we shouldn't just increment the 'right' pointer but do as we did with the case of 'right' pointer touched from behind . That is, remove all the smallest char indices that lies within the range of 'right' part that we traversed so far , it is not difficult to guess why. Because at the same distance from 'left' and 'right' pointer, 'left' has a smaller char than 'right' so 'right' part can never be minimal rotation.
The test case that actually caused the problem has a 'b' somewhere deep inside the ocean of 99999 no of 'a' and that caused the actual problem.
Accepted code :- (i have comented the place where the changes took place)
#include <bits/stdc++.h>
using namespace std;
#define std_modulo 1000000007
void minimal_rotation()
{
string s;
cin >> s;
if (s.size() == 1)
{
cout << s;
return;
}
// Just some code to extract smallest indices
vector<int> v;
v.reserve(1000000);
for (int i = 0; i < s.size(); i++)
{
if (v.empty())
{
v.push_back(i);
}
else
{
if (s[i] - 'a' <= s[v.back()] - 'a')
{
v.push_back(i);
}
}
}
vector<int> small_indices; // vector of smallest char indices
small_indices.reserve(1000000);
small_indices.push_back(v.back()); | {
"domain": "codereview.stackexchange",
"id": 45046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, strings, time-limit-exceeded, vectors",
"url": null
} |
c++, algorithm, strings, time-limit-exceeded, vectors
for (int i = v.size() - 2; i >= 0; i--)
{
if (s[v[i]] == s[v[i + 1]])
{
small_indices.push_back(v[i]);
}
else
{
break;
}
}
reverse(small_indices.begin(), small_indices.end());
// vector of smallest indices ready
// actual algo begins now
s = s + s;
int n = s.size();
if (small_indices.size() == 1)
{
for (int i = *small_indices.begin(); i < n / 2; i++)
{
cout << s[i];
}
for (int i = 0; i < *small_indices.begin(); i++)
{
cout << s[i];
}
return;
}
// if more than 1 smallest indices
int left = 0;
int right = 1;
while (right < small_indices.size())
{
int i = 0;
while (i < n / 2)
{
// If we touched 'right' pointer from behind
if (small_indices[left] + i == small_indices[right])
{
int removing_range = small_indices[right] + i;
while (right < small_indices.size() && small_indices[right] < removing_range)
{
right++;
}
break;
}
else
{
if (s[small_indices[left] + i] < s[small_indices[right] + i])
{
// edited part goes here.
int removing_range = small_indices[right] + i;
while (right < small_indices.size() && small_indices[right] < removing_range)
{
right++;
}
break;
// edited part ends here | {
"domain": "codereview.stackexchange",
"id": 45046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, strings, time-limit-exceeded, vectors",
"url": null
} |
c++, algorithm, strings, time-limit-exceeded, vectors
// earlier we had only "right++"
}
else if (s[small_indices[left] + i] > s[small_indices[right] + i])
{
left = right;
right = left + 1;
break;
}
else
{
i++;
}
}
}
}
cout << s.substr(small_indices[left], n / 2);
}
int main()
{
minimal_rotation();
} | {
"domain": "codereview.stackexchange",
"id": 45046,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, algorithm, strings, time-limit-exceeded, vectors",
"url": null
} |
c++, performance, opencv
Title: OpenCV calculate center of mass for a single contour
Question: I was recently going through some OpenCV code that finds the center of mass in a contour and realized there is potential room for optimisation.
What I noticed looking back through my code is when I calculate the mass I'm using contours.size() which makes me believe that I'm calculating the moments and center of mass for all of my contours.
In my cases this is not needed as I have a function that returns the largest contour that I have found getMaxAreaContourId(contours, imageSize); which returns an int that I can use like contours[largestContour] and largestContour would be set from the result of getMaxAreaContourId
So if I'm not mistaken would I be able to just find the moment and mass from a single contour and completely remove two for loops?
Because Ultimately I end up doing this:
int CenterOfContourX = mc[largestContour].x;
int CenterOfContourY = mc[largestContour].y;
Really the end goal is to end up with two integers that represent the center of mass of my contour.
Code to optimise:
// Get the moments
mu.reserve(contours.size());
for( int i = 0; i < contours.size(); i++ )
{ mu[i] = moments( contours[i], false ); }
// Get the mass centers:
std::vector<cv::Point2f> mc( contours.size() );
for( int i = 0; i < contours.size(); i++ )
{ mc[i] = cv::Point2f( mu[i].m10/mu[i].m00 , mu[i].m01/mu[i].m00 ); }
Answer: It seem like you can definitely merge the two loops together.
Also you should avoid iterating using i, instead, use iterators, or the range-based for loop (since C++11).
// if you needed this vector
mu.reserve(contours.size());
// Get the mass centers:
std::vector<cv::Point2f> mc( contours.size() );
for( auto& c : contours )
{
auto m = moments(c, false);
mu.push_back(m); // only if you need the mu vector
mc.push_back(cv::Point2f( m.m10/m.m00 , m.m01/m.m00 ));
} | {
"domain": "codereview.stackexchange",
"id": 45047,
"lm_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, opencv",
"url": null
} |
c++, performance, opencv
And this can even be simplified to a call to std::transfer with std::back_inserter:
std::transform(
std::begin(contours),
std::end(contours),
std::back_inserter(mc),
[](const contour& c) -> cv::Point2f {
auto m = moments(c, false);
return cv::Point2f( m.m10/m.m00 , m.m01/m.m00 )
}
);
And of course if you only need to know moments of one countour, there is no need to count it for all, but since you haven't included that part of the code, it's hard to tell anything about it. | {
"domain": "codereview.stackexchange",
"id": 45047,
"lm_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, opencv",
"url": null
} |
java, matrix, generics, library, linear-algebra
Title: Generic matrix library in Java
Question: I have this repository. The most important source files follow.
com.github.coderodde.math.linear.matrix.AbstractMatrix.java:
package com.github.coderodde.math.linear.matrix;
import java.util.Objects; | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
/**
* This abstract class defines the API for the matrix data types.
*
* @param <M> the actual implementing matrix type.
* @param <E> the matrix element type.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 13, 2023)
* @since 1.6 (Aug 13, 2023)
*/
public abstract class AbstractMatrix<M extends AbstractMatrix<M, E>, E> {
/**
* The width of this matrix.
*/
protected final int width;
/**
* The height of this matrix.
*/
protected final int height;
/**
* The field element API.
*/
protected final FieldElement<E> fieldElements;
protected AbstractMatrix(int width,
int height,
FieldElement<E> fieldElements) {
this.width = checkWidth(width);
this.height = checkHeight(height);
this.fieldElements = Objects.requireNonNull(fieldElements);;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
/**
* Sets each element in this matrix to its negative.
*/
public abstract void negate();
/**
* Returns a copy of this matrix with each element negated. After this
* operation, this matrix remains intact.
*
* @return new, negated matrix.
*/
public abstract M immutableNegate();
/**
* Adds the input matrix to this matrix.
*
* @param other the matrix to add to this matrix.
*/
public abstract void add(M other);
/**
* Returns a copy of this matrix with elements from {@code other} added to
* it. After this operation, this matrix remains intact.
*
* @param other the matrix to add.
*
* @return copy of this matrix with input elements added.
*/
public abstract M immutableAdd(M other);
/**
* Creates a new matrix and sets it to the product of this and {@code right} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
/**
* Creates a new matrix and sets it to the product of this and {@code right}
* matrices. After this operation, this matrix remains intact.
*
* @param right the right hand matrix in the product. This matrix is the
* left hand matrix.
*
* @return the matrix product.
*/
public abstract M multiply(M right);
/**
* Returns the element at {@code y}th row, {@code x}th column.
*
* @param x the {@code X}-coordinate of the element.
* @param y the {@code Y}-coordinate of the element.
*
* @return the matrix element at specified coordinates.
*/
public abstract E get(int x, int y);
/**
* Sets the value {@code value} at {@code y}th row, {@code x}th column.
*
* @param x the {@code X}-coordinate of the value.
* @param y the {@code Y}-coordinate of the value.
* @param value the value to set.
*/
public abstract void set(int x, int y, E value);
/**
* Checks whether {@code o} is an abstract matrix and has the same content
* as this matrix.
*
* @param o the matrix to check against.
* @return {@code true} only if the two matrices are equal.
*/
@Override
public boolean equals(Object o) {
AbstractMatrix<M, E> other = (AbstractMatrix<M, E>) o;
if (width != other.width || height != other.height) {
return false;
}
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (!get(x, y).equals(other.get(x, y))) {
return false;
}
}
}
return true;
}
protected static int checkWidth(int widthCandidate) {
if (widthCandidate == 0) {
throw new IllegalArgumentException("Matrix width is zero.");
}
if (widthCandidate < 0) { | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
}
if (widthCandidate < 0) {
throw new IllegalArgumentException(
"Matrix width is negative: " + widthCandidate);
}
return widthCandidate;
}
protected static int checkHeight(int heightCandidate) {
if (heightCandidate == 0) {
throw new IllegalArgumentException("Matrix width is zero.");
}
if (heightCandidate < 0) {
throw new IllegalArgumentException(
"Matrix width is negative: " + heightCandidate);
}
return heightCandidate;
}
protected void checkCoordinates(int x, int y) {
checkX(x);
checkY(y);
}
private void checkX(int x) {
if (x < 0) {
throw new IndexOutOfBoundsException(
"X-coordinate is negative: " + x);
}
if (x >= width) {
throw new IndexOutOfBoundsException(
"X-coordinate is too large: "
+ x
+ ". Must be at most "
+ (width - 1)
+ ".");
}
}
private void checkY(int y) {
if (y < 0) {
throw new IndexOutOfBoundsException(
"Y-coordinate is negative: " + y);
}
if (y >= height) {
throw new IndexOutOfBoundsException(
"Y-coordinate is too large: "
+ y
+ ". Must be at most "
+ (height - 1)
+ ".");
}
}
protected void checkMatrixHaveSameDimensions(M matrix1, M matrix2) {
if (matrix1.getWidth() != matrix2.getWidth()) {
throw new MatricesNotAddableException(
"Matrix widths mismatch: "
+ matrix1.getWidth() | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
"Matrix widths mismatch: "
+ matrix1.getWidth()
+ " vs "
+ matrix2.getWidth()
+ ".");
}
if (matrix1.getHeight() != matrix2.getHeight()) {
throw new MatricesNotAddableException(
"Matrix heights mismatch: "
+ matrix1.getHeight()
+ " vs "
+ matrix2.getHeight()
+ ".");
}
}
protected void checkMatricesCanBeMultiplied(M leftMatrix, M rightMatrix) {
if (leftMatrix.getWidth() != rightMatrix.getHeight()) {
throw new MatricesNotMultipliableException(
"Cannot multiply the matrices. Width of left matrix is "
+ leftMatrix.getWidth()
+ ", the height of the right matrix is "
+ rightMatrix.getHeight()
+ ".");
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
com.github.coderodde.math.linear.matrix.DenseMatrix2D.java:
package com.github.coderodde.math.linear.matrix;
/**
* This class implements a (dense) matrix stored as a two-dimensional array.
*
* @param <E> the matrix element type.
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 13, 2023)
* @since 1.6 (Aug 13, 2023)
*/
public class DenseMatrix2D<E> extends AbstractMatrix<DenseMatrix2D<E>, E> {
/**
* The actual matrix holding the elements.
*/
private final E[][] data;
/**
* Constructs a new dense matrix that stores all the elements in a two-
* dimensional array.
*
* @param width the width of this matrix.
* @param height the height of this matrix.
* @param fieldElements the field element API object.
*/
public DenseMatrix2D(int width, int height, FieldElement<E> fieldElements) {
super(width, height, fieldElements);
data = (E[][]) new Object[height][];
for (int y = 0; y < height; y++) {
data[y] = (E[]) new Object[width];
}
}
/**
* {@inheritDoc }
*/
@Override
public E get(int x, int y) {
checkCoordinates(x, y);
return data[y][x];
}
/**
* {@inheritDoc }
*/
@Override
public void set(int x, int y, E value) {
if (value == null || fieldElements.identity().equals(value)) {
data[y][x] = fieldElements.identity();
} else {
data[y][x] = value;
}
}
/**
* {@inheritDoc }
*/
@Override
public void negate() {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
set(x, y, fieldElements.negate(get(x, y)));
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
/**
* {@inheritDoc }
*/
@Override
public DenseMatrix2D<E> immutableNegate() {
DenseMatrix2D<E> ret = new DenseMatrix2D<>(width,
height,
fieldElements);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
ret.set(x, y, fieldElements.negate(get(x, y)));
}
}
return ret;
}
/**
* {@inheritDoc }
*/
@Override
public void add(DenseMatrix2D<E> other) {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
set(x, y, fieldElements.add(get(x, y), other.get(x, y)));
}
}
}
/**
* {@inheritDoc }
*/
@Override
public DenseMatrix2D<E> immutableAdd(DenseMatrix2D<E> other) {
DenseMatrix2D<E> ret = new DenseMatrix2D<>(width,
height,
fieldElements);
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
ret.set(x, y, fieldElements.add(get(x, y), other.get(x, y)));
}
}
return ret;
} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
/**
* {@inheritDoc }
*/
@Override
public DenseMatrix2D<E> multiply(DenseMatrix2D<E> right) {
DenseMatrix2D<E> ret = new DenseMatrix2D<>(right.getWidth(),
this.getHeight(),
fieldElements);
for (int row = 0; row < height; row++) {
for (int col = 0; col < right.getWidth(); col++) {
ret.set(col, row, combineRowColumn(col, row, right));
}
}
return ret;
}
private E combineRowColumn(int col, int row, DenseMatrix2D<E> right) {
E sum = fieldElements.identity();
for (int x = 0; x < width; x++) {
E product = fieldElements.multiply(get(x, row), right.get(col, x));
sum = fieldElements.add(sum, product);
}
return sum;
}
}
com.github.coderodde.math.linear.matrix.SparseMatrix.java:
package com.github.coderodde.math.linear.matrix;
import java.util.HashMap;
import java.util.Map;
/**
* This class implements a sparse matrix.
*
* @param <E> the matrix element type.
* @author Rodion "rodde" Efremov
* @version 1.6 (Aug 13, 2023)
* @since 1.6 (Aug 13, 2023)
*/
public class SparseMatrix<E> extends AbstractMatrix<SparseMatrix<E>, E> {
private final Map<Integer, Map<Integer, E>> dataXY = new HashMap<>();
private final Map<Integer, Map<Integer, E>> dataYX = new HashMap<>();
public SparseMatrix(int width, int height, FieldElement<E> fieldElements) {
super(width, height, fieldElements);
}
@Override
public void negate() {
for (Map.Entry<Integer, Map<Integer, E>> entry1 : dataXY.entrySet()) {
for (Map.Entry<Integer, E> entry2 : entry1.getValue().entrySet()) {
entry2.setValue(fieldElements.negate(entry2.getValue()));
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
@Override
public SparseMatrix<E> immutableNegate() {
SparseMatrix<E> ret = new SparseMatrix<>(width, height, fieldElements);
for (Map.Entry<Integer, Map<Integer, E>> entry1 : dataXY.entrySet()) {
int x = entry1.getKey();
for (Map.Entry<Integer, E> entry2 : entry1.getValue().entrySet()) {
int y = entry2.getKey();
ret.set(x, y, fieldElements.negate(entry2.getValue()));
}
}
return ret;
}
@Override
public void add(SparseMatrix<E> other) {
for (Map.Entry<Integer, Map<Integer, E>> entry1
: other.dataXY.entrySet()) {
int x = entry1.getKey();
for (Map.Entry<Integer, E> entry2 : entry1.getValue().entrySet()) {
int y = entry2.getKey();
set(x, y, fieldElements.add(get(x, y), entry2.getValue()));
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
@Override
public SparseMatrix<E> immutableAdd(SparseMatrix<E> other) {
SparseMatrix<E> ret = new SparseMatrix<>(width, height, fieldElements);
for (Map.Entry<Integer, Map<Integer, E>> entry1 : dataXY.entrySet()) {
int x = entry1.getKey();
for (Map.Entry<Integer, E> entry2 : entry1.getValue().entrySet()) {
int y = entry2.getKey();
ret.set(x, y, entry2.getValue());
}
}
for (Map.Entry<Integer, Map<Integer, E>> entry1
: other.dataXY.entrySet()) {
int x = entry1.getKey();
for (Map.Entry<Integer, E> entry2 : entry1.getValue().entrySet()) {
int y = entry2.getKey();
ret.set(x,
y,
fieldElements.add(ret.get(x, y),
other.get(x, y)));
}
}
return ret;
}
@Override
public SparseMatrix<E> multiply(SparseMatrix<E> right) {
checkMatricesCanBeMultiplied(this, right);
SparseMatrix<E> ret = new SparseMatrix<>(width, height, fieldElements);
for (int leftRow = 0; leftRow < height; leftRow++) {
for (int rightColumn = 0;
rightColumn < right.width;
rightColumn++) {
ret.set(rightColumn,
leftRow,
combineRowCol(dataYX.get(leftRow),
right.dataXY.get(rightColumn)));
}
}
return ret;
}
@Override
public E get(int x, int y) {
if (!dataXY.containsKey(x)) {
return fieldElements.identity();
}
return dataXY.get(x).getOrDefault(y, fieldElements.identity());
} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
@Override
public void set(int x, int y, E value) {
if (value == null || value.equals(fieldElements.identity())) {
deleteZeroEntry(x, y);
} else {
updateEntry(x, y, value);
}
}
private void deleteZeroEntry(int x, int y) {
if (dataXY.containsKey(x)) {
dataXY.get(x).remove(y);
if (dataXY.get(x).isEmpty()) {
dataXY.remove(x);
}
}
if (dataYX.containsKey(y)) {
dataYX.get(y).remove(x);
if (dataYX.get(y).isEmpty()) {
dataYX.remove(y);
}
}
}
private void updateEntry(int x, int y, E value) {
if (!dataXY.containsKey(x)) {
Map<Integer, E> subMap = new HashMap<>();
subMap.put(y, value);
dataXY.put(x, subMap);
} else {
dataXY.get(x).put(y, value);
}
if (!dataYX.containsKey(y)) {
Map<Integer, E> subMap = new HashMap<>();
subMap.put(x, value);
dataYX.put(y, subMap);
} else {
dataYX.get(y).put(x, value);
}
}
private E combineRowCol(Map<Integer, E> map1, Map<Integer, E> map2) {
E sum = fieldElements.identity();
if (map1 == null || map2 == null) {
return sum;
}
if (map1.size() < map2.size()) {
return combineRowCol(map2, map1);
}
for (Map.Entry<Integer, E> entry : map2.entrySet()) {
int a = entry.getKey();
E rowValue = entry.getValue();
if (map1.containsKey(a)) {
E columnValue = map1.get(a);
E product = fieldElements.multiply(columnValue, rowValue);
sum = fieldElements.add(sum, product);
}
}
return sum;
}
} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
Typical demo output
The demonstration program outputs something like that:
Warming up...
Benchmarking...
Created dense matrix in 1 ms.
Created sparse matrix in 1 ms.
Dense matrix addition in 15 ms.
Sparse matrix addition in 2 ms.
Addition matches: true
Dense matrix multiplication in 15572 ms.
Sparse matrix multiplication in 185 ms.
Multiplication matches: true
So we see that sparse matrix multiplication is much faster than the dense matrix multiplication.
Critique request
Can I improve anything here? Please tell me anything that comes to mind.
Answer:
Dense matrix multiplication in 15572 ms.
Going by the demo code I assume this was the product between two 1000x1000 matrices. By my estimate based on old code the raw operations by themselves could take somewhere around 70ms under good conditions (on a PC from a decade ago, single threaded), which sounds mad compared to 15572ms, but the conditions that enabled that are incompatible with this generic API.
You probably cannot use SIMD. Java has SIMD APIs these days, but you're dealing with generic elements. Even if you cheat with instanceof and write some type-specific implementations, there would be no SIMD-friendly access to the underlying values. If there were type-specific matrix types (so that a matrix of integers has a raw int[] to work with) then it could be done, I'm not necessarily recommending that, you can think about it.
You can use loop-tiling to improve the memory access pattern partially. The extra indirection throws a bit of a wrench into the memory access pattern anyway, but I expect some gain from that.
There are not many algorithms implemented (yet?) so not much to really do with these matrices. No transpose even. As for other algorithms I suppose a blocker is that:
public interface FieldElement<E> extends Negable<E>,
Addable<E>,
Multipliable<E>,
Zero<E> {
} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
.. is not a field, just a ring. It can add, multiply, and negate, but not take multiplicative inverses. That is relatively annoying in linear algebra.
You could do more with actual fields, eg LU-decomposition and solving Ax=b. That includes not just float/double and complex, but also finite fields - for that aspect perhaps you can draw some inspiration from FFLAS-FFPACK
BTW here's some video (first in a series) about sparse matrix algorithms, maybe you can use it to draw inspiration from it too: https://www.youtube.com/watch?v=1dGRTOwBkQs
@Override
public SparseMatrix<E> multiply(SparseMatrix<E> right) {
checkMatricesCanBeMultiplied(this, right);
SparseMatrix<E> ret = new SparseMatrix<>(width, height, fieldElements);
for (int leftRow = 0; leftRow < height; leftRow++) {
for (int rightColumn = 0;
rightColumn < right.width;
rightColumn++) {
ret.set(rightColumn,
leftRow,
combineRowCol(dataYX.get(leftRow),
right.dataXY.get(rightColumn)));
}
}
return ret;
} | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
java, matrix, generics, library, linear-algebra
Having dataXY and dataYX is a neat trick, enabling simple efficient sparse matrix multiplication. You don't actually need to store the matrix twice though, there are algorithms for multiplying sparse matrices that are represented in only column format or only row format too (or two matrices with opposite representation, but that's easy, then you get the same algorithm that you already have). There are various different approaches.
Here's one example, assuming both matrices are stored by column: take a column from the right matrix, for each non-zero element in it, take the corresponding column from the left matrix and generate all products. Add the products into their corresponding locations in the result matrix, creating new entries as necessary. This is normally an annoying approach (ie when directly manipulating a matrix in CSC format) but with a map of maps it's actually fine. I'm not sure if I got this algorithm 100% right, but the approach is something like this anyway. | {
"domain": "codereview.stackexchange",
"id": 45048,
"lm_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, matrix, generics, library, linear-algebra",
"url": null
} |
python, beginner
Title: Username-Password Matching Program
Question: I started university this semester. Can you review my code and share your thoughts with me
# 5-November-2020
username = input("Please enter your username: ")
password = input("Please enter your password: ")
username_password = {
'Mert': "mertt"
}
if username in username_password:
if username == "Mert" and password == username_password[username]:
print("Welcome Sir")
else:
print("You're not authorized!")
else:
confirmation = input("Do you want to register? (Y/N): ")
if confirmation == "Y":
username = input("Enter your username: ")
password = input("Enter your password: ")
password_2 = input("Confirm your password: ")
if password == password_2:
username_password[username] = password
else:
print("Your password is incorrect!")
else:
print("Good bye")
print(username_password)
If you have any improvement suggestion please tell me.
Answer: Validate input
You should be certain that your program wouldn't fail for any kind of bad input, something the user shouldn't have entered that might cause the program to behave incorrectly
Is this possible for your program? Yes, take this line
username = input("Please enter your username: ")
If the user enters Ctrl+Z here, it causes an error and the program stops.
EOFError
We can catch these exceptions using try and except in Python
try:
username = input("Please enter your username: ")
except (Exception, KeyboardInterrupt):
print("Please enter a valid username!")
The same applies to the input for password
One step further, I would also like to check the length of the details, i.e if the username or password is too short. Show a custom message if that is true | {
"domain": "codereview.stackexchange",
"id": 45049,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, beginner
On an exception
Due to the changes we made previously, we can easily print an error message if we catch an exception rather than the termination of the program. But what happens after?
You have two options, either to stop the program there because you cannot process bad input or, you can ask for input again.
If you choose the second option, that will take a few more lines of code but is surely better because the user gets another chance rather than running the whole program again
For that, we need to wrap it in a while loop that will iterate till it gets valid input
def username_input():
while True:
try:
username = input("Please enter your username: ")
except Exception:
print("Please a enter valid username! \n\n")
continue
return username
def password_input():
while True:
try:
password = input("Please enter your password: ")
except Exception:
print("Please enter a valid password! \n\n")
continue
return password
Here we are repeating ourselves, the functions are identical. With a little hack, we can clean up the code
def ask_input(field):
while True:
try:
word = input(f"Please enter your {field}: ")
except (Exception, KeyboardInterrupt):
print(f"Please enter a valid {field}! \n\n")
continue
if not word: continue # if field is empty
return word
def take_input():
username = ask_input("username")
password = ask_input("password")
return username, password
Split work into functions
In my last point, you must've noticed I moved something into a function
We can really clean up our code if we follow the SRP rule or the Single-responsibility principle | {
"domain": "codereview.stackexchange",
"id": 45049,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, beginner
The single-responsibility principle (SRP) is a computer-programming
principle that states that every module, class, or function in a
computer program should have responsibility over a single part of that
program's functionality,
If assig the task of taking input in this program, to let's say take_input()
We can re-use the same function if we would ever want to perform the same task again, without copy-pasting the same segment of code
username, password = take_input()
process_login( username, password ):
take_input() will take care of the input related tasks, and when it has proper valid it returns a username and password
process_login() decides whether the login will be authorized or not, based on the records
Check with key username
if username in username_password:
if username == "Mert" and password == username_password[username]:
print("Welcome Sir")
else:
print("You're not authorized!")
This works right now, but only due to the fact that the size of records is 1, any extra records added and your algorithm will fail, if the size was 50 you cannot write 50 if statements, you need to check with the username entered
def process_login(username, password, records):
try:
if records[username] == password:
print("Authorized")
return True
except KeyError:
print("Not authroized")
return False
Here, if the username isn't present in records, a KeyError is raised, which I will catch and print Not authorized
Re-written
def ask_input(field):
while True:
try:
word = input(f"Please enter your {field}: ")
except (Exception, KeyboardInterrupt):
print(f"Please enter a valid {field}! \n\n")
continue
if not word: continue
return word
def take_input():
username = ask_input("username")
password = ask_input("password")
return username,password | {
"domain": "codereview.stackexchange",
"id": 45049,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
python, beginner
def process_login(username, password, records):
try:
if records[username] == password:
print("Authorized")
except KeyError:
print("Not authroized")
I have left out the last part, which is the "registration". Which I will explain next
records = {
"__Testu" : "__Testp",
"__Testu2" : "__Testp2"
}
username, password = take_input()
process_login(username, password, records)
Write records into a file
As it is currently, you have pre-added a record to your dictionary, any record added after this is pointless since the next time you run the program, the dictionary will be initialized again with the same one record you added.
You need some way to save the users records so that the next time he opens your program, his previous details are saved
The best way to do this is the user the csv module in Python, - csv.DictReader which will automate all reading/writing of the file for you. But is something you would have to write on your own.
Cheers
>>> Please enter your username: (empty input)
>>> Please enter your username: __Testu
>>> Please enter your password: (empty input)
>>> Please enter your password: __Testp
>>> Authorized | {
"domain": "codereview.stackexchange",
"id": 45049,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner",
"url": null
} |
c++, chess
Title: C++ Chess Engine - Initialization of Magic Bitboard Attack Tables
Question: I've just completed the generation of magic bitboard attack tables for bishops and rooks in my C++ chess engine.
Main Questions
The functions generateMagicNumbers() and populateAttackDatabase() take 4 parameters, and searchForMagicNumber() takes 5. Is this too many? Is there a way to improve on this?
calculateAttacks() takes a function pointer as a parameter, and this function serves as a way for telling calculateAttacks() how to actually calculate the attacks, depending on if the piece is a bishop or rook. Is there anything wrong with this? It feels kinda like a code smell to me and was wondering if there is a way to improve on this? Ultimately I could combine calculateBishopAttackBoard() and calculateRookAttackBoard() into one function calculateAttackBoard(), and that would eliminate the need to pass these functions as parameters
searchForMagicNumber() takes a square parameter only to be used for debugging purposes. Is this acceptable?
Of course any and all feedback would be greatly appreciated!
magicbitboard.h
#pragma once
#include "types.h"
#include "bitboard.h"
#include "utils.h"
#include "constants.h"
#include <iostream>
#include <vector>
#include <array>
namespace magic_bitboards
{
struct HashInformation
{
Bitboard blockerMask;
u64 magicNumber;
int shiftAmount;
};
extern HashInformation BISHOP_HASHING_INFORMATION[Square::NUMBER_OF_SQUARES];
extern HashInformation ROOK_HASHING_INFORMATION[Square::NUMBER_OF_SQUARES];
// Bishops have between 32 and 512 unique possible blocker variations depending on the square
constexpr int LARGEST_AMOUNT_OF_BISHOP_BLOCKER_CONFIGURATIONS = 512;
// Rooks have between 1024 and 4096 unique possible blocker variations depending on the square
constexpr int LARGEST_AMOUNT_OF_ROOK_BLOCKER_CONFIGURATIONS = 4096;
constexpr int MINIMUM_NUMBER_OF_BITS_FOR_BISHOP_HASHING = 3;
constexpr int MINIMUM_NUMBER_OF_BITS_FOR_ROOK_HASHING = 6; | {
"domain": "codereview.stackexchange",
"id": 45050,
"lm_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++, chess",
"url": null
} |
c++, chess
extern Bitboard BISHOP_ATTACKS[Square::NUMBER_OF_SQUARES][LARGEST_AMOUNT_OF_BISHOP_BLOCKER_CONFIGURATIONS];
extern Bitboard ROOK_ATTACKS[Square::NUMBER_OF_SQUARES][LARGEST_AMOUNT_OF_ROOK_BLOCKER_CONFIGURATIONS];
void init();
namespace
{
extern u64 BISHOP_MAGIC_NUMBERS[Square::NUMBER_OF_SQUARES];
extern u64 ROOK_MAGIC_NUMBERS[Square::NUMBER_OF_SQUARES];
// The number of set bits in the bishop blocker mask for each square
constexpr int NUMBER_OF_SET_BITS_IN_BISHOP_BLOCKER_MASK[Square::NUMBER_OF_SQUARES] = {
6, 5, 5, 5, 5, 5, 5, 6,
5, 5, 5, 5, 5, 5, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 9, 9, 7, 5, 5,
5, 5, 7, 7, 7, 7, 5, 5,
5, 5, 5, 5, 5, 5, 5, 5,
6, 5, 5, 5, 5, 5, 5, 6,
};
// The number of set bits in the rook blocker mask for each square
constexpr int NUMBER_OF_SET_BITS_IN_ROOK_BLOCKER_MASK[Square::NUMBER_OF_SQUARES] = {
12, 11, 11, 11, 11, 11, 11, 12,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
11, 10, 10, 10, 10, 10, 10, 11,
12, 11, 11, 11, 11, 11, 11, 12,
};
// Define an alias for passing calculate<Piece>AttackBoard() as a parameter to another function
using calculateAttackBoardFunction = Bitboard (*)(const Square & square, const Bitboard & blockerVariation);
void initializeHashInformationEntries();
void generateBlockerMasks();
Bitboard calculateBishopBlockerMask(const Bitboard &bitboard);
Bitboard calculateRookBlockerMask(const Bitboard &bitboard);
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> calculateBlockerVariations(HashInformation const * HASH_INFORMATION_TABLE); | {
"domain": "codereview.stackexchange",
"id": 45050,
"lm_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++, chess",
"url": null
} |
c++, chess
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> calculateAttacks(calculateAttackBoardFunction calculateAttackBoard,
const std::array<std::vector<Bitboard>,
Square::NUMBER_OF_SQUARES> & blockerVariations);
void generateMagicNumbers(HashInformation * hashInformationTable,
const int minimumBitsRequiredForHashing,
const std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> & blockerVariations,
const std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> & attackBoards);
u64 searchForMagicNumber(const Square square,
const HashInformation & hashInformation,
const int minimumAmountOfBitsInLastByte,
const std::vector<Bitboard> & allBlockerVariations,
const std::vector<Bitboard> & attackBoards);
template <size_t rows, size_t columns>
void populateAttackDatabase(Bitboard (&attackDatabase)[rows][columns],
const HashInformation * hashInformationTable,
const std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> & blockerVariations,
const std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> & attackBoards);
int hashBlockerVariation(const Bitboard & blockerVariation, const u64 magicNumber, const int shiftAmount);
std::vector<Bitboard> enumerateSubmasks(Bitboard blockerMask);
Bitboard calculateBishopAttackBoard(const Square & square, const Bitboard & blockerVariation);
Bitboard calculateRookAttackBoard(const Square & square, const Bitboard & blockerVariation);
bool targetSquareIsBlocked(Bitboard targetSquare, Bitboard occupiedSquares);
Bitboard getPotentialBishopAttacks(const int square, const Bitboard &blockers); | {
"domain": "codereview.stackexchange",
"id": 45050,
"lm_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++, chess",
"url": null
} |
c++, chess
Bitboard getPotentialBishopAttacks(const int square, const Bitboard &blockers);
} // anonymous namespace
} // namespace magic_bitboards
magicbitboard.cpp
#include "magicbitboard.h"
namespace magic_bitboards
{
HashInformation BISHOP_HASHING_INFORMATION[Square::NUMBER_OF_SQUARES];
HashInformation ROOK_HASHING_INFORMATION[Square::NUMBER_OF_SQUARES];
Bitboard BISHOP_ATTACKS[Square::NUMBER_OF_SQUARES][LARGEST_AMOUNT_OF_BISHOP_BLOCKER_CONFIGURATIONS];
Bitboard ROOK_ATTACKS[Square::NUMBER_OF_SQUARES][LARGEST_AMOUNT_OF_ROOK_BLOCKER_CONFIGURATIONS];
void init()
{
initializeHashInformationEntries();
generateBlockerMasks();
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> bishopBlockerVariations = calculateBlockerVariations(BISHOP_HASHING_INFORMATION);
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> rookBlockerVariations = calculateBlockerVariations(ROOK_HASHING_INFORMATION);
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> bishopAttacks = calculateAttacks(calculateBishopAttackBoard, bishopBlockerVariations);
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> rookAttacks = calculateAttacks(calculateRookAttackBoard, rookBlockerVariations);
std::cout << "Searching for bishop magics, this could take up to 30 seconds... " << std::endl;
generateMagicNumbers(BISHOP_HASHING_INFORMATION, MINIMUM_NUMBER_OF_BITS_FOR_BISHOP_HASHING, bishopBlockerVariations, bishopAttacks);
std::cout << "DONE." << std::endl;
std::cout << "Searching for rook magic numbers, this could take up to 30 seconds... " << std::endl;
generateMagicNumbers(ROOK_HASHING_INFORMATION, MINIMUM_NUMBER_OF_BITS_FOR_ROOK_HASHING, rookBlockerVariations, rookAttacks);
std::cout << "DONE." << std::endl;
populateAttackDatabase(BISHOP_ATTACKS, BISHOP_HASHING_INFORMATION, bishopBlockerVariations, bishopAttacks);
populateAttackDatabase(ROOK_ATTACKS, ROOK_HASHING_INFORMATION, rookBlockerVariations, rookAttacks);
} | {
"domain": "codereview.stackexchange",
"id": 45050,
"lm_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++, chess",
"url": null
} |
c++, chess
namespace
{
u64 BISHOP_MAGIC_NUMBERS[Square::NUMBER_OF_SQUARES];
u64 ROOK_MAGIC_NUMBERS[Square::NUMBER_OF_SQUARES];
void initializeHashInformationEntries()
{
for (int square = 0; square < Square::NUMBER_OF_SQUARES; square++)
{
HashInformation bishopEntry;
HashInformation rookEntry;
BISHOP_HASHING_INFORMATION[square] = bishopEntry;
ROOK_HASHING_INFORMATION[square] = rookEntry;
}
}
void generateBlockerMasks()
{
for (int square = 0; square < Square::NUMBER_OF_SQUARES; square++)
{
Bitboard squareBitboard(square);
// Calculate the blocker mask for each piece on this square
BISHOP_HASHING_INFORMATION[square].blockerMask = calculateBishopBlockerMask(squareBitboard);
ROOK_HASHING_INFORMATION[square].blockerMask = calculateRookBlockerMask(squareBitboard);
// Store the shift amount to be used in the hash function
BISHOP_HASHING_INFORMATION[square].shiftAmount = BISHOP_HASHING_INFORMATION[square].blockerMask.numberOfSetBits();
ROOK_HASHING_INFORMATION[square].shiftAmount = ROOK_HASHING_INFORMATION[square].blockerMask.numberOfSetBits();
}
}
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> calculateBlockerVariations(HashInformation const * hashInformationTable)
{
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> blockerVariations;
for (int square = 0; square < Square::NUMBER_OF_SQUARES; square++)
{
blockerVariations[square] = enumerateSubmasks(hashInformationTable[square].blockerMask);
}
return blockerVariations;
}
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> calculateAttacks(calculateAttackBoardFunction calculateAttackBoard, const std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> & blockerVariations)
{
std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> attacks; | {
"domain": "codereview.stackexchange",
"id": 45050,
"lm_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++, chess",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.