text stringlengths 1 2.12k | source dict |
|---|---|
c++, memory-management, c++20
#if __linux__
#include <cerrno>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#elif _WIN32 || _WIN64
#include <windows.h>
#else
static_assert(false, "Unsupported OS\n");
#endif
namespace frozenca {
class MemoryMappedFile {
public:
static inline constexpr std::size_t new_file_size_ = (1UL << 20UL);
#if __linux__
using handle_type = int;
#elif _WIN32 || _WIN64
using handle_type = HANDLE;
#else
static_assert(false, "Unsupported OS\n");
#endif
using path_type = std::filesystem::path::value_type;
private:
const std::filesystem::path path_;
void *data_ = nullptr;
std::size_t size_ = 0;
handle_type handle_ = 0;
int flags_ = 0;
#if _WIN32 || _WIN64
handle_type mapped_handle_ = 0;
#endif // Windows
public:
MemoryMappedFile(const std::filesystem::path &path) : path_{path} {
bool exists = std::filesystem::exists(path);
open_file(path.c_str(), exists);
map_file();
}
~MemoryMappedFile() noexcept {
if (!data_) {
return;
}
bool error = false;
error = !unmap_file() || error;
error = !close_file() || error;
}
private:
void open_file(const path_type *path, bool exists) {
#if __linux__
flags_ = O_RDWR;
if (!exists) {
flags_ |= (O_CREAT | O_TRUNC);
}
#ifdef _LARGEFILE64_SOURCE
flags |= O_LARGEFILE;
#endif
errno = 0;
handle_ = open(path, flags_, S_IRWXU);
if (errno != 0) {
throw std::runtime_error("file open failed\n");
}
if (!exists) {
if (ftruncate(handle_, new_file_size_) == -1) {
throw std::runtime_error("failed setting file size\n");
}
} | {
"domain": "codereview.stackexchange",
"id": 43607,
"lm_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++, memory-management, c++20",
"url": null
} |
c++, memory-management, c++20
struct stat info;
bool success = (fstat(handle_, &info) != -1);
size_ = info.st_size;
if (!success) {
throw std::runtime_error("failed querying file size\n");
}
#elif _WIN32 || _WIN64
DWORD dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
DWORD dwCreationDisposition = exists ? OPEN_EXISTING : CREATE_ALWAYS;
DWORD dwFlagsandAttributes = FILE_ATTRIBUTE_TEMPORARY;
handle_ = CreateFileW(path, dwDesiredAccess, FILE_SHARE_READ, 0,
dwCreationDisposition, dwFlagsandAttributes, 0);
if (handle_ == INVALID_HANDLE_VALUE) {
throw std::runtime_error("file open failed\n");
}
if (!exists) {
LONG sizehigh = (new_file_size_ >> (sizeof(LONG) * 8));
LONG sizelow = (new_file_size_ & 0xffffffff);
DWORD result = SetFilePointer(handle_, sizelow, &sizehigh, FILE_BEGIN);
if ((result == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) ||
!SetEndOfFile(handle_)) {
throw std::runtime_error("failed setting file size\n");
}
}
typedef BOOL(WINAPI * func)(HANDLE, PLARGE_INTEGER);
HMODULE hmod = GetModuleHandleA("kernel32.dll");
func get_size =
reinterpret_cast<func>(GetProcAddress(hmod, "GetFileSizeEx"));
if (get_size) {
LARGE_INTEGER info;
if (get_size(handle_, &info)) {
std::int64_t size =
((static_cast<int64_t>(info.HighPart) << 32) | info.LowPart);
size_ = static_cast<size_t>(size);
} else {
throw std::runtime_error("failed querying file size");
}
} else {
DWORD hi = 0;
DWORD low = 0;
if ((low = GetFileSize(handle_, &hi)) != INVALID_FILE_SIZE) {
std::int64_t size = (static_cast<int64_t>(hi) << 32) | low;
size_ = static_cast<size_t>(size);
} else {
throw std::runtime_error("failed querying file size");
return;
}
}
#else
static_assert(false, "Unsupported OS\n");
#endif
} | {
"domain": "codereview.stackexchange",
"id": 43607,
"lm_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++, memory-management, c++20",
"url": null
} |
c++, memory-management, c++20
void map_file() {
#if __linux__
void *data =
mmap(0, file_size_, PROT_READ | PROT_WRITE, MAP_SHARED, handle_, 0);
if (data == reinterpret_cast<void *>(-1)) {
throw std::runtime_error("failed mapping file");
}
data_ = data;
#elif _WIN32 || _WIN64
DWORD protect = PAGE_READWRITE;
mapped_handle_ = CreateFileMappingA(handle_, 0, protect, 0, 0, 0);
if (!mapped_handle_) {
throw std::runtime_error("failed mapping file");
}
DWORD access = FILE_MAP_WRITE;
void *data = MapViewOfFileEx(mapped_handle_, access, 0, 0, size_, 0);
if (!data) {
throw std::runtime_error("failed mapping file");
}
data_ = data;
#else
static_assert(false, "Unsupported OS\n");
#endif
}
bool close_file() noexcept {
#if __linux__
return close(handle_) == 0;
#elif _WIN32 || _WIN64
return CloseHandle(handle_);
#else
static_assert(false, "Unsupported OS\n");
#endif
}
bool unmap_file() noexcept {
#if __linux__
return (munmap(data_, file_size_) == 0);
#elif _WIN32 || _WIN64
bool error = false;
error = !UnmapViewOfFile(data_) || error;
error = !CloseHandle(mapped_handle_) || error;
mapped_handle_ = NULL;
return !error;
#else
static_assert(false, "Unsupported OS\n");
#endif
} | {
"domain": "codereview.stackexchange",
"id": 43607,
"lm_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++, memory-management, c++20",
"url": null
} |
c++, memory-management, c++20
public:
void resize(std::ptrdiff_t new_size) {
if (new_size < 0) {
throw std::invalid_argument("new size < 0");
}
if (!data_) {
throw std::runtime_error("file is closed\n");
}
if (!unmap_file()) {
throw std::runtime_error("failed unmappping file\n");
}
#if __linux__
if (ftruncate(handle_, new_size) == -1) {
throw std::runtime_error("failed resizing mapped file\n");
}
#elif _WIN32 || _WIN64
std::int64_t offset = SetFilePointer(handle_, 0, 0, FILE_CURRENT);
if (offset == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) {
throw std::runtime_error("failed querying file pointer");
}
LONG sizehigh = (new_size >> (sizeof(LONG) * 8));
LONG sizelow = (new_size & 0xffffffff);
DWORD result = SetFilePointer(handle_, sizelow, &sizehigh, FILE_BEGIN);
if ((result == INVALID_SET_FILE_POINTER && GetLastError() != NO_ERROR) ||
!SetEndOfFile(handle_)) {
throw std::runtime_error("failed resizing mapped file");
}
sizehigh = (offset >> (sizeof(LONG) * 8));
sizelow = (offset & 0xffffffff);
SetFilePointer(handle_, sizelow, &sizehigh, FILE_BEGIN);
#else
static_assert(false, "Unsupported OS\n");
#endif
size_ = static_cast<std::size_t>(new_size);
map_file();
}
[[nodiscard]] std::size_t size() const noexcept { return size_; }
[[nodiscard]] void *data() noexcept { return data_; }
[[nodiscard]] const void *data() const noexcept { return data_; }
friend bool operator==(const MemoryMappedFile &mmfile1,
const MemoryMappedFile &mmfile2) {
auto res =
(mmfile1.path_ == mmfile2.path_ && mmfile1.data_ == mmfile2.data_ &&
mmfile1.size_ == mmfile2.size_ && mmfile1.handle_ == mmfile2.handle_ &&
mmfile1.flags_ == mmfile2.flags_);
#if _WIN32 || _WIN64
res = res && (mmfile1.mapped_handle_ == mmfile2.mapped_handle_);
#endif // Windows
return res;
} | {
"domain": "codereview.stackexchange",
"id": 43607,
"lm_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++, memory-management, c++20",
"url": null
} |
c++, memory-management, c++20
friend bool operator!=(const MemoryMappedFile &mmfile1,
const MemoryMappedFile &mmfile2) {
return !(mmfile1 == mmfile2);
}
};
} // namespace frozenca
Changes in AllocManager.h (from (C++ imitation of glibc malloc(), free()))
// ... all other code is the same ...
// store *all* chunks
std::pmr::vector<unsigned char> all_chunks_;
public:
AllocManagerDefault(std::size_t init_pool_size, std::pmr::memory_resource *mem_res =
std::pmr::get_default_resource())
: curr_pool_size_{init_pool_size}, fast_bins_(num_fast_bins_, nullptr),
small_bins_(num_small_bins_, nullptr),
all_chunks_(init_pool_size,
std::pmr::polymorphic_allocator<unsigned char>(mem_res)) {
assert(init_pool_size % chunk_alignment_ == 0);
top_chunk_ = first_chunk();
set_size(top_chunk_, init_pool_size);
}
// ... all other code is the same ...
Changes in test code:
int main() {
namespace fc = frozenca;
fc::FileArenaResource arena_res("database.bin");
// two gigabytes
// I've tried 1ULL << 34ULL (16GB), but my machine freezed... let's not overdo
fc::AllocManagerDefault simulator(1UL << 31UL, &arena_res);
// ... all other test code is the same ...
}
I saw that the memory resource successfully makes an 2GB file database.bin, now I will tweak my B-Tree (C++ : B-Tree in C++20 (+Iterator support)) using this memory resource. | {
"domain": "codereview.stackexchange",
"id": 43607,
"lm_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++, memory-management, c++20",
"url": null
} |
c++, memory-management, c++20
Answer: Portability
Your code only works on Linux and Windows, because those are the two operating systems you check for. But mmap() is a POSIX function, so in principle any POSIX-compliant operating system (including BSDs and macOS) will support it. See also how to determine if the operating system is POSIX in C.
Available disk space might be smaller than RAM
While a typical system has more disk space than RAM, this is not always the case. And even if the attached disks are large, not all space might be available to your program due to the disks already being full, or limits being placed on how much a given user is allowed to use.
Note that instead of mapping a file, you can also create an anonymous map. This is basically what malloc() and new nowadays do under the hood to get chunks of memory from the system. Windows has an equivalent. You can use this as a fallback in case you cannot create a large enough file, or do it the other way around: first try an anonymous map, if it doesn't work, fall back to a file.
Beware of memory overcommitment
It is possible to allocate more memory than you can actually use, or even more disk space than you can actually use. This is because often, memory is overcommitted in some way or another.
There might be ways to ensure memory is physically backed before using it. For RAM, you can do this with mlock(). For disk space, you can use posix_fallocate(). However, these calls can be inefficient, and they immediately cause less memory to be available to other users, even if that memory will not actually be used by the application requesting it.
Bad use of a polymorphic memory resource
I do not see the point of making FileArenaResource a polymorphic memory resource, nor using PMR for all_chunks_: there is nothing polymorphic about all_chunks_, it's just a single array of bytes, nothing more. You can only allocate something once from FileArenaResource. | {
"domain": "codereview.stackexchange",
"id": 43607,
"lm_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++, memory-management, c++20",
"url": null
} |
c++, memory-management, c++20
all_chunks_ is a one-off thing, so I wouldn't try to force it to deallocate itself using RAII. But if you do want that, consider using a std::unique_ptr<unsigned char[], Deleter>, where Deleter is taking care of deallocating the mapped file. | {
"domain": "codereview.stackexchange",
"id": 43607,
"lm_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++, memory-management, c++20",
"url": null
} |
haskell
Title: Implement a Queue in Haskell
Question: I teach a data structures and algorithms course. Students can choose C++ or Java. As an exercise for myself, I am doing the assignments in Haskell. My primary goal is to understand what aspects of my class are easier in Haskell, and which aspects are more challenging. I am a fairly noob Haskell coder. Hence, I tend to be unaware of changes within the Haskell community, best practices, and "the right things". This is my secondary goal.
The class includes a List, Stack, Queue, Heap, and hash table. I'm up to the Queue structure so far.
Questions
For the List, I implemented Foldable, Functor, Monoid, Semigroup to allow my List to be "list like" with the rest of Haskell's ecosystem, e.g., fmap, and <>. Should I do that for the Queue too?
In the C++/Java version of the class we implement a doubly-linked list then apply a Stack Interface on top of it. This is to show the flexibility of the doubly-linked list structure. However for the Haskell version it seemed more prudent to express the Queue structure directly, i.e, a thing with a beginning and ending, with some stuff in the middle. Is this a good choice? Is there a better expression of the Queue structure?
Is push still constant time, i.e., O(1)? The recursive call for the More case will match either One or Two and be done.
Errors. head Nil is undefined. This is lame. While head :: Queue a -> Maybe a is an option, is there a better option?
Is there a question I should have asked?
Related Work
A simple queue implementation in Haskell
Uses Maybe which is a hint my implementation should as well.
Derives Eq. That makes sense to compare two Queue's. I'll add that to mine.
Queue Data Structure
module Queue
( Queue (Nil, Unit, More),
head,
pop,
push,
fromList,
empty,
)
where
import Data.List (foldl')
import Prelude hiding (head)
data Queue a
= Nil
| Unit a
| Two a a
| More a (Queue a) a
deriving (Show) | {
"domain": "codereview.stackexchange",
"id": 43608,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
data Queue a
= Nil
| Unit a
| Two a a
| More a (Queue a) a
deriving (Show)
head :: Queue a -> a
head Nil = undefined
head (Unit x) = x
head (Two _ x) = x
head (More _ _ x) = x
pop :: Queue a -> (Queue a, a)
pop Nil = (Nil, undefined)
pop (Unit x) = (Nil, x)
pop (Two x y) = (Unit x, y)
pop (More x middle y) = (More x middle' newEnd, y)
where
(middle', newEnd) = pop middle
empty :: Queue a -> Bool
empty Nil = True
empty _ = False
push :: a -> Queue a -> Queue a
push x Nil = Unit x
push x (Unit y) = Two x y
push x (Two y z) = More x (Unit y) z
push w (More x middle y) = More w (push x middle) y
fromList :: [a] -> Queue a
fromList = foldl' push' Nil
where
push' = flip push
Tests
module QueueSpec (spec) where
import Data.Foldable (toList)
import Data.List (sort)
import Queue as Q
import Test.Hspec
import Test.Hspec.QuickCheck
import Test.QuickCheck
import Test.QuickCheck.Modifiers
spec :: Spec
spec = do
describe "head" $ do
it "put gets back" $ do
Q.head (Unit 5) `shouldBe` 5
it "pop unit" $ do
let x = Nil
let x2 = push 5 x
let (q, y) = pop x2
y `shouldBe` 5
it "pop more" $ do
let x = Unit 1
let x2 = push 2 x
let (q, y) = pop x2
y `shouldBe` 1
it "pop more with priority" $ do
let x = Unit 2
let x2 = push 1 x
let (q, y) = pop x2
y `shouldBe` 2
it "push a list" $ do
let x = fromList [1, 2, 3, 4, 5]
let (q, y) = pop x
y `shouldBe` 1
it "first element of list is first of queue" $
property prop_firstListIsFirstQueue
prop_firstListIsFirstQueue :: NonEmptyList Int -> Bool
prop_firstListIsFirstQueue xs = Prelude.head l == Q.head q
where
l = getNonEmpty xs
q = fromList l | {
"domain": "codereview.stackexchange",
"id": 43608,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
Answer: Use the Right Data Structure
In Haskell, a double-linked list is, as you know, inefficient, as removing an element from the end requires copying all other elements of the list.
In this case, you define four cases, which try to build a list from the middle out. Your push and pop operations still run in linear time, needing to recurse to the root of the structure and generate an entirely new list. This vitiates any advantage of storing the first and last elements in the outermost node.
You are better off using a self-balancing binary tree here, such as a red-black tree, which would be able to re-use the majority of the nodes on each operation. There are also functional FIFO queue structures using, e.g., a push list and a pop list, where the pop list is created by reversing the push list.
If you’re going to perform a linear-time copy of the data, the structure you probably want to use is a Data.Vector, which can add data to the right or shift it to the left as efficiently as possible, even amortizing most of the operations. For example, enqueueing elements could be a constant-time insertion at the end, and dequeueing them could be a constant-time increment of an offset from the beginning. Eventually, your queue will run out of space, and you will need to copy the entire thing to a new Vector. But many smaller queues might never need to do this, and would just get constant time. When the vector does get copied, this is fast because it performs one allocation and then copies a contiguous block of memory.
Replace undefined with a Permanent Solution
If pop on an empty queue should be a runtime error, declare it as an error with a meaningful message. This will help you, or anyone else using your library, debug their code.
Alternatively, pop could return a Maybe value, and pop on an empty queue could then return Nothing, rather than crash the program.
There is, Indeed, a Bug | {
"domain": "codereview.stackexchange",
"id": 43608,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
There is, Indeed, a Bug
As you thought, pop Nil can get called. Consider the following sequence of operations. Please read from the bottom up.
test =
fst . pop $ -- Error! Attempts to pop Nil.
fst . pop $ -- More 3 Nil 2
push 3 $ -- More 3 (Unit 2) 1
push 2 $ -- Two 2 1
push 1 $ -- Unit 1
Nil | {
"domain": "codereview.stackexchange",
"id": 43608,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
haskell
Or with the aid of import Data.Function ((&)):
Nil &
push 1 & -- Unit 1
push 2 & -- Two 2 1
push 3 & -- More 3 (Unit 2) 1
pop & fst & -- More 3 Nil 2
pop & fst -- Error! Attempts to pop Nil.
Consider Using the Names Enqueue and Dequeue
This seems less ambiguous to me than push and pop operations, but those names are widely-used enough for queues that I won’t tell you they’re wrong. | {
"domain": "codereview.stackexchange",
"id": 43608,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
c++, sfml
Title: game interface setup
Question: I've learned that magic numbers are bad in code. However, should the coordinates, and rotation angles of all the sprites be stored in variables? Is the convention in game development to leave those hard-coded values as arguments to set the coordinates or the angles of the transformable?
// Create a texture to hold a graphic on the GPU
Texture textureBackground;
// Load a graphic into the texture
textureBackground.loadFromFile("graphics/background.png");
// Create a sprite
Sprite spriteBackground;
// Attach the texture to the sprite
spriteBackground.setTexture(textureBackground);
// Set the spriteBackground to cover the screen
spriteBackground.setPosition(0, 0);
// Create a tree sprite
Texture textureTree;
textureTree.loadFromFile("graphics/tree.png");
Sprite spriteTree;
spriteTree.setTexture(textureTree);
spriteTree.setPosition(810, 0);
// Prepare the bee
Texture textureBee;
textureBee.loadFromFile("graphics/bee.png");
Sprite spriteBee;
spriteBee.setTexture(textureBee);
spriteBee.setPosition(0, 800);
Answer: Yes magic numbers are bad, as well as the data like "graphics/bee.png".
The problem with that data in your code is that it is hidden, and dispersed across your source code files, and you need to recompile to modify it.
Read about Data Driven Design (and do not confuse with Data Oriented Design).
The idea is to separate the code and the data:
We can put the data in an ascii file (txt, csv, JSON, XML, whatever you want) or binary. You will need to parse it in the code. If you need more parameters for your sprites, just add them at the end of each line and modify the code that extracts them.
==Data.csv==
"graphics/background.png",0,0
"graphics/tree.png",810,0
"graphics/bee.png",0,800
And the code does not include any specific data. Just code to parse the elements and do the actions. Also you "don't repeat yourself" (DRY), you avoid copy/paste the same code for each new sprite.
==PseudoCode==
list<Sprite> m_sprites; | {
"domain": "codereview.stackexchange",
"id": 43609,
"lm_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++, sfml",
"url": null
} |
c++, sfml
for each line in data.csv {
std::string fileName;
int x,y;
parseLine(line, &fileName, &x, &y); // extract the components form the csv/txt/binary data file
Texture texture;
texture.loadFromFile(fileName);
Sprite sprite;
sprite.setTexture(texture);
sprite.setPosition(x, y);
m_sprites.push_back(sprite);
}
Now you can run the same code without compiling/linking and just changing the data file, the scene changes.
You separate the design task (decide what to draw and where) from the programming part (draw a sprite in coordinates x,y). | {
"domain": "codereview.stackexchange",
"id": 43609,
"lm_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++, sfml",
"url": null
} |
performance, php, array
Title: Filter an array, but remove the filtered elements
Question: I needed a PHP function that would filter values from one array into a new one, while also removing those values from the original array. After looking through the docs, I didn't see any such function, so I wrote my own. While I don't expect it to run with any comparable efficiency as a native function, I am curious if there are any optimization steps I could be missing.
This code is written for PHP 8.1.X
/**
* Extract values from an array, and return the results
*
* @param array $array The array to filter
* @param callable|string $callback Function to filter the array with
*
* @return array A new array containing the filtered elements
*/
function array_excise(array &$array, callable|string $callback): array {
$results = [];
$arr_len = count($array);
for($i = 0; $i < $arr_len; $i++) {
if(is_callable($callback))
{
if($callback($array[$i]))
{
$results[] = $array[$i];
unset($array[$i]);
}
}
else if(is_string($callback))
{
if(call_user_func($callback, $array[$i]))
{
$results[] = $array[$i];
unset($array[$i]);
}
}
}
$array = array_values($array);
return $results;
}
Usage Example:
$people = [
[
"name" => "Billy Jean",
"filter" => false,
],
[
"name" => "Ronald Reagan",
"filter" => true,
],
[
"name" => "Bill Clinton",
"filter" => true,
],
[
"name" => "Michael Jackson",
"filter" => false,
],
[
"name" => "Johnny Cash",
"filter" => false,
],
];
$presidents = array_excise($people, function($p){ return $p["filter"]; });
print_r($people);
print_r($presidents); | {
"domain": "codereview.stackexchange",
"id": 43610,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, php, array",
"url": null
} |
performance, php, array
print_r($people);
print_r($presidents);
/* output
Array
(
[0] => Array
(
[name] => Billy Jean
[filter] =>
)
[1] => Array
(
[name] => Michael Jackson
[filter] =>
)
[2] => Array
(
[name] => Johnny Cash
[filter] =>
)
)
Array
(
[0] => Array
(
[name] => Ronald Reagan
[filter] => 1
)
[1] => Array
(
[name] => Bill Clinton
[filter] => 1
)
)
*/
Answer:
It might be worth mentioning in your docblock declaration that the input array is required to be an indexed array in your code.
Your code returns an indexed array and unconditionally re-indexes the mutated input array. There are scenarios where indexed arrays may damage valuable associative keys. I'll recommend using a foreach() to iterate the dataset and avoid forcing indexed keys. If the code that calls this function needs either of the arrays to be indexed, array_values() is not an expensive or ugly call.
You should not write the is_callable() check inside the loop -- it will pass or fail but will not change. Make the check before looping and return early if the parameter is not callable.
Both styles of calling the dynamic callback will work regardless of if you declared a string name or an anonymous function, to keep your script lean, just either choose call_user_func() or the variably named function for easier reading.
As a matter of PSR-12 compliance, please do not write else if in PHP -- it is a single word.
Suggested code: (Demo) (or Demo)
function array_excise(array &$array, callable|string $callback): array {
$result = [];
if (!is_callable($callback)) {
return $result;
}
foreach ($array as $key => $value) {
if ($callback($value)) {
$result[$key] = $value;
unset($array[$key]);
}
}
return $result;
} | {
"domain": "codereview.stackexchange",
"id": 43610,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, php, array",
"url": null
} |
performance, php, array
Granted your function is called "excise" -- which infers "cutting away" -- I can appreciate that your function mutates the input array. However, I do like what @lukas.j mentions about not mutating the input and instead returning all arrays.
If you wanted to move toward that approach, you could set up a grouping function that creates first level keys from the passed in callback parameter. If your callback returns a boolean result, then expect to handle 0 and 1 group keys. Something like this: (Demo)
function array_group(array $array, callable|string $callback): array {
$groups = [];
if (!is_callable($callback)) {
return $groups;
}
foreach ($array as $key => $value) {
$groups[$callback($value)][$key] = $value;
}
return $groups;
}
var_export(
array_group(
$people,
fn($p) => substr($p["name"], 0, 4)
)
); | {
"domain": "codereview.stackexchange",
"id": 43610,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, php, array",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
Title: Tic Tac Toe - Python
Question: I made a program that allows a player to play Tic Tac Toe against a computer. Of course, I didn't make it analyse the slightly harder algorithms, as I am just a beginner at programming. Are there any ways to improve this code? Is it quite long and hard to read.
from random import randint
from turtle import Screen
import math
import turtle
import numpy
####################################################################
def draw_board():
#setup screen
screen = Screen()
screen.setup(300, 300)
screen.setworldcoordinates(0, -300, 300, 0)
#setup turtle
turtle.hideturtle()
turtle.speed(0)
#draw colored box
turtle.color("BlanchedAlmond", "BlanchedAlmond")
turtle.begin_fill()
for i in range(4):
turtle.forward(300)
turtle.right(90)
turtle.end_fill()
turtle.width(3)
turtle.color("gold")
turtle.penup()
#draw y lines
turtle.penup()
turtle.goto(0, -100)
turtle.pendown()
turtle.forward(300)
turtle.penup()
turtle.goto(0, -200)
turtle.pendown()
turtle.forward(300)
#draw x lines
turtle.right(90)
turtle.penup()
turtle.goto(100, 0)
turtle.pendown()
turtle.forward(300)
turtle.penup()
turtle.goto(200, 0)
turtle.pendown()
turtle.forward(300)
#titles
turtle.color("black")
turtle.penup()
turtle.goto(100, 45)
turtle.pendown()
s = ("Arial", "15", "bold")
turtle.write("Column", font=s)
turtle.penup()
turtle.goto(-115, -150)
turtle.pendown()
s = ("Arial", "15", "bold")
turtle.write("Row", font=s) | {
"domain": "codereview.stackexchange",
"id": 43611,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
#y Column
turtle.penup()
turtle.goto(45, 10)
turtle.pendown()
s = ("Arial", "13", "bold")
turtle.write("1", font=s)
turtle.penup()
turtle.goto(145, 10)
turtle.pendown()
s = ("Arial", "13", "bold")
turtle.write("2", font=s)
turtle.penup()
turtle.goto(245, 10)
turtle.pendown()
s = ("Arial", "13", "bold")
turtle.write("3", font=s)
#x Row
turtle.penup()
turtle.goto(-35, -50)
turtle.pendown()
s = ("Arial", "13", "bold")
turtle.write("1", font=s)
turtle.penup()
turtle.goto(-35, -150)
turtle.pendown()
s = ("Arial", "13", "bold")
turtle.write("2", font=s)
turtle.penup()
turtle.goto(-35, -250)
turtle.pendown()
s = ("Arial", "13", "bold")
turtle.write("3", font=s)
turtle.color("blue")
turtle.penup()
turtle.goto(315, -150)
turtle.pendown()
s = ("Arial", "12", "bold")
turtle.write("User: X", font=s)
turtle.penup()
turtle.goto(315, -170)
turtle.pendown()
s = ("Arial", "12", "bold")
turtle.write("Computer: O", font=s)
####################################################################
#computer move
def comp_move(co, us):
if not co[2][2] and not us[2][2]:
draw(2, 2, "O") #middle
else:
while True:
r = randint(1, 3)
c = randint(1, 3)
if not co[r][c] and not us[r][c]:
draw(r, c, "O")
break
####################################################################
#user move
def user_move(co, us):
while True:
r, c = [int(j) for j in input("Input row and column:").split(",")]
if r in [1,2,3] and c in [1,2,3] \
and not co[r][c] and not us[r][c]:
draw(r, c, "X")
break
else:
print("Invalid")
#################################################################### | {
"domain": "codereview.stackexchange",
"id": 43611,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
####################################################################
#draw X & O
def draw(r, c, symbol):
turtle.penup()
if symbol == "X":
us[r][c] = True
turtle.setheading(0)
turtle.goto(c * 100 - 90, -(r * 100 - 90))
turtle.pendown()
turtle.color("black")
turtle.goto(c * 100 - 10, -(r * 100 - 10))
turtle.penup()
turtle.left(90)
turtle.forward(80)
turtle.pendown()
turtle.left(135)
turtle.forward(80 * math.sqrt(2))
turtle.penup()
elif symbol == "O":
co[r][c] = True
turtle.setheading(0)
turtle.goto(c * 100 - 50, -(r * 100 - 50) - 40)
turtle.pendown()
turtle.color("black")
turtle.circle(40)
turtle.penup()
#################################################################### | {
"domain": "codereview.stackexchange",
"id": 43611,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
####################################################################
#check lines
def check_win(co, us):
global win
win = False
turtle.color("red")
turtle.width(7)
if (us[1][1] and us[2][2] and us[3][3]) \
or (co[1][1] and co[2][2] and co[3][3]):
#diagonal
turtle.penup()
turtle.goto(50, -50)
turtle.pendown()
turtle.goto(250, -250)
elif (us[1][3] and us[2][2] and us[3][1]) \
or (co[1][3] and co[2][2] and co[3][1]):
#diagonal
turtle.penup()
turtle.goto(250, -50)
turtle.pendown()
turtle.goto(50, -250)
elif (us[1][1] and us[1][2] and us[1][3]) \
or (co[1][1] and co[1][2] and co[1][3]):
#row 1
turtle.penup()
turtle.goto(50, -50)
turtle.pendown()
turtle.goto(250, -50)
elif (us[2][1] and us[2][2] and us[2][3]) \
or (co[2][1] and co[2][2] and co[2][3]):
#row 2
turtle.penup()
turtle.goto(50, -150)
turtle.pendown()
turtle.goto(250, -150)
elif (us[3][1] and us[3][2] and us[3][3]) \
or (co[3][1] and co[3][2] and co[3][3]):
#row 3
turtle.penup()
turtle.goto(50, -250)
turtle.pendown()
turtle.goto(250, -250)
elif (us[1][1] and us[2][1] and us[3][1]) \
or (co[1][1] and co[2][1] and co[3][1]):
#column 1
turtle.penup()
turtle.goto(50, -50)
turtle.pendown()
turtle.goto(50, -250)
elif (us[1][2] and us[2][2] and us[3][2]) \
or (co[1][2] and co[2][2] and co[3][2]):
#column 2
turtle.penup()
turtle.goto(150, -50)
turtle.pendown()
turtle.goto(150, -250)
elif (us[1][3] and us[2][3] and us[3][3]) \
or (co[1][3] and co[2][3] and co[3][3]):
#column 3
turtle.penup()
turtle.goto(250, -50)
turtle.pendown()
turtle.goto(250, -250) | {
"domain": "codereview.stackexchange",
"id": 43611,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
#check winner
turtle.width(3)
turtle.color("blue")
if (us[1][1] and us[2][2] and us[3][3]) \
or (us[1][3] and us[2][2] and us[3][1]) \
or (us[1][1] and us[1][2] and us[1][3]) \
or (us[2][1] and us[2][2] and us[2][3]) \
or (us[3][1] and us[3][2] and us[3][3]) \
or (us[1][1] and us[2][1] and us[3][1]) \
or (us[1][2] and us[2][2] and us[3][2]) \
or (us[1][3] and us[2][3] and us[3][3]):
turtle.penup()
turtle.goto(50, -350)
turtle.pendown()
s = ("Arial", "20", "bold")
turtle.write("User wins!", font=s)
win = True
elif (co[1][1] and co[2][2] and co[3][3]) \
or (co[1][3] and co[2][2] and co[3][1]) \
or (co[1][1] and co[1][2] and co[1][3]) \
or (co[2][1] and co[2][2] and co[2][3]) \
or (co[3][1] and co[3][2] and co[3][3]) \
or (co[1][1] and co[2][1] and co[3][1]) \
or (co[1][2] and co[2][2] and co[3][2]) \
or (co[1][3] and co[2][3] and co[3][3]):
turtle.penup()
turtle.goto(50, -350)
turtle.pendown()
s = ("Arial", "20", "bold")
turtle.write("Computer wins!", font=s)
win = True
#################################################################### | {
"domain": "codereview.stackexchange",
"id": 43611,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
#check for two-in-a-row
def check2(p1, p2):
global moved
moved = True
comb = numpy.logical_or(p1, p2)
#row
if p1[1][1] and p1[1][2] and not comb[1][3]: draw(1, 3, "O")
elif p1[1][1] and p1[1][3] and not comb[1][2]: draw(1, 2, "O")
elif p1[1][2] and p1[1][3] and not comb[1][1]: draw(1, 1, "O")
elif p1[2][1] and p1[2][2] and not comb[2][3]: draw(2, 3, "O")
elif p1[2][1] and p1[2][3] and not comb[2][2]: draw(2, 2, "O")
elif p1[2][2] and p1[2][3] and not comb[2][1]: draw(2, 1, "O")
elif p1[3][1] and p1[3][2] and not comb[3][3]: draw(3, 3, "O")
elif p1[3][1] and p1[3][3] and not comb[3][2]: draw(3, 2, "O")
elif p1[3][2] and p1[3][3] and not comb[3][1]:
draw(3, 1, "O")
#column
elif p1[1][1] and p1[2][1] and not comb[3][1]:
draw(3, 1, "O")
elif p1[1][1] and p1[3][1] and not comb[2][1]:
draw(2, 1, "O")
elif p1[2][1] and p1[3][1] and not comb[1][1]:
draw(1, 1, "O")
elif p1[1][2] and p1[2][2] and not comb[3][2]:
draw(3, 2, "O")
elif p1[1][2] and p1[3][2] and not comb[2][2]:
draw(2, 2, "O")
elif p1[2][2] and p1[3][2] and not comb[1][2]:
draw(1, 2, "O")
elif p1[1][3] and p1[2][3] and not comb[3][3]:
draw(3, 3, "O")
elif p1[1][3] and p1[3][3] and not comb[2][3]:
draw(2, 3, "O")
elif p1[2][3] and p1[3][3] and not comb[1][3]:
draw(1, 3, "O")
#diagonal
elif p1[1][1] and p1[2][2] and not comb[3][3]:
draw(3, 3, "O")
elif p1[1][1] and p1[3][3] and not comb[2][2]:
draw(2, 2, "O")
elif p1[2][2] and p1[3][3] and not comb[1][1]:
draw(1, 1, "O")
elif p1[1][3] and p1[2][2] and not comb[3][1]:
draw(3, 1, "O")
elif p1[1][3] and p1[3][1] and not comb[2][2]:
draw(2, 2, "O")
elif p1[2][2] and p1[3][1] and not comb[1][3]:
draw(1, 3, "O")
#not moved
else:
moved = False | {
"domain": "codereview.stackexchange",
"id": 43611,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
####################################################################
####################################################################
#main
#draw board
draw_board()
#initialize variables
co = numpy.full((4, 4), False)
us = numpy.full((4, 4), False)
#pick first p1ayer
comp = False
user = False
if randint(0, 1) == 0:
user = True
else:
comp = True
#first two moves
if comp: #comp first move in middle or corner
ran1 = randint(1, 5)
if ran1 == 1: draw(1, 1, "O")
elif ran1 == 2: draw(1, 3, "O")
elif ran1 == 3: draw(2, 2, "O")
elif ran1 == 4: draw(3, 1, "O")
elif ran1 == 5: draw(3, 3, "O")
user_move(co, us) #user move
user = False
comp = True
else: #user first move
user_move(co, us)
if not us[2][2]: #comp move middle
draw(2, 2, "O")
else: #comp move corner
ran2 = randint(1, 4)
if ran2 == 1: draw(1, 1, "O")
elif ran2 == 2: draw(1, 3, "O")
elif ran2 == 3: draw(3, 1, "O")
elif ran2 == 4: draw(3, 3, "O")
user = True
comp = False
#7 moves left
for i in range(7):
if comp:
check2(co, us) #check to win
if not moved:
check2(us, co) #check to block
if not moved:
comp_move(co, us)
comp = False
user = True
elif user:
user_move(co, us)
user = False
comp = True
check_win(co, us)
if win:
break
#draw
if not win:
turtle.penup()
turtle.goto(110, -350)
turtle.pendown()
s = ("Arial", "20", "bold")
turtle.write("Draw", font=s)
# Win: If the p1ayer has two in a row, they can p1ace a third to get three in a row.
# Block: If the opponent has two in a row, the p1ayer must p1ay the third themselves to block the opponent.
# Fork: Create an opportunity where the p1ayer has two ways to win (two non-blocked lines of 2). | {
"domain": "codereview.stackexchange",
"id": 43611,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
python, beginner, python-3.x, tic-tac-toe
# Fork: Create an opportunity where the p1ayer has two ways to win (two non-blocked lines of 2).
# Blocking an opponent's fork: If there is only one possible fork for the opponent, the p1ayer should block it. Otherwise, the p1ayer should block all forks in any way that simultaneously allows them to create two in a row.
# Center: A p1ayer marks the center.
# Opposite corner: If the opponent is in the corner, the p1ayer p1ays the opposite corner.
# Empty corner: The p1ayer p1ays in a corner square.
# Empty side: The p1ayer p1ays in a middle square on any of the 4 sides.
Answer: Your code is long because it repeats a lot of code / has lots of hard coded conditionals. A lot of it could be refactored as appropriately dictionaries or dataclasses.
Try to find terms that group data or functionality. If you can give a code block a name, you can refactor it into its own method. After you have split up your code into lots of little chunks of code, you can start to look for similarities and generalizations.
For starters, I would recommend reading into programming principles like DRY
For more in depth info, you can read my recent post about how to make code more readable. | {
"domain": "codereview.stackexchange",
"id": 43611,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
Title: Tic-Tac-Toe - JS + HTML
Question: Coming from a python background, I recently started learning django, currently at the javascript section. This tic-tac-toe code is to familiarize myself with javascript basic concepts. No application code is included, just JS and HTML.
tic-tac-toe.css
td {
background: black;
width: 2em;
height: 2em;
font-size: 3em;
text-align: center;
color: orange;
}
table {
margin: auto;
}
h1 {
margin-left: 46%;
}
tic-tac-toe.js
function markCell(cell, marks) {
if (marks.length === 0) {
marks.push('O')
marks.push('X')
}
if (cell.textContent === '') {
cell.textContent = marks.pop()
}
}
function clearBoard() {
for (let cell of document.getElementsByTagName('td')) {
cell.textContent = ''
}
}
function updateWinnerScore(winner) {
let scores = document.querySelector('h1').innerText
let score1 = parseInt(scores[0])
let score2 = parseInt(scores[4])
if (winner === 'XXX') {
score1 += 1
clearBoard()
} else if (winner === 'OOO') {
score2 += 1
clearBoard()
}
document.getElementsByTagName('h1')[0].innerHTML = score1 + ' - ' + score2
}
function updateScores(cells) {
let values = []
for (let c of cells) {
values.push(c.textContent)
}
let combinations = [values.slice(0, 3).join(''), values.slice(3, 6).join(''), values.slice(6, 9).join('')]
for (let i = 0; i < 3; ++i) {
combinations.push([values[i], values[i + 3], values[i + 6]].join(''))
}
combinations.push([values[0], values[4], values[8]].join(''))
combinations.push([values[2], values[4], values[6]].join(''))
let winner
for (let state of ['XXX', 'OOO']) {
if (combinations.includes(state)) {
winner = state
}
}
updateWinnerScore(winner)
if (values.join('').length === 9) {
clearBoard()
}
} | {
"domain": "codereview.stackexchange",
"id": 43612,
"lm_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, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
function updateBoard(marks) {
let cells = Array.from(document.getElementsByTagName('td'))
for (let c of cells) {
c.addEventListener('click', function () {
markCell(c, marks)
})
c.addEventListener('click', function () {
updateScores(cells)
})
}
}
tic-tac-toe.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tic Tac Toe</title>
<link rel="stylesheet" href="tic-tac-toe.css">
<script src="tic-tac-toe.js"></script>
</head>
<body>
<h1>0 - 0</h1>
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
<script>
let marks = ['O', 'X']
updateBoard(marks)
</script>
</body>
</html>
Answer: There are many ways to implement TicTacToe, and its good to try out several of them. There are lots of examples on this site, it would serve you well to compare some of them and learn from the feedback given. The definition of 'improve' is rather subjective, depending on the problem at hand and the developer knowledge. Javascript is very flexible in terms of how you might organise the code.
I don't think there is much merit in actually outlining many of the ways you could refactor the code, so I'll just present a rework of the code that largely follows the existing, and some general pointers:
Consider how functions and variables in the main scope affect the global scope. Reducing the number of global symbols will help you be a good citizen alongside other scripts. In my rework I've not gone all the way, just providing a hint that its easy to remove dependencies (such as on DOM element retrieval) and pass them in where necessary. | {
"domain": "codereview.stackexchange",
"id": 43612,
"lm_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, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
You are largely maintaining game state in the DOM (for example using element.textContent). In a trivial example such as this that's likely ok, but as your script gain complexity, you'll want to consider maintaining state within the game and updating the DOM to match it. This will make debugging easier, as you can track state updates more easily. It's a technique used by many of the UI frameworks, so worth learning. I've gone some of the way, but not all, just to indicate how you can encapsulate some of the state into the entry point.
In updateScores you had a somewhat complicated and repetitive way of determining which cells contributed to a win. Refactoring this out to a list of possibles and then comparing makes things clearer.
Use functions (often arrow functions) to help describe what the purpose of a more complex statement is. You can see this with gameOver(). Or assign the result to a variable and then compare if you prefer, either way, the name of the variable/function makes the intention clearer.
function markCell(cell, player) {
if (cell.textContent === '') {
cell.textContent = player
return true
}
return false
}
function updateScores(cells, reset, updateWinnerScore) {
let values = cells.map(c => c.textContent)
const lines = [
[ 0, 1, 2 ],
[ 3, 4, 5 ],
[ 6, 7, 8 ],
[ 0, 3, 6 ],
[ 1, 4, 7 ],
[ 2, 5, 8 ],
[ 0, 4, 8 ],
[ 2, 4, 6 ],
]
const winner = lines.reduce((acc, line) => {
return acc || line.reduce((acc, index) => {
return acc === values[index] ? acc : undefined
}, values[0])
}, undefined)
updateWinnerScore(winner)
const gameOver = () => winner || values.join('').length == 9
if (gameOver()) {
reset()
}
}
function startGame(container) { | {
"domain": "codereview.stackexchange",
"id": 43612,
"lm_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, html, tic-tac-toe",
"url": null
} |
javascript, html, tic-tac-toe
function startGame(container) {
const cells = Array.from(document.querySelectorAll(`${container} td`))
const heading = document.querySelector(`${container} .score`)
let player
if (cells.length !== 9 || heading === undefined) {
alert('Invalid markup');
return
}
const reset = () => {
cells.forEach(c => c.textContent = '')
player = 'X'
}
const updateWinnerScore = winner => {
if (winner !== 'X' && winner !== 'O') {
return
}
const score = heading.querySelector(`.${winner}`)
score.innerText = parseInt(score.innerText) + 1
}
reset()
for (let c of cells) {
c.addEventListener('click', function () {
if (markCell(c, player)) {
player = player === 'X' ? 'O' : 'X'
updateScores(cells, reset, updateWinnerScore)
}
})
}
}
startGame('.board')
td {
background: black;
width: 2em;
height: 2em;
font-size: 3em;
text-align: center;
color: orange;
}
table {
margin: auto;
}
h1 {
margin-left: 46%;
}
<div class="board">
<h1 class="score"><span class="X">0</span> - <span class="O">0</span></h1>
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
</div> | {
"domain": "codereview.stackexchange",
"id": 43612,
"lm_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, html, tic-tac-toe",
"url": null
} |
haskell
Title: Haskell function that executes each action until a predicate returns True
Question: The following function executes each action from the list until a predicate returns True. I have a feeling that this function can be rewritten using fold and without the do construct but I don't know how.
execUntil :: (Eq a, Monad m) => [m a] -> (a -> Bool) -> m ()
execUntil [] p = return ()
execUntil (a:as) p = do
r <- a
if p r then return () else execUntil as p
Answer: Not totally sure what you're looking for, but maybe something like this?
import Control.Monad (void)
import Data.Bool (bool)
execUntil :: Monad m => [m a] -> (a -> Bool) -> m ()
execUntil = flip $ \p -> void . foldl (\ma mb -> ma >>= bool (p <$> mb) (pure True)) (pure False)
I wouldn't recommend it, though. foldl doesn't have any way to short-circuit, so this implementation will traverse the entire [m a], even beyond when the a -> Bool predicate is satisfied.
IMO, the code you've provided is totally fine as-is! Except perhaps for the unnecessary Eq a constraint ;p | {
"domain": "codereview.stackexchange",
"id": 43613,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "haskell",
"url": null
} |
bash, amazon-web-services
Title: Bash script to take user input to set AWS envrionment variable the first time and automatically in subsequent calls
Question: Background
Our team has a utility called envmgr to set aws iam roles. The credentials are only good for 4 hours or so. As such, I have a number of scripts that call the command $(envmgr -e ENVIRONMENT -r ROLE) to refresh the credentials and avoid a time-out while in the middle of a process.
The problem is that there is a lot of duplication in our codebase because we have separate scripts in separate parts of our architecture that do functionally the same things, but under a different environment. So I've written a script that sets a global AWS_ENVIRONMENT variable, so the first time the script is called, it'll make sure you properly set the environment, but still subsequently call the original envmgr... command without necessarily having to re-take an input from the user.
Potential Improvements
Is there a way to limit choices? currently the script requires the user to type "production" or "systems" or it will keep prompting them. Is there a way where they are given options that will auto fill?
Maybe there could be a check to see remaining time on credentials? And only refresh at a certain point? This is likely unnecessary as setting AWS credentials has minimal overhead.
For our purposes, I don't want the environment to change, so I'm ok to only take a single input and then automatically use that input for other scripts that get ran in the process. Some may want the option to assume different environments and will want a way to set environment variables automatically.
Script
#!/usr/bin/env bash -e
export AWS_ROLE='event-platform-developer'
# If our AWS_ENVIRONMENT variable has been not ben set, then we need to ask the user for input
if [ -z ${AWS_ENVIRONMENT+x} ]; then
read -p "Which environment are you trying to access? (production or systems): " response
response=$(echo "$response" | tr '[:upper:]' '[:lower:]') | {
"domain": "codereview.stackexchange",
"id": 43614,
"lm_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, amazon-web-services",
"url": null
} |
bash, amazon-web-services
while [ $response != 'production' ] && [ $response != 'systems' ]
do
read -p "Which environment are you trying to access? (production or systems): " response
response=$(echo "$response" | tr '[:upper:]' '[:lower:]')
done
AWS_ENVIRONMENT=$response
echo -e "Setting your AWS credentials as: envmgr -e $AWS_ENVIRONMENT --role $AWS_ROLE"
eval $(envmgr -e $AWS_ENVIRONMENT --role $AWS_ROLE)
unset response
# If our AWS_ENVIORNMENT variable has been set previously, then we can skip taking a response, but
# we still want to update our credentials
else
echo -e "Your AWS enviornment was previously set to: $AWS_ENVIRONMENT\n"
echo -e "Refreshing your AWS credentials as: envmgr -e $AWS_ENVIRONMENT --role $AWS_ROLE"
eval $(envmgr -e $AWS_ENVIRONMENT --role $AWS_ROLE)
fi
Answer: good
Nice indentation
Good variable names
Excellent sh-bang line (env lets bash be anywhere and -e for exiting on errors is good too.)
suggestions
Put a comment at the top of the code explaining what it is trying to do
Use double square brackets instead of single square brackets to avoid surprises.
Your eval $(envmgr... lines are a bit confusing. Firstly, you don't need eval to substitute variables or have it run the command. The only point to eval would be if envmgr outputs variables that you want to effect your current script. Since there's no code below this those variables wouldn't effect anything anyway. Secondly, you are repeating yourself and this line could move below the fi.
Put quotes around your variable substitutions to protect against something containing a space causing it to get split into multiple arguments.
Your conditional for the while has extra brackets in the middle. It should be one long [[ .... && .... ]].
The unset response seems superfluous. This variable will go away when the script exits, which is right after you unset this variable.
try shellcheck
rewrite (untested)
#!/usr/bin/env bash -e | {
"domain": "codereview.stackexchange",
"id": 43614,
"lm_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, amazon-web-services",
"url": null
} |
bash, amazon-web-services
rewrite (untested)
#!/usr/bin/env bash -e
export AWS_ROLE='event-platform-developer'
# If our AWS_ENVIRONMENT variable has been not ben set, then we need to ask the user for input
if [[ -z "${AWS_ENVIRONMENT+x}" ]]; then
read -p "Which environment are you trying to access? (production or systems): " response
response=$(echo "$response" | tr '[:upper:]' '[:lower:]')
while [[ "$response" != 'production' && "$response" != 'systems' ]]; do
read -p "Which environment are you trying to access? (production or systems): " response
response=$(echo "$response" | tr '[:upper:]' '[:lower:]')
done
AWS_ENVIRONMENT="$response"
echo -e "Setting your AWS credentials as: envmgr -e $AWS_ENVIRONMENT --role $AWS_ROLE"
# If our AWS_ENVIORNMENT variable has been set previously, then we can
# skip taking a response, but we still want to update our credentials
else
echo -e "Your AWS enviornment was previously set to: $AWS_ENVIRONMENT\n"
echo -e "Refreshing your AWS credentials as: envmgr -e $AWS_ENVIRONMENT --role $AWS_ROLE"
fi
envmgr -e "$AWS_ENVIRONMENT" --role "$AWS_ROLE"
answers to questions
Is there a way to limit choices? currently the script requires the user to type "production" or "systems" or it will keep prompting them. Is there a way where they are given options that will auto fill?
First, I'd put the two lines that prompt and read the response into a function so you code follows the Don't Repeat Yourself principal.
Then, I would use a case statement to see if the choices fit one of the acceptable ones. You could add a case for empty responses that set the response to one of your valid choices. Then the default/fall-through case would print a warning about the response not fitting one of the available responses.
Sorry for not including these ideas in the rewrite. | {
"domain": "codereview.stackexchange",
"id": 43614,
"lm_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, amazon-web-services",
"url": null
} |
bash, amazon-web-services
Maybe there could be a check to see remaining time on credentials? And only refresh at a certain point? This is likely unnecessary as setting AWS credentials has minimal overhead.
You can use if aws sts get-caller-identity > /dev/null to see if your credentials are still valid. It will hit the else case when you need to reauthenticate. This if does not need square brackets since we are testing the return code of the aws command. Otherwise, it operates like the if you've already used.
I have not found a way to see how long you have left on your current credentials. | {
"domain": "codereview.stackexchange",
"id": 43614,
"lm_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, amazon-web-services",
"url": null
} |
python, pandas
Title: Iterate and assign weights based on two columns (python)
Question:
FI_name
ISN
Sector
Industry
REC
INE02
PS
FS
HDB
INE03
PR
FS
ABC
INE04
PR
FS
RHC
INE05
PR
CO
ZHE
INE06
PR
FS
HSE
INE07
PR
FS
ZAK
INE08
PS
MT
HGB
INE09
PR
FS
YUJ
INE10
PR
MT
WSD
INE11
PS
FS
REC
INE12
PS
FS
HDB
INE13
PR
FS
ABC
INE14
PR
FS
RHC
INE15
PR
CO
ZHE
INE16
PR
FS
HSE
INE17
PR
FS
ZAK
INE18
PS
MT
HGB
INE19
PR
FS
YUJ
INE20
PR
MT
WSD
INE21
PS
FS
All the unique ISN should be assigned an equal weight (totals 100) but with the following exceptions.
Each unique Industry which has sector type "PR" is capped at 25%
So any ISN with sector 'PR' for their entire Industry should not cross the 25% limit.
If any industry has breached the 25% limit (i.e., if total number of ISNs in any industry is more than 5) then all those ISNs in that particular industry should be adjusted between the 25%
No limit for ISNs with sector == 'PS' (irrespective of the Industry)
the expected weights should be like this....
FI_name
ISN
Sector
Industry
Weights
REC
INE02
PS
FS
7.5%
HDB
INE03
PR
FS
2.5%
ABC
INE04
PR
FS
2.5%
RHC
INE05
PR
CO
7.5%
ZHE
INE06
PR
FS
2.5%
HSE
INE07
PR
FS
2.5%
ZAK
INE08
PS
MT
7.5%
HGB
INE09
PR
FS
2.5%
YUJ
INE10
PR
MT
7.5%
WSD
INE11
PS
FS
7.5%
REC
INE12
PS
FS
7.5%
HDB
INE13
PR
FS
2.5%
ABC
INE14
PR
FS
2.5%
RHC
INE15
PR
CO
7.5%
ZHE
INE16
PR
FS
2.5%
HSE
INE17
PR
FS
2.5%
ZAK
INE18
PS
MT
7.5%
HGB
INE19
PR
FS
2.5%
YUJ
INE20
PR
MT
7.5%
WSD
INE21
PS
FS
7.5% | {
"domain": "codereview.stackexchange",
"id": 43615,
"lm_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
ZAK
INE18
PS
MT
7.5%
HGB
INE19
PR
FS
2.5%
YUJ
INE20
PR
MT
7.5%
WSD
INE21
PS
FS
7.5%
There are total 10 ISNs with Sector == 'PR' and Industry == 'FS', so all these ISNs are assigned an equal weight of 2.5% (25%/10)
Since industries apart from FS (and sector 'PR') do not breach the limit of 25%, so 7.5% (75%/10) has been assigned for the rest.
This is the current code but I believe there's a better approach. Is there any other approach to tackle the above condition? any shorter method?
# Sector weight identification
import pandas as pd
sff1 = pd.read_excel (r'C:\Users\RajashekarR\Downloads\Test_CodeR.xlsx')
swi = sff1.loc[sff1['Sector'] != "PS"]
swi_pivot = swi.pivot_table(values=['ISN'], index = 'Industry', aggfunc= ['count'])
swi_pivot.columns = ['count',]
swi = pd.merge(swi, swi_pivot, how='inner', on='Industry')
swi2 = pd.merge(sff1, swi, how='left', left_on=['ISN', 'FI_name', 'Sector', 'Industry'], right_on=['ISN', 'FI_name', 'Sector', 'Industry'])
# Sector weight allocation
o = 20
l = 0.25
n = o*l
c= swi2['count']
n1 = c[c > n].count()
n2 = o-n1
swi3 = swi2.loc[swi2['count'] > n]
swi3['Weights'] = l/swi2['count']
s_sum = swi3['Weights'].sum()
l1 = 1-s_sum
swif = pd.merge(swi2, swi3, how='left', left_on=['ISN', 'FI_name', 'Sector', 'Industry', 'count'], right_on=['ISN', 'FI_name', 'Sector', 'Industry', 'count'])
swif = swif.set_index('ISN')
swi4 = swif[swif['Weights'].isna()]
swi4['Weights'] = l1/n2
swif = swif.reindex(columns=swif.columns.union(swi4.columns))
swif.update(swi4)
swif.reset_index(inplace=True)
final = swif.drop(['count'], axis=1)
final.to_excel('Test_CodeR_Final.xlsx') | {
"domain": "codereview.stackexchange",
"id": 43615,
"lm_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
Answer: Your use of pivot_table, reindex and merge is in all cases unnecessary. I also find that you hold onto a lot of temporary values, none very well-named, when you can just reassign to older variables and allow Python to do cleanup based on dropped references.
Rather than c[c > n].count(), you can call .sum() directly on the boolean predicate.
There's probably more simplification possible, but the results from this pass match yours.
import pandas as pd
sff1 = pd.read_csv('Weights - Sheet1.csv')
# Sector weight allocation
o = len(sff1)
l = 0.25
n = o*l
is_not_ps = sff1.Sector != "PS"
sff1.loc[is_not_ps, 'count'] = (
sff1[is_not_ps]
.groupby('Industry')
.ISN.transform('count')
)
n1 = (sff1['count'] > n).sum()
n2 = o - n1
swi3 = sff1[sff1['count'] > n]
swi3['Weights'] = l/sff1['count']
l1 = 1 - swi3.Weights.sum()
sff1['Weights'] = swi3.Weights
sff1 = sff1.set_index('ISN')
swi4 = sff1[sff1.Weights.isna()]
swi4['Weights'] = l1 / n2
sff1.update(swi4)
final = sff1.drop(['count'], axis=1) | {
"domain": "codereview.stackexchange",
"id": 43615,
"lm_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, natural-language-processing
Title: Python voice assistant that acts on trigger phrases
Question: I made a Python voice assistant. It takes the user's voice input and there are multiple if-else statements that specify a condition and if it satisfies that condition it executes a specific function. How I can implement if-else statements in a more efficient way?
async def main():
def there_exists(terms):
for term in terms:
if term in response or SequenceMatcher(None, response, term).ratio() > 0.85:
return True
while True:
print("Listening..")
response = takeCommand()
if there_exists(["close current tab", 'close tab']):
keyboard.press_and_release('ctrl+w')
elif there_exists(['goodbye', 'bye', 'see you later', 'ok bye']):
speak("Nice talking with you!")
sys.exit(0)
elif there_exists(['open google', 'open new tab in google', 'new tab in google']):
webbrowser.open_new_tab("https://www.google.com")
speak("Google chrome is open now")
time.sleep(5)
elif there_exists(['open gmail', 'gmail']):
webbrowser.open_new_tab("https://mail.google.com/mail/u/0/#inbox")
speak("Gmail is open now")
time.sleep(5)
elif 'open youtube' in response:
openYoutube()
elif there_exists(['whats the day today', 'what day is it today', 'day']):
speak(f'Today is {getDay()}')
elif there_exists(['battery percentage', 'what is the battery like right now', 'tell me the battery percentage']):
speak("Current battery percentage is at" + str(percent) + "percent")
elif there_exists(['what is the current brightness', 'current brightness', 'what is the brightness like right now']):
speak(str(sbc.get_brightness()) + "percent") | {
"domain": "codereview.stackexchange",
"id": 43616,
"lm_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, natural-language-processing",
"url": null
} |
python, natural-language-processing
elif there_exists(["current location", "location", "where am i", "where am I right now"]):
location()
elif there_exists(['increase volume', 'volume up']):
for i in range(3):
pyautogui.press('volumeup')
speak("Increase volume by 10 percent")
elif there_exists(['decrease volume', 'volume down']):
for i in range(3):
pyautogui.press('volumedown')
speak("Decreased volume by 10 percent")
elif there_exists(["play"]):
search_term = response.replace("play", '')
kit.playonyt(search_term)
speak(f"Playing {search_term}")
elif there_exists(["on youtube"]):
search_term = response.replace("on youtube", '')
url = f"https://www.youtube.com/results?search_query={search_term}"
webbrowser.get().open(url)
speak(f'Here is what I found for {search_term} on youtube')
elif there_exists(["price of", "what is the price of", "tell me the price of"]):
engine.setProperty("rate", 150)
search_term = response.lower().split(" of ")[-1].strip()
stock = getStock(search_term)
speak(stock)
print(stock)
engine.setProperty("rate", 175)
elif there_exists(['take a note', 'note', 'note this down', 'remember this', 'take this down']):
speak("What do you want me to note down?")
response = takeCommand()
note(response)
speak("I have made a note of that")
elif there_exists(['tell me a joke', 'not funny', 'make me laugh', 'joke', 'tell me another joke']):
joke = (pyjokes.get_joke())
speak(joke)
print(joke) | {
"domain": "codereview.stackexchange",
"id": 43616,
"lm_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, natural-language-processing",
"url": null
} |
python, natural-language-processing
elif there_exists(["search for"]) and 'youtube' not in response:
search_term = response.split("for")[-1]
url = f"https://google.com/search?q={search_term}"
webbrowser.get().open(url)
speak(f'Here is what I found for {search_term} on google')
elif there_exists(['what is the time now', 'what time is it', 'time']):
strTime = datetime.datetime.now().strftime("%H:%M")
speak(f"the time is {strTime}")
elif 'search' in response:
response = response.replace("search", "")
webbrowser.open_new_tab(response)
time.sleep(5)
elif there_exists(['sign out', 'log off']):
speak(
"Your pc will log off in 10 sec make sure you exit from all applications")
subprocess.call(["shutdown", "/l"])
elif there_exists(['shutdown the pc', 'shutdown', 'shutdown the laptop']):
speak("Shutting down your pc, make sure you exit from all applications")
subprocess.call(["shutdown", "/s"])
elif there_exists(['restart', 'restart the pc', 'restart the laptop']):
speak("Restarting your pc, make sure you exit from all applications")
subprocess.call(["shutdown", "/r"])
elif there_exists(['what is the weather like right now', 'current temperature', 'climate']):
weather = getWeather()
speak(weather)
print(weather)
elif there_exists(['increase brightness', 'the brightness is low']):
if sbc.get_brightness() == 100:
speak("Brightness is already at max")
else:
brightness = sbc.set_brightness(current_brightness + 10)
speak(f"Increased brightness by 10 percent") | {
"domain": "codereview.stackexchange",
"id": 43616,
"lm_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, natural-language-processing",
"url": null
} |
python, natural-language-processing
elif there_exists(
['decrease brightness', 'dim', 'dim the laptop', 'dim the screen', 'the screen is too bright']):
sbc.set_brightness(current_brightness - 10)
speak(f"Decreased brightness by 10 percent")
elif there_exists(['take a screenshot', 'screenshot', 'capture the screen', 'take a photo of this']):
image = pyscreenshot.grab()
speak("Should I open the image?")
response = takeCommand()
if there_exists(['yes', 'show', 'show the screenshot']):
image.show()
else:
speak("Ok")
elif there_exists(['what is the weather in']):
search_term = response.replace("what is the weather in", '')
weather = getWeatherLocation(search_term)
speak(weather)
print(weather)
elif there_exists(['what', 'who', 'why', 'where', 'when', 'which']):
ans = getQuickAnswers(response)
speak(ans)
print(ans)
elif there_exists(['send a message to']):
search_term = response.replace('send a message to', '').replace(' ', '')
await Methods().sendUserMessage(search_term)
asyncio.run(main())
time.sleep(3)
Answer: You can make a dict with the expected input as keys and the actions as values.
@dataclass
class ActionInput(Hashable):
def __hash__(self) -> int:
return str(self.value).__hash__()
value: list[str]
actions = {
ActionInput(["close current tab", 'close tab']): (lambda: print('ctrl+w')),
# ...
}
and then loop over them:
for key in actions:
if there_exists(key.value):
actions[key]() | {
"domain": "codereview.stackexchange",
"id": 43616,
"lm_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, natural-language-processing",
"url": null
} |
c++, c++11, rational-numbers, overloading
Title: Add two fractions or two integers using template class and overloading
Question: Question:
Need to create three classes.
Number
Fraction
Integer
Requirements
The first class should support “display”, “==”, and “+”.
"Display" : This operation displays the Number itself in its original form.
"+" : This operation adds the number itself with another number and returns a third number whose numeric value is equal to the sum of the numeric values of the former two.
The Fraction class, which is represented by its numerator and denominator (both are integers).
For a Fraction, it needs to be displayed in its original form. That is, 2/4 has to be displayed as “2/4”, not “1/2” or “0.5”.
Solution
Number.h
#pragma once
template<class T>
class Number
{
virtual T& operator= (const T &) = 0;
virtual const T operator+ (const T &) = 0;
virtual void display() = 0;
};
Fraction.h
#pragma once
#include "Number.h"
class Fraction : public Number<Fraction>
{
private:
int _numerator;
int _denominator;
public:
void display();
Fraction();
Fraction(int num, int den);
Fraction& operator= (const Fraction &);
const Fraction operator+ (const Fraction &);
int Fraction::gcdCalculate(int val1, int val2);
int Fraction::lcmCalculate(const int val1, const int val2);
~Fraction();
};
Fraction.cpp
#include "Fraction.h"
#include <iostream>
using namespace std;
// constructor
Fraction::Fraction()
{
_numerator = 0;
_denominator = 1;
}
// parameterised constructor setting the denominator and numerator values
Fraction::Fraction(int num, int den)
{
_numerator = num;
_denominator = den;
}
// display the fraction value
void Fraction::display()
{
std::cout << this->_numerator << "/";
std::cout << this->_denominator << endl;
}
// "=" operator overloading
Fraction& Fraction::operator=(const Fraction &num)
{
_numerator = num._numerator;
_denominator = num._denominator;
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, rational-numbers, overloading",
"url": null
} |
c++, c++11, rational-numbers, overloading
// "+" operator overloading
const Fraction Fraction::operator+(const Fraction &numberTwo)
{
Fraction outputFraction;
int lcm = lcmCalculate(this->_denominator, numberTwo._denominator);
int multiplier1 = 0;
if (this->_denominator)
multiplier1 = lcm / this->_denominator;
int multiplier2 = 0;
if (numberTwo._denominator)
multiplier2 = lcm / numberTwo._denominator;
outputFraction._numerator = this->_numerator * multiplier1 + numberTwo._numerator * multiplier2;
outputFraction._denominator = lcm;
return outputFraction;
}
// LCM Calculation
int Fraction::lcmCalculate(const int val1, const int val2)
{
int temp = gcdCalculate(val1, val2);
return temp ? (val1 / temp * val2) : 0;
}
// GCD Calculation
int Fraction::gcdCalculate(int val1, int val2)
{
for (;;)
{
if (val1 == 0) return val2;
val2 %= val1;
if (val2 == 0) return val1;
val1 %= val2;
}
}
// destructor
Fraction::~Fraction()
{}
Integer.h
#pragma once
#include "Number.h"
class Integer : public Number<Integer>
{
private:
int intValue;
public:
void display();
Integer();
Integer(int num);
Integer& operator= (const Integer &);
const Integer operator+ (const Integer &);
~Integer();
};
Integer.cpp
#include "Integer.h"
#include "Number.h"
#include <iostream>
using namespace std;
// constructor
Integer::Integer()
{
intValue = 0;
}
// parameterized constructor
Integer::Integer(int num)
{
intValue = num;
}
// display the int value
void Integer::display()
{
std::cout << this->intValue << endl;
}
// operator "=" overloading
Integer& Integer::operator=(const Integer &secondNumber)
{
intValue = secondNumber.intValue;
return *this;
}
// operator "+" overloading
const Integer Integer::operator+(const Integer &secondNumber)
{
Integer temp;
temp.intValue = this->intValue + secondNumber.intValue;
return temp;
}
// destructor
Integer::~Integer(){} | {
"domain": "codereview.stackexchange",
"id": 43617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, rational-numbers, overloading",
"url": null
} |
c++, c++11, rational-numbers, overloading
// destructor
Integer::~Integer(){}
Main.cpp
#include "Integer.h"
#include <iostream>
#include "Fraction.h"
using namespace std;
int main()
{
Integer sumOfInteger;
Integer int1(30);
Integer int2(40);
sumOfInteger = int1 + int2;
sumOfInteger.display();
Fraction sumOfFraction;
Fraction fracOne(2,4);
Fraction fracTwo(2,4);
sumOfFraction = fracOne + fracTwo;
sumOfFraction.display();
return 0;
}
Can someone please review and help me in improving my overall coding skills and standards.
Answer: It looks like you are trying to use the Curiously-Recurring Template Pattern to achieve static polymorphism, however you also use the virtual keyword. virtual is used for runtime polymorphism, hence choose one paradigm, CRTP, e.g., static or virtual, e.g, runtime.
You put your variables at the top of the class, and used the private access specifier. Classes are already private by default, so the private specifier is superfluous.
Your display() function is hard to unit-test because it causes side effects. Declare display to take a stream as an input parameter. Then you can unit-test the function with a string stream, and pass std::cout when you want to print stuff out.
template <typename OStream>
void display(OStream& os) { os << "Write your data here."; }
Your destructors are default, so declare them as such:
class Fraction {
~Fraction() = default;
}
const Fraction Fraction::operator+(const Fraction &numberTwo) returns a copy as const. Never return const since it prevents the Named Value Return Optimization (NVRO). Additionally, this function doesn't mutate its members, so make it member const:
Fraction Fraction::operator+(const Fraction &numberTwo) const
More Explanation
Number.h
#pragma once
template<class T>
class Number
{
public:
T& operator= (const T &)
{
return impl().operator=(T);
}
T operator+ (const T &) const
{
return impl().operator+(T);
} | {
"domain": "codereview.stackexchange",
"id": 43617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, rational-numbers, overloading",
"url": null
} |
c++, c++11, rational-numbers, overloading
T operator+ (const T &) const
{
return impl().operator+(T);
}
template <typename Stream>
void display(Stream& os) const
{
impl().display(os);
}
private:
T& impl() {
return *static_cast<T*>(this);
}
T const & impl() const {
return *static_cast<T const *>(this);
}
};
Fraction.h
#pragma once
#include "Number.h"
class Fraction : public Number<Fraction>
{
int _numerator{0};
int _denominator{1};
public:
template <typename Stream>
void display(Stream& os) const
{
os << this->_numerator << "/";
os << this->_denominator << '\n';
}
Fraction() = default;
Fraction(int num, int den);
~Fraction() = default;
Fraction& operator= (const Fraction &);
Fraction operator+ (const Fraction &) const;
int Fraction::gcdCalculate(int val1, int val2) const;
int Fraction::lcmCalculate(const int val1, const int val2) const;
};
Fraction.cpp
#include "Fraction.h"
#include <iostream>
using namespace std;
// parametrised constructor setting the denominator and numerator values
Fraction::Fraction(int num, int den)
:
_numerator(num),
_denominator(den)
{
}
// "=" operator overloading
Fraction& Fraction::operator=(const Fraction &num)
{
_numerator = num._numerator;
_denominator = num._denominator;
return *this;
}
// "+" operator overloading
Fraction Fraction::operator+(const Fraction &numberTwo) const
{
Fraction outputFraction;
int lcm = lcmCalculate(this->_denominator, numberTwo._denominator);
int multiplier1 = 0;
if (this->_denominator)
multiplier1 = lcm / this->_denominator;
int multiplier2 = 0;
if (numberTwo._denominator)
multiplier2 = lcm / numberTwo._denominator;
outputFraction._numerator = this->_numerator * multiplier1 + numberTwo._numerator * multiplier2;
outputFraction._denominator = lcm;
return outputFraction;
} | {
"domain": "codereview.stackexchange",
"id": 43617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, rational-numbers, overloading",
"url": null
} |
c++, c++11, rational-numbers, overloading
// LCM Calculation
int Fraction::lcmCalculate(const int val1, const int val2) const
{
int temp = gcdCalculate(val1, val2);
return temp ? (val1 / temp * val2) : 0;
}
// GCD Calculation
int Fraction::gcdCalculate(int val1, int val2) const
{
for (;;)
{
if (val1 == 0) return val2;
val2 %= val1;
if (val2 == 0) return val1;
val1 %= val2;
}
}
Integer.h
#pragma once
#include "Number.h"
class Integer : public Number<Integer>
{
int intValue{0};
public:
template <typename Stream>
void display(Stream& os) const
{
os << this->intValue << '\n';
}
Integer() = default;
~Integer() = default;
Integer(int num);
Integer& operator= (const Integer &);
Integer operator+ (const Integer &) const;
};
Integer.cpp
#include "Integer.h"
#include "Number.h"
#include <iostream>
using namespace std;
// parameterized constructor
Integer::Integer(int num)
:
intValue(num) //Prefer to use initializer lists
{
}
// operator "=" overloading
Integer& Integer::operator=(const Integer &secondNumber)
{
intValue = secondNumber.intValue;
return *this;
}
// operator "+" overloading
Integer Integer::operator+(const Integer &secondNumber) const
{
Integer temp;
temp.intValue = this->intValue + secondNumber.intValue;
return temp;
}
Main.cpp
#include "Integer.h"
#include <iostream>
#include "Fraction.h"
using namespace std;
template <typename INumberType>
void GenericDisplay(const Number<INumberType>& num) //Here we are calling through the Number<> Interface
{
num.display(std::cout);
}
int main()
{
//Use the Classes Directly
/// --> Don't declare stuff until you need it... Integer sumOfInteger;
Integer int1(30);
Integer int2(40);
auto sumOfInteger = int1 + int2;
GenericDisplay(sumOfInteger);
Fraction fracOne(2,4);
Fraction fracTwo(2,4);
auto sumOfFraction = fracOne + fracTwo;
GenericDisplay(sumOfFraction);
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43617,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, rational-numbers, overloading",
"url": null
} |
python, algorithm, time-limit-exceeded
Title: USACO Training - Section 1.5 - Arithmetic Progressions
Question: I am working on the USACO problem Arithmetic Progression. Here is their problem statement:
An arithmetic progression is a sequence of the form a, a+b, a+2b, ..., a+nb where n=0, 1, 2, 3, ... . For this problem, a is a non-negative integer and b is a positive integer.
Write a program that finds all arithmetic progressions of length n in the set S of bisquares. The set of bisquares is defined as the set of all integers of the form p² + q² (where p and q are non-negative integers).
Furthermore, input is read from a file ariprog.in, and output should be written to another file ariprog.out. Help is not required for this part, but a sample ariprog.in is shown below:
5
7
And here is the input format:
Line 1: N (3≤N≤25), the length of progressions for which to search
Line 2: M (1≤M≤250), an upper bound to limit the search to the bisquares with 0≤p,q≤M.
And here is the output format:
If no sequence is found, a single line reading `NONE'. Otherwise, output one or more lines, each with two integers: the first element in a found sequence and the difference between consecutive elements in the same sequence. The lines should be ordered with smallest-difference sequences first and smallest starting number within those sequences first.
There will be no more than 10,000 sequences.
For my code, here are my steps.
Read the file and save variables N and M
Generate all possible bi-squares (p² + q²) and save it to a list
Loop through starting values for arithmetic progressions
Loop through ending values for arithmetic progressions
If the end of a possible sequence (calculated with start + (length - 1) * difference is larger than the largest value in the list of possible bi-squares (found in step 2), skip this case
Test a starting value and difference by looping through it until the length is achieved
Sort the list according to output format
Write to file | {
"domain": "codereview.stackexchange",
"id": 43618,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, time-limit-exceeded",
"url": null
} |
python, algorithm, time-limit-exceeded
Out of these, steps 3-6 take the time. I am interested in speed improvements and optimizations, not a full solution.
My logic is working, I pass 5/9 of the tests. I fail on the test case with the input being 18 100 due to too much time taken
Now, here is the actual code so far:
'''
ID: ***
LANG: PYTHON3
TASK: ariprog
'''
#import os
#try:
# os.chdir(os.path.dirname(__file__))
#except:
# pass
#import time
from itertools import combinations_with_replacement
with open('ariprog.in', 'r') as file:
N, M = map(int, [line.replace('\n', '') for line in file.readlines()])
def calculateBisquares(limit):
p_or_q_values = range(limit+1)
return sorted(list(set([((i[0]**2) + (i[1]**2)) for i in combinations_with_replacement(p_or_q_values, 2)])))
def checkNum(bisquare_index, all_bisquares, difference):
for sequence_item_number in range(2, N):
if(int(all_bisquares[bisquare_index] + difference * sequence_item_number) not in all_bisquares):
return False
return True
#print(f'starting: {time.time()}')
#start = time.time()
all_bisquares = calculateBisquares(M)
maximum_number = 2 * (M ** 2)
sequences = []
for starting_index in range(0, len(all_bisquares) - N + 1):
for ending_index in range(starting_index + 1, len(all_bisquares) - N + 2):
difference = all_bisquares[ending_index] - all_bisquares[starting_index]
if all_bisquares[starting_index] + (N - 1) * difference > maximum_number:
break
if checkNum(starting_index, all_bisquares, difference):
sequences.append([all_bisquares[starting_index], difference])
if len(sequences) != 0:
sequences.sort(key=lambda d: d[1])
out = '\n'.join([' '.join(list(map(str, sequence))) for sequence in sequences])
else:
out = 'NONE'
#print(f'ending: {time.time()}')
#print(f'time taken: {time.time()-start}')
with open('ariprog.out', 'w') as file:
file.write(out + '\n') | {
"domain": "codereview.stackexchange",
"id": 43618,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, time-limit-exceeded",
"url": null
} |
python, algorithm, time-limit-exceeded
with open('ariprog.out', 'w') as file:
file.write(out + '\n')
Side note: I am interested in an optimization but haven't yet implemented in Python.
Answer: The link you provided for an optimization suggested using a Boyer-Moore like algorithm. That got me thinking about using string.find() and then re.search() to find the sequences. The idea is to create a bytearray in which the bisquares are marked with b'1' and the other numbers are marked with b'0'. Then build a regular expression to search the bytearray for a sequence of equally-spaced b'1's of the desired length.
import re
def bisquares(n):
limit = 2*n*n
bsqs = bytearray(b'0' * (limit + 1))
for i in range(n+1):
for j in range(i, n+1):
k = i*i+j*j
if k <= limit:
bsqs[k] = ord('1')
return bsqs
def find_arithmetic_sequences(n, m):
bss = bisquares(m)
for width in range(len(bss)//n + 1):
# pattern looks like b'1..1..1..1, where 'width' determines
# the number of '.'s and 'n' determines the number of '1's.
pattern = f'1(?:.{{{width}}}1){{{n-1}}}'.encode('utf8')
regex = re.compile(bytes(pattern))
start = 0
while (match := regex.search(bss, start)):
start = match.start() + 1
yield match.start(), width + 1
def main():
with open('ariprog.in', 'r') as ifile:
N = int(next(ifile))
M = int(next(ifile))
found_some = False
with open('ariprog.out', 'w') as ofile:
for index, difference in find_arithmetic_sequences(N, M):
print(index, difference, file=ofile)
found_some = True
if not found_some:
print('NONE', file=ofile)
main()
For N, M = 18, 100 it takes under 2 seconds, compared to over 36 for your code. | {
"domain": "codereview.stackexchange",
"id": 43618,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, time-limit-exceeded",
"url": null
} |
javascript, dom
Title: JavaScript front end for Odin Project book library database
Question: I am currently working on The Odin Project and have reached the JavaScript Part. There is a project, to create a Website that serves a a library. You can add a book and it appears on the site as a tile/panel.
I have finished the project and as far as I can see it works fine. But I feel like my JavaScript code is extremely messy and not very effective at all.
I would really appreciate it, if someone could take the time to look it over and give me some "style" feedback. Or maybe some do's and dont's!
Here is my JavaScript code:
let myLibrary = []; //array for storing books, each book is an object
let counter = 0;
const title = document.querySelector("#title");
const author = document.querySelector("#author");
const pages = document.querySelector("#pages");
const checkbox = document.getElementById("read");
const error = document.querySelector(".error");
document.querySelector(".addBook").addEventListener("click", () => {
document.querySelector(".popup").style.display = "flex";
});
document.querySelector(".close").addEventListener("click", () => {
document.querySelector(".popup").style.display = "none";
})
document.querySelector(".submit").addEventListener("click", function(event) { | {
"domain": "codereview.stackexchange",
"id": 43619,
"lm_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, dom",
"url": null
} |
javascript, dom
event.preventDefault();
//get input from fields.
let bookTitle = title.value;
let bookAuthor = author.value;
let bookPages = pages.value;
let bookRead ;
if(checkbox.checked) {
bookRead = Boolean(true);
}
else {
bookRead = Boolean(false);
}
if(bookTitle.length > 0 && bookAuthor.length > 0 && bookPages.length > 0) {
const book = new Book(bookTitle, bookAuthor, bookPages, bookRead);
if(isInLibrary(book)) {
error.textContent = "This book is already in your library";
}
else {
addBookToLibrary(book);
displayBookInLibrary(book);
document.querySelector(".popup").style.display = "none";
reset();
}
}
else {
error.textContent = "Fill out all fields";
}
changeColor();
remove();
});
function reset() {
title.value = null;
author.value = null;
pages.value = null;
checkbox.checked = false;
error.textContent = "";
}
function Book(title, author, pages, read) {
this.title = title;
this.author = author;
this.pages = pages;
this.read = Boolean(read);
}
function addBookToLibrary(book) {
myLibrary.push(book);
}
function isInLibrary(book) {
let includes = false;
for(i = 0; i < myLibrary.length; i++) {
if(myLibrary[i].title == book.title) {
includes = true;
}
else {
includes = false;
}
}
return includes;
}
function displayBookInLibrary(book) {
const bookContainer = document.querySelector("#bookContainer");
//add book to grid.
let div = document.createElement("div");
let hasRead = "";
let clr = "";
if(book.read) {
hasRead = "Read";
clr ="green";
}
else {
hasRead = "Not read yet";
clr="red";
}
div.setAttribute("data-num", counter); | {
"domain": "codereview.stackexchange",
"id": 43619,
"lm_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, dom",
"url": null
} |
javascript, dom
div.style.width = "13rem";
div.style.height = " 13rem";
div.style.border = " 4px solid #c31";
div.style.display = "flex";
div.style.flexDirection = "column";
div.style.gap = "10px";
div.style.justifyContent = "center";
div.style.alignItems = "center";
div.style.textAlign = "center";
div.style.borderRadius = "5px";
div.innerHTML = `
<p class="BookTitle">"${book.title}"</p>
<p class="BookAuthor">${book.author}</p>
<p class="BookPages">${book.pages}${" pages"}</p>
<button style="background: ${clr}; color: white; padding: 5px; border-radius: 4px;" class="HasRead">${hasRead}</button>
<button class="Remove">Remove</button>
`;
bookContainer.appendChild(div);
book.dataNum = `${counter}`;
counter++;
console.log(book);
}
function changeColor() {
//change color and text of read buttons
const buttons = document.querySelectorAll(".HasRead").length;
for(var i = 0; i < buttons; i++) {
let currentBtn = document.querySelectorAll(".HasRead")[i];
currentBtn.addEventListener("click", function() {
if(currentBtn.textContent == "Read") {
currentBtn.textContent = "Not read yet";
currentBtn.style.background = "red";
}
else {
currentBtn.textContent = "Read";
currentBtn.style.background = "green";
}
})
}
}
function remove() { | {
"domain": "codereview.stackexchange",
"id": 43619,
"lm_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, dom",
"url": null
} |
javascript, dom
function remove() {
//remove buttons:
const buttonsRemove = document.querySelectorAll(".Remove").length;
console.log(buttonsRemove);
for(var i = 0; i < buttonsRemove; i++) {
let currentBtn = document.querySelectorAll(".Remove")[i];
currentBtn.addEventListener("click", function() {
//get parent element attribute
//remove said button from everything
let parentAttr = currentBtn.parentNode.getAttribute("data-num");
for(const book of myLibrary) {
if(book.dataNum == parentAttr) {
const index = myLibrary.indexOf(book);
const div = document.querySelector(`div[data-num="${parentAttr}"]`);
document.getElementById("bookContainer").removeChild(div);
myLibrary.splice(index, 1);//remove said book from array
}
else {
return;
}
}
});
}
}
Here is a link to my Github repository with the whole project, should you be interested:
https://github.com/morloq/Library.
Answer: There are of course many ways to structure the code, and its interesting that you opted to encapsulate Book but not Library. You might want to look into how OOP would help you group together related concepts and methods. e.g.
const library = new Library();
library.addBook(new Book(...)); | {
"domain": "codereview.stackexchange",
"id": 43619,
"lm_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, dom",
"url": null
} |
javascript, dom
You also aren't taking advantage of the standard library (as in API, not because JS already contains the concept of a book repository), and have some misunderstandings about Boolean types.
Use of Boolean(true|false)
This is unnecessary. The constants true and false are booleans, so you just need to assign them (e.g. bookRead = true). There is a place for wrapping a non-boolean (such as a counter) but in reality its rare as we can rely on non-zero, non-null, non-undefined values being interpretted as boolean depending on context. e.g.
let value = Math.random();
if (value) {
// will be here for any non-zero value
} else {
// will be here only for zero value
Because of this, most people will use double negation to convert a 'truthy' value to a boolean, e.g.:
let value = Math.random();
let bool = !!value; // true for non-zero value
This misunderstanding is most apparent here:
if(checkbox.checked) {
bookRead = Boolean(true);
} else {
bookRead = Boolean(false);
}
Which can simply become:
bookRead = checkbox.checked;
This leads onto unnecessary verbosity when testing numeric values:
if(bookTitle.length > 0 && bookAuthor.length > 0 && bookPages.length > 0) { ...
This can be simplified to:
if(bookTitle.length && bookAuthor.length && bookPages.length) { ... | {
"domain": "codereview.stackexchange",
"id": 43619,
"lm_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, dom",
"url": null
} |
javascript, dom
This can be simplified to:
if(bookTitle.length && bookAuthor.length && bookPages.length) { ...
Sometimes it pays to be more explicit, but other times not.
isInLibrary
As mentioned above, you have a tendancy to long hand instead of leveraging the standard library methods.
myLibrary is an array, and Array has standard methods to determine whether an item is in a collection. Array.prototype.includes is not useful here, because we are not comparing the whole book (and object comparison is a separate topic worth understanding), but we can leverage Array.prototype.find.
Indeed, your implementation doesn't work because it compares every book title in the library, so will only return true when the target book is the last book. In the loop, you should return as soon as a match is found.
Leveraging the standard library, we can succinctly write:
function isInLibrary(book) {
return myLibrary.find(item => item.title === book.title) !== undefined
}
NB: Generally, you should use strict equality (===) instead of == to avoid type conversions that lead to unintended results.
changeColor
Here is an example of where you are doing more work than necessary.
querySelectorAll returns a NodeList, which has a forEach method. In your implementation, you are querying multiple times, throwing away useful information, I think because you are focussing on the concept of for loops instead of iteration.
function changeColor() {
document.querySelectorAll('.HasRead').forEach(button => {
button.addEventListener('click', () => {
button.textContent = button.textContent === 'Read' ? 'Not read yet' : 'Read';
button.style.background = button.style.background === 'red' ? 'green' : 'red';
});
} | {
"domain": "codereview.stackexchange",
"id": 43619,
"lm_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, dom",
"url": null
} |
javascript, dom
I've not delved closely into the code, but you should check to make sure that you aren't repeatedly adding the same listener to DOM elements. You might not spot the duplication, but it'll add overhead to every event fired.
You can use this same style in the remove method.
remove
Using Array.prototype.splice in the for loop works in this instance, but there is a trap that you can fall into. Modifying the array whilst iterating over it will cause items to be skipped. There are ways around that (iterating backwards), but it's possible to filter and acheive the same result.
function remove() {
document.querySelectorAll('.Remove').forEach(button => {
button.addEventListener('click', () => {
const dataNum = button.parentNode.getAttribute('data-num');
myLibrary = myLibrary.filter((book, index) => {
if (book.dataNum === dataNum) {
const div = document.querySelector(`div[data-num="${dataNum}"]`);
div.parentNode.removeChild(div);
return false;
}
return true;
});
}
There is a slight overhead here, in that filter is going to compare dataNum on all books, rather than returning after the first match. We return false for the match (the one we are removing) so that its filtered out of the new array assigned to myLibrary, and true for the non-matching ones we want to keep.
Assuming that bookContainer is the direct parent of item we are removing, we don't need to do another querySelector. | {
"domain": "codereview.stackexchange",
"id": 43619,
"lm_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, dom",
"url": null
} |
python, python-3.x, multithreading, beautifulsoup, python-requests
Title: Compare between two dictionaries
Question: Hello beautiful people!
I have currently worked on a small script that I would of course continue to work with whenever I get a good feedback from the best code reviewer in here <3 - I have worked on a small template of monitor where I use threadpoolexeuctor to do a GET requests on multiple URL's where each URL will return a dictionary of different values (in my case its the title and repo_count.
import random
import time
from concurrent.futures import as_completed
from concurrent.futures.thread import ThreadPoolExecutor
import requests
from bs4 import BeautifulSoup
URLS = [
'https://github.com/search?q=hello+world',
'https://github.com/search?q=python+3',
'https://github.com/search?q=world',
'https://github.com/search?q=i+love+python',
'https://github.com/search?q=sport+today',
'https://github.com/search?q=how+to+code',
'https://github.com/search?q=banana',
'https://github.com/search?q=android+vs+iphone',
'https://github.com/search?q=please+help+me',
'https://github.com/search?q=batman',
]
def doRequest(url):
response = requests.get(url)
time.sleep(random.randint(10, 30))
return response, url
def doScrape(response):
soup = BeautifulSoup(response.text, 'html.parser')
return {
'title': soup.find("input", {"name": "q"})['value'],
'repo_count': soup.find("span", {"data-search-type": "Repositories"}).text.strip()
}
def checkDifference(old_state, new_state):
for key in new_state:
if key not in old_state:
print(f"New key: {key}")
elif old_state[key] != new_state[key]:
print(f"Difference: {key}")
print(f"Old: {old_state[key]}")
print(f"New: {new_state[key]}")
else:
print(f"No difference: {key}") | {
"domain": "codereview.stackexchange",
"id": 43620,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, multithreading, beautifulsoup, python-requests",
"url": null
} |
python, python-3.x, multithreading, beautifulsoup, python-requests
def threadPoolLoop():
store_data = {}
with ThreadPoolExecutor(max_workers=5) as executor:
future_tasks = [
executor.submit(
doRequest,
url
) for url in URLS]
for future in as_completed(future_tasks):
response, url = future.result()
if response.status_code == 200:
store_data[url] = doScrape(response)
return store_data
if __name__ == '__main__':
old_state = threadPoolLoop()
while True:
new_state = threadPoolLoop()
checkDifference(old_state, new_state)
old_state = new_state
What the code basically does is that it takes each URL and compares between previous state from itself and whenever we do see a change between those two states, I would like to print out whenever there is a difference and that's pretty much it
Looking forward for improvements! :)
Answer: Most of this code should be deleted and replaced with API calls. Sign up for a free access token to increase your rate limit. I doubt threading will help.
Beyond that, the algorithm itself is questionable. For instance, searching "world" among repositories yields 1,980,298 results. What do you realistically expect to accomplish with only the first page of these data, particularly when you accept default sortation of "best match" (whatever Github thinks that means)? This might be more practical if all of the terms you've shown are fake and you're looking for something much more targeted. | {
"domain": "codereview.stackexchange",
"id": 43620,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, multithreading, beautifulsoup, python-requests",
"url": null
} |
rust
Title: Rust book: Employees and departments exercise
Question: I am learning Rust from the official book, and I have solved the following recommended challenge from the end of chapter 8:
Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.
Are there any bad practices in my code? The code works, and this is the closest form to idiomatic Rust that I could come up with.
use std::io;
use std::collections::HashMap;
enum Command {
Add { name: String, department: String },
List { department: String },
All,
Quit,
}
impl Command {
fn from_string(s: &String) -> Option<Self> {
let el: Vec<&str> = s.trim().split_whitespace().collect();
match el.as_slice() {
["Add", name, "to", department] => Some(Self::Add { name: name.to_string(), department: department.to_string() }),
["List", department] => Some(Self::List { department: department.to_string() }),
["All"] => Some(Self::All),
["Quit"] => Some(Self::Quit),
_ => None,
}
} | {
"domain": "codereview.stackexchange",
"id": 43621,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
fn process(&self, deps: &mut &mut HashMap<String, Vec<String>>) -> bool {
fn print_department(deps: &mut &mut HashMap<String, Vec<String>>, department: String) {
if let Some(v) = deps.get_mut(&department) {
v.sort();
println!("Department {}", department);
for emp in v {
println!("{}", emp);
}
} else {
println!("Invalid department");
}
}
match &self {
Self::Add { name, department } => {
deps.entry(department.to_string()).or_insert(vec![]).push(name.to_string());
false
},
Self::List { department } => {
print_department(deps, department.to_string());
false
},
Self::All => {
for (k, _) in deps.clone() {
print_department(deps, k.to_string());
}
false
},
Self::Quit => {
true
}
}
}
}
fn main() {
let mut deps: HashMap<String, Vec<String>> = HashMap::new();
let mut cmd = String::new();
loop {
cmd.clear();
io::stdin().read_line(&mut cmd).expect("Cannot read command");
match Command::from_string(&cmd) {
Some(cmd) => match cmd.process(&mut &mut deps) {
true => break,
_ => (),
},
None => println!("Invalid command"),
};
}
}
Answer: Your code is good for the most parts, however there are some improvements that can be made:
This can be simplified:
Some(cmd) => match cmd.process(&mut &mut deps) {
true => break,
_ => (),
},
to
Some(cmd) => {
if deps.process(cmd) {
break;
}
}
fn process(&self, deps: &mut &mut HashMap<String, Vec<String>>) -> bool {
No need for the double &mut. | {
"domain": "codereview.stackexchange",
"id": 43621,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
No need for the double &mut.
fn process(&self, deps: &mut &mut HashMap<String, Vec<String>>) -> bool {
fn print_department(deps: &mut &mut HashMap<String, Vec<String>>, department: String) {
The functions should not be nested.
I would define type aliases for department and person to make the code more readable.
type Department = String;
type Person = String;
fn process(&self, deps: &mut HashMap<Department, Vec<Person>>) -> bool {...}
fn print_department(deps: &mut HashMap<Department, Vec<Person>>, department: Department) {...}
process() should take self (consume the Command) to avoid cloning the Strings in it.
match &self {
Self::Add { name, department } => {
deps.entry(department.to_string()).or_insert(vec![]).push(name.to_string()); // No need to call to_string() here if we use self
false
},
Self::List { department } => {
print_department(deps, department.to_string()); // No need to call to_string() here if we use self
false
},
Self::All => {
for (k, _) in deps.clone() {
print_department(deps, k.to_string()); // No need to call to_string() here if we use self
}
false
},
Self::Quit => {
true
}
}
You should restructure your code so that you are not cloning `deps` here:
Self::All => {
for (k, _) in deps.clone() {
print_department(deps, k.to_string());
}
false
},
Furthermore, you can use .keys() to get only the department name.
You can also check if there are any departments and if not, display a message.
I would suggest creating a wrapper around the map of departments and implementing the methods on it, see Final code bellow.
Final code:
use std::collections::HashMap;
use std::io;
enum Command {
Add { name: String, department: String },
List { department: String },
All,
Quit,
}
impl Command {
fn from_string(s: &str) -> Option<Self> {
let el: Vec<_> = s.trim().split_whitespace().collect(); | {
"domain": "codereview.stackexchange",
"id": 43621,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
match el.as_slice() {
["Add", name, "to", department] => Some(Self::Add {
name: name.to_string(),
department: department.to_string(),
}),
["List", department] => Some(Self::List {
department: department.to_string(),
}),
["All"] => Some(Self::All),
["Quit"] => Some(Self::Quit),
_ => None,
}
}
}
type Department = String;
type Person = String;
#[derive(Clone, Debug, Default)]
struct Departments {
departments: HashMap<Department, Vec<Person>>,
}
impl Departments {
pub fn new() -> Departments {
Self {
departments: HashMap::new(),
}
}
pub fn process(&mut self, command: Command) -> bool {
match command {
Command::Add { name, department } => {
self.departments
.entry(department)
.or_insert(vec![])
.push(name);
false
}
Command::List { department } => {
self.print_department(&department);
false
}
Command::All => {
if self.departments.is_empty() {
println!("No departments");
} else {
for department in self.departments.keys() {
self.print_department(department);
}
}
false
}
Command::Quit => true,
}
}
fn print_department(&self, department: &Department) {
if let Some(mut v) = self.departments.get(department).cloned() {
v.sort();
println!("Department {}", department);
for emp in v {
println!("{}", emp);
}
} else {
println!("Invalid department");
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43621,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
fn main() {
let mut deps = Departments::new();
let mut cmd = String::new();
loop {
cmd.clear();
io::stdin()
.read_line(&mut cmd)
.expect("Cannot read command");
match Command::from_string(&cmd) {
Some(cmd) => {
if deps.process(cmd) {
break;
}
}
None => println!("Invalid command"),
};
}
}
If you want to make even more improvements, I would suggest replacing the vector of people with a structure that keeps the order when adding elements, to avoid sorting the vector every time. You can also create structs for Department and Person and implement Display on them, which would be more idiomatic than having a separate function that handles the printing.
I would also recommend using rust-clippy to help you write more idiomatic code. | {
"domain": "codereview.stackexchange",
"id": 43621,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
java, jni
Title: Custom object Cleaner for old JDK
Question: I'm implementing a JNI library that needs to dispose a few native objects after use. The main library class implements Closeable and is almost always used within try-with-resources. Even then, as the library will be used in by a larger audience within the company, I want to make a safe-guard to make it harder to introduce native memory leaks.
Initially I did this by implementing the finalize() method. But this was bad for two reasons:
Finalizers are deprecated since Java 9 (in favor of Cleaners).
After benchmarking it, finalizers were slowing down GC significantly. Even if all objects were explicitly closed before finalization.
Using Cleaners would be ok, but they are only available since Java 9, and my library needs to support Java 8. Besides, they keep the cleaner thread alive forever and I wanted something that allowed the cleaner thread to be killed if no new objects were pending finalization after keepAlive milliseconds. This is why I created the class CleanerThread below.
It contains a lot of code borrowed from java.lang.ref.Cleaner and also sun.misc.Cleaner, but with changes to allow the thread to be killed and respawned as needed. Please, keep in mind that CleanerThread is only meant to be used by library code (not user code). I would appreciate feedback on potential bugs in this implementation.
It should be used like this:
public class Resource implements Closeable {
private static final CleanerThread CLEANER = new CleanerThread(5000, "Cleanup Thread");
private final CleanerThread.Cleaner cleaner;
public Resource() {
cleaner = CLEANER.register(this, new ResourceCleaningAction());
}
@Override
public void close() {
cleaner.clean(); // preemptively clean resources
} | {
"domain": "codereview.stackexchange",
"id": 43622,
"lm_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, jni",
"url": null
} |
java, jni
private static class ResourceCleaningAction implements CleanerThread.CleaningAction {
@Override
public void clean(boolean leak) {
// perform cleaning actions
}
}
}
And here is CleanerThread implementation:
import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;
public class CleanerThread {
public interface Cleaner {
void clean();
}
public interface CleaningAction {
void clean(boolean leak);
}
private final ReferenceQueue<Object> queue = new ReferenceQueue<>();
private final long keepAlive;
private final String name;
private boolean threadRunning = false;
private Node first;
public CleanerThread(long keapAlive, String name) {
this.keepAlive = keapAlive;
this.name = name;
}
public Cleaner register(Object obj, CleaningAction action) {
Node node = new Node(obj, action);
add(node);
return node;
}
private synchronized boolean checkEmpty() {
if (first == null) {
threadRunning = false;
return true;
}
return false;
}
private synchronized void add(Node node) {
if (first != null) {
node.next = first;
first.prev = node;
}
first = node;
if (!threadRunning) {
threadRunning = true;
startThread();
}
} | {
"domain": "codereview.stackexchange",
"id": 43622,
"lm_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, jni",
"url": null
} |
java, jni
private void startThread() {
Thread thread = new Thread(() -> {
while (true) {
try {
Node ref = (Node) queue.remove(keepAlive);
if (ref != null) {
ref._clean(true);
} else if (checkEmpty()) {
break;
}
} catch (Throwable e) {
// ignore exceptions from the cleanup action
// (including interruption of cleanup thread)
}
}
}, name);
thread.setDaemon(true);
thread.start();
}
private synchronized boolean remove(Node node) {
// If already removed, do nothing
if (node.next == node)
return false;
// Update list
if (first == node)
first = node.next;
if (node.next != null)
node.next.prev = node.prev;
if (node.prev != null)
node.prev.next = node.next;
// Indicate removal by pointing the cleaner to itself
node.next = node;
node.prev = node;
return true;
}
private class Node extends PhantomReference<Object> implements Cleaner {
private final CleaningAction action;
private Node prev;
private Node next;
public Node(Object referent, CleaningAction action) {
super(referent, queue);
this.action = action;
}
@Override
public void clean() {
_clean(false);
}
private void _clean(boolean leak) {
if (!remove(this))
return;
try {
action.clean(leak);
} catch (Throwable e) {
// Should not happen if cleaners are well-behaved
e.printStackTrace();
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43622,
"lm_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, jni",
"url": null
} |
java, jni
Answer: Sincere question: it is worth and still correct to make the following refactoring? Btw, a nit: rename checkEmpty() to isEmpty().
private synchronized boolean checkEmpty() {
if (first == null) {
threadRunning = false;
}
return !threadRunning;
}
Another question: what happens if it is passed null for the parameters below? I.e., does the method needs defensive null checking?
public Node(Object referent, CleaningAction action) { | {
"domain": "codereview.stackexchange",
"id": 43622,
"lm_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, jni",
"url": null
} |
algorithm, swift, trie
Title: Trie data structure in Swift lang
Question: This is an implementation of a generic Trie DS, in Swift-lang, that is using however, for the sake of a easy example, strings.
It implements two operations, insert and search. So it can insert a text, and look for substrings of that text, for example.
I'd be interested in recommendations as to how correct the code is, but also how idiomatic, relative to the Swift language.
The Node<T>struct represents a node in the Trie<T> tree. Each node holds a dictionary that maps a key of type T, towards another Node<T>.
This is the code:
import Foundation
struct Node<T: Hashable> {
var children: [T : Node<T>] = [:]
var isLeaf: Bool {
children.isEmpty
}
mutating func addChild(withKey key: T) {
guard children[key] == nil else { return }
children[key] = Node()
}
func hasChild(withKey key: T) -> Bool {
children[key] != nil
}
}
struct Trie<T: Hashable> {
public var root = Node<T>()
mutating func addContent(of content: some Collection<T>) {
var iter = content.makeIterator()
addCotentHelper(&root, &iter)
func addCotentHelper(_ node: inout Node<T>, _ iter: inout some IteratorProtocol<T>) {
guard let key = iter.next() else { return }
node.addChild(withKey: key)
addCotentHelper(&node.children[key]!, &iter)
}
} | {
"domain": "codereview.stackexchange",
"id": 43623,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, trie",
"url": null
} |
algorithm, swift, trie
private func containsPrefix(of content: some Collection<T>, at root: Node<T>) -> Bool {
guard let first = content.first else { return true }
if root.hasChild(withKey: first) {
return containsPrefix(of: content.dropFirst(), at: root.children[first]!)
}
return false
}
public func hasContent(of word: some Collection<T>) -> Bool {
return hasContentHelper(of: word, at: root)
func hasContentHelper(of word: some Collection<T>, at root: Node<T>) -> Bool {
guard !word.isEmpty else { return true }
guard root.isLeaf == false else {
return false
}
if containsPrefix(of: word, at: root) {
return true
}
return root.children.values.contains(where: { child in hasContentHelper(of: word, at: child) })
}
}
func printTrie() {
printTrieHelper(node: root, indent: 1)
func printTrieHelper(node: Node<T>, indent: Int) {
let leading_indent = "| "
let last_indent = "|-"
for (k, v) in node.children {
print(
String(
repeating: leading_indent,
count: indent - 1) + last_indent,
terminator: "")
print(k, terminator: "\n")
printTrieHelper(node: v, indent: indent + 1)
}
}
}
}
Answer: Access control
Some types and methods are explicitly made public, but in order to make the code compilable and usable as an external library, all types and methods which are meant to be called from outside must be made public. Also Trie needs a public init method. So the public interface should look like this:
public struct Node<T> where T : Hashable {
}
public struct Trie<T> where T : Hashable { | {
"domain": "codereview.stackexchange",
"id": 43623,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, trie",
"url": null
} |
algorithm, swift, trie
public struct Trie<T> where T : Hashable {
public init()
public mutating func addContent(of content: some Collection<T>)
public func hasContent(of word: some Collection<T>) -> Bool
public func printTrie()
}
Another option is to make Node private to the Trie type:
public struct Trie<T: Hashable> {
private struct Node<T: Hashable> { ... }
private var root = Node<T>()
// ...
}
Minor remarks
The generic type placeholder can be omitted if it is given from the context, i.e. in struct Node<T: Hashable> can
var children: [T : Node<T>] = [:]
be simplified to
var children: [T : Node] = [:]
There is a typo in addCotentHelper().
To guard or not to guard
The guard statement is useful to avoid the “if-let pyramid of doom” and to handle exceptional situations. But it should (in my opinion) not be used as a general “if not” statement. So it is perfectly fine here
guard let key = iter.next() else { return }
But these statements
guard children[key] == nil else { return }
children[key] = Node()
guard !word.isEmpty else { return true }
guard root.isLeaf == false else {
return false
}
are easier to read and to understand as simple if statements:
if children[key] == nil {
children[key] = Node()
}
if word.isEmpty {
return true
}
if root.isLeaf {
return false
}
Simplifying the code
The addContent() method uses recursion and passes Node instances as inout parameters around a lot. This gets much easier if we make Node a class (so that pointers to instances can be passed around) and let the addChild() return the child node:
class Node<T: Hashable> {
var children: [T : Node] = [:]
func addChild(withKey key: T) -> Node {
if let child = children[key] {
return child
} else {
let child = Node()
children[key] = child
return child
}
}
// ...
} | {
"domain": "codereview.stackexchange",
"id": 43623,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, trie",
"url": null
} |
algorithm, swift, trie
public mutating func addContent(of content: some Collection<T>) {
var node = root
for key in content {
node = node.addChild(withKey: key)
}
}
Similarly, containsPrefix() can now use iteration of recursion, and creating slices of the content is no longer necessary:
private func containsPrefix(of content: some Collection<T>, at root: Node<T>) -> Bool {
var node = root
for key in content {
guard let next = node.children[key] else {
return false
}
node = next
}
return true
}
In hasContentHelper(), the check for word.isEmpty is not needed because containsPrefix(of: word, at: root) will return true in that case. The check for root.isLeaf is also not needed, because root.children.values.contains will return false if there are not children.
It is a matter of taste, but I find an explicit loop easier to read than calling root.children.values.contains() with a closure:
for child in root.children.values {
if hasContentHelper(of: word, at: child) {
return true
}
}
return false
With the above changes the isLeaf property and the hasChild() method of Node are no no longer needed.
Naming
Again a matter of personal taste, but I would use
private func containsPrefix(_ content: some Collection<T>, at root: Node<T>)
public func contains(_ word: some Collection<T>) -> Bool
func containsHelper(_ word: some Collection<T>, at root: Node<T>) -> Bool
public func print()
The first three method resemble the contains() method of collections. And “Trie” in printTrie() is a “needless word” because it just repeats the type, which is clear from the context.
As an alternative to a print() method one can also implement the CustomStringConvertible or CustomDebugStringConvertible protocol, e.g.
extension Trie: CustomDebugStringConvertible {
public var debugDescription: String {
// add code here ...
}
} | {
"domain": "codereview.stackexchange",
"id": 43623,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "algorithm, swift, trie",
"url": null
} |
c#
Title: Constructors for a generic subclass pool
Question: I'm trying to pool & recycle a number of classes, A, B and C which are all subclasses of Z. I'd like to have one class that handles all of the pools, such as
internal class Pooled {
Queue<A> AvailableA;
Queue<B> AvailableB;
Queue<C> AvailableC;
}
I'd like to save myself some redundant typing so ideally we'd put them all in one dictionary. In my mind it would go something like this:
internal class Pooled {
Dictionary<Type, Queue<Z>> dict;
public T Get<T> () where T : Z {
Queue<Z> queue = null;
if (dict.TryGetValue(typeof(T), out queue) == false) {
queue = new Queue<Z>();
dict[typeof(T)] = queue;
}
if (queue.TryDequeue(out var result))
return (T)result;
// <-- Must construct and return new instance here
return null;
}
} | {
"domain": "codereview.stackexchange",
"id": 43624,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
I don't know if the above approach is alright, but the core of my problem is below.
For the construction code, ideally I could have all Z subclasses have a static function Build() to generate a new instance. But I don't think I can just call return T.Build();
So I thought of making a constructor delegate and then map them to the classes. The Pooled class now looks like this:
internal class Pooled {
Dictionary<Type, Queue<Z>> dict = new Dictionary<Type, Queue<Z>>();
delegate Z BuildDelegate();
Dictionary<Type, BuildDelegate> builders = new Dictionary<Type, BuildDelegate>() {
{typeof(A), () => new A()},
{typeof(B), () => new B()},
{typeof(C), () => new C()}
};
public T Get<T> () where T : Z {
Queue<Z> queue = null;
if (dict.TryGetValue(typeof(T), out queue) == false) {
queue = new Queue<Z>();
dict[typeof(T)] = queue;
}
if (queue.TryDequeue(out var result))
return (T)result;
return (T)builders[typeof(T)]();
}
public void Recycle<T>(T obj) where T : Z {
Queue<Z> queue = null;
if (dict.TryGetValue(typeof(T), out queue) == false) {
queue = new Queue<Z>();
dict[typeof(T)] = queue;
}
queue.Enqueue(obj);
}
}
Honestly, it felt a little hacky and it probably looks uglier than manually writing a method for each subclass. Typing the constructors in that dictionary seemed to defeat the point of making the pool generic. I also really don't like casting or all the typeof() uses.
Is there a better (or cleaner) way to approach this kind of task?
Answer: you could solve this by just adjusting the generic constraint :
internal class Pool<T> where T : Z, new() { .. }
this would enforce using the default ctor for the provided classes. and if you want to expand the support to all classes, you just replace the constraint to
where T : class, new() | {
"domain": "codereview.stackexchange",
"id": 43624,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
c#
adding new() would change your creating from return (T)builders[typeof(T)](); to return new T(); , using this would remove the need of builders dictionary along with its delegate.
So, you won't need them, and you won't need to implement Build() methods in all classes. You only need to expose their default constructor.
The other note is using Dictionary here is not optimal for asynchronous operations. you will need to use one of the thread-safe collections which is under System.Collections.Concurrent namesapce. Something like ConcurrentDictionary would replace the use of Dictionary.
ObjectPool<T> is already exists under Microsoft.Extensions.ObjectPool namespace, and I encourage you to use it instead of re-invent the wheel. | {
"domain": "codereview.stackexchange",
"id": 43624,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
Title: Get the 64 most popular items from a list of tree species using webscraping | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
Question: I made this python program to find the 64 most common elements of a list stored in a text file. Since this works using binomial names of trees I decided to use the number of mentions in PubMed Central as a metric of popularity.
I am just a beginner and somewhat self-taught so I'd like to know if there are any ways of either optimizing this code or improving readability and whether it follows webscraping best practices.
The output will be used to seed Facebook polls inside a botany group.
Currently the input file has 81825 rows and can be found in this GitHub repository: https://github.com/ascyphermoonshot/larch-madness
import os
import random
import requests
import bs4
import re
from progress.bar import Bar
os.chdir(r"C:\Users\HP\Desktop\larch_madness") #or whatever your filepath is
trees=open('tree_list.txt',mode='r')
trees.seek(0)
treelist=trees.read().splitlines()
treelist=[tree.replace(" ","+").lower() for tree in treelist]
trees.close()
random.shuffle(treelist)
testlist=treelist
baseurl="https://www.ncbi.nlm.nih.gov/pmc/?term=%22{}%22"
finalists=[]
class Tree:
def __init__(self,binomial,popularity):
self.binomial=binomial.replace("+"," ").capitalize()
self.popularity=popularity
def __str__(self):
return self.binomial
def popsearch(baseurl,tree):
searchurl=baseurl.format(tree)
try:
sresult=requests.get(searchurl,timeout=10)
except:
try:
sresult=requests.get(searchurl,timeout=10)
except:
try:
sresult=requests.get(searchurl,timeout=10)
except:
#print("timeout")
return None
soup=bs4.BeautifulSoup(sresult.text,"lxml")
def noresults(soup):
stext=str(soup)
return "No items found." in stext
if not noresults(soup):
try:
resfound=str(soup.find('a', {'title' : 'Total Results'}).text)
#print(resfound) | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
#print(resfound)
num=re.search(r"(?<=\()\d+(?=\))",resfound)
num=num.group(0)
#print(num)
return(int(num))
except:
#print ("not found")
return None
else:
#print("no results")
return None
def avoid_riots(finalists):
favs=['Sequoiadendron giganteum','Rhizophora mangle','Ginkgo biloba','Hura crepitans','Taxus baccata','Sequoia sempervivens','Pinus longaeva','Ceiba petandra','Hippomane mancinella','Dracaena cinnabari','Juniperus virginiana','Dendrocnide moroides','Artocarpus heterophyllus','Litchi chinensis','Angiopteris evecta','Pyrus calleryana']
diff=list(set(finalists[0:-15]) - set(favs))
if len(diff)<0:
for x in range(len(diff)):
try:
finalists.pop()
except:
pass
finalists.extend(favs)
finalists=set(finalists)
return list(finalists)
if __name__ == '__main__':
bar = Bar('Scraping', max=len(testlist),suffix='%(percent)d%%')
for tree in testlist:
#print(tree.replace("+"," ").capitalize())
popularity=popsearch(baseurl,tree)
if popularity!=None:
finalists.append(Tree(tree,popularity))
#print("found")
bar.next()
bar.finish()
print("\n"*3)
finalists.sort(key=lambda x: x.popularity, reverse=True)
print(len(finalists))
finalists=finalists[0:64]
tfinalists=[x.binomial for x in finalists]
tfinalists=avoid_riots(tfinalists)
random.shuffle(tfinalists)
for tree in tfinalists:
print(tree)
with open('final tree list.txt', 'w') as f:
f.writelines("%s\n" % l for l in tfinalists) | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
Answer: There are several layers of non-ideal decisions in the design of this program, so let's peel them off:
Layer 1
Assuming that the data-gathering approach is good as-is, which it isn't - but we'll get to that later.
Application Design
I don't think it's a good idea to chdir() to a hard-coded directory, particularly one in Users. Either accept this as a parameter, or don't do it at all and assume that the current working directory is already correct.
if len(diff)<0 makes no sense because a collection length can never be negative. Assuming that this application works correctly, that entire block can be deleted because it will never evaluate to True.
Basic Python
Move global imperative code into functions.
Add PEP484 type hints.
Format your Python via PEP8 (get a linter or IDE to suggest how this is done).
Put file operations in a context manager, and don't explicitly close; guarantee the close call via with.
Don't seek(0); that's redundant for a newly-opened file.
Don't write a triple-nested exception block; just write a loop.
Use sets and set comprehensions more directly for your hilariously-titled avoid_riots logic.
Don't != None; write is not None because None is a singleton.
Delete your commented-out debug printing.
You don't need to provide a sortation lambda if you use a NamedTuple whose first element is the sortation key.
Split your favs literal to multiple lines. It can also be represented as a capitalised constant in the global namespace.
Library use
mode='r' is already the default so you don't need to do that.
Don't URLencode your data; let requests do that for you.
Don't bake your query into the URL; let requests do that for you.
Add a strainer so that BeautifulSoup can narrow its parsing scope.
Don't ignore HTTP errors; call raise_for_status.
Put the requests response object in context management.
Layer 2 | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
Put the requests response object in context management.
Layer 2
You perform (and scrape) a full search and then throw away everything except for the result count. The PMC Advanced Search Builder offers a different interface that doesn't render any of the search results, only a summary of the search term, count and time. If you need to scrape (which you don't), use this instead. POST parameters are easily captured via reverse engineering in the browser.
Covering layers 1 and 2, your application could look like this. For simplicity I am limiting the number of search results and skipping the progress bar.
import random
from itertools import islice
from typing import Iterable, Iterator, NamedTuple | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
import bs4
from bs4.element import SoupStrainer
from requests import Session
HTTP_TRIES = 3
DEBUG_LIMIT = 5
TOP_POPULAR = 64
BASE_URL = 'https://www.ncbi.nlm.nih.gov/pmc'
STRAINER = SoupStrainer(name='table', id='HistoryView')
ENTREZ_QUERY = {
'EntrezSystem2.PEntrez.PMC.Pmc_PageController.PreviousPageName': 'advanced',
'EntrezSystem2.PEntrez.DbConnector.Cmd': 'Preview',
'EntrezSystem2.PEntrez.DbConnector.Db': 'pmc',
'p$l': 'EntrezSystem2',
}
FAVOURITES = {
'Sequoiadendron giganteum', 'Rhizophora mangle', 'Ginkgo biloba', 'Hura crepitans', 'Taxus baccata',
'Sequoia sempervivens', 'Pinus longaeva', 'Ceiba petandra', 'Hippomane mancinella', 'Dracaena cinnabari',
'Juniperus virginiana', 'Dendrocnide moroides', 'Artocarpus heterophyllus', 'Litchi chinensis',
'Angiopteris evecta', 'Pyrus calleryana',
}
class Tree(NamedTuple):
popularity: int
binomial: str
def __str__(self) -> str:
return self.binomial
@classmethod
def fetch_all(cls, tree_names: Iterable[str]) -> Iterator['Tree']:
with Session() as session:
for tree_name in tree_names:
popularity = pop_search(session, tree_name)
if popularity is not None:
yield cls(popularity, tree_name.capitalize())
def fetch_retry(session: Session, term: str) -> str:
for _ in range(HTTP_TRIES):
try:
with session.post(
url=BASE_URL,
headers={'Accept': 'text/html'},
timeout=10,
data={
'EntrezSystem2.PEntrez.DbConnector.Term': term,
**ENTREZ_QUERY,
},
) as sresult:
sresult.raise_for_status()
return sresult.text
except IOError as e:
last_ex = e
raise last_ex | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
raise last_ex
def parse(html: str, term: str) -> int:
soup = bs4.BeautifulSoup(markup=html, features='lxml', parse_only=STRAINER)
table: bs4.element.Tag = soup.contents[-1]
heads = [th.text for th in table.find('thead').find_all('th')]
rows = [
{
head: td.text
for head, td in zip(heads, tr.find_all('td'))
} for tr in table.find_all('tr', recursive=False)
]
# The history interface is stateful. Assume that the first listed search term
# is the one we care about. A more paranoid implementation could e.g. sort
# antichronologically on the Search # column.
record = next(
row for row in rows
if row['Query'] == f'Search {term}'
)
return int(record['Items found'])
def pop_search(session: Session, tree: str) -> int:
term = f'"{tree.lower()}"'
html = fetch_retry(session, term)
return parse(html, term)
def load(filename: str = 'tree_list.txt') -> Iterator[str]:
with open(filename) as f:
for line in f:
yield line.rstrip()
def avoid_riots(finalists: set[str]) -> set[str]:
return finalists | FAVOURITES
def fetch_top(tree_names: Iterable[str]) -> list[Tree]:
return sorted(
islice(Tree.fetch_all(tree_names), DEBUG_LIMIT),
reverse=True,
)[:TOP_POPULAR]
def main() -> None:
tree_names = list(load())
random.shuffle(tree_names)
trees = fetch_top(tree_names)
names = {x.binomial for x in trees}
augmented_names = list(avoid_riots(names))
random.shuffle(augmented_names)
print('\n'.join(augmented_names))
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
print('\n'.join(augmented_names))
if __name__ == '__main__':
main()
Ginkgo biloba
Dendrocnide moroides
Eucalyptus albida
Rhizophora mangle
Litchi chinensis
Angiopteris evecta
Hura crepitans
Orania oreophila
Ceiba petandra
Sequoia sempervivens
Sequoiadendron giganteum
Croton hancei
Taxus baccata
Utania nervosa
Hippomane mancinella
Juniperus virginiana
Artocarpus heterophyllus
Pinus longaeva
Barringtonia jebbiana
Dracaena cinnabari
Pyrus calleryana
Layer 3
Don't scrape! Some trivial googling reveals the E-Utilities API. This can much more narrowly target your use case, and is morally the "right thing to do" for a public service.
I demonstrate a functioning implementation that abides by the rate limitation constraints in the documentation; this can be sped up by getting an API key. I actually did get an API key, and added a logger to see what typical timing is. It turns out that basically all calls to the service take slightly longer than the minimum rate period, so as a consequence
you might be able to get away with a simplified rate limitation strategy that simply issues requests with no delay, sleeping if you get a TOO_MANY_REQUESTS; and
you might be able to add a threaded or asynchronous implementation that interleaves requests for higher performance while still staying within the limit.
import logging
import time
from contextlib import contextmanager
from http.client import TOO_MANY_REQUESTS
from itertools import islice
from random import shuffle
from typing import Iterable, Iterator, NamedTuple
from requests import Session
logger = logging.getLogger()
# See https://www.ncbi.nlm.nih.gov/books/NBK25497/#chapter2.Coming_in_December_2018_API_Key
API_KEY = None
UNAUTHENTICATED_RATE = 3
AUTHENTICATED_RATE = 10
RATE = AUTHENTICATED_RATE if API_KEY else UNAUTHENTICATED_RATE
HTTP_TRIES = 3
COOLOFF = 5
DEBUG_LIMIT = 10
TOP_POPULAR = 64 | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
# See https://www.ncbi.nlm.nih.gov/books/NBK25499/#chapter4.ESearch
BASE_URL = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi'
FAVOURITES = {
'Sequoiadendron giganteum', 'Rhizophora mangle', 'Ginkgo biloba', 'Hura crepitans', 'Taxus baccata',
'Sequoia sempervivens', 'Pinus longaeva', 'Ceiba petandra', 'Hippomane mancinella', 'Dracaena cinnabari',
'Juniperus virginiana', 'Dendrocnide moroides', 'Artocarpus heterophyllus', 'Litchi chinensis',
'Angiopteris evecta', 'Pyrus calleryana',
}
class Tree(NamedTuple):
popularity: int
binomial: str
@classmethod
def fetch_all(cls, session: Session, tree_names: Iterable[str]) -> Iterator['Tree']:
for tree_name in tree_names:
popularity = pop_search(session, tree_name)
yield cls(popularity, tree_name.capitalize())
@contextmanager
def wait_rate() -> Iterator:
# See for rate-limiting information:
# https://www.ncbi.nlm.nih.gov/books/NBK25497/#chapter2.Frequency_Timing_and_Registrati
# Unauthenticated rate limit is 3/second; authenticated is 10/s
start = time.monotonic()
yield
dur = time.monotonic() - start
wait_for = 1/RATE - dur + 0.01
logger.debug('Would wait for %.3f s', wait_for)
if wait_for > 0:
time.sleep(wait_for)
def fetch_retry(session: Session, term: str) -> dict:
params = {
'db': 'pmc',
'term': term,
'usehistory': 'n',
'rettype': 'count',
'retmode': 'json',
}
if API_KEY:
params['api_key'] = API_KEY | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
for _ in range(HTTP_TRIES):
with wait_rate():
try:
with session.get(
url=BASE_URL,
params=params,
headers={'Accept': 'application/json'},
timeout=10,
) as sresult:
if sresult.status_code == TOO_MANY_REQUESTS:
time.sleep(COOLOFF)
sresult.raise_for_status()
return sresult.json()
except IOError as e:
last_ex = e
raise last_ex
def pop_search(session: Session, tree: str) -> int:
term = f'"{tree.lower()}"'
response = fetch_retry(session, term)
return int(response['esearchresult']['count'])
def load(filename: str = 'tree_list.txt') -> Iterator[str]:
with open(filename) as f:
for line in f:
yield line.rstrip()
def avoid_riots(finalists: set[str]) -> set[str]:
return finalists | FAVOURITES
def fetch_top(tree_names: Iterable[str]) -> list[Tree]:
with Session() as session:
return sorted(
islice(Tree.fetch_all(session, tree_names), DEBUG_LIMIT),
reverse=True,
)[:TOP_POPULAR]
def main() -> None:
logging.basicConfig(level=logging.DEBUG)
tree_names = list(load())
shuffle(tree_names)
trees = fetch_top(tree_names)
names = {x.binomial for x in trees}
augmented_names = list(avoid_riots(names))
shuffle(augmented_names)
print('\n'.join(augmented_names))
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
Output
With an API key defined. The negative delays mean that it never waits.
DEBUG:urllib3.connectionpool:Starting new HTTPS connection (1): eutils.ncbi.nlm.nih.gov:443
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22endiandra+hypotephra%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.240 s
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22byrsonima+formosa%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.072 s
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22xylosma+raimondii%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.075 s
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22cryptocarya+hypospodia%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.064 s
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22erythroxylum+platyclados%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.100 s
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22campylospermum+letouzeyi%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.047 s
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22parkia+biglandulosa%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.073 s | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
python, beginner, web-scraping, beautifulsoup
DEBUG:root:Would wait for -0.073 s
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22palicourea+schomburgkii%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.057 s
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22dillenia+talaudensis%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.047 s
DEBUG:urllib3.connectionpool:https://eutils.ncbi.nlm.nih.gov:443 "GET /entrez/eutils/esearch.fcgi?db=pmc&term=%22stenocarpus+villosus%22&usehistory=n&rettype=count&retmode=json&api_key=******************** HTTP/1.1" 200 None
DEBUG:root:Would wait for -0.065 s
Hura crepitans
Sequoia sempervivens
Xylosma raimondii
Taxus baccata
Erythroxylum platyclados
Sequoiadendron giganteum
Rhizophora mangle
Ceiba petandra
Palicourea schomburgkii
Endiandra hypotephra
Stenocarpus villosus
Artocarpus heterophyllus
Campylospermum letouzeyi
Cryptocarya hypospodia
Byrsonima formosa
Ginkgo biloba
Dracaena cinnabari
Litchi chinensis
Angiopteris evecta
Parkia biglandulosa
Pyrus calleryana
Dendrocnide moroides
Pinus longaeva
Juniperus virginiana
Hippomane mancinella
Dillenia talaudensis | {
"domain": "codereview.stackexchange",
"id": 43625,
"lm_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, web-scraping, beautifulsoup",
"url": null
} |
c#, algorithm, .net, api, binary-search-tree
Title: C# Binary Search Tree implementation
Question: I have implemented a Binary Search Tree and would really appreciate it if someone could take time to check it and give me feedback.
I try to keep my code clear and simple.
Is it readable?
Is the API of constructors well-designed?
Did I handle the nullable fields of the tree and iterators well?
Please be as strict as possible with me.
Code:
GitHub
TreeNode code:
public class TreeNode
{
public readonly T Value;
public TreeNode? LeftLeaf;
public TreeNode? RightLeaf;
public TreeNode(T elem)
{
Value = elem;
LeftLeaf = null;
RightLeaf = null;
}
public TreeNode(T elem, TreeNode? left, TreeNode? right) : this(elem)
{
LeftLeaf = left;
RightLeaf = right;
}
}
BinarySearchTree fields, properties and constructors:
public class BinarySearchTree<T> : ICollection<T>
where T : IComparable<T>
{
//TreeNode code
//{
// see it above
//}
public BinarySearchTree()
{
Root = null;
_size = 0;
}
public BinarySearchTree(T firstElem)
{
Root = new TreeNode(firstElem);
_size = 0;
}
public BinarySearchTree(
T[] arry,
BinarySearchTreeSortOrder order = BinarySearchTreeSortOrder.Ascdending
Comparer<T>? comparer = null)
{
if (arry == null) throw new ArgumentNullException(nameof(arry));
if (arry.Length == 0) throw new ArgumentException(nameof(arry));
this.Root = new TreeNode(arry[0]);
this._size = 1;
_order = order;
_comparer = comparer;
}
// properties
public int Count => _size;
public bool IsReadOnly => false;
// methods
// Add()
// Compare()
// Clear()
// Contains()
// CopyTo()
// Min()
// Max()
// Remove()
// enumerators section
} | {
"domain": "codereview.stackexchange",
"id": 43626,
"lm_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, .net, api, binary-search-tree",
"url": null
} |
c#, algorithm, .net, api, binary-search-tree
Add method:
/// <summary>
/// Adds an element to the Binary Search Tree in O(n) worse case
/// and O(log(n)) average case.
/// If the given element already exists in the tree adds a duplicate.
/// </summary>
/// <param name="item"></param>
public void Add(T item)
{
Add(Root, item);
_size++;
}
// returns the subtree of the given TreeNode that contains new item.
private TreeNode Add(TreeNode? addRoot, T item)
{
if (addRoot == null) addRoot = new TreeNode(item);
else
{
var cmp = this.Compare(item, addRoot.Value);
if (cmp <= 0) addRoot.LeftLeaf = Add(addRoot.LeftLeaf, item);
if (cmp > 0) addRoot.RightLeaf = Add(addRoot.RightLeaf, item);
}
return addRoot;
}
Compare method:
private int Compare(T item1, T item2)
{
int compVal = this._comparer?.Compare(item1, item2) ?? item1.CompareTo(item2);
return compVal * (_order == BinarySearchTreeSortOrder.Ascdending ? 1 : -1);
}
Clear method:
/// <summary>
/// Clears the BinarySearchTree. Assigns null to the root element.
/// </summary>
public void Clear()
{
this.Root = null;
this._size = 0;
}
Contains method:
/// <summary>
/// If BinarySearchTree contains the specified element returns true
///and false otherwise.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Contains(T item)
{
var node = Root;
while (node != null)
{
int cmp = this.Compare(item, node.Value);
if (cmp < 0) node = node.LeftLeaf;
else if (cmp > 0) node = node.RightLeaf;
else return true;
}
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43626,
"lm_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, .net, api, binary-search-tree",
"url": null
} |
c#, algorithm, .net, api, binary-search-tree
return false;
}
CopyTo method:
/// <summary>
/// Copies elements of the BinarySearchTree to the specified array in sorted order.
/// </summary>
/// <param name="array"></param>
/// <param name="arrayIndex"></param>
public void CopyTo(T[] array, int arrayIndex)
{
using (var enumerator = this.GetEnumerator(Traversal.InOrder))
{
int i = arrayIndex;
for (int j = 0; j < i; j++) enumerator.MoveNext();
while (enumerator.MoveNext()) array[i++] = enumerator.Current;
}
}
Min method:
/// <summary>
/// Extracts the minimal element of the BinarySearchTree in O(1) time.
/// </summary>
/// <returns></returns>
/// <exception cref="NullReferenceException"></exception>
public T Min()
{
if (Root == null) throw new NullReferenceException(nameof(Root));
return this.Min(Root).Value;
}
private TreeNode Min(TreeNode minRoot)
{
while (minRoot.LeftLeaf != null) minRoot = minRoot.LeftLeaf;
return minRoot;
}
Max method:
/// <summary>
/// Extracts the biggest element of the BinarySearchTree in O(n) worse case
///and O(log(n)) average case.
/// </summary>
/// <returns></returns>
/// <exception cref="NullReferenceException"></exception>
public T Max()
{
if (Root == null) throw new NullReferenceException(nameof(Root));
return this.Max(this.Root).Value;
}
private TreeNode Max(TreeNode maxRoot)
{
while (maxRoot.RightLeaf != null) maxRoot = maxRoot.RightLeaf;
return maxRoot;
}
Remove method:
/// <summary>
/// Performs removal of specified item from the BinarySearchTree in O(n) worse
/// case and O(log(n)) average case.
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public bool Remove(T item)
{
if (!Contains(item)) return false;
Root = Remove(Root, item);
_size--;
return true;
}
private TreeNode? Remove(TreeNode? removeRoot, T item)
{
if (removeRoot == null) return null;
var cmp = this.Compare(item, removeRoot.Value); | {
"domain": "codereview.stackexchange",
"id": 43626,
"lm_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, .net, api, binary-search-tree",
"url": null
} |
c#, algorithm, .net, api, binary-search-tree
var cmp = this.Compare(item, removeRoot.Value);
if (cmp == 1) removeRoot.RightLeaf = Remove(removeRoot.RightLeaf, item);
else if (cmp == -1) removeRoot.LeftLeaf = Remove(removeRoot.LeftLeaf, item);
else
{
if (removeRoot.LeftLeaf == null && removeRoot.RightLeaf == null)
return null;
//there are 2 leafs
if (removeRoot.RightLeaf != null && removeRoot.LeftLeaf != null)
{
//find min, replace root with the min and remove min
var rightMin = Min(removeRoot.RightLeaf);
rightMin.RightLeaf = Remove(removeRoot.RightLeaf, rightMin.Value);
rightMin.LeftLeaf = removeRoot.LeftLeaf;
return rightMin;
}
return removeRoot.LeftLeaf ?? removeRoot.RightLeaf;
}
return removeRoot;
}
GetEnumerator method:
public IEnumerator<T> GetEnumerator() => GetEnumerator(Traversal.InOrder);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(Traversal.InOrder);
public IEnumerator<T> GetEnumerator(Traversal traversal)
{
switch (traversal)
{
case Traversal.InOrder: return new InOrderIterator(this);
case Traversal.PreOrder: return new PreOrderIterator(this);
case Traversal.LevelOrder: return new LevelOrderIterator(this);
}
return new InOrderIterator(this);
}
InOrderEnumerator:
private class InOrderIterator : IEnumerator<T>
{
private readonly BinarySearchTree<T> _bst;
private readonly Stack<TreeNode> _stack = new();
private TreeNode _trav;
private TreeNode _current;
public InOrderIterator(BinarySearchTree<T> bst)
{
this._bst = bst ?? throw new NullReferenceException(nameof(bst));
_trav = bst.Root ?? throw new NullReferenceException(nameof(bst.Root));
_stack.Push(bst.Root);
_current = bst.Root;
}
public bool MoveNext()
{
if (_stack.Count == 0) return false; | {
"domain": "codereview.stackexchange",
"id": 43626,
"lm_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, .net, api, binary-search-tree",
"url": null
} |
c#, algorithm, .net, api, binary-search-tree
while (_trav.LeftLeaf != null)
{
_stack.Push(_trav.LeftLeaf);
_trav = _trav.LeftLeaf;
}
_current = _stack.Pop();
if (_current.RightLeaf != null)
{
_stack.Push(_current.RightLeaf);
_trav = _current.RightLeaf;
}
return true;
}
public void Reset()
{
if (_bst.Root != null)
{
_trav = _bst.Root;
_stack.Push(_bst.Root);
}
}
public T Current => _current.Value;
object IEnumerator.Current => Current;
public void Dispose()
{
/*throw new NotImplementedException();*/
}
}
PreOrderEnumerator:
private class PreOrderIterator : IEnumerator<T>
{
private readonly BinarySearchTree<T> _bst;
private readonly Stack<TreeNode> _stack = new();
private TreeNode _current;
public PreOrderIterator(BinarySearchTree<T> bst)
{
this._bst = bst ?? throw new NullReferenceException(nameof(bst));
_current = bst.Root ?? throw new NullReferenceException(nameof(bst.Root));
_stack.Push(bst.Root);
}
public T Current => _current.Value;
object IEnumerator.Current => throw new NotImplementedException();
public void Dispose()
{
//throw new NotImplementedException();
}
public bool MoveNext()
{
if (_stack.Count == 0) return false;
_current = _stack.Pop();
if (_current.RightLeaf != null) _stack.Push(_current.RightLeaf);
if (_current.LeftLeaf != null) _stack.Push(_current.LeftLeaf);
return true;
}
public void Reset()
{
if (_bst.Root != null)
{
_stack.Clear();
_stack.Push(_bst.Root);
}
}
}
LevelOrderEnumerator:
private class LevelOrderIterator : IEnumerator<T>
{
private BinarySearchTree<T> _bst;
private Queue<TreeNode> _queue = new();
private TreeNode _current; | {
"domain": "codereview.stackexchange",
"id": 43626,
"lm_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, .net, api, binary-search-tree",
"url": null
} |
c#, algorithm, .net, api, binary-search-tree
private Queue<TreeNode> _queue = new();
private TreeNode _current;
public LevelOrderIterator(BinarySearchTree<T> bst)
{
this._bst = bst ?? throw new ArgumentNullException(nameof(bst));
if (bst.Root == null)
throw new NullReferenceException($"{nameof(bst.Root)} is null.");
_current = new TreeNode(bst.Root.Value,
bst.Root.LeftLeaf,
bst.Root.RightLeaf);
_queue.Enqueue(bst.Root);
}
public bool MoveNext()
{
if (_queue.Count == 0) return false;
_current = _queue.Dequeue();
if (_current.LeftLeaf != null) _queue.Enqueue(_current.LeftLeaf);
if (_current.RightLeaf != null) _queue.Enqueue(_current.RightLeaf);
return true;
}
public void Reset()
{
if (_bst.Root != null)
{
_queue.Clear();
_queue.Enqueue(_bst.Root);
}
}
public T Current => _current.Value;
object IEnumerator.Current => throw new NotImplementedException();
public void Dispose()
{
//throw new NotImplementedException();
}
}
Declared outside of the BinarySearchTree
Traversal type:
public enum Traversal
{
InOrder,
PreOrder,
LevelOrder,
PostOrder
}
Sort order:
public enum BinarySearchTreeSortOrder
{
Ascdending,
Descending
}
Answer: My apologies that I do not have enough time to review the entire code, but I do have remarks about the stuff towards the top.
Class TreeNode
I would alter the constructors differently than what you show. What you have is nice enough, and I do struggle on whether this is my personal preference or a better design, so I offer this an an alternative.
public TreeNode(T elem) : this(elem, null, null)
{ }
public TreeNode(T elem, TreeNode? left, TreeNode? right)
{
Value = elem;
LeftLeaf = left;
RightLeaf = right;
} | {
"domain": "codereview.stackexchange",
"id": 43626,
"lm_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, .net, api, binary-search-tree",
"url": null
} |
c#, algorithm, .net, api, binary-search-tree
BinarySearchTree contructor #2
public BinarySearchTree(T firstElem)
{
Root = new TreeNode(firstElem);
_size = 0;
}
Should that be _size = 1; ???
BinarySearchTree contructor #3
What you have:
public BinarySearchTree(
T[] arry,
BinarySearchTreeSortOrder order = BinarySearchTreeSortOrder.Ascdending
Comparer<T>? comparer = null)
{
if (arry == null) throw new ArgumentNullException(nameof(arry));
if (arry.Length == 0) throw new ArgumentException(nameof(arry));
this.Root = new TreeNode(arry[0]);
this._size = 1;
_order = order;
_comparer = comparer;
}
Observations:
You restrict the input to be an array of T. It would be more flexible is you allowed it to be IList<T>. It would be even more flexible if you allowed it to be IEnumerable<T>. If you do use enumerable, then you also have to change checks for Length or grabbing index [0].
You seem to only set the Root with the first element in the array, and then do nothing with remaining elements. What if someone passes in a 5 element collection?
Here's a short (imperfect) stub demonstrating using enumerable input:
public BinarySearchTree(
IEnumerable<T> elements,
BinarySearchTreeSortOrder order = BinarySearchTreeSortOrder.Ascdending
Comparer<T>? comparer = null)
{
if (elements == null) throw new ArgumentNullException(nameof(elements));
if (!elements.Any()) throw new ArgumentException(nameof(elements));
this.Root = new TreeNode(elements.First());
this._size = 1;
_order = order;
_comparer = comparer;
// To process more elements, use something like:
foreach (var element in elements.Skip(1))
{
// do something
}
} | {
"domain": "codereview.stackexchange",
"id": 43626,
"lm_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, .net, api, binary-search-tree",
"url": null
} |
c++, reinventing-the-wheel, memory-management
Title: C++ imitation of glibc malloc(), free()
Question: I wrote a C++ simulator that performs algorithms for glibc malloc() and free().
The core logic is basically the same, with the following differences:
chunk alignment unit is sizeof(Chunk) (32 in a typical 64bit machine), whereas in glibc it is 2 * sizeof(size_t) (16 in a typical 64bit machine). glibc uses an equilibristic hack for that (frequent casting between size_t and Chunk*). I think I can simulate that as well, but writing this was already too tired...
when an arena runs out of memory, glibc requests another arena via sysmalloc(). My simulator uses std::vector<unsigned char> as arena, and all the allocated pointers are on that vector, so expanding arena will invalidate all allocated pointers. I don't know a simple way to mitigate this.
Code:
#include <algorithm>
#include <bit>
#include <cassert>
#include <chrono>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <ranges>
#include <stdexcept>
#include <unordered_map>
#include <random>
#include <vector>
// sizeof(Chunk) == 32 in typical 64bit machines,
// but the 'foot' of the current chunk is actually
// represented as the prev_size of the (unallocated) next chunk
// foot - head it is at least and aligned as sizeof(Chunk)
// sizeof(Chunk) should be a power of 2 | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_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++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
// chunks are look like this:
//
// chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Size of previous chunk, if unallocated (U clear) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Size of chunk, in bytes |0|U|I|
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Forward pointer to next chunk in list (only used if free) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Back pointer to previous chunk in list (only used if free) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Unused space (multiple of sizeof(Chunk) bytes) |
// nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// `foot:' | Size of chunk, in bytes (written by prev chunk) |
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
// | Size of next chunk, in bytes |0|U|I|
// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
struct Chunk {
std::size_t prev_size_ = 0;
// invariant: size_ > 0
// invariant: rightmost three (or two) bits of size_ are flags (CHUNK_IN_USE,
// CHUNK_UNSORTED)
std::size_t size_ = 0;
// pointers to prev/next within bins, only used for free chunks.
// nothing to do with prev/next chunks within the global arena, beware!
Chunk* next_ = nullptr;
Chunk* prev_ = nullptr;
};
static_assert(sizeof(std::size_t) == 8 || sizeof(std::size_t) == 4);
constexpr std::size_t CHUNK_IN_USE = 0x1;
constexpr std::size_t CHUNK_UNSORTED = 0x2;
constexpr std::size_t CHUNK_FLAG_MASK = 0x7;
constexpr std::size_t CHUNK_FLAG_UNMASK =
(sizeof(std::size_t) == 8) ? 0xFFFFFFFFFFFFFFF8 : 0xFFFFFFF8; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_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++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
struct GetSize {
std::size_t operator()(Chunk* iter) const noexcept {
assert(iter);
return iter->size_;
}
};
class AllocManager {
private:
static constexpr std::size_t chunk_alignment_ = sizeof(Chunk);
static_assert(std::has_single_bit(chunk_alignment_));
static constexpr std::size_t align_multiplier = (sizeof(std::size_t) == 8) ? 1UL : 2UL;
static constexpr std::size_t bin_shift_ = (sizeof(std::size_t) == 8) ? 5UL : 4UL;
static constexpr std::size_t num_fast_bins_ = 8UL * align_multiplier;
static constexpr std::size_t num_small_bins_ = 56UL * align_multiplier;
static constexpr std::size_t min_fast_size_ = chunk_alignment_;
static constexpr std::size_t min_small_size_ = chunk_alignment_ * num_fast_bins_;
static constexpr std::size_t min_large_size_ =
chunk_alignment_ * (num_small_bins_ + num_fast_bins_);
std::size_t curr_pool_size_ = 0;
// bins that store chunks of 32, 64, 96, ..., 224 bytes respectively
// (or 16, 32, ..., 112)
// LIFO singly linked list, NOT merged when freed
std::vector <Chunk*> fast_bins_;
// bins that store chunks of 256, 288, ..., 2016 bytes respectively
// (or 128, 144, ..., 1008)
// FIFO doubly linked list, chunks are merged with adjacent chunks when freed
// if adjacent
std::vector <Chunk*> small_bins_;
// a *single* bin that store chunks of 2048+ bytes (or 1024+)
// maintain the sorted order w.r.t. chunk size in *increasing* order
// chunks are merged with adjacent chunks when freed if adjacent
std::vector <Chunk*> large_bin_;
// a bin for freed chunks and remainder chunks
// when an allocation request fails to search chunk in other bins,
// this bin is searched
Chunk* unsorted_bin_ = nullptr;
Chunk* top_chunk_ = nullptr;
// store *all* chunks
std::vector <unsigned char> all_chunks_; | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_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++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
// store *all* chunks
std::vector <unsigned char> all_chunks_;
public:
AllocManager(std::size_t init_pool_size)
: curr_pool_size_{init_pool_size}, fast_bins_(num_fast_bins_, nullptr),
small_bins_(num_small_bins_, nullptr), all_chunks_(init_pool_size) {
assert(init_pool_size % chunk_alignment_ == 0);
top_chunk_ = first_chunk();
set_size(top_chunk_, init_pool_size);
}
private:
[[nodiscard]] bool is_begin(const Chunk* chunk) const noexcept {
assert(chunk);
assert(reinterpret_cast<const unsigned char*>(chunk) >=
all_chunks_.data());
return reinterpret_cast<const unsigned char*>(chunk) == all_chunks_.data();
}
Chunk* first_chunk() noexcept {
return reinterpret_cast<Chunk*>(all_chunks_.data());
}
const Chunk* first_chunk() const noexcept {
return reinterpret_cast<const Chunk*>(all_chunks_.data());
}
// don't need is_last, as top_chunk_ is always the last chunk
std::size_t* get_foot(Chunk* chunk) noexcept {
assert(chunk && chunk != top_chunk_);
return reinterpret_cast<std::size_t*>(reinterpret_cast<unsigned char*>(chunk) +
realsize(chunk));
}
const std::size_t* get_foot(const Chunk* chunk) const noexcept {
assert(chunk && chunk != top_chunk_);
return reinterpret_cast<const std::size_t*>(
reinterpret_cast<const unsigned char*>(chunk) + realsize(chunk));
}
[[nodiscard]] std::size_t get_flags(const Chunk* chunk) const noexcept {
assert(chunk);
return chunk->size_ & CHUNK_FLAG_MASK;
}
void set_flags(Chunk* chunk, std::size_t flags) {
assert(chunk && chunk != top_chunk_);
chunk->size_ &= CHUNK_FLAG_UNMASK;
chunk->size_ |= flags;
// add the foot
std::size_t* foot = get_foot(chunk);
*foot &= CHUNK_FLAG_UNMASK;
*foot |= flags;
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_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++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
// erase flags and make a nonzero mulitple of chunk_alignment_
std::size_t realsize(std::size_t sz) const noexcept {
assert(sz >= chunk_alignment_);
return (sz >> bin_shift_) << bin_shift_;
}
std::size_t realsize(const Chunk* chunk) const noexcept {
assert(chunk && chunk->size_ >= chunk_alignment_);
return realsize(chunk->size_);
}
void set_size(Chunk* chunk, std::size_t sz) {
assert(chunk);
chunk->size_ = sz;
// add the foot
if (chunk != top_chunk_) {
std::size_t* foot = get_foot(chunk);
*foot = sz;
}
}
std::size_t verify_size(const Chunk* chunk) const noexcept {
assert(chunk && chunk->size_ >= chunk_alignment_);
// check the foot
assert(chunk == top_chunk_ || *get_foot(chunk) == chunk->size_);
return chunk->size_;
}
Chunk* prev_chunk(Chunk* chunk) noexcept {
if (!chunk || is_begin(chunk)) {
return nullptr;
}
return reinterpret_cast<Chunk*>(reinterpret_cast<unsigned char*>(chunk) -
realsize(chunk->prev_size_));
}
const Chunk* prev_chunk(const Chunk* chunk) const noexcept {
if (!chunk || is_begin(chunk)) {
return nullptr;
}
return reinterpret_cast<const Chunk*>(
reinterpret_cast<const unsigned char*>(chunk) -
realsize(chunk->prev_size_));
}
Chunk* next_chunk(Chunk* chunk) noexcept {
if (!chunk || chunk == top_chunk_) {
return nullptr;
}
return reinterpret_cast<Chunk*>(reinterpret_cast<unsigned char*>(chunk) +
realsize(chunk));
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_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++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
const Chunk* next_chunk(const Chunk* chunk) const noexcept {
if (!chunk || chunk == top_chunk_) {
return nullptr;
}
return reinterpret_cast<const Chunk*>(
reinterpret_cast<const unsigned char*>(chunk) + realsize(chunk));
}
bool verify_fastbins() const {
assert(fast_bins_.size() == num_fast_bins_);
for (std::size_t i = 0; i < num_fast_bins_; ++i) {
auto chunk = fast_bins_[i];
while (chunk) {
assert(realsize(verify_size(chunk)) == fast_size(i));
assert(get_flags(chunk) == CHUNK_IN_USE);
chunk = chunk->next_;
}
}
return true;
}
bool verify_smallbins() const {
assert(small_bins_.size() == num_small_bins_);
for (std::size_t i = 0; i < num_small_bins_; ++i) {
auto chunk = small_bins_[i];
while (chunk) {
assert(verify_size(chunk) == small_size(i));
assert(chunk->prev_ && chunk->next_ && chunk->prev_->next_ == chunk &&
chunk->next_->prev_ == chunk);
if (chunk == chunk->next_) {
assert(chunk == chunk->prev_);
break;
}
chunk = chunk->next_;
if (chunk == small_bins_[i]) {
break;
}
}
}
return true;
}
bool verify_largebin() const {
assert(std::ranges::is_sorted(large_bin_, std::ranges::less{}, GetSize{}));
assert(std::ranges::all_of(large_bin_, [this](const auto& chunk) {
return chunk && get_flags(chunk) == 0 &&
verify_size(chunk) >= min_large_size_ &&
(chunk->size_ % chunk_alignment_) == 0;
}));
return true;
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_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++, reinventing-the-wheel, memory-management",
"url": null
} |
c++, reinventing-the-wheel, memory-management
bool verify_unsorted() const {
auto chunk = unsorted_bin_;
while (chunk) {
assert(verify_size(chunk) >= chunk_alignment_ &&
(realsize(chunk) % chunk_alignment_) == 0);
assert(get_flags(chunk) == CHUNK_UNSORTED);
assert(chunk->prev_ && chunk->next_ && chunk->prev_->next_ == chunk &&
chunk->next_->prev_ == chunk);
if (chunk == chunk->next_) {
assert(chunk == chunk->prev_);
break;
}
chunk = chunk->next_;
if (chunk == unsorted_bin_) {
break;
}
}
return true;
}
bool verify() const {
assert(!all_chunks_.empty() && all_chunks_.size() == curr_pool_size_);
const Chunk* chunk = first_chunk();
while (chunk) {
assert(chunk->size_ >= chunk_alignment_ &&
(realsize(chunk) % chunk_alignment_) == 0);
auto next = next_chunk(chunk);
if (!next) {
assert(chunk == top_chunk_ && get_flags(chunk) == 0);
assert(reinterpret_cast<const unsigned char*>(chunk) + chunk->size_ ==
all_chunks_.data() + all_chunks_.size());
}
chunk = next;
}
assert(verify_fastbins());
assert(verify_smallbins());
assert(verify_largebin());
assert(verify_unsorted());
return true;
}
[[nodiscard]] std::size_t fast_index(std::size_t num_bytes) const noexcept {
return (num_bytes >> bin_shift_);
}
[[nodiscard]] std::size_t fast_size(std::size_t idx) const noexcept {
return (idx << bin_shift_);
}
[[nodiscard]] std::size_t small_index(std::size_t num_bytes) const noexcept {
assert(num_bytes >= min_small_size_);
return ((num_bytes - min_small_size_) >> bin_shift_);
} | {
"domain": "codereview.stackexchange",
"id": 43627,
"lm_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++, reinventing-the-wheel, memory-management",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.