instruction stringlengths 71 95.1k |
|---|
Pretty new to React/Next.js. This is for a "back to top" button. Any thoughts on whether this can be improved? I haven't really got my head around when useEffect should be used, for example, but what I've written is running fine.
import React, { useEffect } from 'react';
import Chevron from '@/components/Icons/Chevron'... |
Background
This is for an API and I'd like to use this Upsert action to take data from a request and only update the requested fields. I.e. These are partial updates and I will not update every field from a model in every request. A previous version from examples I was working through took the incoming data and updated... |
If I have a class running its own thread, I almost always try to write it like the following, with the thread started by the constructor. The reason for this is that an object can never be constructed on multiple threads, so there is never a danger of two threads trying to start the thread. This class prints a message ... |
I have a sealed interface that I use in pretty much every one of my Android projects. It implements the loading-content-error pattern, often called a Resource, Response, or Result. (I chose LoadState instead as a name since I've found it generally has fewer naming conflicts.) My class is different in that it adds a 4th... |
I've recently attempted to get into rust. I thought I would try convert my weather logging app from python to rust to maybe save some CPU cycles on my little Raspberry Pi.
I have a little ESP8266 with a web server that allows you to pull data from it, it returns a JSON:
{
"Readings": {
"temperature": 23.62999916,... |
I wrote a bash script that installs Arch Linux. I wanted to simplify the installation of the Arch Linux system by automating things like setting locale, hostname, networking, etc. This is my second bigger script right to the two scripts that automate setting the ZFS filesystem. Any code review of what can I improve is ... |
I have a list of events. They are html elements.
The premium events have a data attribute in their parent element: data-premium-event.
I need to separate the events in two lists:
a list of premium events
a list of regular (non-premium) events
I then show oder hide them using the logic in handleVisibleEvents.
The meth... |
This is a simple stock exchange model.
There will be stock observers who are observing some specific stocks and multliple stocks can be registered at a stock exchange. Please advise how this implementation can be improved, I am not sure if the stock observer can subscribe to specific instruments?
#include <iostream>
#i... |
Since c++20 std::ranges doesn't have a zip view like range-v3 does, I am working on implementing a basic version of such a zip view to iterate over two ranges at the same time. The ranges should be equal in size. If they are not equal in size, the view should iterate over both ranges and stop as soon as one range has r... |
This code is an arithmetic parser as is the code in a previous question of mine. However this parser handles floating point arguments and mathematical functions, and handles them without needing to define a new function for every precedence level. The component to parse function names is the topic of a different previo... |
I created this python number-guessing game and I have two concerns with it. The code works as intended with no flaws; however, I'm not too fond of the way I wrote it. It is messy, unorganized, and all over the place. There is repeated code such as the while loop that checks for a negative number or a number greater tha... |
An embedded project my team is working on is having issues with sensor drift over time. To solve this, I thought it might work to use a high-pass filter, since the portion of the signal that we care about is generally at a significantly higher frequency than the drift. I'd like feedback on if this is a good general app... |
I am working with a rather large data set (upwards of 1 million entries across 3 variables), and need to isolate a subset of that data with specific values in one of the 3 data fields. The data are strings in hexadecimal. I have working code that performs the necessary steps, but the part of the code that checks whethe... |
I want to know if this GPG class in PHP is up to snuff as a professional-level class. I did my best to include everything and make it easy to use. I'm calling the object by invoke(). If anyone can figure anything I've missed, or how I can do better then, I'd really appreciate it.
This is a very simple codebase I made t... |
Requesting for a code review for a scala implementation.
Problem
Given an expression string made of numbers and operators +,-,/,* , break it in a list of Integer or String.
Example
"1+2+3" --> List(1, "+", 2 , "+", 3)
"+1++2++3" --> List(1, "+", 2 , "+", 3) //unary +
"1+-2+-3" --> List(1, "+", -2 , "+", -3)//unary -
"1... |
I'm on Ruby for three weeks and now I want to learn more.
Please review this SFTP client and suggest any necessary changes.
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of t... |
The goal of this program is to convert the given weight of the user LBS or KG into the opposite of what they used ex: 180lbs will convert to kg
Weight = float(input("Enter your weight: "))
Weight_Metric = input("Type L/l for LBS and K/k for KG: ")
if Weight_Metric == "L" or Weight_Metric == "l":
lbs_to_kg = (float... |
I'm trying to efficiently generate all pairs of factors of a number n.
For example, when n=27, the factor pairs are (1, 27), (3, 9), (9, 3), (27, 1)
The order in which the pairs are found is not important for my use case.
I've put together a solution using the crates primal and itertools:
The prime sieve yields the pr... |
import random
random_number = random.randint(1, 15)
guess = int(input("What do you think my number is? "))
tries = 1
while guess != random_number:
tries = tries + 1
retry = int(input("You got it wrong you're welcome to try again: "))
if retry == random_number:
print(f"You got it right in {tries} tr... |
I have tried to implement my Binary Search Tree in C. The following are the 18 operations defined:
create a bst
is_empty
insert
delete
clear
find
find_min
find_max
height
size
depth
level order traversal
preorder traversal
inorder traversal
postorder traversal
inorder successor
is_bst (is the tree a binary search tree... |
Learning coding with my daughter again. This is our first C++ program. I'm sure there's much that could be improved on. Any comments gratefully received.
New version here: Noughts & Crosses (tic-tac-toe) revisited (using C++20 modules)
ttt.cpp
#include <iostream>
#include <cstdint>
#include <limits>
#include "Board.h"
... |
This is a follow up to: struct sockaddr_storage initialization by network format string
First of all thanks to @Haris, @Toby Speight, @G. Sliepen and @chux - Reinstate for their help. I learned a lot and try to use it for future projects.
I removed the Addr type for this code to keep it clean and based on the basic str... |
I needed Nginx Docker image with additional modules (Lua and headers more) and Lua Prometheus lib. I did not want to use Openresty for that because its Alpine docker image weighs ~110MB, when Nginx Alpine image weighs 22MB. So I decided to create my own Nginx image with modules I need.
My image weighs 38MB and I think ... |
I'm using selenium for testing, and I've written code that waits for one of two locations before it continues. This is really easy when both locations are within the same frame, because then I can just use a WebDriverWait, which is the obvious solution. That's not the case for this situation though.
This is the basic i... |
I was answering a question, Java Exception Error Enumerations Anti-pattern, on Software Engineering Stack Exchange and found myself writing up a fair bit of code. It could use a code review so I'm bringing it here.
The question starts out with this enum:
package so.example;
public enum ErrorType {
INVALID_DATA_FORMA... |
This is a follow-up question for A recursive_transform Template Function with Unwrap Level for std::array Implementation in C++. Following the suggestion mentioned in G. Sliepen's answer, the function recursive_transform implementation is updated. The constraint using requires clause is performed instead of using stati... |
Introduction
I decided to program a two player Chess game in C# windows forms to help me to improve my programming skills and OOP skills.
I have come to a working finished program (as far as I can tell) where two players on the same computer can play chess together.
Here is the Github link to my repo for easy access:
h... |
This code displays a simple decimal calculator with operations like add, subtract, multiply and divide. It also has a function to clear the result.
I try to reduce code repetition. I still think I used a lot of unnecessary if-else blocks here but tried my best. How can I reduce use of if-else blocks here?
<head>
<m... |
This is JS animation using Greensock's timeline feature as a learning assignment. I don't have a lot of experience with JS so not sure how to optimize it/clean it up. Here's HTML:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" conte... |
I inherited a very long and messy C# function with a task to make it more readable and Clean Architecture Pattern friendly.
The primary goal of a function is to send an API request to an endpoint and stream a collection of sport events which took place on a specific date. Response need to be saved to local File Storage... |
I've got 2 Java programs, with the aim of solving some matrix math that involves complex numbers (an EE problem). Both programs have main functions, the one with all the complex math operations has a main function to test the functions in that program itself. I rectified the issue of having an array of objects that hav... |
ToTemp is a temperature conversion package with Celsius, Delisle, Fahrenheit, Kelvin, Rankine, Réaumur, Newton and Rømer scales. With a documentation and already in PyPI.
The source code for the main implementation here, since is too long to be completely shown, it is basically a ABC for Abstract Temperature Scales, wh... |
I'm using a script to monitor a file. When a pattern is detected, it will send an email to notify someone.
I am creating a Windows Service via NSSM.
My question is : How can I improve performance of my script ? I have to monitor a large log file during the day. a rolling log file (log1.log, then log2.log, then log3.log... |
I am currently learning more about lock free programming and wondered how I could implement mutual exclusion using std::atomics. I implemented the following code to realize a pipe class for passing values between threads. pipe_t uses the exclusive_executor_t to provide mutual exclusion for its critical sections. exclu... |
This is my new library for managing flutter rebuilds based on state changes. It is very similar to AnimatedBuilder but takes a factory to create the notifier instead of an instance of the notifier. It also includes the notifier in the builder method. I would like to know if you can spot potential bugs.
import 'package:... |
I would like to find out how much time lays in between 22.00 and 6.00 o’clock for a given event per day.
So if the event start at 21.00 and ends at 23.59 the result would be 1.59. For a start at 22.00 and end at 7.00 it would be 2.00 + 6.00 = 8.00 hours. So basically I want to calculate the night shift part per day.
I ... |
The goal is to simulate a real flat plate capacitor in 2D. The potential of the armature is fixed to +V and -V, on the edges of the simulation cell the potential is zero. Between the plates of the capacitor a dielectric material is placed. The capacity is also calculated by numerically determining the charge on the pla... |
I'm still a beginner and I wanted to ask if I'm doing my code right? The comments are the tasks that I need to do for each function.
#include<stdio.h>
#include<string.h>
#include<conio.h>
#define max 5
typedef struct
{
char name[50];
float score;
char grade;
}Student;
void Initialize(Student s[]);
void InputSco... |
Problem: In order to be able to use the arrow crate's infer_file_schema function with input piped to /dev/stdin, I need to manually implement the Seek trait on a Reader, as it doesn't exist for piped /dev/stdin/ by default.
The function that uses that Reader reads n lines, infers the schema from these n lines, then see... |
I've struggled to make a small stock project for almost 5 hours (biggest one so far).
The project is simple: I've chosen a stock (Tesla in my case) and I've decided to get a message on my phone with the last 3 news from Tesla, everytime the stock increased/decreased by 5%.
I've used 3 API's and some JSON data formattin... |
I have tried to implement my Heap in C. The following are the 13 operations defined:
build_maxheap
insert
exctract_max (delete heap max root)
max_delete (delete an element or key)
max_heapify
clear
heapSort
get_max
print
increase_key (helper function for insert and delete key functions)
height
is_empty
is_maxheap (che... |
I tried to serialize a doubly linked list. Can you rate it, and what could be improved?
I open the file with fopen(path, "wb") and write all data in binary mode.
#include <string>
#include <unordered_map>
#include <vector>
#include <random>
#include <iostream>
struct ListNode {
ListNode* prev = nullptr;
List... |
This is a follow-up question for A recursive_transform Template Function with Unwrap Level for std::array Implementation in C++. Considering the suggestion mentioned in Davislor's answer, I am trying to implement recursive_transform_view template function and comparing it with recursive_transform template function. The... |
ERROR: type should be string, got "https://github.com/speedrun-program/constant_time_snake_game\nMemory efficient snake game with O(1) algorithm for snake movement and bug placement.\nThree grids are used:\n\na grid representing the game grid\na grid partitioned into empty coords, future bug coords, current bug coords, and snake spaces\na grid which maps game grid coords to partitioned grid coords/indexes\n\nThe partitioned grid is needed to randomly select bug spaces in O(1) time.\nIt's also used to find existing bug locations in O(1) time.\ncontrols:\n\nwasd or arrow keys control the snake\nz and x change bug hints\np pauses the game\n\nmain.py:\nimport pygame\n\nfrom bitpacking import BitPackingArray\nfrom clickablebox import ClickableBox, TextEntryBox\n\nfrom random import randrange\n\nfrom collections.abc import Iterable\nfrom typing import Dict, Tuple, Union\n\n# memory efficient snake game with O(1) algorithm for snake movement and bug placement.\n# three grids are used:\n# - a grid representing the game grid\n# - a grid partitioned into empty coords, future bug coords, current bug coords, and snake spaces\n# - a grid which maps game grid coords to partitioned grid coords/indexes\n\n# the partitioned grid is needed to randomly select bug spaces in O(1) time.\n# it's also used to find existing bug locations in O(1) time.\n\n# controls:\n# - wasd or arrow keys control the snake\n# - z and x change bug hints\n# - p pauses the game\n\n\n# values of grid spaces\nEMPTY = 0\nSNAKE_UP = 1\nSNAKE_RIGHT = 2\nSNAKE_DOWN = 3\nSNAKE_LEFT = 4\nBUG = 5\n\nGRID_Y_OFFSET = 20\nGRID_X_OFFSET = 20\nGRID_GUI_WIDTH = 15\nGRID_GUI_HEIGHT = 15\nGRID_SPACE_SIZE = 35\nGUI_WIDTH = 1200\nGUI_HEIGHT = 700\n\n# a class which makes it easier to access data from the memory used by the Game class\n# 0 is a special value which means it's the same as the index being used to access it\n# this is done because bytearray objects initialize their values to 0 very quickly\nclass GridHelper:\n def __init__(\n self,\n grid: BitPackingArray,\n width: int,\n height: int,\n bits_per_index: int,\n start_bit: int,\n bits_to_read: int,\n is_game_grid: bool = False) -> None:\n self.grid = grid\n self.width = width\n self.height = height\n self.bits_per_index = bits_per_index\n self.start_bit = start_bit\n self.bits_to_read = bits_to_read\n self.is_game_grid = is_game_grid\n \n \n def __getitem__(self, pos: Union[Iterable[int, int], int]) -> int:\n if not isinstance(pos, int):\n pos = (pos[0] * self.width) + pos[1]\n \n value = (self.grid[pos] >> self.start_bit) & ((1 << self.bits_to_read) - 1)\n if not self.is_game_grid:\n if value == 0:\n return pos\n return value - 1\n return value\n \n \n def __setitem__(self, pos: Union[Iterable[int, int], int], new_value: int) -> None:\n if not isinstance(pos, int):\n pos = (pos[0] * self.width) + pos[1]\n if not isinstance(new_value, int):\n new_value = (new_value[0] * self.width) + new_value[1]\n \n new_value += not self.is_game_grid\n if not 0 <= new_value <= ((1 << self.bits_to_read) - 1):\n raise ValueError(f\"value must be in range(0, {((1 << self.bits_to_read) - 1)}), value was {new_value}\")\n \n number_of_end_bits = self.bits_per_index - self.start_bit - self.bits_to_read\n bits_at_end = self.grid[pos] & (((1 << number_of_end_bits) - 1) << (self.start_bit + self.bits_to_read))\n bits_at_start = self.grid[pos] & ((1 << self.start_bit) - 1)\n self.grid[pos] = bits_at_end + (new_value << self.start_bit) + bits_at_start\n\n\nclass Game:\n extra_memory = BitPackingArray(0, 0)\n \n def __init__(\n self,\n width: int,\n height: int,\n min_bugs: int,\n max_bugs: int,\n snake_speed: int) -> None:\n total_grid_spaces = width * height\n \n self.snake_spaces = 5\n self.available_bug_spaces = total_grid_spaces - self.snake_spaces\n self.min_bugs = min(self.available_bug_spaces, min_bugs)\n self.max_bugs = min(self.available_bug_spaces, max_bugs)\n self.bug_spaces = self.max_bugs\n self.future_bug_spaces = 0\n self.bug_spawn_cycle = 1\n self.bug_hint_idx = total_grid_spaces - self.snake_spaces - self.max_bugs # used to look up bug location from self.partitioned_grid\n \n self.tail = (height // 2, (width // 2) - 3)\n self.head = (height // 2, (width // 2) + 1)\n \n self.width = width\n self.height = height\n self.snake_speed = snake_speed\n \n # if the maximum number of bugs is always on the grid, the spawn cycle trick isn't needed\n if self.max_bugs != self.min_bugs:\n possible_bug_spawn_cycles = (total_grid_spaces - self.snake_spaces - self.max_bugs) // (self.max_bugs - self.min_bugs)\n possible_bug_spawn_cycles += (total_grid_spaces - self.snake_spaces - self.max_bugs) % (self.max_bugs - self.min_bugs) != 0 # for last cycle\n else:\n possible_bug_spawn_cycles = 1\n \n game_grid_bits = (possible_bug_spawn_cycles + 5).bit_length()\n other_grid_bits = total_grid_spaces.bit_length()\n bits_per_grid_space = (other_grid_bits * 2) + game_grid_bits\n \n Game.extra_memory.reshape(total_grid_spaces, bits_per_grid_space)\n \n self.game_grid = GridHelper(Game.extra_memory, width, height, bits_per_grid_space, 0, game_grid_bits, True)\n self.key_grid = GridHelper(Game.extra_memory, width, height, bits_per_grid_space, game_grid_bits, other_grid_bits)\n self.partitioned_grid = GridHelper(Game.extra_memory, width, height, bits_per_grid_space, game_grid_bits + other_grid_bits, other_grid_bits)\n \n # setting initial snake spaces\n for n in range(5):\n snake_segment = (height // 2, (width // 2 - 3) + n)\n end_position = (self.height - 1, self.width - 1 - n)\n self.game_grid[snake_segment] = SNAKE_RIGHT\n self.key_grid[snake_segment] = end_position\n self.key_grid[end_position] = snake_segment\n self.partitioned_grid[snake_segment] = end_position\n self.partitioned_grid[end_position] = snake_segment\n \n # setting initial bug spaces\n for n in range(1, self.max_bugs + 1):\n partitioned_grid_replace_idx = total_grid_spaces - self.snake_spaces - n\n partitioned_grid_random_idx = randrange(self.available_bug_spaces)\n key_grid_random_idx = self.swap(partitioned_grid_replace_idx, partitioned_grid_random_idx)[1]\n self.game_grid[key_grid_random_idx] = BUG\n self.available_bug_spaces -= 1\n \n \n def free_memory(self) -> None:\n Game.extra_memory.reshape(0, 0)\n \n \n def get_next_coord(self, coord: Iterable[int, int], direction: int) -> Tuple[int, int]:\n vertical_change, horizontal_change = ((-1, 0), (0, 1), (1, 0), (0, -1))[direction - SNAKE_UP]\n return (coord[0] + vertical_change, coord[1] + horizontal_change)\n \n \n def change_bug_hint(self, backwards: bool = False) -> None:\n direction = -1 if backwards else 1\n self.bug_hint_idx += direction\n if self.bug_hint_idx < self.available_bug_spaces + self.future_bug_spaces:\n self.bug_hint_idx = self.available_bug_spaces + self.future_bug_spaces + self.bug_spaces - 1\n elif self.bug_hint_idx >= self.available_bug_spaces + self.future_bug_spaces + self.bug_spaces:\n self.bug_hint_idx = self.available_bug_spaces + self.future_bug_spaces\n \n \n def swap(self, idx_1: Union[Iterable[int, int], int], idx_2: Union[Iterable[int, int], int]) -> Tuple[int, int]:\n swap_value_1 = self.partitioned_grid[idx_1]\n swap_value_2 = self.partitioned_grid[idx_2]\n \n self.partitioned_grid[idx_1] = swap_value_2\n self.partitioned_grid[idx_2] = swap_value_1\n \n self.key_grid[swap_value_2] = idx_1\n self.key_grid[swap_value_1] = idx_2\n \n return (swap_value_1, swap_value_2)\n \n \n # - look up where new_head and old_tail are positioned in partitioned grid using key grid\n # - partitioned grid new_head and old_tail positions swap places, so old_tail is in unoccupied section\n # and new_head is in snake space section\n # - key grid new_head and old_tail positions update so they say where they're positioned in partitioned grid\n def move_into_empty(self, next_head_coord: Union[Iterable[int, int], int], direction: int) -> None:\n partitioned_tail_idx = self.key_grid[self.tail]\n partitioned_head_idx = self.key_grid[next_head_coord]\n \n self.swap(partitioned_tail_idx, partitioned_head_idx)\n \n old_tail_coord = self.tail\n self.tail = self.get_next_coord(self.tail, self.game_grid[self.tail])\n self.game_grid[old_tail_coord] = EMPTY\n self.game_grid[self.head] = direction\n self.head = next_head_coord\n self.game_grid[next_head_coord] = direction\n \n \n # - look up where new_head/future_bug_space and old_tail are positioned in partitioned grid using key grid\n # - partitioned grid new_head and old_tail positions swap places, so old_tail is in future bug space section\n # and new_head/future_bug_space is in snake space section\n # - key grid new_head/future_bug_space and old_tail positions update so they say where they're positioned in partitioned grid\n # - randomly choose new future_bug_space\n # - if new future_bug_space ends up where the tail was, stop here\n # - partitioned grid new future_bug_space and old_tail positions swap places, so old_tail is in unoccupied section\n # and new future_bug_space is in future bug space section\n # - key grid new future_bug_space and old_tail positions update so they say where they're positioned in partitioned grid\n def move_into_future_bug(self, next_head_coord: Union[Iterable[int, int], int], direction: int) -> None:\n partitioned_tail_idx = self.key_grid[self.tail]\n partitioned_head_idx = self.key_grid[next_head_coord]\n \n self.swap(partitioned_tail_idx, partitioned_head_idx)\n \n random_partitioned_grid_idx = randrange(self.available_bug_spaces + 1)\n if random_partitioned_grid_idx == self.available_bug_spaces: # old tail coord was chosen as new future bug space\n old_tail_coord = self.tail\n self.tail = self.get_next_coord(self.tail, self.game_grid[self.tail])\n self.game_grid[old_tail_coord] = BUG + self.bug_spawn_cycle\n self.game_grid[self.head] = direction\n self.head = next_head_coord\n self.game_grid[next_head_coord] = direction\n return\n \n bug_location = self.swap(random_partitioned_grid_idx, partitioned_head_idx)[0]\n \n old_tail_coord = self.tail\n self.tail = self.get_next_coord(self.tail, self.game_grid[self.tail])\n self.game_grid[old_tail_coord] = EMPTY\n self.game_grid[self.head] = direction\n self.head = next_head_coord\n self.game_grid[next_head_coord] = direction\n \n self.game_grid[bug_location] = BUG + self.bug_spawn_cycle\n \n \n # - randomly choose new future_bug_space\n # - look up where new_head/bug_space is positioned in partitioned grid using key grid\n # - partitioned grid new_head/bug_space and the bug position touching the snake space section swap places, so\n # new_head/bug_space becomes part of the snake space section\n # - key grid new_head/bug_space and position touching snake space section update so they say where\n # they're positioned in partitioned grid\n # - partitioned grid future_bug_space and the unoccupied position touching the future bug space section swap places, so\n # future_bug_space becomes part of the future bug space section\n # - key grid future_bug_space and position touching future bug space section update so they say where\n # they're positioned in partitioned grid\n def move_into_bug(self, next_head_coord: Union[Iterable[int, int], int], direction: int) -> None:\n touching_snake_idx = self.available_bug_spaces + self.bug_spaces + self.future_bug_spaces - 1\n \n partitioned_head_idx = self.key_grid[next_head_coord]\n \n self.swap(partitioned_head_idx, touching_snake_idx)\n \n if self.available_bug_spaces > 0:\n random_partitioned_grid_idx = randrange(self.available_bug_spaces)\n touching_bug_idx = self.available_bug_spaces - 1\n \n bug_location = self.swap(random_partitioned_grid_idx, touching_bug_idx)[0]\n \n self.future_bug_spaces += 1\n \n self.game_grid[bug_location] = BUG + self.bug_spawn_cycle if self.max_bugs != self.min_bugs else BUG\n \n self.available_bug_spaces -= self.available_bug_spaces > 0\n self.game_grid[self.head] = direction\n self.head = next_head_coord\n self.game_grid[next_head_coord] = direction\n \n self.snake_spaces += 1\n self.bug_spaces -= 1\n if self.bug_spaces == self.min_bugs - 1: # future bug spaces become current bug spaces\n self.bug_spaces += self.future_bug_spaces\n self.future_bug_spaces = 0\n self.bug_spawn_cycle += 1\n \n if self.bug_hint_idx == partitioned_head_idx:\n self.bug_hint_idx = self.available_bug_spaces + self.future_bug_spaces\n elif self.bug_hint_idx == touching_snake_idx:\n self.bug_hint_idx = partitioned_head_idx\n \n \n def error_check(self) -> None:\n # testing function\n for i in range(self.available_bug_spaces):\n idx = self.partitioned_grid[i]\n if self.game_grid[idx] > 0:\n print(\n \"non-empty space referenced in empty area of self.partitioned_grid.\",\n f\"game grid value: {self.game_grid[idx]}\",\n f\"self.partitioned_grid index: {i}\",\n sep=\"\\n\"\n )\n raise ValueError\n for i in range(self.available_bug_spaces, self.available_bug_spaces + self.future_bug_spaces):\n idx = self.partitioned_grid[i]\n if self.game_grid[idx] != BUG + self.bug_spawn_cycle:\n print(\n \"non-future_bug_space referenced in bug area of self.partitioned_grid.\",\n f\"game grid value: {self.game_grid[idx]}\",\n f\"self.partitioned_grid index: {i}\",\n sep=\"\\n\"\n )\n raise ValueError\n for i in range(self.available_bug_spaces + self.future_bug_spaces, self.available_bug_spaces + self.future_bug_spaces + self.bug_spaces):\n idx = self.partitioned_grid[i]\n if not BUG <= self.game_grid[idx] < BUG + self.bug_spawn_cycle:\n print(\n \"non-bug space referenced in empty area of self.partitioned_grid.\",\n f\"game grid value: {self.game_grid[idx]}\",\n f\"self.partitioned_grid index: {i}\",\n sep=\"\\n\"\n )\n raise ValueError\n for i in range(self.available_bug_spaces + self.future_bug_spaces + self.bug_spaces, self.height * self.width):\n idx = self.partitioned_grid[i]\n if not SNAKE_UP <= self.game_grid[idx] <= SNAKE_LEFT:\n print(\n \"non-snake space referenced in empty area of self.partitioned_grid.\",\n f\"game grid value: {self.game_grid[idx]}\",\n f\"self.partitioned_grid index: {i}\",\n sep=\"\\n\"\n )\n raise ValueError\n \n s1 = set()\n s2 = set()\n for i in range(self.height * self.width):\n value = self.key_grid[i]\n if value in s1:\n print(f\"duplicate value {value} found at index {i} in self.key_grid\")\n raise ValueError\n s1.add(value)\n for i in range(self.height * self.width):\n value = self.partitioned_grid[i]\n if value in s2:\n print(f\"duplicate value {value} found at index {i} in self.partitioned_grid\")\n raise ValueError\n s2.add(value)\n\n\nclass GUI:\n def __init__(self) -> None:\n self.win = pygame.display.set_mode((GUI_WIDTH, GUI_HEIGHT))\n self.font = pygame.font.Font(pygame.font.get_default_font(), 24)\n self.textbox_text = (\"MINIMUM_BUGS\", \"MAXIMUM_BUGS\", \"SNAKE_SPEED\", \"GRID_WIDTH\", \"GRID_HEIGHT\")\n self.textboxes = (\n TextEntryBox(self.win, self.font, \"\", (20, 20), (10, 45), (1000, 30), (15, 50), 20),\n TextEntryBox(self.win, self.font, \"\", (20, 120), (10, 145), (1000, 30), (15, 150), 20),\n TextEntryBox(self.win, self.font, \"\", (20, 220), (10, 245), (1000, 30), (15, 250), 20),\n TextEntryBox(self.win, self.font, \"\", (20, 320), (10, 345), (1000, 30), (15, 350), 20),\n TextEntryBox(self.win, self.font, \"\", (20, 420), (10, 445), (1000, 30), (15, 450), 20)\n )\n self.buttons = (\n ClickableBox(self.win, self.font, \"START\", (GUI_WIDTH - 100, GUI_HEIGHT - 290), (GUI_WIDTH - 110, GUI_HEIGHT - 330), (100, 100)),\n ClickableBox(self.win, self.font, \"CONFIG\", (GUI_WIDTH - 108, GUI_HEIGHT - 180), (GUI_WIDTH - 110, GUI_HEIGHT - 220), (100, 100)),\n (quit_button := ClickableBox(self.win, self.font, \"QUIT\", (GUI_WIDTH - 90, GUI_HEIGHT - 70), (GUI_WIDTH - 110, GUI_HEIGHT - 110), (100, 100))),\n ClickableBox(self.win, self.font, \"<\", (572, GUI_HEIGHT - 40), (565, GUI_HEIGHT - 40), (30, 30)), # NOT CURRENTLY USED\n ClickableBox(self.win, self.font, \">\", (615, GUI_HEIGHT - 40), (605, GUI_HEIGHT - 40), (30, 30)) # NOT CURRENTLY USED\n )\n self.quit_button = quit_button # this specific button is checked in several areas in the code\n \n self.settings = read_cfg()\n if int(self.settings[\"MINIMUM_BUGS\"]) > int(self.settings[\"MAXIMUM_BUGS\"]):\n self.settings[\"MINIMUM_BUGS\"] = self.settings[\"MAXIMUM_BUGS\"]\n \n for button in self.buttons[:3]:\n button.draw()\n \n self.game_drawn = False\n self.config_drawn = False\n self.cfg_page_number = 0 # NOT CURRENTLY USED\n self.cfg_pages = 1 # NOT CURRENTLY USED\n \n \n def toggle_top_two_buttons(self) -> None:\n if self.buttons[0].box is None: # this means self.buttons[0].box isn't drawn\n self.buttons[0].draw()\n self.buttons[1].draw()\n self.buttons[2].text = \"QUIT\"\n self.buttons[2].text_location = (GUI_WIDTH - 90, GUI_HEIGHT - 70)\n self.buttons[2].draw()\n else:\n self.buttons[0].undraw()\n self.buttons[1].undraw()\n self.buttons[2].text = \"BACK\"\n self.buttons[2].text_location = (GUI_WIDTH - 95, GUI_HEIGHT - 70)\n self.buttons[2].draw()\n \n \n def toggle_cfg_screen(self) -> None:\n self.set_messages(\"\")\n self.toggle_top_two_buttons()\n self.cfg_page_number = 0\n if not self.config_drawn:\n # self.buttons[3].draw()\n # self.buttons[4].draw()\n for i in range(len(self.textboxes)):\n self.textboxes[i].text = self.textbox_text[i]\n self.textboxes[i].box_text = self.settings[self.textbox_text[i]]\n self.textboxes[i].draw(self.textboxes[i].box_text)\n self.config_drawn = True\n else:\n # self.buttons[3].undraw()\n # self.buttons[4].undraw()\n for t in self.textboxes:\n t.undraw()\n self.config_drawn = False\n \n \n def toggle_game_screen(self) -> None:\n self.toggle_top_two_buttons()\n if not self.game_drawn:\n self.game_drawn = True\n else:\n pygame.draw.rect(self.win, (0, 0, 0), (GRID_X_OFFSET, GRID_Y_OFFSET, GRID_SPACE_SIZE * GRID_GUI_WIDTH, GRID_SPACE_SIZE * GRID_GUI_HEIGHT)) # undrawing grid\n self.game_drawn = False\n \n \n def set_messages(self, *messages: Iterable[str]) -> None:\n # undrawing previous message\n pygame.draw.rect(self.win, (0, 0, 0), (50, GRID_Y_OFFSET + (GRID_SPACE_SIZE * GRID_GUI_HEIGHT), GUI_WIDTH - 160, GUI_HEIGHT - GRID_Y_OFFSET + (GRID_SPACE_SIZE * GRID_GUI_HEIGHT)))\n \n for n, message in enumerate(messages):\n text_surface = self.font.render(message, True, (50, 50, 50))\n self.win.blit(text_surface, (50, 570 + (50 * n)))\n \n \n def get_grid_color(\n self,\n grid: GridHelper,\n grid_width: int,\n grid_height: int,\n grid_y: int,\n grid_x: int,\n bug_spawn_cycle: int) -> tuple[int, int, int]:\n if (not 0 <= grid_y < grid_height) or (not 0 <= grid_x < grid_width):\n return (100, 100, 100)\n else:\n try:\n grid_value = grid[grid_y, grid_x]\n except TypeError:\n grid_value = grid[grid_y][grid_x] # this function should be able to work with normal lists too\n if grid_value == 0:\n return (200, 200, 200)\n elif SNAKE_UP <= grid_value <= SNAKE_LEFT:\n return (255, 243, 128)\n elif BUG <= grid_value < BUG + bug_spawn_cycle:\n return (65, 163, 23)\n elif grid_value == BUG + bug_spawn_cycle: # this can be used for testing\n return (200, 200, 200) # (255, 165, 0)\n else:\n return (106, 13, 173) # error color\n \n \n def draw_grid_not_centered_on_head(\n self,\n grid: GridHelper,\n grid_width: int,\n grid_height: int,\n bug_spawn_cycle: int) -> None:\n for grid_y in range(grid_height):\n for grid_x in range(grid_width):\n color = self.get_grid_color(grid, grid_width, grid_height, grid_y, grid_x, bug_spawn_cycle)\n pygame.draw.rect(self.win, color, (GRID_X_OFFSET + (grid_x * GRID_SPACE_SIZE), GRID_Y_OFFSET + (grid_y * GRID_SPACE_SIZE), GRID_SPACE_SIZE, GRID_SPACE_SIZE))\n \n \n def draw_grid(\n self,\n grid: GridHelper,\n grid_width: int,\n grid_height: int,\n snake_coord: Iterable[int, int],\n bug_spawn_cycle: int) -> None:\n if grid_width <= 15 and grid_height <= 15:\n self.draw_grid_not_centered_on_head(grid, grid_width, grid_height, bug_spawn_cycle)\n return\n \n for gui_y, grid_y in enumerate(range(snake_coord[0] - 7, snake_coord[0] + 8)):\n for gui_x, grid_x in enumerate(range(snake_coord[1] - 7, snake_coord[1] + 8)):\n color = self.get_grid_color(grid, grid_width, grid_height, grid_y, grid_x, bug_spawn_cycle)\n pygame.draw.rect(self.win, color, (GRID_X_OFFSET + (gui_x * GRID_SPACE_SIZE), GRID_Y_OFFSET + (gui_y * GRID_SPACE_SIZE), GRID_SPACE_SIZE, GRID_SPACE_SIZE))\n\n\ndef read_cfg() -> Dict[str, str]:\n try:\n with open(\"config.txt\") as f:\n settings = dict(map(str.split, f))\n \n # checking if the file is valid\n for k in (\"MINIMUM_BUGS\", \"MAXIMUM_BUGS\", \"SNAKE_SPEED\", \"GRID_WIDTH\", \"GRID_HEIGHT\"):\n if (v := settings.get(k)) is None or (int_v := int(v)) < 0 or (int_v == 0 and k != \"SNAKE_SPEED\"):\n raise ValueError\n \n if int(settings[\"GRID_WIDTH\"]) < 10:\n settings[\"GRID_WIDTH\"] = \"10\"\n if int(settings[\"GRID_HEIGHT\"]) < 10:\n settings[\"GRID_HEIGHT\"] = \"10\"\n if int(settings[\"MINIMUM_BUGS\"]) > int(settings[\"MAXIMUM_BUGS\"]):\n settings[\"MINIMUM_BUGS\"] = settings[\"MAXIMUM_BUGS\"]\n return settings\n except (FileNotFoundError, ValueError, KeyError):\n settings = {\n \"MINIMUM_BUGS\": \"1\",\n \"MAXIMUM_BUGS\": \"1\",\n \"SNAKE_SPEED\": \"30\",\n \"GRID_WIDTH\": \"10\",\n \"GRID_HEIGHT\": \"10\"\n }\n write_cfg(settings)\n return settings\n\n\ndef write_cfg(settings: Dict[str, str]) -> None:\n with open(\"config.txt\", \"w\") as f:\n f.write(\"\\n\".join(map(\" \".join, settings.items())))\n\n\ndef config(gui: GUI) -> bool:\n new_settings = gui.settings.copy() # used to check if settings were changed\n active_box = None\n \n while True:\n pygame.time.wait(16)\n pygame.display.update()\n \n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n return False\n elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:\n mouse_position = pygame.mouse.get_pos()\n if any((tb := textbox).clicked(mouse_position) for textbox in gui.textboxes):\n if active_box is not None:\n active_box.color = (150, 150, 150)\n active_box.redraw()\n active_box = tb\n active_box.color = (200, 200, 200)\n active_box.redraw()\n elif gui.quit_button.clicked(mouse_position):\n if active_box is not None:\n active_box.color = (150, 150, 150)\n active_box.redraw()\n if int(new_settings[\"GRID_WIDTH\"]) < 10:\n new_settings[\"GRID_WIDTH\"] = \"10\"\n if int(new_settings[\"GRID_HEIGHT\"]) < 10:\n new_settings[\"GRID_HEIGHT\"] = \"10\"\n if int(new_settings[\"MINIMUM_BUGS\"]) > int(new_settings[\"MAXIMUM_BUGS\"]):\n new_settings[\"MINIMUM_BUGS\"] = new_settings[\"MAXIMUM_BUGS\"]\n if new_settings != gui.settings: # don't write to file if settings weren't changed\n for k in gui.textbox_text:\n gui.settings[k] = new_settings[k]\n write_cfg(gui.settings)\n return True\n elif event.type == pygame.KEYDOWN and active_box is not None:\n if event.key == pygame.K_BACKSPACE:\n active_box.redraw(active_box.box_text[:-1])\n new_settings[active_box.text] = active_box.box_text\n elif (ch := (pygame.key.name(event.key))).isdecimal():\n active_box.redraw(active_box.box_text + ch)\n new_settings[active_box.text] = active_box.box_text\n\n\ndef wait_for_input(gui: GUI, waiting_for_unpause: bool = False) -> Tuple[int, int]:\n while True:\n pygame.time.wait(16)\n pygame.display.update()\n \n events = pygame.event.get()\n for event in events:\n if (\n (event.type == pygame.MOUSEBUTTONUP and event.button == 1 and gui.quit_button.clicked(pygame.mouse.get_pos()))\n or event.type == pygame.QUIT\n or (event.type == pygame.KEYDOWN and (event.key == pygame.K_p or not waiting_for_unpause))\n ):\n return event.type != pygame.MOUSEBUTTONUP, event.type != pygame.QUIT\n\n\ndef play_game(game: Game, gui: GUI) -> Tuple[int, int]:\n gui.set_messages(\"\")\n ticks_since_last_movement = 0\n direction = None\n current_head_direction = game.game_grid[game.head]\n next_head_y, next_head_x = game.head\n bug_hint_coord = game.partitioned_grid[game.bug_hint_idx]\n bug_hint_x, bug_hint_y = (bug_hint_coord % game.width, bug_hint_coord // game.width)\n gui.set_messages(f\"snake: ({next_head_x}, {next_head_y})\", f\"bug: ({bug_hint_x}, {bug_hint_y})\")\n \n while True:\n pygame.time.wait(16)\n pygame.display.update()\n ticks_since_last_movement += game.snake_speed != 0\n \n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n return False, False\n elif event.type == pygame.MOUSEBUTTONUP and event.button == 1 and gui.quit_button.clicked(pygame.mouse.get_pos()):\n return False, True\n elif event.type == pygame.KEYDOWN:\n if (event.key == pygame.K_UP or event.key == pygame.K_w) and current_head_direction != SNAKE_DOWN:\n direction = SNAKE_UP\n elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and current_head_direction != SNAKE_LEFT:\n direction = SNAKE_RIGHT\n elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and current_head_direction != SNAKE_UP:\n direction = SNAKE_DOWN\n elif (event.key == pygame.K_LEFT or event.key == pygame.K_a) and current_head_direction != SNAKE_RIGHT:\n direction = SNAKE_LEFT\n elif event.key == pygame.K_p:\n ticks_since_last_movement = 0\n gui.set_messages(\"paused\")\n keep_playing, keep_running = wait_for_input(gui, True)\n if not keep_playing or not keep_running:\n return keep_playing, keep_running\n gui.set_messages(f\"snake: ({next_head_x}, {next_head_y})\", f\"bug: ({bug_hint_x}, {bug_hint_y})\")\n elif event.key == pygame.K_z or event.key == pygame.K_x:\n game.change_bug_hint(event.key == pygame.K_x)\n bug_hint_coord = game.partitioned_grid[game.bug_hint_idx]\n bug_hint_x, bug_hint_y = (bug_hint_coord % game.width, bug_hint_coord // game.width)\n gui.set_messages(f\"snake: ({next_head_x}, {next_head_y})\", f\"bug: ({bug_hint_x}, {bug_hint_y})\")\n if direction is not None or (game.snake_speed != 0 and ticks_since_last_movement == game.snake_speed):\n if direction is None:\n direction = game.game_grid[game.head]\n ticks_since_last_movement = 0\n next_head_y, next_head_x = game.get_next_coord(game.head, direction)\n if not 0 <= next_head_y < game.height or not 0 <= next_head_x < game.width or SNAKE_UP <= game.game_grid[next_head_y, next_head_x] <= SNAKE_LEFT:\n game.free_memory() # free memory immediately since it will need to be freed later anyways\n gui.set_messages(\"you lose, press any key to reset\")\n return wait_for_input(gui)\n if game.game_grid[next_head_y, next_head_x] == EMPTY:\n game.move_into_empty((next_head_y, next_head_x), direction)\n elif game.game_grid[next_head_y, next_head_x] == 5 + game.bug_spawn_cycle:\n game.move_into_future_bug((next_head_y, next_head_x), direction)\n else:\n game.move_into_bug((next_head_y, next_head_x), direction)\n if game.snake_spaces == game.width * game.height:\n gui.draw_grid(game.game_grid, game.width, game.height, game.head, game.bug_spawn_cycle)\n game.free_memory() # free memory immediately since it will need to be freed later anyways\n gui.set_messages(\"you win, press any key to reset\")\n return wait_for_input(gui)\n gui.draw_grid(game.game_grid, game.width, game.height, game.head, game.bug_spawn_cycle)\n bug_hint_coord = game.partitioned_grid[game.bug_hint_idx]\n bug_hint_x, bug_hint_y = (bug_hint_coord % game.width, bug_hint_coord // game.width)\n gui.set_messages(f\"snake: ({next_head_x}, {next_head_y})\", f\"bug: ({bug_hint_x}, {bug_hint_y})\")\n current_head_direction = game.game_grid[game.head]\n direction = None\n\n\ndef main() -> None:\n pygame.init()\n pygame.display.set_caption(\"snake game\")\n gui = GUI()\n \n keep_running = True\n while keep_running:\n pygame.time.wait(16)\n pygame.display.update()\n \n events = pygame.event.get()\n for event in events:\n if event.type == pygame.QUIT:\n keep_running = False\n elif (\n event.type == pygame.MOUSEBUTTONUP\n and event.button == 1\n and any((b := button).clicked(pygame.mouse.get_pos()) for button in gui.buttons)\n ):\n if b.text == \"QUIT\":\n keep_running = False\n elif b.text == \"CONFIG\":\n gui.toggle_cfg_screen()\n keep_running = config(gui)\n gui.toggle_cfg_screen()\n elif b.text == \"START\":\n error_happened = False\n keep_playing = True\n gui.toggle_game_screen()\n while keep_playing and keep_running:\n try:\n game = Game(\n int(gui.settings[\"GRID_WIDTH\"]),\n int(gui.settings[\"GRID_HEIGHT\"]),\n int(gui.settings[\"MINIMUM_BUGS\"]),\n int(gui.settings[\"MAXIMUM_BUGS\"]),\n int(gui.settings[\"SNAKE_SPEED\"])\n )\n except (MemoryError, OverflowError) as e:\n gui.set_messages(e.__class__.__name__)\n error_happened = True\n break\n gui.set_messages(\"press any key to start\")\n gui.draw_grid(game.game_grid, game.width, game.height, game.head, game.bug_spawn_cycle)\n pygame.display.update()\n keep_playing, keep_running = wait_for_input(gui)\n if keep_playing and keep_running:\n keep_playing, keep_running = play_game(game, gui)\n game.free_memory()\n gui.toggle_game_screen()\n if not error_happened:\n gui.set_messages(\"\")\n \n pygame.quit()\n\n\nif __name__ == \"__main__\":\n main()\n\nclickablebox.py:\nimport pygame\n\nfrom collections.abc import Iterable\nfrom typing import Optional\n\n# button class\nclass ClickableBox:\n def __init__(\n self,\n win: pygame.Surface,\n font: pygame.font.Font,\n text: str,\n text_location: Iterable[int, int],\n box_location: Iterable[int, int],\n dimensions: Iterable[int, int],\n color: Iterable[int, int, int] = (150, 150, 150)) -> None:\n self.font = font\n self.text = text\n self.text_location = tuple(text_location)\n self.box_location = tuple(box_location)\n self.dimensions = tuple(dimensions)\n self.color = tuple(color)\n \n self.win = win\n self.box = None\n \n \n def draw(self) -> None:\n self.box = pygame.draw.rect(self.win, self.color, (*self.box_location, *self.dimensions))\n text_surface = self.font.render(self.text, True, (50, 50, 50))\n self.win.blit(text_surface, self.text_location)\n \n \n def undraw(self) -> None:\n pygame.draw.rect(self.win, (0, 0, 0), (*self.box_location, *self.dimensions))\n self.box = None\n \n \n def redraw(self) -> None:\n self.undraw()\n self.draw()\n \n \n def clicked(self, coords: Iterable[int, int]) -> bool:\n return self.box is not None and self.box.collidepoint(coords)\n\n\n# text box class\nclass TextEntryBox(ClickableBox):\n def __init__(\n self,\n win: pygame.Surface,\n font: pygame.font.Font,\n text: str,\n text_location: Iterable[int, int],\n box_location: Iterable[int, int],\n dimensions: Iterable[int, int],\n typing_location: Iterable[int, int],\n max_text: int,\n color: Iterable[int, int, int] = (150, 150, 150)) -> None:\n super().__init__(win, font, text, text_location, box_location, dimensions, color)\n self.typing_location = tuple(typing_location)\n self.max_text = max_text\n self.box_text = \"\"\n \n \n def redraw(self, new_box_text: Optional[str] = None) -> None:\n self.undraw()\n self.draw(new_box_text)\n \n \n def draw(self, new_box_text: Optional[str] = None) -> None:\n super().draw()\n new_box_text = new_box_text[:self.max_text] if new_box_text is not None else self.box_text\n typing_surface = self.font.render(new_box_text, True, (70, 70, 70))\n self.win.blit(typing_surface, self.typing_location)\n self.box_text = new_box_text\n \n \n def undraw(self) -> None:\n upper_left_undraw_box = (self.box_location[0], self.text_location[1])\n undraw_box_dimensions = (self.dimensions[0], self.dimensions[1] + (self.box_location[1] - self.text_location[1]))\n pygame.draw.rect(self.win, (0, 0, 0), (*upper_left_undraw_box, *undraw_box_dimensions))\n self.box = None\n\nbitpacking.py:\nimport sys\n\nfrom collections.abc import Iterable, Iterator\ntry: # typing.Self isn't available before 3.11\n from typing import Optional, Self, Tuple, Union\nexcept ImportError:\n from typing import Optional, Tuple, Union\n\nIS_AT_LEAST_3DOT11 = sys.version_info.major > 3 or (sys.version_info.major == 3 and sys.version_info.minor >= 11)\n\n# a class which lets you use a byte array as if it was an arbitrarily deeply nested\n# array with each index being any number of bits wide\nclass BitPackingArray:\n def __init__(\n self,\n dimensions: Union[Iterable[int], int],\n bits_per_index: int,\n bytearrayview: Optional[memoryview] = None,\n start_bit_offset: int = 0,\n current_dimension: int = 0) -> None:\n self.bits_per_index = bits_per_index\n self.dimensions = tuple(map(int, dimensions)) if not isinstance(dimensions, int) else (dimensions,)\n \n if len(self.dimensions) == 1 and self.dimensions[0] == 0:\n self.byte_array = bytearray(0)\n self.start_bit_offset = 0\n self.current_dimension = 0\n return\n \n if bytearrayview is None:\n if any(d <= 0 for d in self.dimensions):\n raise ValueError(\"all dimensions must be greater than 0\")\n elif bits_per_index <= 0:\n raise ValueError(\"bits_per_index must be greater than 0\")\n elif not dimensions:\n raise ValueError(\"no dimensions given\")\n \n total_bits = bits_per_index\n for d in self.dimensions:\n total_bits *= d\n \n total_bytes = (total_bits // 8) + (total_bits % 8 != 0)\n self.byte_array = bytearray(total_bytes)\n else:\n self.byte_array = bytearrayview\n self.start_bit_offset = start_bit_offset\n self.current_dimension = current_dimension\n \n \n # error checks indexes and turns negative indexes into normal indexes\n def index_generator(self, position: Iterable[int]) -> Iterator[int]:\n for depth, (pos, dimension_length) in enumerate(zip(position, self.dimensions)):\n actual_position = pos if pos >= 0 else dimension_length + pos\n if not 0 <= actual_position < dimension_length:\n raise IndexError(f\"attempted to access index {pos} of dimension {depth}, which is length {dimension_length}\")\n \n yield actual_position\n \n \n # finds byte position and bit position of data being accessed\n def get_actual_position(self, position: Union[Iterable[int], int]) -> Tuple[int, int]: # returns (start_byte, start_bit)\n if isinstance(position, int):\n position = (position,)\n if (len(position) != len(self.dimensions)):\n raise ValueError(\n f\"position argument had {len(position)} dimensions, \"\n f\"but self.dimensions has {len(self.dimensions)} dimensions\"\n )\n \n index_generator = self.index_generator(position)\n which_bit = next(index_generator)\n for i, pos in enumerate(index_generator, 1):\n which_bit = (which_bit * self.dimensions[i]) + pos\n which_bit *= self.bits_per_index\n which_bit += self.start_bit_offset\n \n return divmod(which_bit, 8)\n \n \n def get(self, position: Union[Iterable[int], int]) -> int:\n which_byte, byte_start_position = self.get_actual_position(position)\n bits_left_to_read = self.bits_per_index\n current_bit_position = min(8 - byte_start_position, bits_left_to_read)\n \n # reading first byte\n value = (self.byte_array[which_byte] >> byte_start_position) & ((1 << current_bit_position) - 1)\n bits_left_to_read -= current_bit_position\n which_byte += 1\n \n # reading middle byte(s)\n while bits_left_to_read >= 8:\n value += self.byte_array[which_byte] << current_bit_position\n bits_left_to_read -= 8\n current_bit_position += 8\n which_byte += 1\n \n #reading last byte\n if bits_left_to_read > 0:\n value += (self.byte_array[which_byte] & ((1 << bits_left_to_read) - 1)) << current_bit_position\n \n return value\n \n \n def set(self, position: Union[Iterable[int], int], new_value: int) -> None:\n which_byte, byte_start_position = self.get_actual_position(position)\n bits_left_to_set = self.bits_per_index\n \n # setting first byte\n bits_left_in_first_byte = min(8 - byte_start_position, bits_left_to_set)\n first_byte_start_bits = self.byte_array[which_byte] & ((1 << byte_start_position) - 1)\n current_value_to_write = new_value & ((1 << bits_left_in_first_byte) - 1)\n self.byte_array[which_byte] >>= byte_start_position + bits_left_in_first_byte\n self.byte_array[which_byte] <<= bits_left_in_first_byte\n self.byte_array[which_byte] += current_value_to_write\n self.byte_array[which_byte] <<= byte_start_position\n self.byte_array[which_byte] += first_byte_start_bits\n new_value >>= bits_left_in_first_byte\n bits_left_to_set -= bits_left_in_first_byte\n which_byte += 1\n \n # setting middle byte(s)\n while bits_left_to_set >= 8:\n current_value_to_write = new_value & 0b11111111\n self.byte_array[which_byte] = current_value_to_write\n new_value >>= 8\n bits_left_to_set -= 8\n which_byte += 1\n \n # setting last byte\n if bits_left_to_set > 0:\n self.byte_array[which_byte] >>= bits_left_to_set\n self.byte_array[which_byte] <<= bits_left_to_set\n self.byte_array[which_byte] += new_value\n \n \n def __getitem__(self, idx: int) -> Union[Self if IS_AT_LEAST_3DOT11 else None, int]:\n actual_idx = idx if idx >= 0 else self.dimensions[0] + idx\n if not 0 <= actual_idx < self.dimensions[0]:\n raise IndexError(f\"attempted to get index {idx} of dimension {self.current_dimension}, which is length {self.dimensions[0]}\")\n \n if len(self.dimensions) == 1:\n return self.get(idx)\n \n new_dimensions = self.dimensions[1:]\n \n bits_per_outer_index = self.bits_per_index\n for d in new_dimensions:\n bits_per_outer_index *= d\n \n start_bit = (bits_per_outer_index * actual_idx) + self.start_bit_offset\n stop_bit = (bits_per_outer_index * (actual_idx + 1)) + self.start_bit_offset\n start_byte, start_byte_bit_offset = divmod(start_bit, 8)\n stop_byte = (stop_bit // 8) + (stop_bit % 8 != 0)\n bytearrayview = memoryview(self.byte_array)[start_byte:stop_byte]\n \n return BitPackingArray(new_dimensions, self.bits_per_index, bytearrayview, start_byte_bit_offset, self.current_dimension + 1)\n \n \n def __setitem__(self, idx: int, new_value: int) -> None:\n if len(self.dimensions) > 1:\n raise ValueError(\"__setitem__ only supported on 1-dimensional arrays, len(self.dimensions) must be 1\")\n if not 0 <= idx if idx >= 0 else self.dimensions[0] + idx < self.dimensions[0]:\n raise IndexError(f\"attempted to set index {idx} of dimension {self.current_dimension}, which is length {self.dimensions[0]}\")\n if not 0 <= new_value <= ((1 << self.bits_per_index) - 1):\n raise ValueError(f\"value must be in range(0, {((1 << self.bits_per_index) - 1)}), value was {new_value}\")\n \n self.set(idx, new_value)\n \n \n def append(self, new_value: int) -> None:\n if len(self.dimensions) > 1 or self.current_dimension > 0:\n raise ValueError(\"appending only supported on 1-dimensional arrays\")\n if not 0 <= new_value <= ((1 << self.bits_per_index) - 1):\n raise ValueError(f\"value must be in range(0, {((1 << self.bits_per_index) - 1)}), value was {new_value}\")\n \n # allocating more space if necessary\n total_bits = self.bits_per_index * (self.dimensions[0] + 1)\n total_bytes = (total_bits // 8) + (total_bits % 8 != 0)\n while len(self.byte_array) < total_bytes:\n self.byte_array.append(0)\n \n self.dimensions = ((self.dimensions[0] + 1),)\n self.set(-1, new_value)\n \n \n def reshape(self, dimensions: Union[Iterable[int], int], bits_per_index: int) -> None:\n if isinstance(self.byte_array, memoryview):\n raise ValueError(\"can only reshape entire BitPackingArray\")\n \n self.bits_per_index = bits_per_index\n self.dimensions = tuple(map(int, dimensions)) if not isinstance(dimensions, int) else (dimensions,)\n \n if len(self.dimensions) == 1 and self.dimensions[0] == 0:\n self.byte_array = bytearray(0)\n return\n \n if any(d <= 0 for d in self.dimensions):\n raise ValueError(\"all dimensions must be greater than 0\")\n elif bits_per_index <= 0:\n raise ValueError(\"bits_per_index must be greater than 0\")\n elif not dimensions:\n raise ValueError(\"no dimensions given\")\n \n total_bits = bits_per_index\n for d in self.dimensions:\n total_bits *= d\n total_bytes = (total_bits // 8) + (total_bits % 8 != 0)\n \n self.byte_array.__init__(total_bytes)\n\n\nif not IS_AT_LEAST_3DOT11:\n BitPackingArray.__getitem__.__annotations__[\"return\"] = Union[BitPackingArray, int]\n\n" |
I'm making an application that has a UIViewController with a UITableView in order to show the favorite users that the user of the app have added. They are being stored in UserDefaults, for which I have created a UserDefaultsManager struct to handle its logic.
I had the following ViewController:
import UIKit
class Favo... |
I am creating a functions to validate the array's duplicate by column wise from the given array. it works. Any one help me to minimize my code:
const array = [
[1,2,3,4,5,6,7,8],
[9,8,7,6,5,4,3,2]
];
const colLength = Array.from({length:8});
const rowFinder = [];
colLength.forEach((item,i) => {
rowFinder[i] = r... |
Below is my solution for managing multiple DataFrames, in an abstract enough way that it may apply to objects outside of a pandas.DataFrame hence the Protocol SupportsGetAndSetItemSequence.
This solution supports a MultiIndex index and assumes columns will be a single Index
Typically I would stuff all of the data into ... |
Would somebody be kind enough to show me the best way to loop through this so it much more efficient that just repeating everything?
const playButton = document.querySelector("#btnPlay");
const playButton1 = document.querySelector("#btnPlay1");
const playButton2 = document.querySelector("#btnPlay2");
const playButton3 ... |
This code searches helps to choose a word and locate the word in a PDF, by highlighting it, and drawing a box around it.
I found problem with the border of the rectangle, as it's thickness cannot be increased. Eventually I would like to know if the shape can be replaced with a circle/oval.
I also want to know if my cod... |
here is the A* implementation:
#include <queue>
#include <stdexcept>
#include <unordered_map>
enum class TileType {
DebugWall,
Empty,
Floor,
Wall,
Obstacle,
Player,
HealthPotion,
ArmourPotion,
HealthBoostPotion,
ArmourBoostPotion,
SpeedBoostPotion,
FireRateBoostPotion
};
template<class T>
inli... |
I am currently working on testing some codes on python to solve differential equations by finite differences, but some problems and equations i am dealing with are:
Too big to keep manually writing it without heavy risk of mistakes
Often contain nonuniform grids which makes the usual evenly spaced grids finite differe... |
I've made a script (Triangle.m) to calculate the area of a triangle in MATLAB:
function Triangle()
% Main function
clc;
clear variables;
close all;
% Set function values
base = force_positive_finite("Base");
height = force_positive_finite("Height");
area = tri_area(base,height);
fp... |
Looking at this questoin, I was inspired by the idea and the approach, so I tried to write a second version of the code, taking most of the comments into considerations.
Please note that I am still new to meta-programming, and I had a bit of challenge to make it work.
I notice that my version is slower than the origina... |
Im trying to make a retro game of Breakout using an SDL library. Im still trying to learn developing and OOP. I got to the part where i want to check for collision between paddle and the ball, and later on with the bricks. I have a general idea on how it suppose to be done, but Im not quite sure how to do it in the OOP... |
The idea is to have a minimal script that demonstrate how Git works. I would like to be able to build objects, trees, blobs, commits and demonstrate that a Git repository could be created using bash commands, zlib algorithm and SHA1.
I am not an expert in bash and I would like some review:
#!/usr/bin/bash
# Description... |
I have the requirement to validate product codes which include EAN-8, EAN-13 and UPC-A encoded as EAN-13. I have implemented a use-case to perform this check by comparing the actual check digit with the computed one. I followed this explanation for EAN-13 and that one for EAN-8.
The reason I'm asking for a review is be... |
I am writing small a hashmap library (not full featured yet) but I have some questions about the algorithm I wrote, the formula I hope I got right from wikipedia and general things.
Measured ~14.3 million inserts in ~5.3 seconds with a load factor of 0.75, 2.1 s at 0.5.
From the sparsehash readme:
RESOURCE USAGE
spar... |
I need/want to extend created array instance, to add extra methods that i see as useful.
class.labels.js
const {
find,
filter,
value,
key
} = require("./labels.js");
module.exports = class Labels extends Array {
constructor(...args) {
super(...args);
}
find(...args) {
retu... |
I decided to write a solution for the Longest Palindromic Substring using more declarative (IMO) style as opposed to a C-style code.
One of C++'s idioms is "zero-cost abstraction", so I expected this code to be optimized and have a runtime performance identical to a C-styled version.
But my expectations were not met, a... |
I have written a threadsafe queue and I would like you to suggest what can be improved and how to write good unit tests for this implementation.
#include <mutex>
#include <queue>
#include <atomic>
#include <condition_variable>
#include <concepts>
#include <optional>
template<typename LockT>
concept Lockable = requires... |
I've amended a code for the Black-Scholes formula for European pricing options found here at the bottom of the page and fixed the math functions accordingly. Unlike the code on the website, mine has run successfully giving me the correct mathematical solution.
Would this be the method in solving this issue?
Could the ... |
I've been tasked with finding the distance between two letters in the alphabet. Below is my solution. My main concerns are if there is any shorter way to do this, and if there are any edge cases I'm not. Thanks!
import string
LETTERS = string.ascii_lowercase
def shortest_distance_between_letters(a: str, b: str) -> in... |
I would like any feedback on making the unit test for a BlockingQueue class more robust or better? improvements to the coding style, use of the gtest framework, better test cases etc. C++ style suggestions (up to c++ 14). Feel free to add suggestion to improve the BlockingQueue class if you feel inclined to.
BlockingQu... |
I wrote the following HTTP server stress tester in Rust. My actual goal was to write an efficient template for writing load testers, so I can swap out the inner loop to do e.g. requests to a Redis cluster. Looking for advice on two things:
Idiomatic usage of Rust?
Any optimization advice for Tokio i.e. if I'm joining ... |
I have a repository that provides three metric TSP solvers:
Brute-force solver,
Genetic solver,
Greedy approximate solver;
solver 3 is the subject matter of this post.
The typical output is:
GA duration : 1318 ms.
Brute-force duration: 4212 ms.
Greedy duration: 1 ms.
---
GA cost : 1430.3658515139... |
I have made three classes and I have put all the UI code in a different class and used method for labels, text fields etc so it does not mix up. Please look into this code and tell me is it good approach?.
The UI is complete but the i just started working on functionality and was getting nowhere. The thing I want to do... |
Edit
I do know the example key event doesn't carry any data (like keycode) but that isn't really the point of the review - the overall setup is :)
Original
After reading quite few suggestions on this StackExchange and doing some additional research, I have decided to give it a try and implement my own Event system.
The... |
I've written this JavaScript code, which disables textboxes if the previous textbox is empty. This is so people enter the text in order — write first in the first textbox, only then the second textbox enables, write in the second, enable the third, etc. It also clears and disables any textboxes below the one that had i... |
This is a follow-up question for A recursive_transform_view Template Function Implementation. Following the suggestions mentioned in G. Sliepen's answer:
Of course, it might be interesting in itself to create a recursive_transform_view() that does return a view...
I am trying to update recursive_transform_view templa... |
The following code is my solution to the Closest Pick problem from Codejam 2021.
You are entering a raffle for a lifetime supply of pancakes. N tickets have already been sold. Each ticket contains a single integer between 1 and K, inclusive. Different tickets are allowed to contain the same integer. You know exactly w... |
My goal was to make playing sounds in my React game easy and efficient. Using <audio> tags wasn't an option, because on mobile it creates huge delays between the action and the sound. I'm just starting with the Web Audio API, so please forgive me if I did something silly. It works though.
I decided to make it a React h... |
I am learning the behavior of C++'s special member function, using a naive String class as example. (The code is modified from this tutorial) Here is the implementation so-question.cpp:
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;
class String {
private:
uint32_t size;
char *buffe... |
I have created a Bill Splitter page that asks for the total bill amount, tip percentage, and the number of people. Then it displays the tip and the total amount (including the tip) each person has to pay out of that bill. I have used simple vanilla JavaScript to complete this project. Being a beginner in front-end deve... |
I want to reduce a list to its sequence. Or I could say I want to remove duplicate neighbors in a list.
This Python code does what I want.
#!/usr/bin/env python3
data = [True, False, False, False, False, True, True]
expected = [True, False, True]
result = []
for d in data:
try:
if result[-1] != d:
... |
I'm building an error handler which handles different kinds of errors arranged hierarchically. As part of that, I need a way to figure out what errors to send a recipient based on what their subscription level is. The below function gives me what I want, but it feels a bit crude to me. Please advise if there is a bette... |
I have created a simple web scraper that fetches news article previews from nature.com and saves each article to a file containing the article preview text.
I am learning independently, so I would like feedback on code structure, code cleanliness, and OOP design (or even whether OOP is the best approach here, as it's m... |
I am very new to coding, and I just jumped in and am trying some things.
I have been using the following code to create a password dictionary to crack Wi-Fi passwords with brute force, but it will take a lifetime for it to run all possible combinations. How would I change the code so it doesn't start with 11111111 but ... |
The Code
So i have the following function that just gathers a system of equations so it can be input into the standard solvers of scipy
def EDP7 (v):
T_N = np.reshape(v, (N_points_1, N_points_2)) #Variable declaration
#Model
sys = np.empty_like(v)
l=0
##Boundary Condition... |
Inspired by this answer from SO, I try to find a version of fork()/exec()/wait() which:
starts a child process;
catches stdout, stderr and return code separately;
properly handles all possible errors from system calls (e.g., out of memory, unable to open files, file not found) and makes sure no resources are leaked no... |
The objective of the game is to guess a five-lettered word in five guesses or less. When the user (player) enters a word, the application will inform the user whether their guess was correct or not. If the user guesses the correct word the application will simply "move to the next level" and prompt the user to guess an... |
This code is designed to scrape Stack Overflow and GitHub, pulling information based on a user-specified programming language and processing the data into a format for AI learning.
It uses a number of techniques such as caching, proxy and throttling to prevent overloading websites and being blocked. It also uses multit... |
See the following equation:
I have made the following code for it:
def i_t(t, t_s, t_max, i_min, i_max):
if t >= t_max:
return i_max
elif t_s <= t < t_max:
s = (i_max - i_min) / (t_max - t_s)
return s*(t-t_s)
else:
return 0
x_real = pd.DataFrame([[0.322,0.062,0.045,0.05,0.09... |
This is a C# console application that creates Parquet file for SQL Server table.
Given a 5GB SQL table, it takes nearly 65 minutes, so for our bigger tables (up to 500GB), it may end up taking days to complete.
Can someone suggest how I can improve performance of this solution?
namespace Parquet_Generator
{
public ... |
Question
Using Cucumber and Java17, I refactored functional tests for a basic CRUD app as I found the previous tests using special variables for different test scenarios and I felt they were brittle and difficult to work with. So I came up with the following.
I'm being told that the solution, specifically the StepLabel... |
I've got the following code, which calculates net delivery cost to 4 decimal places. Delivery can be either standard or express shipping. It is intended to return a string in 4 decimal places of the cost of delivery.
I can't think of another time where I've written something like $standardShipping = !$expressShipping... |
I've been learning about Data Oriented Programming, and when trying to implement this simple Raytracer, I decided to do it in this manner using Rust. This is also in the context of an optimisation course where I wanted to apply the principles we learned (for example: avoiding cache misses).
My question is mostly about ... |
I have written a tic-tac-toe game in Haskell and was wondering if anyone could provide any hints on how it could be improved
import Data.Bits
import System.IO
import Data.List
type Board = (Int, Int) -- the first Int is X's board, the second Int is O's board
data Player = X | O deriving (Eq, Show)
emptyBoard :: Board... |
I want to have a layout for desktop screens, so mostly wide screens with 4:3 or 16:9 aspect ratio.
The layout is made out of 2 sections: right and left. The left section takes 2/3 of the width and the right section should take the remaining 1/3 of the width.
I have 2 options but I am not sure which one is better, or if... |
Again, here is the previous question. I have (re)revised my custom scoped timer using the valuable feedback I got from a helpful member of this community. However I feel the need to ask this question so that my new solution is reviewed.
Here is the code (Compiler Explorer):
#include <chrono>
#include <type_traits>
#inc... |
Made this generator to practice using imports from other modules and better readability for coding. What could I have done better and what did I do wrong?
File called test_generator.py
from test_dictionary import math as Math, trivia as Trivia
import random
math = list(Math.keys())
trivia = list(Trivia.keys())
def ge... |
I am working on a Daily Coding Challenge to convert a sorted singly-linked list into a binary search tree.
We are given the head of the list; the definitions of ListNode and TreeNode are provided by the challenge.
Below is my code in Python 3.11. Code works fine and produces desired output.
Please can anyone review it ... |
Context
Just for learning purposes and using asynchronous iterators, I am creating a data loader that could be useful for machine learning especially images. Tensorflow has a similar function I think, much more complex.
This is a little code for loading images (or other data) and the corresponding labels files.
import ... |
I am writing a small library where I don't want to include Polly since I want to keep the number of dependencies as small as possible. I also thought it was a good learning exercise to do this on my own since I'm learning the language. However if my implementation is subpar, I might consider Polly instead.
My goal is t... |
This is a follow-up question for A recursive_transform_view Template Function which returns a view in C++. I am trying to revise the structure of recursive_transform template function implementation in C++. As the suggestion mentioned in Davislor's answer, For dealing with dangling reference issue, the updated recursiv... |
I am trying to see if there is a way to improve my code this program ask for 3 number and calculate the what type of triangle it is
import java.util.Scanner;
public class Triangle{
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Enter 3 numbers th... |
This is a very simple code that expresses a function in terms of Trigonometric Fourier Series and generates a animation based on the harmonics. I would like to know some ways to improve the performance of the code and its readability. I believe that any question about the mathematical part can be answered here.
Here's ... |
I recently wrote a testing tool (called plink) for retrieving all the links from a website (and then retreiving links from the linked pages, and so on).
Essentially, the tool is designed to be pointed at a site, and will give you a summary of any broken links etc.
It includes whitelisting/blacklisting and allows you to... |
I am writing my simple shared pointer. I am asking to review existing functions (understand that my implementations is not full, e.g now operator*)
Review please correctness
Copy/move constructors and operator=
Destructors
My code
template<typename T>
class my_shared_ptr {
public:
my_shared_ptr() {}
my_share... |
I'm new to this community and also to Java programming!
I recently picked up "Head First Java" and I did my Battleship project.
If you could kindly, give me feedback on the code?
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int location;
Battleship ship = new Bat... |
I'm trying to make my first Python package as a learning experience. There's a lot of things that I suspect I am doing poorly, but this post is specifically about my HttpRequest class. I made this class so that I can use retries and persistent session.
class HttpRequest:
__session = None
@staticmethod
def ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.