text
stringlengths
1
2.12k
source
dict
c++, chess for (int square = 0; square < Square::NUMBER_OF_SQUARES; square++) { int numberOfBlockerVariations = blockerVariations[square].size(); std::vector<Bitboard> attackBoards(numberOfBlockerVariations); for (int i = 0; i < numberOfBlockerVariations; i++) { attackBoards[i] = calculateAttackBoard((Square)square, blockerVariations[square][i]); } attacks[square] = attackBoards; } return attacks; } void generateMagicNumbers(HashInformation * hashInformationTable, const int minimumBitsRequiredForHashing, const std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> & blockerVariations, const std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> & attackBoards) { for (int square = 0; square < Square::NUMBER_OF_SQUARES; square++) { hashInformationTable[square].magicNumber = searchForMagicNumber((Square)square, hashInformationTable[square], minimumBitsRequiredForHashing, blockerVariations[square], attackBoards[square]); } } u64 searchForMagicNumber(const Square square, const HashInformation & hashInformation, const int minimumAmountOfBitsInLastByte, const std::vector<Bitboard> & allBlockerVariations, const std::vector<Bitboard> & attackBoards) { Bitboard tempAttackDatabase[LARGEST_AMOUNT_OF_ROOK_BLOCKER_CONFIGURATIONS]; const int numberOfBlockerVariations = allBlockerVariations.size(); u64 magicNumberCandidate; bool foundMagicNumber = false; while (foundMagicNumber == false) { bool currentMagicNumberIsValid = true; // Reset the attack database to all empty boards std::fill(std::begin(tempAttackDatabase), std::end(tempAttackDatabase), Bitboard(constants::UNIVERSE)); // Calculate a magic number candidate for this square magicNumberCandidate = utils::getSparselyPopulatedRandom64BitInteger();
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
c++, chess // Verify the magic number effeciently maps bits from the blocker mask to the most significant bit positions of the product if (Bitboard( (hashInformation.blockerMask * magicNumberCandidate) & 0xFF00000000000000ULL ).numberOfSetBits() < minimumAmountOfBitsInLastByte) { continue; } // Hash each blocker variation and attempt to store the attack boards for (int i = 0; (i < numberOfBlockerVariations) && currentMagicNumberIsValid; i++) { int hashedIndex = hashBlockerVariation(allBlockerVariations[i], magicNumberCandidate, hashInformation.shiftAmount); // Check if this spot in the database is empty if (tempAttackDatabase[hashedIndex].getBoard() == constants::UNIVERSE) { tempAttackDatabase[hashedIndex] = attackBoards[i]; } // If the collision gives us the same attack board, then we're fine // If the collision gives us a different attack board, search for a new magic number else if (tempAttackDatabase[hashedIndex].getBoard() != attackBoards[i].getBoard()) { currentMagicNumberIsValid = false; } } // If we made it through the previous for loop with no collisions then we found a magic number if (currentMagicNumberIsValid) { foundMagicNumber = true; } } #if DEBUG if (foundMagicNumber) { std::cout << "(Square " << square << ") FOUND magic number: " << magicNumberCandidate << std::endl; } else { std::cout << "(Square " << square << ") ERROR, no magic number found" << magicNumberCandidate << std::endl; } #endif return magicNumberCandidate; } int hashBlockerVariation(const Bitboard & blockerVariation, const u64 magicNumber, const int shiftAmount) { return (blockerVariation * magicNumber) >> (Square::NUMBER_OF_SQUARES - shiftAmount); }
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
c++, chess template <size_t rows, size_t columns> void populateAttackDatabase(Bitboard (&attackDatabase)[rows][columns], const HashInformation * hashInformationTable, const std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> & blockerVariations, const std::array<std::vector<Bitboard>, Square::NUMBER_OF_SQUARES> & attackBoards) { for (int square = 0; square < Square::NUMBER_OF_SQUARES; square++) { const HashInformation & hashInfo = hashInformationTable[square]; int numberOfBlockerVariations = blockerVariations[square].size(); for (int i = 0; i < numberOfBlockerVariations; i++) { int hashedIndex = hashBlockerVariation(blockerVariations[square][i], hashInfo.magicNumber, hashInfo.shiftAmount); attackDatabase[square][hashedIndex] = attackBoards[square][i]; } } } std::vector<Bitboard> enumerateSubmasks(Bitboard blockerMask) { /* * This solved problem is also known as: enumerate all submasks of a bitmask. * Here is a link with some explanation: https://www.geeksforgeeks.org/print-all-submasks-of-a-given-mask/ * One with better explanation: https://cp-algorithms.com/algebra/all-submasks.html */ std::uint16_t numberOfBlockerVariations = pow(2, blockerMask.numberOfSetBits()); std::vector<Bitboard> allBlockerVariations(numberOfBlockerVariations); std::uint16_t i = 0; for (u64 blockerVariation = blockerMask.getBoard(); blockerVariation; blockerVariation = (blockerVariation - 1) & blockerMask.getBoard()) { allBlockerVariations[i] = blockerVariation; i++; } return allBlockerVariations; } Bitboard calculateBishopAttackBoard(const Square & square, const Bitboard & blockerVariation) { Bitboard attackBoard; Bitboard squareBitboard(square);
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
c++, chess int numberOfMovesNorthEast = utils::calculateDistanceFromEdgeOfBoard(square, NORTH_EAST); int numberOfMovesNorthWest = utils::calculateDistanceFromEdgeOfBoard(square, NORTH_WEST); int numberOfMovesSouthEast = utils::calculateDistanceFromEdgeOfBoard(square, SOUTH_EAST); int numberOfMovesSouthWest = utils::calculateDistanceFromEdgeOfBoard(square, SOUTH_WEST); // TODO: maybe we can implement a function like the following? // attackBoard |= calculateAttacksInDirection(NORTH_EAST, numberOfMovesNorthEast, squareBitboard, blockerVariation); // Attacks to the north east for (int i = 1; i < numberOfMovesNorthEast; i++) { Bitboard targetSquare = utils::shiftCurrentSquareByDirection(squareBitboard, i * NORTH_EAST); if (targetSquareIsBlocked(targetSquare, blockerVariation)) { break; } else { attackBoard |= targetSquare; } } // Attacks to the north west for (int i = 1; i < numberOfMovesNorthWest; i++) { Bitboard targetSquare = utils::shiftCurrentSquareByDirection(squareBitboard, i * NORTH_WEST); if (targetSquareIsBlocked(targetSquare, blockerVariation)) { break; } else { attackBoard |= targetSquare; } } // Attacks to the south east for (int i = 1; i < numberOfMovesSouthEast; i++) { Bitboard targetSquare = utils::shiftCurrentSquareByDirection(squareBitboard, i * SOUTH_EAST); if (targetSquareIsBlocked(targetSquare, blockerVariation)) { break; } else { attackBoard |= targetSquare; } } // Attacks to the south west for (int i = 1; i < numberOfMovesSouthWest; i++) { Bitboard targetSquare = utils::shiftCurrentSquareByDirection(squareBitboard, i * SOUTH_WEST); if (targetSquareIsBlocked(targetSquare, blockerVariation)) { break; } else { attackBoard |= targetSquare; } } return attackBoard; }
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
c++, chess return attackBoard; } Bitboard calculateRookAttackBoard(const Square & square, const Bitboard & blockerVariation) { Bitboard attackBoard; Bitboard squareBitboard(square); int numberOfMovesNorth = utils::calculateDistanceFromEdgeOfBoard(square, NORTH); int numberOfMovesSouth = utils::calculateDistanceFromEdgeOfBoard(square, SOUTH); int numberOfMovesEast = utils::calculateDistanceFromEdgeOfBoard(square, EAST); int numberOfMovesWest = utils::calculateDistanceFromEdgeOfBoard(square, WEST); // TODO: maybe we can implement a function like the following? // attackBoard |= calculateAttacksInDirection(NORTH_EAST, numberOfMovesNorthEast, squareBitboard, blockerVariation); // Attacks to the north for (int i = 1; i < numberOfMovesNorth; i++) { Bitboard targetSquare = utils::shiftCurrentSquareByDirection(squareBitboard, i * NORTH); if (targetSquareIsBlocked(targetSquare, blockerVariation)) { break; } else { attackBoard |= targetSquare; } } // Attacks to the south for (int i = 1; i < numberOfMovesSouth; i++) { Bitboard targetSquare = utils::shiftCurrentSquareByDirection(squareBitboard, i * SOUTH); if (targetSquareIsBlocked(targetSquare, blockerVariation)) { break; } else { attackBoard |= targetSquare; } } // Attacks to the east for (int i = 1; i < numberOfMovesEast; i++) { Bitboard targetSquare = utils::shiftCurrentSquareByDirection(squareBitboard, i * EAST); if (targetSquareIsBlocked(targetSquare, blockerVariation)) { break; } else { attackBoard |= targetSquare; } } // Attacks to the west for (int i = 1; i < numberOfMovesWest; i++) { Bitboard targetSquare = utils::shiftCurrentSquareByDirection(squareBitboard, i * WEST); if (targetSquareIsBlocked(targetSquare, blockerVariation)) { break; } else { attackBoard |= targetSquare; } } }
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
c++, chess bool targetSquareIsBlocked(Bitboard targetSquare, Bitboard occupiedSquares) { return ( (targetSquare & occupiedSquares).numberOfSetBits() == 1 ); } Bitboard calculateBishopBlockerMask(const Bitboard & bitboard) { Bitboard potentialBlockersToTheBishop; Square square = static_cast<Square>(bitboard.findIndexLSB()); // This is for magic bitboards, subtract 1 since the edge of the board isn't considered a blocking square int numberOfMovesNorthEast = utils::calculateDistanceFromEdgeOfBoard(square, NORTH_EAST) - 1; int numberOfMovesNorthWest = utils::calculateDistanceFromEdgeOfBoard(square, NORTH_WEST) - 1; int numberOfMovesSouthEast = utils::calculateDistanceFromEdgeOfBoard(square, SOUTH_EAST) - 1; int numberOfMovesSouthWest = utils::calculateDistanceFromEdgeOfBoard(square, SOUTH_WEST) - 1; for (int i = 1; i <= numberOfMovesNorthEast; i++) { potentialBlockersToTheBishop |= utils::shiftCurrentSquareByDirection(bitboard, i * NORTH_EAST); } for (int i = 1; i <= numberOfMovesNorthWest; i++) { potentialBlockersToTheBishop |= utils::shiftCurrentSquareByDirection(bitboard, i * NORTH_WEST); } for (int i = 1; i <= numberOfMovesSouthEast; i++) { potentialBlockersToTheBishop |= utils::shiftCurrentSquareByDirection(bitboard, i * SOUTH_EAST); } for (int i = 1; i <= numberOfMovesSouthWest; i++) { potentialBlockersToTheBishop |= utils::shiftCurrentSquareByDirection(bitboard, i * SOUTH_WEST); } return potentialBlockersToTheBishop; } Bitboard calculateRookBlockerMask(const Bitboard &bitboard) { Bitboard potentialBlockersToTheRook; Square square = static_cast<Square>(bitboard.findIndexLSB());
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
c++, chess // This is for magic bitboards, subtract 1 since the edge of the board isn't considered a blocking square int numberOfMovesNorth = utils::calculateDistanceFromEdgeOfBoard(square, NORTH) - 1; int numberOfMovesSouth = utils::calculateDistanceFromEdgeOfBoard(square, SOUTH) - 1; int numberOfMovesEast = utils::calculateDistanceFromEdgeOfBoard(square, EAST) - 1; int numberOfMovesWest = utils::calculateDistanceFromEdgeOfBoard(square, WEST) - 1; for (int i = 1; i <= numberOfMovesNorth; i++) { potentialBlockersToTheRook |= utils::shiftCurrentSquareByDirection(bitboard, i * NORTH); } for (int i = 1; i <= numberOfMovesSouth; i++) { potentialBlockersToTheRook |= utils::shiftCurrentSquareByDirection(bitboard, i * SOUTH); } for (int i = 1; i <= numberOfMovesEast; i++) { potentialBlockersToTheRook |= utils::shiftCurrentSquareByDirection(bitboard, i * EAST); } for (int i = 1; i <= numberOfMovesWest; i++) { potentialBlockersToTheRook |= utils::shiftCurrentSquareByDirection(bitboard, i * WEST); } return potentialBlockersToTheRook; } } // anonymous namespace } // namespace magic_bitboards Answer: Answers to your questions The functions generateMagicNumbers() and populateAttackDatabase() take 4 parameters, and searchForMagicNumber() takes 5. Is this too many? Is there a way to improve on this? Sometimes it just is necessary to have that many parameters. However, in this case we can improve things. First, prefer to return data instead of passing an out-pointer as a parameter. Second, maybe there is a way to group related data into a struct. For example: struct Variations { std::array<std::vector<BitBoard>, Square::NUMBER_OF_SQUARES> blockers; std::array<std::vector<BitBoard>, Square::NUMBER_OF_SQUARES> attacks; };
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
c++, chess std::array<HashInformation, Square::NUMBER_OF_SQUARES> generateMagicNumbers(const int minimumBitsForHashing, const Variations& variations) { std::array<HashInformation, Square::NUMBER_OF_SQUARES> hashInformationTable; for (std::size_t square = 0; square < hashInformationTable.size(); ++square) { auto& info = hashInformationTable[square]; info[square].magicNumber = searchForMagicNumber(square, info, minimumBitsRequiredForHashing, variations[square]); } return hashInformationTable; } calculateAttacks() takes a function pointer as a parameter, and this function serves as a way for telling calculateAttacks() how to actually calculate the attacks, depending on if the piece is a bishop or rook. Is there anything wrong with this? It feels kinda like a code smell to me and was wondering if there is a way to improve on this? Ultimately I could combine calculateBishopAttackBoard() and calculateRookAttackBoard() into one function calculateAttackBoard(), and that would eliminate the need to pass these functions as parameters Passing a function pointer is perfectly fine! It makes the code more modular and avoids some code duplication. Compilers are also great at inlining, so it probably won't affect performance at all. searchForMagicNumber() takes a square parameter only to be used for debugging purposes. Is this acceptable?
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
c++, chess It might be handy for debugging, but it makes the code more complex than necessary. I would avoid it. Also consider that you can have the caller print the debug message; they know which square it is and they get the magicNumberCandidate from the return value. Code formatting Avoid putting multiple statements on one line. Especially since your variable names are quite long, you have to scroll a lot to see the body of if and else-statements in your code. Avoid repetitive code There is quite a lot of code duplication in your program. Apart from having to type in everything, having to maintain it, it also makes it easy for copy&paste errors to creep in. Try to find ways to avoid repeating the same thing. There are various ways to do this. Creating helper functions is one way, using a more data-drive approach is another. Consider for example: Bitboard calculateRookBlockerMask(const Bitboard &bitboard) { Bitboard potentialBlockersToTheRook; auto square = static_cast<Square>(bitboard.findIndexLSB()); for (auto direction: {NORTH, SOUTH, EAST, WEST}) { int numberOfMoves = utils::calculateDistanceFromEdgeOfBoard(square, direction) - 1; for (int i = 1; i <= numberOfMoves; i++) { potentialBlockersToTheRook |= utils::shiftCurrentSquareByDirection(bitboard, i * direction); } } return potentialBlockersToTheRook; } You can also avoid repeating long type names by using more auto, or creating type aliases. For example: using BitBoardArray = std::array<std::vector<BitBoard>, Square::NUMBER_OF_SQUARES>; BitBoardArray calculateBlockVariations(…); void init() { … auto bishopBlockerVariations = calculateBlockerVariations(BISHOP_HASHING_INFORMATION); … }
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
c++, chess Avoid using floating points unnecessarily pow() always works on and returns a floating point number. However, if you just want to raise two to the power of something, you can instead shift the integer 1 by the same amount. So: std::uint16_t numberOfBlockerVariations = 1 << blockerMask.numberOfSetBits(); Prefer using the standard fixed-width integer types I see you use std::uint16_t in one place, but u64 in some others. I recommend you don't define your own types, but stick to the ones from the standard library. Especially if you define them incorrectly, like like: using u64 = unsigned long; Which is wrong depending on the platform you are compiling for. If you want to make an alias, then in this case it might be better to name it after what it is being used for: magic numbers, so perhaps Magic or MagicNumber? You can let the initialization be done at compile time The calculation of the bitboards can be done at compile time. To do this, make sure all the functions involved in it are constexpr. How easy this is depends on the version of C++ you are using. Since C++20 there is also constinit and consteval that can be used to force compile-time evaluation and initialization.
{ "domain": "codereview.stackexchange", "id": 45050, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, chess", "url": null }
bash, shell, markdown, jq Title: Script to loop through a list of YouTube channels, and output metadata to a Markdown file Question: Overview I have created a bash script (triggered via GitHub Actions) that does the following: Parse a list of YouTube channel IDs and nicknames. Fetch their metadata via YouTube's Channel API. Build up Markdown tables using this metadata. Load a Markdown template, and replace a placeholder with the generated Markdown. Additional functionality implemented is: Display optional arbitrary emoji next to specific channel names (${ARRAY_LINE[2]}). Format numbers to be human readable (e.g. 1200 -> 1.2K). Log channels being processed. Whilst I've run the code through ShellCheck and made other improvements, I suspect there are weaknesses around: Parsing output.json 5x, fetching a different field each time. Replacing the placeholder text. Code The script itself youtube-update.sh: #!/bin/bash HEADER_PREFIX="#### " PLACEHOLDER_TEXT="dynamic-channel-data" OUTPUT="" # Convert list of channels into Markdown tables while read -r LINE; do if [[ ${LINE} == ${HEADER_PREFIX}* ]]; then echo "Adding header ${LINE}" OUTPUT="${OUTPUT}\n${LINE}\n\n" OUTPUT="${OUTPUT}| Channel | # Videos | Subscribers | Views |\n| --- | --- | --- | --- |\n" else IFS=';' read -r -a ARRAY_LINE <<< "${LINE}" # Split line by semi-colon echo "Adding channel ${ARRAY_LINE[1]} (${ARRAY_LINE[0]})" curl "https://youtube.googleapis.com/youtube/v3/channels?part=statistics,snippet&id=${ARRAY_LINE[0]}&key=${API_KEY}" \ --header 'Accept: application/json' \ -fsSL -o output.json
{ "domain": "codereview.stackexchange", "id": 45051, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, shell, markdown, jq", "url": null }
bash, shell, markdown, jq # Pull channel data out of response if possible if [[ $(jq -r '.pageInfo.totalResults' output.json) == 1 ]]; then TITLE=$(jq -r '.items[0].snippet.title' output.json) URL=$(jq -r '.items[0].snippet.customUrl' output.json) VIDEO_COUNT=$(jq -r '.items[0].statistics.videoCount' output.json | numfmt --to=si) SUBSCRIBER_COUNT=$(jq -r '.items[0].statistics.subscriberCount' output.json | numfmt --to=si) VIEW_COUNT=$(jq -r '.items[0].statistics.viewCount' output.json | numfmt --to=si) echo "Added ${TITLE}: ${VIDEO_COUNT} videos (${VIEW_COUNT} views)" OUTPUT="${OUTPUT}| ${ARRAY_LINE[2]}[${TITLE}](https://youtube.com/${URL}) | ${VIDEO_COUNT} | ${SUBSCRIBER_COUNT} | ${VIEW_COUNT} |\n" else echo "Failed! Bad response received: $(<output.json)" exit 1 fi fi done < "${WORKSPACE}/automation/channels.txt" # Replace placeholder in template with output, updating the README TEMPLATE_CONTENTS=$(<"${WORKSPACE}/automation/template.md") echo -e "${TEMPLATE_CONTENTS//${PLACEHOLDER_TEXT}/${OUTPUT}}" > "${WORKSPACE}/README.md" # Debug cat "${WORKSPACE}/README.md" For additional context, this script is triggered via a GitHub actions workflow (metadata-update.yml): name: Update YouTube stats on: schedule: - cron: '0 8 * * *' workflow_dispatch:
{ "domain": "codereview.stackexchange", "id": 45051, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, shell, markdown, jq", "url": null }
bash, shell, markdown, jq on: schedule: - cron: '0 8 * * *' workflow_dispatch: jobs: metadata-update: runs-on: ubuntu-latest permissions: contents: write steps: - name: Checkout channel config file uses: actions/checkout@v3.5.3 with: sparse-checkout: | automation/* README.md sparse-checkout-cone-mode: false - name: Update YouTube data run: | chmod +x ./automation/youtube-update.sh ./automation/youtube-update.sh env: API_KEY: ${{ secrets.API_KEY }} WORKSPACE: ${{ github.workspace }} - name: Save changes uses: stefanzweifel/git-auto-commit-action@v4 with: commit_message: Updated YouTube statistics commit_author: GitHub Actions <actions@github.com> file_pattern: 'README.md' The YouTube API response (truncated to relevant fields) looks like: { "pageInfo": { "totalResults": 1 }, "items": [ { "snippet": { "title": "Google for Developers", "customUrl": "@googledevelopers" }, "statistics": { "viewCount": "234466180", "subscriberCount": "2300000", "videoCount": "5807" } } ] } Examples Console log of the script executing Example channel list Example template Example output file. A typical run might convert: #### Stream Archives UC2oWuUSd3t3t5O3Vxp4lgAA;2018-streams; UC4ik7iSQI1DZVqL18t-Tffw;2016-2018streams UCjyrSUk-1AGjALTcWneRaeA;2016-2017streams into: #### Stream Archives | Channel | # Videos | Subscribers | Views | | --- | --- | --- | --- | | [Jerma Stream Archive](https://youtube.com/@jermastreamarchive) | 770 | 274K | 88M | | [Ster/Jerma Stream Archive](https://youtube.com/@sterjermastreamarchive) | 972 | 47K | 20M | | [starkiller201096x](https://youtube.com/@starkiller201096x) | 79 | 2.9K | 1.5M | Answer: Nice script! Read multiple values by name rather than into an array Instead of:
{ "domain": "codereview.stackexchange", "id": 45051, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, shell, markdown, jq", "url": null }
bash, shell, markdown, jq Answer: Nice script! Read multiple values by name rather than into an array Instead of: IFS=';' read -r -a ARRAY_LINE <<< "${LINE}" # Split line by semi-colon You could get the values directly into variables with descriptive names: IFS=';' read -r channel_id channel_name emoji <<< "${line}" Read multiple values from a single jq call You could read multiple values with a single call by making jq print all the relevant fields, and using read, for example: { read -r title read -r url } < <(jq -r '.items[0].snippet.title, .items[0].snippet.customUrl' < output.json) To avoid the line becoming too long, I would put the fields into an array like this: jq_fields=( '.items[0].snippet.title' '.items[0].snippet.customUrl' '.items[0].statistics.videoCount' '.items[0].statistics.subscriberCount' '.items[0].statistics.viewCount' ) { read -r title read -r url read -r video_count read -r subscriber_count read -r view_count } < <(IFS=','; jq -r "${jq_fields[*]}" < output.json) Accumulate lines in an array The way you accumulated the lines in the string value OUTPUT is ok. I prefer to use arrays in situations like this, it would look something like this: output=() # ... output+=("${line}") output+=("") output+=("| Channel | # Videos | Subscribers | Views |\n| --- | --- | --- | --- |") # ... output+=("| ${emoji}[${title}](https://youtube.com/${url}) | ${video_count} | ${subscriber_count} | ${view_count} |") # ... ( IFS=$'\n' echo "${template_content//${placeholder_text}/${output[*]}}" ) >"${WORKSPACE}/README.md"
{ "domain": "codereview.stackexchange", "id": 45051, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, shell, markdown, jq", "url": null }
bash, shell, markdown, jq Do not use ALL_CAPS names for your variables To avoid conflict and confusion with system environment variables, it's recommended to not use ALL_CAPS names in script variables. By making the script's own variables lowercase, it becomes clear what is expected to be present in the environment and what belongs to the script, which improves readability. Put repeatedly used constant values into variables output.json is referenced in multiple places. To leave open the option to use a different name or at a different path, I would put this into a variable. This way code editors could also help you avoid typos. Define important constants in variables early in the file The paths "${WORKSPACE}/automation/channels.txt" and "${WORKSPACE}/README.md" are very important key pieces in the behavior of the script. To make them easy to see (and adjust), I would put these values in variables, defined near the top of the file, right alongside header_prefix and placeholder_text.
{ "domain": "codereview.stackexchange", "id": 45051, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, shell, markdown, jq", "url": null }
python, classes Title: Improving readability of semi-nested classes for loading data of separate runs of a joint testing campaign Question: A bit of background: Most often I am analysing data (mostly timeseries) of mechanical machine conditions (vibrations, temperatures...) that were acquired in different 'runs'. All runs were acquired over distinct non-overlapping periods in time. While they were all acquired in a common testing campaign with a certain sample rate, using a fixed set of sensors, etc. the runs all have individual (metadata) characteristics (e.g. the time of acquisition, the type of event that was recorded, a certain machine setting during acquisition...). Since I require similar operations for each of the runs (loading data, performing preprocessing, plotting the data...), my current approach is the following: I define a TestCampaign class, for which I can define all shared parameters for all of the runs. Examples of methods for a TestCampaign instance are: __init__ (of course) Where I can specify the path to the folder containing all data and the path to an excel file which holds all metadata for the campaign itself and all separate runs. load_metadata Which loads the metadata excel file to class attribute(s). Each of the runs have a certain ID assigned to them in this metadata file in order to easily reference to them. load_run_by_id Which creates a TestRun instance. To create this instance, only the ID of the run (as specified in the metadata excel file) is required and all specific information of the run is passed to this instance from the metadata attribute of the test campaign. I also define a TestRun class. This has methods like: __init__ Which takes the "parent" TestCampaign instance as input and stores it as an attribute for later reference. Additionally it takes all the metadata information for this run as input and stores that as an attribute as well. load_data Which loads the data from a file for which the path is specified in the metadata
{ "domain": "codereview.stackexchange", "id": 45052, "lm_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, classes", "url": null }
python, classes My current problem: While I was writing code for my most recent project, I started wondering whether this 'standard' approach I take is actually Pythonic and whether I am unaware of some much more readable or efficient way of achieving what I want. I am aware that generic best practices are outside the scope of this site, so let's forget about this 'general structure' and focus specifically on my current project: Within a certain testcampaign, I recorded data for 3 different runs, for which I stored the information in a metadata xlsx-file (in tab 'Runlist'): ID Date Time Folder Fault 1 2023-08-14 11:20:21 20230816 No fault 2 2023-08-15 09:45:03 20230816 Gear fault 3 2023-08-16 14:55:47 20230816 Bearing fault For each run, I recorded thermal images with 8 sensors. Each sensor is placed on one side of the machine (Left or Right), a certain position (Outer or Inner) and the sensor is inspecting a certain machine component (Bearing or Gear), which is also included in the metadata xlsx-file (in tab 'Sensors'): ID Full serial name Side Component Location 1-10056002a 00560055-...-203400000000 Right Gear Outer 1-00350020 00350020-...-203400000000 Right Bearing Outer 1-0040001f 0040001f-...-203400000000 Right Bearing Inner 1-00560055 0056002a-...-203400000000 Right Gear Inner 2-0053004e 0053004e-...-203400000000 Left Bearing Inner 2-0044002a 0044002a-...-203400000000 Left Gear Outer 2-00540025 00540025-...-203400000000 Left Gear Inner 2-00310021 00310021-...-203400000000 Left Bearing Outer Each sensor generates a single numpy array of dimensions (120, 160), which are stored to a .npy-file. I would like to be able to load all data for each run individually and perform some operation on the data, e.g., plot the data based on their physical location for easy visual inspection, such as I implemented here: import pandas as pd import os import matplotlib.pyplot as plt from glob import glob
{ "domain": "codereview.stackexchange", "id": 45052, "lm_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, classes", "url": null }
python, classes class TestCampaign(): def __init__(self, datafolder_path='', metadata_filepath='metadata.xlsx'): self.datafolder_path = datafolder_path self.runlist, self.sensor_config = self.load_metadata(metadata_filepath) def load_metadata(self, filepath): excel_file = pd.ExcelFile(filepath) runlist = excel_file.parse('Runlist', index_col='ID') sensor_config = excel_file.parse('Sensors', index_col='ID') return runlist, sensor_config def load_run_by_id(self, run_id): return TestRun(self, run_id) def get_sensor_ids_for_setting(self, side=None, location=None, component=None): if side is None: side = self.sensor_config['Side'].unique() elif isinstance(side, str): side = [side] if location is None: location = self.sensor_config['Location'].unique() elif isinstance(location, str): location = [location] if component is None: component = self.sensor_config['Component'].unique() elif isinstance(component, str): component = [component] return self.sensor_config.index[self.sensor_config['Side'].isin(side) & self.sensor_config['Location'].isin(location) & self.sensor_config['Component'].isin(component)].values class TestRun(): def __init__(self, test_instance=TestCampaign(), run_id=1): self.test = test_instance self.info = self.test.runlist.loc[run_id] self.data = self.load_all_data() def load_all_data(self): # Load data of all sensors to single list data = {} for sensor_id in self.test.sensor_config.index.values: data[sensor_id] = self.load_data_sensor(sensor_id) return data
{ "domain": "codereview.stackexchange", "id": 45052, "lm_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, classes", "url": null }
python, classes def load_data_sensor(self, sensor_id): filenames = glob(os.path.join(self.test.datafolder_path, str(self.info.Folder), sensor_id, '*.npy')) if filenames: return np.load(filenames[0]) # only load the first file if there are multiple, this loads a numpy array of size (120, 160). else: print('No data found for', sensor_id) return [] def plot_data(self, figsize=(12.8, 5)): if figsize == 'small': figsize = (6.4, 3) elif figsize == 'large': figsize = (12.8, 5) fig = plt.figure(constrained_layout=True, figsize=figsize) components = ['Gear', 'Bearing'] # Divide figure in two subfigures for the two sides of the machine subfigs = fig.subfigures(nrows=1, ncols=2) for side, subfig in zip(['Left', 'Right'], subfigs): if side == 'Left': locations = ['Outer', 'Inner'] else: locations = ['Inner', 'Outer'] # Plot the images axes = subfig.subplots(nrows=2, ncols=2) for ax_r, location in zip(axes, locations): for ax_rc, component in zip(ax_r, components): id = self.test.get_sensor_ids_for_setting(side=side, location=location, component=component)[0] if np.size(self.data[id]) != 0: ax_rc.imshow(self.data[id], label=id) else: # deal with empty data arrays ax_rc.imshow(np.zeros((120, 160))) ax_rc.set_xticks([]) ax_rc.set_yticks([])
{ "domain": "codereview.stackexchange", "id": 45052, "lm_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, classes", "url": null }
python, classes # Lay-out subfig.suptitle(side + ' side') for ax, location in zip(axes[0], locations): ax.set_title(location) for ax, component in zip(axes[:,0], components): ax.set_ylabel(component, size='large') plt.show() if __name__ == "__main__": datafolder = r"Sample data" metadata_filepath = r"Sample data/metadata.xlsx" tc = TestCampaign(datafolder, metadata_filepath) for run_id in range(3): tr = tc.load_run_by_id(run_id) tr.plot_data() The key idea for my two classes is thus that I want to have general information at the TestCampaign level and run-specific information at the TestRun level. I use additional methods at both levels (e.g., for normalising data at run-level, or for comparing runs at test campaign-level), which I left out for simplicity. I feel like I am abusing the idea of classes here and my code is not really readable because of 'semi-nesting' one class into the other. Especially setting the default TestCampaign instance as the default value for test_instance during the initialisation of TestRun seems bad practice, as this can give problems with the folderpaths required for TestCampaign. I do this now anyways, to make sure my IDE can autofill the attributes and methods for self.test within the TestRun class. Ideas on how to improve the readability and fix this initialisation problem while achieving the same functionality would be highly appreciated. EDIT: fixed the lay-out of the tables EDIT2: clarified the initialisation problem of the TestRun class Answer: In the runlist sheet I confess I'm not excited to see each timestamp split into a (date, time) pair, but fine, whatever. It's ISO-8601 so we can't go too far wrong. key idea [is] I want to have general information at the TestCampaign level and run-specific information at the TestRun level. Sounds perfect. abusing the idea of classes here [?]
{ "domain": "codereview.stackexchange", "id": 45052, "lm_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, classes", "url": null }
python, classes Sounds perfect. abusing the idea of classes here [?] No, not at all. It fits in nicely with normalization and with DRY. There should be one piece of code that knows how to do each required task, and there should be one piece of data (a class instance) that stores what we're required to know. The idea of a class is "data + behaviors", and you have the right chunk of data with the right behaviors attached to it. code is not really readable because of 'semi-nesting' one class into the other Not at all. Where you say "nesting", I say "abstraction". You have abstracted away the common setup from each test run. That lets a TestRun instance focus on what it should know about -- observations peculiar to that specific run. my IDE can autofill the attributes and methods Nothing to worry about. Easing the development workflow in that way sounds like a "requirement", which you've addressed in a perfectly natural way. private method def load_metadata(self, filepath): This is part of the __init__ ctor, and it's very nice that you broke it out in that way. For one thing, now it is unit testable on its own. It is not part of your Public API, so an _ underscore prefix, _load_metadata, would be appropriate. Similarly for _load_all_data down in TestRun. And very likely for _load_data_sensor. each method offers some level of abstraction We begin working down at the raw bits and bytes level, and gradually build up verbs that get us closer and closer to the business domain. Eventually at the end we invoke doit() or main(), which calls a handful of verbs at lower abstraction level, which make deeper calls until we're down at the machine level. def load_run_by_id(self, run_id): return TestRun(self, run_id) This method does not appear to be pulling its weight. It doesn't abstract away any details. If you feel you need a synonym with this spelling, at least put it where it belongs, over in the TestRun class. But I see little point in that.
{ "domain": "codereview.stackexchange", "id": 45052, "lm_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, classes", "url": null }
python, classes default args if side is None: side = self.sensor_config['Side'].unique() In get_sensor_ids_for_setting we could take advantage of a standard idiom for defaulting input args. Prefer: side = side or self.sensor_config['Side'].unique() If caller specified side, then side = side is a no-op. If not, then None or foo always evaluates to just foo, and we assign that. Similarly for location and component. I'm not super excited about the "turn scalar foo into a list [foo]", as it tends to invite caller confusion and bugs. My preference is to insist that caller specified the Right Thing; that way library and caller are in sync, they have a common view of what's happening, with no automagical surprises. If you feel you need to accommodate both types of input, at least spell out the details in the method's """docstring""". Concretely, consider putting ..., side: Optional[str] = None, ... in the signature, and then unconditionally use [side] to turn it into a list. That implies adding from typing import Optional A default of None is bog standard and perfectly nice. Given that there's no valid use case for "" empty string here, I feel ..., side: str = "", ... would be a bit tidier. mutable default param class TestRun(): def __init__(self, test_instance=TestCampaign(), run_id=1):
{ "domain": "codereview.stackexchange", "id": 45052, "lm_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, classes", "url": null }
python, classes Uggh! This is, kind of terrible. There's a whole class of bugs you really don't want to venture any place near to. In C we distinguish between computing a quantity at "compile time" versus at "run time". In python the distinction is "import time" versus "run time". A mutable object was created when import evaluated the def, and creating several instances won't create several such objects. We just stick with the one from the import. Even if you only plan to create a single object, don't leave such a ticking time bomb lying around for future maintainers. Avoid the "mutable default" anti-pattern. Standard idiom would be to put =None in the signature, and then: self.test = test_instance or TestCampaign() ... setting the default TestCampaign instance as the default value for test_instance during the initialisation of TestRun seems bad practice, Consider not offering a default value at all, if you want caller to always explicitly specify it. vague identifier self.info = self.test.runlist.loc[run_id] Ok fine, maybe you really need that shorthand notation and you didn't want to use a @property decorator. Calling it info doesn't help anyone. It looks like it's actually a run_id -- seems like a good identifier to use here. comments lie! def load_all_data(self): # Load data of all sensors to single list data = {} zomg, what is going on here? We promise the caller we'll load a list, and then in the next breath ignore that and start building a dict? The code is specific, it gives the "how". Comments should be poetic (that is, vague, broad strokes), to give the "why". Call it a "container", if you like. Or rename the method to load_all_sensor_data and elide the comment. return np.load(filenames[0]) # only load the first file if there are multiple, # this loads a numpy array of size (120, 160).
{ "domain": "codereview.stackexchange", "id": 45052, "lm_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, classes", "url": null }
python, classes Thank you for the helpful comment. It is fine, as far as it goes. Maybe I believe it. I bet it was true at one point, for at least one input file. Consider rephrasing like this: arr = np.load(filenames[0]) assert (120, 160) == arr.shape, arr.shape return arr Now the Gentle Reader is well and truly convinced that every time this method will definitely be returning an array with exactly that shape. No need to read an English sentence which may or may not be true today. Or tomorrow. else: print('No data found for', sensor_id) return [] Consider raise ValueError(f'No data found for {sensor_id}'). I'm concerned that caller might view empty-list as a small amount of valid data. use Path Also, DRY. datafolder = r"Sample data" metadata_filepath = r"Sample data/metadata.xlsx" I'm slightly sad that didn't come out as: from pathlib import Path datafolder = Path(r"Sample data") metadata_filepath = datafolder / "metadata.xlsx" This codebase appears to achieve most of its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45052, "lm_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, classes", "url": null }
performance, algorithm, rust Title: Two sum sliding window challenge Question: The task is a simple coding challenge I took part in. It is a spin on the two sum problem. In the two sum problem you are given an validation sequence A and a test input I. I is valid if it's the sum of any two elements in the A. You can solve this in O(Nlog(N)) by first sorting A first, then using the two pointer technique. The challenge is worded as follows: "The first 100 numbers of the mine are always secure, but after that, the next number is only safe if it is the sum of 2 numbers in the previous 100". My solution allows for Mine segments to be generic. I call them Blocks. It also generic over the validation window size - 100 in the thext of the challenge. Full solution can be found on my github. /// Block in a [Mine]. Has blanket implementation for numerical types. pub trait Block: Eq + Add<Output = Self> + Sized {} impl<T> Block for T where T: Eq + Add<Output = Self> + Sized {} #[derive(Debug, Error, PartialEq, Eq)] pub enum MineError<const VALIDATION_WINDOW_SIZE: usize, B: Block> { #[error( "Initialization blocks must have at least: {} blocks. Size of the blocks provided: {0}", VALIDATION_WINDOW_SIZE )] InvalidInitializationBlocksSize, #[error( "Validation for block number {1} failed. Invalid block value: {0}. A block is valid iff it is the sum of any two blocks in the previous: {}.", VALIDATION_WINDOW_SIZE )] InvalidBlock(B, usize), }
{ "domain": "codereview.stackexchange", "id": 45053, "lm_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, algorithm, rust", "url": null }
performance, algorithm, rust /// Responsible for mining new [Blocks](Block). /// A new block is valid [iff](https://en.wikipedia.org/wiki/If_and_only_if) it's the /// sum of any two blocks in the previous [VALIDATION_WINDOW_SIZE] blocks. /// /// # Performance /// - The size of [Mine] scales with O(VALIDATION_WINDOW_SIZE<sup>2</sup>). /// /// [VALIDATION_WINDOW_SIZE]: Mine<VALIDATION_WINDOW_SIZE> #[derive(Clone, Debug)] pub struct Mine<const VALIDATION_WINDOW_SIZE: usize, B: Block + Hash + Copy> { /// Holds [VALIDATION_WINDOW_SIZE] blocks used for validation. validation_blocks: VecDeque<B>, /// Holds all the possible two element sums from the [validation_blocks](Self::validation_blocks). /// Used for quick validation of new blocks. block_pair_sums: HashMultiSet<B>, /// Used for tracking how many blocks have been validated total_blocks: usize, } impl<const VALIDATION_WINDOW_SIZE: usize, B> Mine<VALIDATION_WINDOW_SIZE, B> where B: Block + Hash + Copy, for<'a> &'a B: Add<&'a B, Output = B>, for<'a> B: Add<&'a B, Output = B>, { /// Create a new mine with given `initialization_blocks`. /// No validation is performed on the initialization blocks. /// /// # Performance /// This is a potentially costly operation with the running time of O(VALIDATION_WINDOW_SIZE<sup>2</sup>). pub fn new(initialization_blocks: [B; VALIDATION_WINDOW_SIZE]) -> Self { // Allocating half the max size. Worst case scenario with no overlapping sums // requires only 1 more allocation. let capacity = VALIDATION_WINDOW_SIZE.pow(2) / 2; let mut sums = HashMultiSet::with_capacity(capacity); for (i, first) in initialization_blocks[0..VALIDATION_WINDOW_SIZE - 1] .iter() .enumerate() { for second in initialization_blocks.iter().skip(i + 1) { sums.insert(first + second); } }
{ "domain": "codereview.stackexchange", "id": 45053, "lm_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, algorithm, rust", "url": null }
performance, algorithm, rust Self { validation_blocks: VecDeque::from(initialization_blocks), block_pair_sums: sums, total_blocks: VALIDATION_WINDOW_SIZE, } } /// Try to extend the [Mine] by a single [Block] `new_block`. /// If the validation is successful the mine is extended, otherwise /// a an error [MineError::InvalidBlock] is returned. Details on validation /// can be seen in [Mine] documentation. /// /// If you want to try and add many blocks see [Mine::try_extend]. pub fn try_extend_one( &mut self, new_block: B, ) -> Result<(), MineError<VALIDATION_WINDOW_SIZE, B>> { if !self.block_pair_sums.contains(&new_block) { Err(MineError::InvalidBlock(new_block, self.total_blocks + 1)) } else { // New block value is already validated. It is now correct // to remove any previous entry and sum entry. let old_block = self .validation_blocks .pop_front() .expect("Mine always has VALIDATION_WINDOW_SIZE blocks"); for block in self.validation_blocks.iter() { // remove all sums where the first block was a summand self.block_pair_sums.remove(&(old_block + block)); // add new sums where the new block is a summand self.block_pair_sums.insert(new_block + block); } self.validation_blocks.push_back(new_block); self.total_blocks += 1; Ok(()) } } }
{ "domain": "codereview.stackexchange", "id": 45053, "lm_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, algorithm, rust", "url": null }
performance, algorithm, rust Ok(()) } } } Window size in the given test data was 100. So the O(N2) size of the hash set didn't seem like a problem. I've tried the two pointer approach for validation. But removing / inserting elements to an ordered set seemed to be performing worse than this solution. I didn't want to put the Hash bound on Block as that seems a part of the implementation of mine. The bounds I used for reference addition on the other hand, bother me but I still prefer them to dereferencing in the code. Problem with perf tests I find it hard to performance try_extend_one using criterion. The crux of the problem for me is that the size of the elements in the validation sequence has to be increasing (Assuming no more than one 0 in the initial sequence). Since criterion needs a lot of iterations to give good results, this led to overflow. Maybe I could play with criterion setup to reduce the number of iterations but I assume this would sacrifice precision. Other option I have is to clone the entire Mine on every iteration then I guess I'm not really measuring try_extend_one. Any advice? I'm mostly interested in building a performant solution to this problem. Any other comments are also welcome. Answer: Hmmm, interesting approach, consuming quadratic memory to save time. In the copy-n-pasted Cargo.toml you probably intended "edition = 2023". Informative comments /// Block in a [Mine]. Has blanket implementation for numerical types. pub trait Block: Eq + Add... + Sized {} Thank you for the comment. It is the start of something helpful. An URL citation of the original problem would have been helpful. Certainly the mention of "numerical" is a useful hint. What I really wanted to know at this point is that a Block is a positive integer, which can exceed 2 ** 64 but will fit within a u128. nit: Consider renaming to just WINDOW_SIZE or even WINDOW, with the comment spelling out its validation role.
{ "domain": "codereview.stackexchange", "id": 45053, "lm_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, algorithm, rust", "url": null }
performance, algorithm, rust messages that are diagnostic "Initialization blocks must have at least: {} blocks. Size of the blocks provided: {0}", nit, grammar: Strike the first : colon. The "blocks ... blocks" remark, about e.g. 100 initialization integers which must each have at least {100 bits?, 100 integers?}, threw me for a moment. Please prefer singular "The initialization block" "The initial blocks", to clarify. EDIT The collective noun "a block", such as "a block of numbers", is what I was getting hung up on. What we're shooting for is: Of a great many blocks, we can apply an "initial" adjective to the first few, the ones that shall be unconditionally accepted. If a block is not an initial block, then it must survive a windowed validation process. The diagnostic seems to be speaking of the length of some grouping, a grouping for which we've not yet introduced a Defined Term. /// Used for tracking how many blocks have been validated total_blocks: usize, Go with active verb of "Tracks how many ..." beef up the Block trait pub struct Mine<..., B: Block + Hash + Copy> { ... impl ... Mine<..., B> where B: Block + Hash + Copy, ... Is there a use case for an unhashable uncopyable Block? I feel they should be part of the trait. range limits /// No validation is performed on the initialization blocks. I feel it is sensible to tell the compiler that every Block is positive, and has limited magnitude. It can help with proofs about whether overflow is possible, and so can affect generated bounds checks and benchmark timings. nit, typo: "mine is extended, otherwise a an error"
{ "domain": "codereview.stackexchange", "id": 45053, "lm_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, algorithm, rust", "url": null }
performance, algorithm, rust algorithm try_extend_one() is very clear, thank you. It took a bit of setup work to make that function a walk in the park. Personally, I had in mind sequentially scanning and then making nested probes of a HashMap, in the hopes that reads are cheaper than writes. Also, a Block that succeeds can terminate early. And seeing sums that are too large also admits of early termination. I am a little surprised you found that 100 (deterministic!) writes plus 100 deletes winds up being cheaper in practice. I encourage you to publish benchmark results in your github repo that folks can read even if they've not run the code. modulo results Choose an arbitrary modulus M. When deciding if a + b might sum to c, we can ask whether a % M and b % M are compatible with (a + b) % M. With decimal notation and an M of ten, examining the units digits will be instructive. If a program grouped the 100 candidates by, say, the three low-order bits (.5 × log2(WINDOW_SIZE)), that may let us ignore the seven eighths of candidates which couldn't possibly produce the proper sum. The speedup would only increase as window size increases. This codebase achieves its design goals. I would be willing to delegate or accept maintenance tasks on it.
{ "domain": "codereview.stackexchange", "id": 45053, "lm_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, algorithm, rust", "url": null }
kotlin, sqlite, jdbc Title: Mapping named parameters to indices for PreparedStatement Question: I needed something to map named SQL parameters into indices for JDBC queries so I wrote the ParameterMap class that takes an SQL query, searchers for parameters prefixed with a colon : and while replacing each instance it counts their indices adding them to the map as a list associated with each name. There is also an extension function forEach that passes one index at a time to the lambda where the actual parameters are set. See also the follow-up. class ParameterMap(sql: String) { private val parameterRegex = Regex("(:([a-z0-9_]+))", RegexOption.IGNORE_CASE) private val map = mutableMapOf<String, List<Int>>() val sqlWithQuestionMarks: String init { var index = 1 // <-- JDBC starts counting with 1 sqlWithQuestionMarks = parameterRegex.replace(sql) { match -> val key = match.groups[2]!!.value.lowercase() map.computeIfPresent(key) { _, indexes -> indexes.plus(index++) } map.computeIfAbsent(key) { mutableListOf(index++) } return@replace "?" } } operator fun get(name: String) = map.getValue(name.lowercase()) override fun toString() = sqlWithQuestionMarks } fun ParameterMap.forEach(name: String, block: (Int) -> Unit) { for (index in this[name]) block(index) } Example: select * from person where (nullif(:first_name, '') is null or first_name = :first_name) and (nullif(:last_name, '') is null or last_name = :last_name) limit 100; val parameterMap = ParameterMap(File("sql/select.sql").readText()) val selectStatement = sqliteConnection.prepareStatement(parameterMap.sqlWithQuestionMarks) parameterMap.forEach("first_name") { selectStatement.setString(it, "John") } parameterMap.forEach("last_name") { selectStatement.setString(it, "Doe") } What do you think of this helper? Can it be made more Kotlin-ish?
{ "domain": "codereview.stackexchange", "id": 45054, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "kotlin, sqlite, jdbc", "url": null }
kotlin, sqlite, jdbc What do you think of this helper? Can it be made more Kotlin-ish? Answer: Name of the class doesn't indicate its purpose. The class is called "ParameterMap" but its use-case (filling in values in a query) doesn't need to know about it having a map somewhere inside - it's an implementation detail. Overriding toString is misleading for a similar reason: if I want to print a "ParameterMap" I expect to see some sort of a map, not a query. But what really is the use-case here? We have an sql statement with placeholders that need to be filled with actual values. Let's write down the use-case in a concise manner: File("sql/select.sql").readText().fill( "first_name" to "John", "last_name" to "Doe", ) So we really only need a function with an interface like this: String.fill(vararg args: Pair<String, String>): PreparedStatement There is no need to expose sqlWithQuestionMarks and the get operator, since they are irrelevant to the end-user, and therefore no need for a class either. Now that we look at the problem this way, we can find a one-line solution: String.executeWith(connection: Connection, vararg args: Pair<String, String>): ResultSet = connection.createStatement().executeQuery(this.also { args.forEach { this.replace(":${it.first}", it.second) } }) Nitpicks: forEach doesn't need to be an extension function since it's defined in the same file as the class it's extending. indexes.plus(index++) uses an operator: indexes + index++ Plural of "index" is "indices". val key = match.groups[2]!!.value.lowercase() - this line could use a comment to explain what .groups[2]!! gives us.
{ "domain": "codereview.stackexchange", "id": 45054, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "kotlin, sqlite, jdbc", "url": null }
c++, performance, csv Title: Process comma separated input and check format Question: I have to read console input and store data in the vector of structs. In case of any data format violation I have to print "Malformed Input" and return 1 Data format: 1 The first line is "#job_id,runtime_in_seconds,next_job_id" 2 The next lines are three comma separated integers (number of lines can be different) Example: #job_id,runtime_in_seconds,next_job_id 1,60,23 2,23,3 3,12,0 23,30,0 Could you please advise how to write better code in terms of time performance? I was thinking about scanf("%d,%d,%d", &arg1, &arg2, &arg3) but not sure that it's C++ style My code: #include <iostream> #include <optional> #include <vector> using namespace std; struct Job { int job_id; int runtime; int next_job_id; }; std::optional<Job> make_job(const string& s) { int job_id = 0, runtime = 0, next_job_id = 0; int i = 0; while (i < s.size() and s[i] >= '0' and s[i] <= '9') { job_id = job_id * 10 + (s[i] - '0'); ++i; } if (i == s.size() or s[i] != ',') { return nullopt; } ++i; while (i < s.size() and s[i] >= '0' and s[i] <= '9') { runtime = runtime * 10 + (s[i] - '0'); ++i; } if (i == s.size() or s[i] != ',') { return nullopt; } ++i; while (i < s.size() and s[i] >= '0' and s[i] <= '9') { next_job_id = next_job_id * 10 + (s[i] - '0'); ++i; } if (i != s.size()) { return nullopt; } return Job {job_id, runtime, next_job_id}; } int main() { string line; getline(cin, line); if (line.compare("#job_id,runtime_in_seconds,next_job_id")) { cout << "Malformed Input"; return 1; }
{ "domain": "codereview.stackexchange", "id": 45055, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, csv", "url": null }
c++, performance, csv vector<Job> jobs; while (getline(cin, line)) { const auto job = make_job(line); if (not job) { cout << "Malformed Input"; return 1; } jobs.push_back(*job); } // process Jobs return 0; } Answer: This is quite complex. A much simpler way would be to use the stream functionality: std::optional<Job> make_job(std::stringstream s) { Job job; s >> job.job_id; if (s.get() != ',') return std::nullopt; s >> job.runtime; if (s.get() != ',') return std::nullopt; s >> job.next_job_id; // check that we have reached the end without any errors if (!s.eof() || !s) return std::nullopt; return job; } This might involve a copy of the string into the stringstream, but since C++23 std::stringstream you can move std::strings into it, or you could use std::spanstream. Alternatively, you could just pass the input stream directly to make_job(): std::optional<Job> make_job(std::istream& s) { … // check that we have reached the end of the line without any errors if (s.get() != '\n' || !s) return std::nullopt; … } Although reading the file explictly line-by-line is probably a good thing to do. If reading a malformed job would be an exceptional event, consider just throwing an exception instead of using std::optional. This will simplify the code: Job make_job(std::stringstream s) { … // check that we have reached the end of the line without any errors if (!s.eof() || !s) throw std::runtime_error("Malformed input"); … } int main() { … while (std::getline(std::cin, line)) { jobs.push_back(make_job(line)); } … } Also ensure you check that you have encountered the end of the file after the while-loop finished; std::getline() returns false also in case of errors, and you don't want to ignore those. So: while (std::getline(std::cin, line)) { … }
{ "domain": "codereview.stackexchange", "id": 45055, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, csv", "url": null }
c++, performance, csv if (!std::cin.eof()) { std::cerr << "Error reading input\n"; return EXIT_FAILURE; }
{ "domain": "codereview.stackexchange", "id": 45055, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, csv", "url": null }
python Title: Remove duplication from WebVTT subtitles Question: I want to perform statistical analysis and index subtitles that are stored in the WebVTT (Web Video Text Tracks) format. Before I can do that I need to remove duplicated text since each cue can contain text from previous cues. This duplication is a side effect of making the subtitled words appear closer to when they are spoken in the video. Instead of switching between long lines of text, you get a scrolling ticker effect that helps portray the flow of the conversation. Here is an example of a WebVTT file that uses this method to display subtitles: WEBVTT X-TIMESTAMP-MAP=MPEGTS:900000,LOCAL:00:00:00.000 531729805 00:00:35.680 --> 00:00:35.840 And 2656472485 00:00:35.840 --> 00:00:36.240 And Ellie, 46078992 00:00:36.240 --> 00:00:37.400 And Ellie, here's 3869256835 00:00:37.400 --> 00:00:37.640 And Ellie, here's what's 954881102 00:00:37.640 --> 00:00:37.760 And Ellie, here's what's leading 2106168935 00:00:37.760 --> 00:00:38.120 And Ellie, here's what's leading the 75332790 00:00:38.120 --> 00:00:38.360 And Ellie, here's what's leading the news 62505917 00:00:38.360 --> 00:00:38.800 And Ellie, here's what's leading the news this 1300648395 00:00:38.800 --> 00:00:39.520 And Ellie, here's what's leading the news this morning 2785830416 00:00:39.520 --> 00:00:39.640 And Ellie, here's what's leading the news this morning. 1208960359 00:00:39.640 --> 00:00:39.800 the news this morning. >> 1485135460 00:00:39.800 --> 00:00:39.960 the news this morning. >> Students 527624481 00:00:39.960 --> 00:00:40.280 the news this morning. >> Students across 593869850 00:00:40.280 --> 00:00:40.640 the news this morning. >> Students across the 2992386592 00:00:40.640 --> 00:00:40.760 the news this morning. >> Students across the country 462963948 00:00:40.760 --> 00:00:41.120 >> Students across the country are 2603260721 00:00:41.120 --> 00:00:41.520 >> Students across the country are set
{ "domain": "codereview.stackexchange", "id": 45056, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python 2603260721 00:00:41.120 --> 00:00:41.520 >> Students across the country are set Tools like Subtitle Edit have a "Merge lines with same text..." feature but it only works when text is added to the end of the cue and ignores cases where part of the text has been removed from the beginning (e.g. at 1208960359). My attempt to create a solution using Python made use of webvtt-py to help read, modify and save the newly created WebVTT file. Now that I can modify the subtitles I need to remove new lines and '>>' symbols and convert the cues to single lines of text that don't duplicate. Maintaining accurate timestamps will allow me to insert the cues into a Lucene index with the search results providing relevant video timestamps. My solution grew organically but turned into a bit of a mess and wondered if there was a better approach that could be made: from webvtt import WebVTT, Caption import os vtt_show = WebVTT.read('show.webvtt') vtt_modified = WebVTT()
{ "domain": "codereview.stackexchange", "id": 45056, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python vtt_show = WebVTT.read('show.webvtt') vtt_modified = WebVTT() caption_reset = False previous_text = "" new_cap_text = " " new_cap_start = vtt_show[0].start new_cap_end = vtt_show[0].end new_caption = Caption( new_cap_start, new_cap_end, new_cap_text ) for caption in vtt_show: caption.text = caption.text.replace('\n.', '.') caption.text = caption.text.replace('\n', ' ') caption.text = caption.text.replace('>> ', '') caption.text = caption.text.replace('>>', '').strip() is_new_line = False if caption.text.startswith(new_cap_text) and new_cap_text.endswith(caption.text): new_cap_end = caption.end elif caption.text.startswith(new_cap_text) and not new_cap_text.endswith(caption.text): new_cap_text = caption.text new_cap_end = caption.end caption_reset = True elif not caption.text.startswith(new_cap_text) and new_cap_text.endswith(caption.text): new_cap_end = caption.end common_prefix = os.path.commonprefix([new_cap_text, caption.text]) if common_prefix != "": new_cap_text = caption.text[len(common_prefix):] is_new_line = True elif not caption.text.startswith(new_cap_text) and not new_cap_text.endswith(caption.text): if caption_reset: if new_cap_text != new_caption.text: new_caption = Caption( new_cap_start, new_cap_end, new_cap_text ) vtt_modified.captions.append(new_caption) new_cap_start = caption.start caption_reset = False new_cap_end = caption.end words2 = caption.text.split()
{ "domain": "codereview.stackexchange", "id": 45056, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python match_found = False removed_words = [] while len(words2) > 0: removed_words.append(words2.pop()) new_string = " ".join(words2) if new_caption.text.endswith(new_string): removed_words.reverse() new_cap_text = " ".join(removed_words) match_found = True break if not match_found: new_cap_text = caption.text if is_new_line: new_caption = Caption( new_cap_start, new_cap_end, new_cap_text ) vtt_modified.captions.append(new_caption) new_cap_start = caption.end previous_text = caption.text new_caption = Caption( new_cap_start, new_cap_end, new_cap_text ) vtt_modified.captions.append(new_caption) vtt_modified.save('vtt_modified.vtt') Answer: You need to move all of your code into functions, ideally with one purpose each. It's doubtful that you should be mutating the text on string properties of the caption object. You should be manipulating bare strings, and once you're happy with the result, then make a new Caption. Your current approach fails to preserve file metadata such as X-TIMESTAMP-MAP. From the object you have, vtt_show, it seems that this can't be helped with the current library as it doesn't load that metadata in the first place; so to fix this issue you'd need to modify or replace the library. Convert this: caption.text = caption.text.replace('\n.', '.') caption.text = caption.text.replace('\n', ' ') caption.text = caption.text.replace('>> ', '') caption.text = caption.text.replace('>>', '').strip() into fluent style: def clean_caption_text(text: str) -> str: return ( text .replace('\n.', '.') .replace('\n', ' ') .replace('>> ', '') .replace('>>', '') .strip() )
{ "domain": "codereview.stackexchange", "id": 45056, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python If performance during your overlap detection is a concern, you may want to investigate suffix trees; see e.g. https://stackoverflow.com/questions/6026483/detecting-length-of-overlap-between-two-strings for some hints.
{ "domain": "codereview.stackexchange", "id": 45056, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
java, swing, audio Title: Beat Box: an app for making, playing, saving, and loading beat patterns Question: I was reading Head First Java. The book featured a project called BeatBox that allowed you to make, play, save, and load beat patterns using Java's Sequencer API and Swing API. While the idea belongs to the author, I implemented it vastly differently and made the app way more complex and flexible. For example, the app can dynamically adapt to match loaded patterns by adding missing instruments or changing the number of beats. Here's the code Note. I removed some of the imports from Java's standard libraries to fit into the character limit. I hope you have the autoimport enabled exceptions.IllegalPatternException package org.example.demos.sequencer.beatBox.exceptions; import org.example.demos.sequencer.beatBox.ManifestComponent; public class IllegalPatternException extends Exception { private static final String FORMAT = "The pattern file doesn't specify a valid %s or does it in an illegal format"; public IllegalPatternException(ManifestComponent problematicManifestComponent) { super(String.format(FORMAT, problematicManifestComponent)); } } exceptions.IllegalPropertyException package org.example.demos.sequencer.beatBox.exceptions; import lombok.RequiredArgsConstructor; public class IllegalPropertyException extends RuntimeException { private static final String FORMAT = "%s value is invalid: should be %s"; public IllegalPropertyException(String propertyName, PropertyIssue propertyIssue) { super(String.format(FORMAT, propertyName, propertyIssue.whatItShouldBeInstead())); } @RequiredArgsConstructor public enum PropertyIssue { NULL("not null"), EMPTY("not empty"), NON_POSITIVE("greater than zero"), NOT_MATCHING_REGEX("matching the regular expression"); private final String whatItShouldBeInstead;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private final String whatItShouldBeInstead; String whatItShouldBeInstead() { return whatItShouldBeInstead; } } } BeatBox package org.example.demos.sequencer.beatBox; import lombok.AccessLevel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import org.example.demos.sequencer.beatBox.exceptions.IllegalPatternException; import org.example.shared.utilities.MidiUtil; import org.example.shared.utilities.UIUtil; import org.example.shared.utilities.Util; import static java.awt.BorderLayout.*; import static javax.sound.midi.Sequencer.LOOP_CONTINUOUSLY; import static javax.sound.midi.ShortMessage.*; import static javax.swing.BoxLayout.Y_AXIS; import static javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; import static javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio @Slf4j public class BeatBox { private final Sequencer sequencer; private final Sequence sequence = Util.wrapInTryCatchAndGet(() -> new Sequence(Sequence.PPQ, 4)); private Track track = sequence.createTrack(); @Getter private int numberOfBeats; private JPanel mainPanel; @Getter(value = AccessLevel.PACKAGE) private JComponent labelBox; @Getter(value = AccessLevel.PACKAGE) private JPanel checkBoxPanel; private final ItemListener checkBoxItemListener = new CheckBoxItemListener(); private final MouseListener checkBoxMouseListener = new CheckBoxMouseListener(); private JButton saveButton; private JButton startButton; private JButton stopButton; private JButton tempoUpButton; private JButton tempoDownButton; private JButton clearButton; private boolean isMousePressed; @Getter private final PressedButtonStrategy pressedButtonStrategy; @Getter private final MissingInstrumentStrategy missingInstrumentStrategy; @Getter private final MissingBeatsStrategy missingBeatsStrategy; @Getter private final ExcessBeatsStrategy excessBeatsStrategy; @Getter private final String separator; @Getter private final String checkMark; @Getter private final String blankMark; @Getter(value = AccessLevel.PACKAGE) private final Map<MidiInstrument, List<JCheckBox>> instrumentMap; private static final Rectangle MAXIMUM_WINDOW_BOUNDS = UIUtil.getMaximumWindowBounds(); private static final int MINIMUM_FRAME_WIDTH = 500; private static final int WIDTH_PER_BEAT = 15; private static final int MINIMUM_FRAME_HEIGHT = 225; private static final int HEIGHT_PER_INSTRUMENT = 20; public BeatBox() { this(BeatBoxConfiguration.configure()); }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public BeatBox() { this(BeatBoxConfiguration.configure()); } BeatBox(BeatBoxConfiguration config) { sequencer = Util.wrapInTryCatchAndGet(() -> { Sequencer s = MidiSystem.getSequencer(); s.open(); s.setTempoInBPM(config.getTempoInBPM()); return s; }); instrumentMap = config.getInstrumentMap(); numberOfBeats = config.getNumberOfBeats(); pressedButtonStrategy = config.getPressedButtonStrategy(); missingInstrumentStrategy = config.getMissingInstrumentStrategy(); missingBeatsStrategy = config.getMissingBeatsStrategy(); excessBeatsStrategy = config.getExcessBeatsStrategy(); separator = config.getSeparator(); checkMark = config.getCheckMark(); blankMark = config.getBlankMark(); } public Collection<MidiInstrument> getInstruments() { return instrumentMap.keySet(); } public float getTempo() { return sequencer.getTempoInBPM(); }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public void launch() { UIUtil.getUIBuilder() .withTitle("Beat Box") .withComponent(CENTER, () -> UIUtil.getComponentBuilder(() -> { mainPanel = new JPanel(new BorderLayout()); return mainPanel; }) .withBorder(() -> BorderFactory.createEmptyBorder(10, 10, 10, 10)) .withComponent(EAST, () -> UIUtil.getComponentBuilder(() -> new Box(Y_AXIS)) .withComponent(() -> { startButton = new JButton("Start"); startButton.setEnabled(false); startButton.addActionListener(new StartButtonListener()); return startButton; }) .withComponent(() -> { stopButton = new JButton("Stop"); stopButton.setEnabled(false); stopButton.addActionListener(new StopButtonListener()); return stopButton; }) .withComponent(() -> { tempoUpButton = new JButton("Tempo Up"); tempoUpButton.setEnabled(false); tempoUpButton.addActionListener(new TempoUpButtonListener()); return tempoUpButton; }) .withComponent(() -> { tempoDownButton = new JButton("Tempo Down"); tempoDownButton.setEnabled(false); tempoDownButton.addActionListener(new TempoDownButtonListener());
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio return tempoDownButton; }) .withComponent(() -> { clearButton = new JButton("Clear"); clearButton.setEnabled(false); clearButton.addActionListener(new ClearButtonListener()); return clearButton; }) .withComponent(() -> { saveButton = new JButton("Save Pattern..."); saveButton.setEnabled(false); saveButton.addActionListener(new SaveButtonListener()); return saveButton; }) .withComponent(() -> { var loadButton = new JButton("Load Pattern..."); loadButton.addActionListener(new LoadButtonListener()); return loadButton; }) .build()) .withComponent(WEST, () -> { labelBox = new Box(Y_AXIS); instrumentMap.keySet().forEach(k -> labelBox.add(new Label(k.getStandardName()))); return labelBox; }) .withComponent(CENTER, () -> { GridLayout gridLayout = new GridLayout(instrumentMap.size(), numberOfBeats); gridLayout.setVgap(1); gridLayout.setHgap(2); checkBoxPanel = new JPanel(gridLayout); checkBoxPanel.addMouseListener(new CheckBoxPanelMouseListener());
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio checkBoxPanel.addMouseListener(new CheckBoxPanelMouseListener()); ensureOneBlankCheckBoxForEachBeat(); return checkBoxPanel; }) .withVerticalScrollBarPolicy(VERTICAL_SCROLLBAR_AS_NEEDED) .withHorizontalScrollBarPolicy(HORIZONTAL_SCROLLBAR_AS_NEEDED) .build()) .withFrameSize(calculateAppropriateWidth(), calculateAppropriateHeight()) .visualize(); }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private void ensureOneBlankCheckBoxForEachBeat() { checkBoxPanel.removeAll(); instrumentMap.values().forEach(checkBoxList -> { checkBoxList.clear(); checkBoxList.addAll( Stream.generate(this::getNewCheckBox) .peek(checkBox -> checkBoxPanel.add(checkBox)) .limit(numberOfBeats) .toList() ); }); ((GridLayout) checkBoxPanel.getLayout()).setColumns(numberOfBeats); adaptFrameSize(); } void addMoreBeats(int numberOfBeatsToAdd) { numberOfBeats += numberOfBeatsToAdd; ensureOneBlankCheckBoxForEachBeat(); } void removeBeats(int numberOfBeatsToRemove) { numberOfBeats -= numberOfBeatsToRemove; ensureOneBlankCheckBoxForEachBeat(); } private int calculateAppropriateWidth() { return Math.min(MAXIMUM_WINDOW_BOUNDS.width, MINIMUM_FRAME_WIDTH + numberOfBeats * WIDTH_PER_BEAT); } private int calculateAppropriateHeight() { return Math.min(MAXIMUM_WINDOW_BOUNDS.height, MINIMUM_FRAME_HEIGHT + instrumentMap.size() * HEIGHT_PER_INSTRUMENT); } private void makeTrackAndStart() { refreshTrack(); addMidiEventsForSelectedCheckBoxes(); addDummyEventAtLastBeat(); setSequenceAndStart(); }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private void addMidiEventsForSelectedCheckBoxes() { for (Map.Entry<MidiInstrument, List<JCheckBox>> mapEntry : instrumentMap.entrySet()) { int instrumentFirstByte = mapEntry.getKey().getFirstByte(); List<JCheckBox> checkBoxList = mapEntry.getValue(); for (int i = 0; i < checkBoxList.size(); i++) { if (checkBoxList.get(i).isSelected()) { track.add(MidiUtil.getMidiEventBuilder() .withCommand(NOTE_ON) .withChannel(9) .withFirstByte(instrumentFirstByte) .withSecondByte(100) .withTick(i) .build()); track.add(MidiUtil.getMidiEventBuilder() .withCommand(NOTE_OFF) .withChannel(9) .withFirstByte(instrumentFirstByte) .withSecondByte(100) .withTick(i + 1) .build()); } } } } private void addDummyEventAtLastBeat() { /* adding an event at the last beat is important because the Sequencer may not * go all the beats otherwise */ track.add(MidiUtil.getMidiEventBuilder() .withCommand(CONTROL_CHANGE) // it could be PROGRAM_CHANGE, it doesn't matter .withChannel(0) // any channel between 0 and 15, doesn't matter .withFirstByte(0) // the bytes should be between 0 and 127 inclusive .withSecondByte(0) // as long as within the range, the byte values don't matter .withTick(numberOfBeats) // the last beat .build()); } private void refreshTrack() { sequence.deleteTrack(track); track = sequence.createTrack(); }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private void setSequenceAndStart() { Util.wrapInTryCatch(() -> { sequencer.setSequence(sequence); sequencer.setLoopCount(LOOP_CONTINUOUSLY); sequencer.start(); }); } void addNewInstrument(MidiInstrument instrument) { var checkBoxes = Stream.generate(this::getNewCheckBox).limit(numberOfBeats).toList(); instrumentMap.put(instrument, checkBoxes); labelBox.add(new Label(instrument.getStandardName())); checkBoxes.forEach(checkBoxPanel::add); var checkBoxPanelLayout = (GridLayout) checkBoxPanel.getLayout(); checkBoxPanelLayout.setRows(checkBoxPanelLayout.getRows() + 1); } private JCheckBox getNewCheckBox() { var checkBox = new JCheckBox(); checkBox.addMouseListener(checkBoxMouseListener); checkBox.addItemListener(checkBoxItemListener); checkBox.setSelected(false); return checkBox; } private void adaptFrameSize() { JFrame frame = getFrame(); if (frame != null) { frame.setSize(calculateAppropriateWidth(), calculateAppropriateHeight()); } } private JFrame getFrame() { return (JFrame) SwingUtilities.getWindowAncestor(mainPanel); } private void togglePlaybackControls() { boolean isRunning = sequencer.isRunning(); stopButton.setEnabled(isRunning); tempoUpButton.setEnabled(isRunning); tempoDownButton.setEnabled(isRunning); } private class StartButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { makeTrackAndStart(); togglePlaybackControls(); } } private class StopButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { sequencer.stop(); togglePlaybackControls(); } }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private class TempoUpButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { float currentTempoFactor = sequencer.getTempoFactor(); sequencer.setTempoFactor(currentTempoFactor * 1.03f); } } private class TempoDownButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { float currentTempoFactor = sequencer.getTempoFactor(); sequencer.setTempoFactor(currentTempoFactor * 0.97f); } } private class ClearButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { instrumentMap.values().stream() .flatMap(Collection::stream) .forEach(checkBox -> checkBox.setSelected(false)); } } private class SaveButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent event) { JFileChooser fileChooser = new JFileChooser(); fileChooser.showSaveDialog(mainPanel); try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileChooser.getSelectedFile()))) { writeManifest(writer); String paddedSeparator = " " + separator + " "; for (Map.Entry<MidiInstrument, List<JCheckBox>> mapEntry : instrumentMap.entrySet()) { writer.write(mapEntry.getKey().getStandardName() + paddedSeparator + mapEntry.getValue().stream() .map(checkBox -> checkBox.isSelected() ? checkMark : blankMark) .collect(Collectors.joining()) + "\n"); } } catch (IOException e) { throw new RuntimeException(e); } }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private void writeManifest(BufferedWriter writer) throws IOException { writer.write("SEPARATOR " + separator + "\n"); writer.write("CHECK MARK " + checkMark + "\n"); writer.write("BLANK MARK " + blankMark + "\n"); } } private class LoadButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent event) { JFileChooser fileChooser = new JFileChooser(); int returnState = fileChooser.showOpenDialog(mainPanel); if (returnState == JFileChooser.APPROVE_OPTION) { performPatternLoading(fileChooser); } else if (returnState == JFileChooser.CANCEL_OPTION) { log.info("No pattern is selected – loading is aborted"); } }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private void performPatternLoading(JFileChooser fileChooser) { boolean frameResizingRequired = false; try (BufferedReader reader = new BufferedReader(new FileReader(fileChooser.getSelectedFile()))) { PatternManifest m = ManifestParser.parseManifest(reader); Map<String, String[]> namedBeatRows = readNamedBeatRows(reader, m); ensureEqualBeatRowLengths(namedBeatRows, m.blankMark()); int numberOfBeatsInPattern = namedBeatRows.values().stream().findAny().orElseThrow().length; if (numberOfBeats < numberOfBeatsInPattern) { missingBeatsStrategy.handle(new BeatsMismatchContext( BeatBox.this, namedBeatRows.values().stream().toList(), m.checkMark() )); } else if (numberOfBeats > numberOfBeatsInPattern) { excessBeatsStrategy.handle(new BeatsMismatchContext( BeatBox.this, namedBeatRows.values().stream().toList(), m.checkMark() )); } for (Map.Entry<String, String[]> entry : namedBeatRows.entrySet()) { String instrumentName = entry.getKey(); String[] instrumentBeats = entry.getValue(); var optionalMatchingEntry = findMatchingEntry(instrumentName); if (optionalMatchingEntry.isPresent()) { copyBeatPattern(optionalMatchingEntry.get().getValue(), instrumentBeats, m); } else { boolean isInstrumentAdded = missingInstrumentStrategy.handle(new InstrumentMismatchContext( BeatBox.this, instrumentName, instrumentBeats, m.checkMark() )); if (isInstrumentAdded) {
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio )); if (isInstrumentAdded) { copyBeatPattern(findMatchingEntry(instrumentName).orElseThrow().getValue(), instrumentBeats, m); frameResizingRequired = true; } } } } catch (IOException e) { throw new RuntimeException(e); } catch (IllegalPatternException e) { log.error(e.getMessage()); } if (frameResizingRequired) { BeatBox.this.adaptFrameSize(); } }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private void ensureEqualBeatRowLengths(Map<String, String[]> namedBeatRows, String blankMark) { int maxBeatsInPattern = getMaxBeatsInPattern(namedBeatRows); namedBeatRows.replaceAll((name, beatRow) -> (beatRow.length < maxBeatsInPattern) ? normalizeRow(beatRow, maxBeatsInPattern, blankMark) : beatRow); } private int getMaxBeatsInPattern(Map<String, String[]> namedBeatRows) { return namedBeatRows.values().stream() .mapToInt(row -> row.length) .max().orElseThrow(); } private Map<String, String[]> readNamedBeatRows(BufferedReader reader, PatternManifest m) throws IOException { Map<String, String[]> namedBeatRows = new HashMap<>(); String line; while ((line = reader.readLine()) != null) { String[] nameBeatsPair = line.split(m.separator()); String instrumentName = nameBeatsPair[0].trim(); String[] instrumentBeats = nameBeatsPair[1].trim().split(""); namedBeatRows.put(instrumentName, instrumentBeats); } return namedBeatRows; } private String[] normalizeRow(String[] beatRow, int requiredLength, String paddingCharacter) { return ArrayUtils.addAll(beatRow, paddingCharacter.repeat(requiredLength - beatRow.length).split("")); } private Optional<Map.Entry<MidiInstrument, List<JCheckBox>>> findMatchingEntry(String instrumentName) { return instrumentMap.entrySet().stream() .filter(entry -> entry.getKey().getStandardName().equalsIgnoreCase(instrumentName)) .findFirst(); }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private void copyBeatPattern(List<JCheckBox> appBeats, String[] patternBeats, PatternManifest m) { for (int i = 0; i < appBeats.size(); i++) { var currentCheckBox = appBeats.get(i); if (i < patternBeats.length) { if (patternBeats[i].equals(m.checkMark())) { currentCheckBox.setSelected(true); } else if (patternBeats[i].equals(m.blankMark())) { currentCheckBox.setSelected(false); } } else { currentCheckBox.setSelected(false); } } } } private class CheckBoxItemListener implements ItemListener { @Override public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { setPatternControlsTo(true); } else if ((e.getStateChange() == ItemEvent.DESELECTED) && noCheckBoxChecked()) { setPatternControlsTo(false); } } private void setPatternControlsTo(boolean value) { startButton.setEnabled(value); saveButton.setEnabled(value); clearButton.setEnabled(value); } private boolean noCheckBoxChecked() { return instrumentMap.values().stream() .flatMap(Collection::stream) .noneMatch(AbstractButton::isSelected); } } private class CheckBoxPanelMouseListener extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { isMousePressed = true; } @Override public void mouseReleased(MouseEvent e) { isMousePressed = false; } } private class CheckBoxMouseListener extends MouseAdapter { private JCheckBox originallyPressedCheckBox; private JCheckBox lastEnteredCheckBox;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio @Override public void mousePressed(MouseEvent e) { originallyPressedCheckBox = (JCheckBox) e.getSource(); isMousePressed = true; } @Override public void mouseReleased(MouseEvent e) { originallyPressedCheckBox = null; lastEnteredCheckBox = null; isMousePressed = false; } @Override public void mouseEntered(MouseEvent e) { if (isMousePressed) { var enteredCheckBox = (JCheckBox) e.getSource(); lastEnteredCheckBox = enteredCheckBox; pressedButtonStrategy.apply(enteredCheckBox); } } @Override public void mouseExited(MouseEvent e) { var exitedCheckBox = (JCheckBox) e.getSource(); if (isMousePressed && exitedCheckBox == originallyPressedCheckBox && exitedCheckBox != lastEnteredCheckBox) { pressedButtonStrategy.apply(exitedCheckBox); } } } } BeatBoxConfiguration package org.example.demos.sequencer.beatBox; import lombok.AccessLevel; import lombok.Getter; import lombok.extern.slf4j.Slf4j; import org.jetbrains.annotations.NotNull;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio @Slf4j public class BeatBoxConfiguration { @Getter(value = AccessLevel.PACKAGE) private Map<MidiInstrument, List<JCheckBox>> instrumentMap = instrumentsToInstrumentMap(InstrumentFactory.getKathysInstruments()); @Getter private int numberOfBeats = 16; @Getter private float tempoInBPM = 120; @Getter private PressedButtonStrategy pressedButtonStrategy = PressedButtonStrategy.TOGGLE; @Getter private MissingInstrumentStrategy missingInstrumentStrategy = MissingInstrumentStrategy.ADD_IF_BEATS_NOT_BLANK; @Getter private MissingBeatsStrategy missingBeatsStrategy = MissingBeatsStrategy.ADD_IF_BEATS_NOT_BLANK; @Getter private ExcessBeatsStrategy excessBeatsStrategy = ExcessBeatsStrategy.TRIM_ALWAYS; @Getter private String separator = ":"; @Getter private String checkMark = "X"; @Getter private String blankMark = "O"; private boolean didUnsuccessfulInstrumentSettingOccur; public static BeatBoxConfiguration configure() { return new BeatBoxConfiguration(); } public Collection<MidiInstrument> getInstruments() { return instrumentMap.keySet(); } public BeatBoxConfiguration setInstruments(@NotNull MidiInstrument... instruments) { setInstruments(Arrays.asList(instruments)); return this; } public BeatBoxConfiguration setInstruments(@NotNull Collection<MidiInstrument> instruments) { BeatBoxUtils.requireNonNull(instruments, "instruments"); var customInstrumentMap = instrumentsToInstrumentMap(instruments); if (!customInstrumentMap.isEmpty()) { instrumentMap = customInstrumentMap; didUnsuccessfulInstrumentSettingOccur = false; } else { didUnsuccessfulInstrumentSettingOccur = true; } return this; }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public BeatBoxConfiguration setNumberOfBeats(int numberOfBeats) { BeatBoxUtils.requirePositive(numberOfBeats, "numberOfBeats"); this.numberOfBeats = numberOfBeats; return this; } public BeatBoxConfiguration setTempoInBPM(float tempoInBPM) { BeatBoxUtils.requirePositive(tempoInBPM, "tempoInBPM"); this.tempoInBPM = tempoInBPM; return this; } public BeatBoxConfiguration setSeparator(@NotNull String separator) { BeatBoxUtils.requireManifestComponentValidity(separator, ManifestComponent.SEPARATOR); this.separator = separator; return this; } public BeatBoxConfiguration setCheckMark(@NotNull String checkMark) { BeatBoxUtils.requireManifestComponentValidity(checkMark, ManifestComponent.CHECK_MARK); this.checkMark = checkMark; return this; } public BeatBoxConfiguration setBlankMark(@NotNull String blankMark) { BeatBoxUtils.requireManifestComponentValidity(blankMark, ManifestComponent.BLANK_MARK); this.blankMark = blankMark; return this; } public BeatBoxConfiguration setMissingInstrumentStrategy(@NotNull MissingInstrumentStrategy strategy) { BeatBoxUtils.requireNonNull(strategy, "missingInstrumentStrategy"); this.missingInstrumentStrategy = strategy; return this; } public BeatBoxConfiguration setMissingBeatsStrategy(@NotNull MissingBeatsStrategy strategy) { BeatBoxUtils.requireNonNull(strategy, "missingBeatsStrategy"); this.missingBeatsStrategy = strategy; return this; } public BeatBoxConfiguration setExcessBeatsStrategy(@NotNull ExcessBeatsStrategy strategy) { BeatBoxUtils.requireNonNull(strategy, "excessBeatsStrategy"); this.excessBeatsStrategy = strategy; return this; }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public BeatBoxConfiguration setPressedButtonStrategy(@NotNull PressedButtonStrategy pressedButtonStrategy) { BeatBoxUtils.requireNonNull(pressedButtonStrategy, "pressedButtonBehavior"); this.pressedButtonStrategy = pressedButtonStrategy; return this; } public BeatBox build() { if (didUnsuccessfulInstrumentSettingOccur) { log.warn("No instruments found. Default instruments are going to be applied"); } return new BeatBox(this); } private Map<MidiInstrument, List<JCheckBox>> instrumentsToInstrumentMap(Collection<MidiInstrument> instruments) { Map<MidiInstrument, List<JCheckBox>> instrumentMap = new LinkedHashMap<>(instruments.size()); for (MidiInstrument instrument : instruments) { instrumentMap.put(instrument, new ArrayList<>(numberOfBeats)); } return instrumentMap; } } BeatBoxUtils package org.example.demos.sequencer.beatBox; import org.example.demos.sequencer.beatBox.exceptions.IllegalPropertyException; import org.example.demos.sequencer.beatBox.exceptions.IllegalPropertyException.PropertyIssue; public class BeatBoxUtils { public static void requireNonEmpty(Collection<?> collection, String propertyName) { requireNonNull(collection, propertyName); if (collection.isEmpty()) { throw new IllegalPropertyException(propertyName, PropertyIssue.EMPTY); } } public static void requireNonEmpty(String property, String propertyName) { requireNonNull(property, propertyName); if (property.isEmpty()) { throw new IllegalPropertyException(propertyName, PropertyIssue.EMPTY); } } public static void requirePositive(int property, String propertyName) { if (property <= 0) { throw new IllegalPropertyException(propertyName, PropertyIssue.NON_POSITIVE); } }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public static void requirePositive(float property, String propertyName) { if (property <= 0) { throw new IllegalPropertyException(propertyName, PropertyIssue.NON_POSITIVE); } } public static void requireNonNull(Object property, String propertyName) { if (property == null) { throw new IllegalPropertyException(propertyName, PropertyIssue.NULL); } } public static void requireManifestComponentValidity(String passedComponent, ManifestComponent componentToMatch) { requireNonNull(passedComponent, "passed " + componentToMatch.getManifestName()); requireNonNull(componentToMatch, "componentToMatch"); if (!Pattern.matches(componentToMatch.getRegex(), passedComponent)) { throw new IllegalPropertyException("passed " + componentToMatch.getManifestName(), PropertyIssue.NOT_MATCHING_REGEX); } } } BeatsMismatchContext package org.example.demos.sequencer.beatBox; import java.util.List; public class BeatsMismatchContext extends MismatchContext { private final List<String[]> beats; public BeatsMismatchContext(BeatBox beatBox, List<String[]> beats, String checkMark) { super(beatBox, checkMark); this.beats = beats; } List<String[]> beats() { return beats; } } BeatsStrategy package org.example.demos.sequencer.beatBox; public interface BeatsStrategy extends Strategy { String BEAT_MISMATCH_WILL_HAVE_EFFECT_MSG = "The sound won't be able to fully match the pattern"; } ExcessBeatsStrategy package org.example.demos.sequencer.beatBox; import lombok.extern.slf4j.Slf4j;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio ExcessBeatsStrategy package org.example.demos.sequencer.beatBox; import lombok.extern.slf4j.Slf4j; @Slf4j public enum ExcessBeatsStrategy implements BeatsStrategy { TRIM_ALWAYS { @Override public void handle(BeatsMismatchContext context) { BeatBox beatBox = context.beatBox(); int lengthInPattern = context.beats().get(0).length; int lengthInApp = beatBox.getNumberOfBeats(); beatBox.removeBeats(lengthInApp - lengthInPattern); log.info(String.format(LOG_FORMAT, lengthInPattern, lengthInApp, BEATS_REMOVED_MSG, BEAT_MISMATCH_FIXED_MSG)); } }, TRIM_NEVER { @Override public void handle(BeatsMismatchContext context) { int lengthInPattern = context.beats().get(0).length; int lengthInApp = context.beatBox().getNumberOfBeats(); log.warn(String.format(LOG_FORMAT, lengthInPattern, lengthInApp, NO_ACTION_TAKEN_MSG, BEAT_MISMATCH_WILL_HAVE_EFFECT_MSG)); } }; // number in pattern; number in instrument map; action; result private static final String LOG_FORMAT = "The number of beats per instrument in the pattern (%d) was lower than the number " + "of beats per instrument in the current instrument map (%d). %s. %s"; private static final String BEATS_REMOVED_MSG = "Excess beats were removed"; private static final String BEAT_MISMATCH_FIXED_MSG = "The number of beats per instrument is now in line with the beat pattern"; public abstract void handle(BeatsMismatchContext context); } InstrumentFactory package org.example.demos.sequencer.beatBox; import java.util.Arrays; import java.util.Collection; import java.util.List; import static org.example.demos.sequencer.beatBox.MidiInstrument.*;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio import static org.example.demos.sequencer.beatBox.MidiInstrument.*; public final class InstrumentFactory { public static Collection<MidiInstrument> getKathysInstruments() { /* Instruments used in Kathy Sierra's book Head First Java */ return List.of( ACOUSTIC_BASS_DRUM, CLOSED_HI_HAT, OPEN_HI_HAT, ACOUSTIC_SNARE, CRASH_CYMBAL_1, HAND_CLAP, HIGH_TOM, HIGH_BONGO, MARACAS, LONG_WHISTLE, LOW_CONGA, COWBELL, VIBRASLAP, LOW_MID_TOM, HIGH_AGOGO, OPEN_HIGH_CONGA ); } public static Collection<MidiInstrument> getAllInstrumentsInStandardOrder() { return Arrays.asList(MidiInstrument.values()); } } InstrumentMismatchContext package org.example.demos.sequencer.beatBox; import java.util.Arrays; public final class InstrumentMismatchContext extends MismatchContext { private final String name; private final String[] beats; public InstrumentMismatchContext(BeatBox beatBox, String name, String[] beats, String checkMark) { super(beatBox, checkMark); this.name = name; this.beats = beats; } String name() { return name; } String[] beats() { return beats; } // I don't really need equals(), hashCode(), and toString() in this class. It just used to be a record and then I converted it to a class via "Convert record to class" to allow inheritance. So it was generated for me and I saw no reason to manually remove it
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio @Override public boolean equals(Object obj) { if (obj == this) return true; if (obj == null || obj.getClass() != this.getClass()) return false; var that = (InstrumentMismatchContext) obj; return this.beatBox().equals(that.beatBox()) && this.name.equals(that.name) && Arrays.equals(this.beats(), that.beats()) && this.checkMark().equals(that.checkMark()); } @Override public int hashCode() { int result = beatBox().hashCode(); result = 31 * result + name.hashCode(); result = 31 * result + Arrays.hashCode(beats()); result = 31 * result + checkMark().hashCode(); return result; } @Override public String toString() { return "InstrumentMismatchContext[" + "beatBox=" + beatBox() + ", " + "name=" + name + ", " + "beats=" + Arrays.toString(beats()) + ", " + "checkMark=" + checkMark() + ']'; } } ManifestComponent package org.example.demos.sequencer.beatBox; import lombok.Getter; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor @Getter public enum ManifestComponent { SEPARATOR("SEPARATOR", ".+"), CHECK_MARK("CHECK MARK", ".{1}"), BLANK_MARK("BLANK MARK", ".{1}"); private final String manifestName; private final String regex; @Override public String toString() { return manifestName; } } ManifestParser package org.example.demos.sequencer.beatBox; import org.example.demos.sequencer.beatBox.exceptions.IllegalPatternException; import java.io.BufferedReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; import static java.lang.String.format; import static org.example.demos.sequencer.beatBox.ManifestComponent.*; public class ManifestParser { private static BufferedReader reader;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public class ManifestParser { private static BufferedReader reader; static PatternManifest parseManifest(BufferedReader reader) throws IllegalPatternException, IOException { ManifestParser.reader = reader; String separator = parse(SEPARATOR); String checkMark = parse(CHECK_MARK); String blankMark = parse(BLANK_MARK); return new PatternManifest(separator, checkMark, blankMark); } private static String parse(ManifestComponent mc) throws IllegalPatternException, IOException { Matcher matcher = Pattern.compile(format("(?<=%s )%s", mc.getManifestName(), mc.getRegex())) .matcher(reader.readLine()); if (matcher.find()) { return matcher.group(); } else { throw new IllegalPatternException(mc); } } } MidiInstrument package org.example.demos.sequencer.beatBox; import lombok.Getter; import lombok.RequiredArgsConstructor; import java.util.Arrays; import java.util.Optional;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio @RequiredArgsConstructor @Getter public enum MidiInstrument { FILTER_SNAP("Filter Snap", 27), SLAP_NOISE("Slap Noise", 28), SCRATCH_PUSH("Scratch Push", 29), SCRATCH_PULL("Scratch Pull", 30), DRUMSTICKS("Drumsticks", 31), CLICK_BOISE("Click Boise", 32), METRONOME_CLICK("Metronome Click", 33), METRONOME_BELL("Metronome Bell", 34), ACOUSTIC_BASS_DRUM("Acoustic Bass Drum", 35), ELECTRIC_BASS_DRUM("Electric Bass Drum", 36), SIDE_STICK("Side Stick", 37), ACOUSTIC_SNARE("Acoustic Snare", 38), HAND_CLAP("Hand Clap", 39), ELECTRIC_SNARE("Electric Snare", 40), LOW_FLOOR_TOM("Low Floor Tom", 41), CLOSED_HI_HAT("Closed Hi-hat", 42), HIGH_FLORR_TOM("High Floor Tom", 43), PEDAL_HI_HAT("Pedal Hi-hat", 44), LOW_TOM("Low Tom", 45), OPEN_HI_HAT("Open Hi-hat", 46), LOW_MID_TOM("Low-Mid Tom", 47), HIGH_MID_TOM("High-Mid Tom", 48), CRASH_CYMBAL_1("Crash Cymbal 1", 49), HIGH_TOM("High Tom", 50), RIDE_CYMBAL_1("Ride Cymbal 1", 51), CHINESE_CYMBAL("Chinese Cymbal", 52), RIDE_BELL("Ride Bell", 53), TAMBOURINE("Tambourine", 54), SPLASH_CYMBAL("Splash Cymbal", 55), COWBELL("Cowbell", 56), CRASH_CYMBAL_2("Crash Cymbal 2", 57), VIBRASLAP("Vibraslap", 58), RIDE_CYMBAL_2("Ride Cymbal 2", 59), HIGH_BONGO("High Bongo", 60), LOW_BONGO("Low Bongo", 61), MUTE_HIGH_CONGA("Mute High Conga", 62), OPEN_HIGH_CONGA("Open High Conga", 63), LOW_CONGA("Low Conga", 64), HIGH_TIMBALE("High Timbale", 65), LOW_TIMBALE("Low Timbale", 66), HIGH_AGOGO("High Agogo", 67), LOW_AGOGO("Low Agogo", 68), CABASA("Cabasa", 69), MARACAS("Maracas", 70), SHORT_WHISTLE("Short Whistle", 71), LONG_WHISTLE("Long Whistle", 72), SHORT_GUIRO("Short Guiro", 73), LONG_GUIRO("Long Guiro", 74), CLAVES("Claves", 75), HIGH_WOODBLOCK("High Woodblock", 76), LOW_WOODBLOCK("Low Woodblock", 77), MUTE_CUICA("Mute Cuica", 78), OPEN_CUICA("Open Cuica", 79), MUTE_TRIANGLE("Mute Triangle", 80),
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio OPEN_CUICA("Open Cuica", 79), MUTE_TRIANGLE("Mute Triangle", 80), OPEN_TRIANGLE("Open Triangle", 81), SHAKER("Shaker", 82), JINGLE_BELL("Jingle Bell", 83), BELL_TREE("Bell Tree", 84), CASTANETS("Castanets", 85), MUTED_SURDO("Muted Surdo", 86), OPEN_SURDO("Open Surdo", 87);
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private final String standardName; private final int firstByte; static Optional<MidiInstrument> getForName(String instrumentName) { return Arrays.stream(values()) .filter(instrument -> instrument.standardName.equalsIgnoreCase(instrumentName)) .findFirst(); } @Override public String toString() { return standardName; } } MismatchContext package org.example.demos.sequencer.beatBox; import lombok.RequiredArgsConstructor; @RequiredArgsConstructor public abstract class MismatchContext { private final BeatBox beatBox; private final String checkMark; BeatBox beatBox() { return this.beatBox; } String checkMark() { return this.checkMark; } } MissingBeatsStrategy package org.example.demos.sequencer.beatBox; import lombok.extern.slf4j.Slf4j; import java.util.Arrays; import java.util.List;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio @Slf4j public enum MissingBeatsStrategy implements BeatsStrategy { ADD_ALWAYS { @Override public void handle(BeatsMismatchContext context) { BeatBox beatBox = context.beatBox(); int lengthInApp = beatBox.getNumberOfBeats(); int lengthInPattern = context.beats().get(0).length; beatBox.addMoreBeats(lengthInPattern - lengthInApp); log.info(String.format(LOG_FORMAT, lengthInApp, lengthInPattern, BEATS_ADDED_MSG, BEAT_MISMATCH_FIXED_MSG)); } }, ADD_IF_BEATS_NOT_BLANK { @Override public void handle(BeatsMismatchContext context) { var patternBeats = context.beats(); int lengthInApp = context.beatBox().getNumberOfBeats(); int lengthInPattern = patternBeats.get(0).length; if (areAdditionalBeatsInPatternBlank(patternBeats, context.checkMark(), lengthInApp)) { log.info(String.format(LOG_FORMAT, lengthInApp, lengthInPattern, NO_ACTION_TAKEN_MSG, BEAT_MISMATCH_IRRELEVANT_MSG)); } else { context.beatBox().addMoreBeats(lengthInPattern - lengthInApp); log.info(String.format(LOG_FORMAT, lengthInApp, lengthInPattern, BEATS_ADDED_MSG, BEAT_MISMATCH_FIXED_MSG)); } } }, ADD_NEVER { @Override public void handle(BeatsMismatchContext context) { List<String[]> patternBeats = context.beats(); int lengthInApp = context.beatBox().getNumberOfBeats(); int lengthInPattern = patternBeats.get(0).length; if (areAdditionalBeatsInPatternBlank(patternBeats, context.checkMark(), lengthInApp)) { log.info(String.format(LOG_FORMAT, lengthInApp, lengthInPattern, NO_ACTION_TAKEN_MSG, BEAT_MISMATCH_IRRELEVANT_MSG)); } else {
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio NO_ACTION_TAKEN_MSG, BEAT_MISMATCH_IRRELEVANT_MSG)); } else { log.warn(String.format(LOG_FORMAT, lengthInApp, lengthInPattern, NO_ACTION_TAKEN_MSG, BEAT_MISMATCH_WILL_HAVE_EFFECT_MSG)); } } };
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio // number in instrument map; number in pattern; action; result private static final String LOG_FORMAT = "The number of beats per instrument in the current " + "instrument map (%d) was lower than the number of beats per instrument in the pattern (%d). %s. %s"; private static final String BEATS_ADDED_MSG = "Missing beats were added"; private static final String BEAT_MISMATCH_FIXED_MSG = "Beat pattern will be copied"; private static final String BEAT_MISMATCH_IRRELEVANT_MSG = "No effect on the sound is expected: additional beats in the pattern were blank"; public abstract void handle(BeatsMismatchContext context); private static boolean areAdditionalBeatsInPatternBlank(List<String[]> patternBeats, String checkMark, int numberOfBeatsInApp) { return patternBeats.stream() .map(beatRow -> Arrays.copyOfRange(beatRow, numberOfBeatsInApp, beatRow.length)) .flatMap(Arrays::stream) .noneMatch(beat -> beat.equals(checkMark)); } } MissingInstrumentStrategy package org.example.demos.sequencer.beatBox; import lombok.extern.slf4j.Slf4j; import java.util.Arrays; import java.util.Optional;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio @Slf4j public enum MissingInstrumentStrategy implements Strategy { ADD_ALWAYS { @Override boolean handle(InstrumentMismatchContext c) { var missingInstrumentName = c.name(); var isInstrumentAdded = tryAndAddMissingInstrument(c); if (isInstrumentAdded) { log.info(String.format(LOG_FORMAT, missingInstrumentName, INSTRUMENT_SUCCESSFULLY_ADDED_MSG, INSTRUMENT_MISMATCH_FIXED_MSG)); } else { if (areBeatsNonBlank(c.beats(), c.checkMark())) { log.warn(String.format(LOG_FORMAT, missingInstrumentName, INSTRUMENT_COULDNT_BE_ADDED_MSG, INSTRUMENT_MISMATCH_WILL_HAVE_EFFECT_MSG)); } else { log.info(String.format(LOG_FORMAT, missingInstrumentName, INSTRUMENT_COULDNT_BE_ADDED_MSG, INSTRUMENT_MISMATCH_IRRELEVANT_MSG)); } } return isInstrumentAdded; } }, ADD_IF_BEATS_NOT_BLANK { @Override boolean handle(InstrumentMismatchContext context) { var missingInstrumentName = context.name(); var beats = context.beats(); var checkMark = context.checkMark(); if (areBeatsNonBlank(beats, checkMark)) { var isInstrumentAdded = tryAndAddMissingInstrument(context); if (isInstrumentAdded) { log.info(String.format(LOG_FORMAT, missingInstrumentName, INSTRUMENT_SUCCESSFULLY_ADDED_MSG, INSTRUMENT_MISMATCH_FIXED_MSG)); } else { log.warn(String.format(LOG_FORMAT, missingInstrumentName, INSTRUMENT_COULDNT_BE_ADDED_MSG, INSTRUMENT_MISMATCH_WILL_HAVE_EFFECT_MSG)); } return isInstrumentAdded; } log.info(String.format(LOG_FORMAT, missingInstrumentName,
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio } log.info(String.format(LOG_FORMAT, missingInstrumentName, NO_ACTION_TAKEN_MSG, INSTRUMENT_MISMATCH_IRRELEVANT_MSG)); return false; } }, ADD_NEVER { @Override boolean handle(InstrumentMismatchContext context) { var missingInstrumentName = context.name(); var beats = context.beats(); var checkMark = context.checkMark(); if (areBeatsNonBlank(beats, checkMark)) { log.warn(String.format(LOG_FORMAT, missingInstrumentName, NO_ACTION_TAKEN_MSG, INSTRUMENT_MISMATCH_WILL_HAVE_EFFECT_MSG)); } else { log.info(String.format(LOG_FORMAT, missingInstrumentName, NO_ACTION_TAKEN_MSG, INSTRUMENT_MISMATCH_IRRELEVANT_MSG)); } return false; } }; // instrument name; action; result static final String LOG_FORMAT = "%s was missing from the current instrument map. %s. %s"; static final String INSTRUMENT_SUCCESSFULLY_ADDED_MSG = "The missing instrument was successfully added"; static final String INSTRUMENT_COULDNT_BE_ADDED_MSG = "The missing instrument couldn't be added " + "(likely because it's not supported by the MIDI standard)"; static final String INSTRUMENT_MISMATCH_FIXED_MSG = "The instrument's beats will be copied"; static final String INSTRUMENT_MISMATCH_WILL_HAVE_EFFECT_MSG = "The beats for the instrument in the pattern " + "were not blank – the sound won't be able to fully match the pattern"; static final String INSTRUMENT_MISMATCH_IRRELEVANT_MSG = "No effect on the sound is expected: the beats for the instrument were blank";
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio abstract boolean handle(InstrumentMismatchContext context); boolean tryAndAddMissingInstrument(InstrumentMismatchContext context) { String missingInstrumentName = context.name(); var beatBox = context.beatBox(); Optional<MidiInstrument> optionalInstrument = MidiInstrument.getForName(missingInstrumentName); if (optionalInstrument.isPresent()) { beatBox.addNewInstrument(optionalInstrument.get()); return true; } return false; } boolean areBeatsNonBlank(String[] beats, String checkMark) { return Arrays.asList(beats).contains(checkMark); } } PatternManifest package org.example.demos.sequencer.beatBox; public record PatternManifest(String separator, String checkMark, String blankMark) { } PressedButtonStrategy package org.example.demos.sequencer.beatBox; import javax.swing.*; public enum PressedButtonStrategy { SELECT { @Override public void apply(JCheckBox checkBox) { checkBox.setSelected(true); } }, TOGGLE { @Override public void apply(JCheckBox checkBox) { checkBox.setSelected(!checkBox.isSelected()); } }, DO_NOTHING { @Override public void apply(JCheckBox checkBox) { } }; public abstract void apply(JCheckBox checkBox); } Strategy package org.example.demos.sequencer.beatBox; public interface Strategy { String NO_ACTION_TAKEN_MSG = "No action was taken"; } Util package org.example.shared.utilities; import org.example.shared.ThrowingRunnable; import java.util.concurrent.Callable; public class Util { // irrelevant utilities omitted public static void requirePositive(int... intValues) { if (Arrays.stream(intValues).anyMatch(intValue -> intValue <= 0)) { throw new IllegalArgumentException("Values must be positive"); } }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public static void wrapInTryCatch(ThrowingRunnable codeBlock) { try { codeBlock.run(); } catch (Exception e) { throw new RuntimeException(e); } } public static <T> T wrapInTryCatchAndGet(Callable<T> returningCodeBlock) { try { return returningCodeBlock.call(); } catch (Exception e) { throw new RuntimeException(e); } } } MidiUtil package org.example.shared.utilities; import javax.sound.midi.MidiEvent; import javax.sound.midi.ShortMessage; public class MidiUtil { public static MidiEventBuilder getMidiEventBuilder() { return new MidiEventBuilder(); } public static class MidiEventBuilder { private int command; private int channel; private int firstByte; private int secondByte; private int tick; public MidiEventBuilder withCommand(int command) { this.command = command; return this; } public MidiEventBuilder withChannel(int channel) { this.channel = channel; return this; } public MidiEventBuilder withFirstByte(int firstByte) { this.firstByte = firstByte; return this; } public MidiEventBuilder withSecondByte(int secondByte) { this.secondByte = secondByte; return this; } public MidiEventBuilder withTick(int tick) { this.tick = tick; return this; } public MidiEvent build() { return Util.wrapInTryCatchAndGet(() -> { ShortMessage message = new ShortMessage(command, channel, firstByte, secondByte); return new MidiEvent(message, tick); }); } } } UIUtil (you can comment on UIUtil specifically here) package org.example.shared.utilities;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio UIUtil (you can comment on UIUtil specifically here) package org.example.shared.utilities; import lombok.NoArgsConstructor; import org.apache.commons.lang3.ArrayUtils; import org.jetbrains.annotations.NotNull; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.util.Objects; import java.util.function.Supplier; import java.util.stream.Stream; public class UIUtil { /* Since MRE rules don't apply on Code Review, I did not trim it thoroughly – only enough to fit into the character limit (which is, as of this writing, 65 536) */ private static Rectangle maximumWindowBounds; public static UIBuilder getUIBuilder() { return new UIBuilder(); } public static UIBuilder getUIBuilderWithLayout(@NotNull Supplier<LayoutManager> layoutSupplier) { Objects.requireNonNull(layoutSupplier); return new UIBuilder() .withLayout(layoutSupplier); } public static UIBuilder getUIBuilderWithContentPane(@NotNull Supplier<Container> contentPaneSupplier) { Objects.requireNonNull(contentPaneSupplier); return new UIBuilder() .withContentPane(contentPaneSupplier); } public static UIBuilder getUIBuilderWithLayoutAndContentPane(@NotNull Supplier<LayoutManager> layoutSupplier, @NotNull Supplier<Container> contentPaneSupplier) { Stream.of(layoutSupplier, contentPaneSupplier).forEach(Objects::requireNonNull); return new UIBuilder() .withLayout(layoutSupplier) .withContentPane(contentPaneSupplier); } public static ComponentBuilder getComponentBuilder(@NotNull Supplier<JComponent> componentSupplier) { Objects.requireNonNull(componentSupplier); return new ComponentBuilder(componentSupplier); }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public static void requestFocusIfBlank(JTextArea textArea, JTextArea... otherTextAreas) { Stream.of(ArrayUtils.add(otherTextAreas, textArea)) .filter(area -> area.getText().isBlank()) .forEach(JComponent::requestFocus); } public static Dimension getScreenSize() { return Toolkit.getDefaultToolkit().getScreenSize(); } public static Rectangle getMaximumWindowBounds() { if (maximumWindowBounds == null) { maximumWindowBounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); } return maximumWindowBounds; } private static void checkBounds(int width, int height) { Stream.of(width, height).forEach(Util::requirePositive); checkAgainstScreenSize(width, height); } private static void checkAgainstScreenSize(int widthOrX, int heightOrY) { var bounds = getMaximumWindowBounds(); if (bounds.width < widthOrX) { throw new IllegalArgumentException("Values like width or X coordinate cannot be greater than screen width"); } else if (bounds.height < heightOrY) { throw new IllegalArgumentException("Values like height or Y coordinate cannot be greater than screen height"); } } @NoArgsConstructor public static class UIBuilder { private final JFrame frame; private final Rectangle maximumWindowBounds = getMaximumWindowBounds(); { frame = new JFrame(); this.withFrameSize(300, 300) .withDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } private UIBuilder withLayout(@NotNull Supplier<LayoutManager> layoutSupplier) { Objects.requireNonNull(layoutSupplier); frame.setLayout(layoutSupplier.get()); return this; }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio private UIBuilder withContentPane(@NotNull Supplier<Container> contentPaneSupplier) { Objects.requireNonNull(contentPaneSupplier); frame.setContentPane(contentPaneSupplier.get()); return this; } public UIBuilder withTitle(@NotNull String title) { Objects.requireNonNull(title); frame.setTitle(title); return this; } public UIBuilder withComponent(@NotNull Supplier<JComponent> componentSupplier) { Objects.requireNonNull(componentSupplier); getAndAddToPane(componentSupplier); return this; } public UIBuilder withComponent(@NotNull String position, @NotNull Supplier<JComponent> componentSupplier) { Stream.of(position, componentSupplier).forEach(Objects::requireNonNull); getAndAddToPane(position, componentSupplier); return this; } public UIBuilder withBackgroundColor(@NotNull Color color) { Objects.requireNonNull(color); frame.getContentPane().setBackground(color); return this; } public UIBuilder withFrameSize(int width, int height) { checkBounds(width, height); int x = (maximumWindowBounds.width - width) / 2; int y = (maximumWindowBounds.height - height) / 2; frame.setBounds(x, y, width, height); // implicit frame centering return this; } private void getAndAddToPane(@NotNull Supplier<JComponent> componentSupplier) { JComponent textField = componentSupplier.get(); frame.getContentPane().add(textField); } private void getAndAddToPane(@NotNull String position, @NotNull Supplier<JComponent> componentSupplier) { JComponent textField = componentSupplier.get(); frame.getContentPane().add(position, textField); }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public UIBuilder withDefaultCloseOperation(int windowConstant) { frame.setDefaultCloseOperation(windowConstant); return this; } public UIBuilder withMenuBar(@NotNull Supplier<JMenuBar> menuBarSupplier) { Objects.requireNonNull(menuBarSupplier); frame.setJMenuBar(menuBarSupplier.get()); return this; } public UIBuilder withResizable(boolean isResizable) { frame.setResizable(isResizable); return this; } public UIBuilder withLocationRelativeTo(JComponent component) { frame.setLocationRelativeTo(component); return this; } public void visualize() { frame.setVisible(true); } } public static class ComponentBuilder { private JComponent component; public ComponentBuilder(@NotNull Supplier<JComponent> panelSupplier) { Objects.requireNonNull(panelSupplier); this.component = panelSupplier.get(); } public ComponentBuilder withBorder(@NotNull Supplier<Border> borderSupplier) { Objects.requireNonNull(borderSupplier); component.setBorder(borderSupplier.get()); return this; } public ComponentBuilder withSize(int width, int height) { checkBounds(width, height); component.setSize(width, height); return this; } public ComponentBuilder withComponent(@NotNull String position, @NotNull Supplier<JComponent> componentSupplier) { Stream.of(position, componentSupplier).forEach(Objects::requireNonNull); component.add(position, componentSupplier.get()); return this; }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public ComponentBuilder withComponent(@NotNull Supplier<JComponent> componentSupplier) { Objects.requireNonNull(componentSupplier); component.add(componentSupplier.get()); return this; } public ComponentBuilder withVerticalScrollBarPolicy(int verticalScrollbarPolicy) { makeComponentScrollableAsNeeded(); ((JScrollPane) component).setVerticalScrollBarPolicy(verticalScrollbarPolicy); return this; } public ComponentBuilder withHorizontalScrollBarPolicy(int horizontalScrollbarPolicy) { makeComponentScrollableAsNeeded(); ((JScrollPane) component).setHorizontalScrollBarPolicy(horizontalScrollbarPolicy); return this; } public ComponentBuilder withPreferredSize(@NotNull Dimension preferredSize) { Objects.requireNonNull(preferredSize); component.setPreferredSize(preferredSize); return this; } public ComponentBuilder withLocation(int x, int y) { checkBounds(x, y); component.setLocation(x, y); return this; } private void makeComponentScrollableAsNeeded() { if (!(component instanceof JScrollPane)) { component = new JScrollPane(component); } } public JComponent build() { return component; } } } ThrowingRunnable package org.example.shared; // it's really not important (you could use Junit's ThrowingRunnable or avoid it altogether), but I included it for completeness public interface ThrowingRunnable { void run() throws Exception; } App package org.example.demos.sequencer.beatBox; import static org.example.demos.sequencer.beatBox.MidiInstrument.*;
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio import static org.example.demos.sequencer.beatBox.MidiInstrument.*; public class App { public static void main(String[] args) { BeatBox beatBox = BeatBoxConfiguration.configure() .setPressedButtonStrategy(PressedButtonStrategy.SELECT) .setNumberOfBeats(10) .setCheckMark("I") // thanks to manifests, it doesn't have to be in line with read patterns' check marks .setInstruments(MARACAS, ACOUSTIC_SNARE, DRUMSTICKS) // or you can remove this line and get default instruments .build(); beatBox.launch(); } } Example pattern you can read (but you don't have to read anything to play): SEPARATOR : CHECK MARK X BLANK MARK O Acoustic Bass Drum : XOOOXOOOXOOOXOOO Closed Hi-Hat : OOXOOOXXOOXOOOXX Open Hi-Hat : OOOOOOOOOOOOOOOO Acoustic Snare : OOOOOOOOOOOOOOOO Crash Cymbal 1 : OOOOOOOOOOOOOOOO Hand Clap : OOOOOOOOOOOOOOOO High Tom : OOOOOOOOOOOOOOOO High Bongo : OOOOOOOOOOOOXXXO Maracas : XOXOXOXOXOXOXOXO Long Whistle : OOOOOOOOOOOOOOOO Low Conga : OOOOOOXOOXXOXOOO Cowbell : OOOOOOOOOOOOOOOO Vibraslap : OOOOOOOOOOOOOOOO Low-mid Tom : OOOOOOOOOOOOOOOO High Agogo : OOOOOOOOOOOOOOOO Open High Conga : OOOXXXOOOOOOXXXO What the app may look like with default settings: What do you think? Answer: Since you aren't dealing with internationalization (i18n), there is no benefit to externalising strings from the site of use to class members, as is done in IllegalPatternException.FORMAT etc. Just use the string inline. I find "some literal string".formatted() to be more natural than String.format("some format string", args...). To illustrate the above, you could have public class IllegalPatternException extends Exception { public IllegalPatternException(ManifestComponent wrongComponent) { super("The pattern file doesn't specify a valid %s or does it in an illegal format".formatted(wrongComponent)); } }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio I'm allergic to Lombok. I find that for the brevity it (sometimes) introduces, it doesn't actually help to improve the code. It encourages declaration (even if it's implicit declaration) of boilerplate accessors, when often those accessors shouldn't exist at all. Stylistically, and in a broad sense, I would recommend taking advantage of modern in-built Java features like records, and if you really don't like the verbosity of Java after that's complete, then... there's always C#, which is better in most ways (yes, I realise this is controversial) and by its design doesn't need the likes of Lombok. Here you need the non-standard org.jetbrains.annotations.NotNull; in C# this is built in. Here's an example of a reflexive declaration of a property that doesn't accomplish what it was meant to do. BeatsMismatchContext has a beats that's already final (good), but is private with a public accessor meant to prevent it from being changed. But the member is already final, so if made public still wouldn't allow it to be changed referentially; and the accessor just returns the list directly so outside callers can still change the contents of the list. So it's in an unhappy middle ground. Either weaken it, getting rid of the accessor and declaring the member public; or strengthen it - from the accessor call Collections.unmodifiableList. (If you actually need the list to be returned modifiable, that's usually a design smell.) Take for another example your IllegalPropertyException. PropertyIssue has a whatItShouldBeInstead which is a String - already immutable! So just make it public: public class IllegalPropertyException extends RuntimeException { public final PropertyIssue issue; public IllegalPropertyException(String name, PropertyIssue issue) { super("%s value is invalid: should be %s".formatted(name, issue.replacement)); this.issue = issue; }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio public enum PropertyIssue { NULL("not null"), EMPTY("not empty"), NON_POSITIVE("greater than zero"), NOT_MATCHING_REGEX("matching the regular expression"); public final String replacement; PropertyIssue(String replacement) { this.replacement = replacement; } } } whatItShouldBeInstead is an awkward name; consider instead replacement or needed. In nearly all cases you should avoid import *. Either use regular import on explicit symbols, or - don't import at all, and use fully-qualified symbol references instead. Your InstrumentFactory can be: import java.util.Arrays; import java.util.Collection; import java.util.List; public abstract class InstrumentFactory { public static Collection<MidiInstrument> getKathysInstruments() { /* Instruments used in Kathy Sierra's book Head First Java */ return List.of( MidiInstrument.ACOUSTIC_BASS_DRUM, MidiInstrument.CLOSED_HI_HAT, MidiInstrument.OPEN_HI_HAT, MidiInstrument.ACOUSTIC_SNARE, MidiInstrument.CRASH_CYMBAL_1, MidiInstrument.HAND_CLAP, MidiInstrument.HIGH_TOM, MidiInstrument.HIGH_BONGO, MidiInstrument.MARACAS, MidiInstrument.LONG_WHISTLE, MidiInstrument.LOW_CONGA, MidiInstrument.COWBELL, MidiInstrument.VIBRASLAP, MidiInstrument.LOW_MID_TOM, MidiInstrument.HIGH_AGOGO, MidiInstrument.OPEN_HIGH_CONGA ); } public static Collection<MidiInstrument> getAllInstrumentsInStandardOrder() { return Arrays.asList(MidiInstrument.values()); } }
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
java, swing, audio Note that it's been demoted to abstract since it only has statics. Similarly, ManifestParser can remove its import * and instead write String separator = parse(ManifestComponent.SEPARATOR); String checkMark = parse(ManifestComponent.CHECK_MARK); String blankMark = parse(ManifestComponent.BLANK_MARK); BeatBox is a clear example of a class with too many responsibilities, and we can see that just from looking at the imports list. This needs to be split into, at the least, a view class having Swing stuff, and a business logic or controller class having midi stuff. writeManifest, instead of writing out plus-concatenated strings and hard-coded newline codepoints, should use printf("SEPARATOR %s%n"). Of course this means you'll need to substitute BufferedWriter with a more capable interface like PrintStream. didUnsuccessfulInstrumentSettingOccur is strange. You have an error flag sitting in the configuration class state, that will get set (and overwritten!) on every call to setInstruments, and won't have any effect until build. Since all it does is produce a warning, why not just... log in place when that condition occurs, with no flag? I don't find Strategy to be a useful interface; it doesn't tell us anything about its implementers. Having MidiEvent be constructed by a builder is not crazy - in a language where there are no keyword arguments. (That is to say, in better languages, there is less need for builders because there is good support for named-argument construction.) All of that said, I see promise here, and especially if you successfully split up your view and controller then this application is not crazy.
{ "domain": "codereview.stackexchange", "id": 45057, "lm_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, swing, audio", "url": null }
c++, utf-8 Title: C++ UTF-8 decoder Question: While writing simple text rendering I found a lack of utf-8 decoders. Most decoders I found required allocating enough space for decoded string. In worse case that would mean that the decoded string would be four times as large as the original string. I just needed to iterate over characters in a decoded format so I would be able to render them on the screen, so I wrote a simple function that would allow me to do that: #include <cstdint> // unsigned integer types typedef uint64_t U64; typedef uint32_t U32; typedef uint16_t U16; typedef uint8_t U8; // signed integer types typedef int64_t I64; typedef int32_t I32; typedef int16_t I16; typedef int8_t I8; U32 NextUTF8Char(const char* str, U32& idx) { // https://en.wikipedia.org/wiki/UTF-8 U8 c1 = (U8) str[idx]; ++idx; U32 utf8c; if (((c1 >> 6) & 0b11) == 0b11) { // at least 2 bytes U8 c2 = (U8) str[idx]; ++idx; if ((c1 >> 5) & 1) { // at least 3 bytes U8 c3 = (U8) str[idx]; ++idx; if ((c1 >> 4) & 1) { // 4 bytes U8 c4 = (U8) str[idx]; ++idx; utf8c = ((c4 & 0b00000111) << 18) | ((c3 & 0b00111111) << 12) | ((c2 & 0b00111111) << 6) | (c1 & 0b00111111); } else { utf8c = ((c3 & 0b00001111) << 12) | ((c2 & 0b00111111) << 6) | (c1 & 0b00111111); } } else { utf8c = ((c1 & 0b00011111) << 6) | (c2 & 0b00111111); } } else { utf8c = c1 & 0b01111111; } return utf8c; } Usage: const char* text = u8"ta suhi škafec pušča"; U32 idx = 0; U32 c; while ((c = NextUTF8Char(text, idx)) != 0) { // c is our utf-8 character in unsigned int format } I'm currently mostly concerned about the following :
{ "domain": "codereview.stackexchange", "id": 45058, "lm_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++, utf-8", "url": null }
c++, utf-8 I'm currently mostly concerned about the following : Readability: The intent of every piece of code is clear to the reader. Correctness: Everything is working as it should (I think it's clear what should happen). Performance: Can anything be done to improve the performance of this code? Answer: // unsigned integer types typedef uint64_t U64; typedef uint32_t U32; typedef uint16_t U16; typedef uint8_t U8; // signed integer types typedef int64_t I64; typedef int32_t I32; typedef int16_t I16; typedef int8_t I8; This has instantly made the code harder to read (as well as being incorrect, since <cstdint> declares those names in the std namespace). I'm not sure why we declare so many types, when we use just two of them anyway. U32 NextUTF8Char(const char* str, U32& idx) Why not return a standard std::wchar_t? Or perhaps a char32_t? Similarly, str ought to be a const char8_t* (so that the example code compiles). I'd use a std::size_t for the index (or more likely get rid of idx altogether, and pass a reference to pointer instead). The whole thing seems like a reinventing a lot of work that's already done for you: #include <cwchar> char32_t NextUTF8Char(const char8_t*& str) { static const int max_utf8_len = 5; auto s = reinterpret_cast<const char*>(str); wchar_t c; std::mbstate_t state; auto len = std::mbrtowc(&c, s, max_utf8_len, &state); if (len > max_utf8_len) { return 0; } str += len; return c; } #include <iostream> int main() { std::locale::global(std::locale{"en_US.utf8"}); const auto* text = u8"ta suhi škafec pušča"; char32_t c; std::size_t i = 0; while ((c = NextUTF8Char(text)) != 0) { std::cout << '[' << i++ << "] = " << (std::uint_fast32_t)c << '\n'; // c is our utf-8 character in unsigned int format } } I think that std::codecvt<char32_t, char8_t, std::mbstate_t> could easily do much the same: #include <locale>
{ "domain": "codereview.stackexchange", "id": 45058, "lm_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++, utf-8", "url": null }
c++, utf-8 char32_t NextUTF8Char(const char8_t*& str) { if (!*str) { return 0; } auto &cvt = std::use_facet<std::codecvt<char32_t, char8_t, std::mbstate_t>>(std::locale()); std::mbstate_t state; char32_t c; char32_t* p = &c+1; auto result = cvt.in(state, str, str+6, str, &c, p, p); switch (result) { case std::codecvt_base::ok: return c; case std::codecvt_base::partial: return c; case std::codecvt_base::error: return 0; case std::codecvt_base::noconv: return 0; } return c; } Either is better than writing your own UTF-8 decoder.
{ "domain": "codereview.stackexchange", "id": 45058, "lm_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++, utf-8", "url": null }
python, pygame Title: Start Screen for pygame Question: I'm making a Start Screen class for my game, it has 3 buttons and they're spread out horizontally on the screen. The screen also has a scrolling background, moves from top to bottom. It's a very basic Start Screen but the code is 111 lines long. I'm sure there's a much more efficient way of doing things, any tips on how to shorten the file or do things better is very much appreciated, thank you! Code: import pygame import game import math pygame.init() def main(): fps = 60 SCREEN_WIDTH = 1000 SCREEN_HEIGHT = 700 FONT = pygame.font.SysFont("comicsans", 30) screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT)) pygame.display.set_caption("Space Avoiders") background = pygame.image.load("background1.png").convert() tiles = math.ceil(SCREEN_WIDTH / background.get_height()) + 1 clock = pygame.time.Clock() scroll = 0 def redraw_window(scroll): screen.blit(screen, (0, 0)) for i in range(-1, tiles): screen.blit(background, (0, i * background.get_height() + scroll)) def start_menu_buttons(): mouse = pygame.mouse.get_pos() #Buttons start = pygame.image.load("Sprites/Buttons/Start.jpg") start_hover = pygame.image.load("Sprites/Buttons/Start_Hover.jpg") start_rect = start.get_rect() start_x = 0 start_y = screen.get_height() / 2 start_rect.x = start_x start_rect.y = start_y settings = pygame.image.load("Sprites/Buttons/Settings.jpg") settings_hover = pygame.image.load("Sprites/Buttons/Settings_Hover.jpg") settings_clicked = pygame.image.load("Sprites/Buttons/Settings_Clicked.jpg") settings_rect = settings.get_rect() settings_x = screen.get_width()/2 - (settings_rect.width / 2) settings_y = screen.get_height() / 2 settings_rect.x = settings_x settings_rect.y = settings_y
{ "domain": "codereview.stackexchange", "id": 45059, "lm_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, pygame", "url": null }
python, pygame customize = pygame.image.load("Sprites/Buttons/Customize.jpg") customize_hover = pygame.image.load("Sprites/Buttons/Customize_Hover.jpg") customize_clicked = pygame.image.load("Sprites/Buttons/Customize_Clicked.jpg") customize_rect = customize.get_rect() customize_x = screen.get_width() - customize_rect.width customize_y = screen.get_height() / 2 customize_rect.x = customize_x customize_rect.y = customize_y start_blit = start settings_blit = settings customize_blit = customize collide_start = start_rect.colliderect(mouse, (1,1)) collide_settings = settings_rect.colliderect(mouse, (1,1)) collide_customize = customize_rect.colliderect(mouse, (1,1)) button_pressed = pygame.mouse.get_pressed()[0] if collide_start: start_blit = start_hover if collide_start and pygame.mouse.get_pressed()[0]: pygame.display.quit() game.game() if collide_settings: settings_blit = settings_hover if collide_settings and button_pressed: settings_blit = settings_clicked if collide_customize: customize_blit = customize_hover if collide_customize and button_pressed: customize_blit = customize_clicked screen.blits(((start_blit, (start_x, start_y)), (settings_blit, (settings_x, settings_y)), (customize_blit, (customize_x, customize_y)))) run = True while run: clock.tick(fps) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False break redraw_window(scroll) start_menu_buttons() pygame.display.update() scroll += 1.5 if scroll >= background.get_height(): scroll = 0 pygame.quit() if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 45059, "lm_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, pygame", "url": null }
python, pygame pygame.quit() if __name__ == "__main__": main() Answer: I believe that the most important issue with your code is that since you call start_menu_buttons() inside your loop, you end up loading all the button images again and again in every iteration of the main loop. It's much more efficient to load the buttons only once at the beginning of the function and just reference them later. Besides that, I think encapsulating the behavior of your buttons into classes would avoid a lot of code repetition, but supposing you are consciously avoiding using classes for some reason, I have a few other suggestions: 1 - One thing I usually do when loading assets for games is to find a way to load everything automatically based on a list of resources. You could do something like this, in the beginning of your main function: button_names = ["Start", "Start_Hover", "Settings", "Settings_Hover", "Settings_Clicked", "Customize", "Customize_Hover", "Customize_Clicked"] button_images = dict() for name in button_names: button_images[name] = pygame.image.load("Sprites/Buttons/{}.jpg".format(name)) And then, you would refer to your assets by their key in the dict. For example: start_rect = button_images["Start"].get_rect() 2 - Your if conditions can be organized in a more efficient and clear way. For example, you check collide_settings, and if its true, you change the value of settings_blit. Immediately below this condition, you check the truth of collide_settings again, and if button_pressed is also true, you change the value of settings_blit again. This could be replaced by: if collide_settings: if button_pressed: settings_blit = settings_clicked else: settings_blit = settings_hover Although you end up with an extra line of code, you may reduce that using Python's equivalent to a ternary operator: if collide_settings: settings_blit = settings_clicked if button_pressed else settings_hover
{ "domain": "codereview.stackexchange", "id": 45059, "lm_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, pygame", "url": null }
python, pygame 3 - For all your buttons, you define button_y as equal to screen.get_height() / 2, and then you set button_rect.y with this value. Instead, you could declare a "constant" like BUTTONS_Y = SCREEN_HEIGHT/2 and set button_rect.y directly. I believe Pygame even allows you to use this rect as the dest parameter of its blits function, ignoring its width and height and using just its coordinates.
{ "domain": "codereview.stackexchange", "id": 45059, "lm_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, pygame", "url": null }
rust, to-do-list Title: Simple Rust Todo List with auto incrementing ID Question: I have recently started learning Rust and thought I'd start out with the classic Todo List application. The application simply loops forever asking the user to type a number to do specific actions, and will quit if the corresponding action (in this case, 4) is pressed. There are comments that I think are parts of the code that need improvement, but if there is anything else then I'd be happy if you could point it out to me. use std::io; use std::process::Command; use std::str::FromStr; fn main() { // NOTE 1) Should I specify the type, even when calling the `new` function on that type? let mut todo_list: TodoList = TodoList::new(); faker_add_todos(&mut todo_list, 5); loop { clear_terminal(); println!("What would you like to do?"); println!("1. Add a new item."); println!("2. Display all items."); println!("3. Toggle item completion."); println!("4. Quit."); let choice = match read_user_input() { Ok(choice) => choice, Err(_) => continue, }; let choice: u8 = parse_string_to_int(choice, 0); clear_terminal(); match choice { 1 => { println!("Enter the name of the to-do item:"); // NOTE 2) This code is repeated a few times, should functions handle OK/Err or not? let name = match read_user_input() { Ok(name) => name, Err(_) => continue, }; let notes: String = name.trim().to_owned(); let item = TodoItem { id: todo_list.auto_increment.increment(), notes, completed: false, };
{ "domain": "codereview.stackexchange", "id": 45060, "lm_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, to-do-list", "url": null }
rust, to-do-list todo_list.items.push(item); }, 2 => { display_items(&todo_list.items); pause_terminal(); }, 3 => { println!("Enter the ID of the task you want to complete."); // NOTE 3) What could cause std::io::read_line to Err? let id: String = match read_user_input() { Ok(id) => id, Err(_) => { println!("Error reading data."); pause_terminal(); continue; }, }; let id: TodoId = match id.parse() { Ok(id) => id, Err(_) => { println!("Please enter a valid ID number."); pause_terminal(); continue; }, }; // Locate the TodoItem that has the corresponding ID. match todo_list.items.iter_mut().find(|i| i.id == id) { Some(item) => toggle_completed_item( item), _ => { println!("That ID could not be found. Please try again."); pause_terminal(); continue; }, } }, 4 => { println!("Goodbye!"); return; }, _ => { println!("Invalid choice."); pause_terminal(); }, } } } /* |------------------------------------------------------------------------------ | Terminal functions |------------------------------------------------------------------------------ | | Functions that handle interaction between the user and the Terminal, or the | system and the Terminal are stored here. | */
{ "domain": "codereview.stackexchange", "id": 45060, "lm_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, to-do-list", "url": null }
rust, to-do-list fn faker_add_todos(todo_list: &mut TodoList, count: u8) { for _ in 1..=count { todo_list.items.push(TodoItem { id: todo_list.auto_increment.increment(), notes: format!("Item {}", todo_list.auto_increment.value), completed: false, }); } } // NOTE 4) Is it acceptable to handle errors within a function, or let the calling code handle the error? fn parse_string_to_int<T: FromStr>(input: String, default: T) -> T { match input.trim().parse::<T>() { Ok(output) => output, Err(_) => default, } } // Forgive me for this horror! fn clear_terminal() { print!("{}[2J", 27 as char); } // NOTE 5) What is the best way to pause a Terminal application. fn pause_terminal() { let _ = Command::new("pause").status(); let _ = Command::new("cmd.exe").arg("/c").arg("pause").status(); } // NOTE 6) The compiler told me to write `let _` but I'm not sure what that means, it just gets rid of the error. fn read_user_input() -> Result<String, String> { let mut buffer = String::new(); let _ = io::stdin().read_line(&mut buffer); Ok(buffer.trim().to_owned()) } /* |------------------------------------------------------------------------------ | Todo List functions |------------------------------------------------------------------------------ | | These are functions that | */ fn toggle_completed_item(todo_item: &mut TodoItem) { todo_item.completed = match todo_item.completed { true => false, false => true, } } fn display_items(items: &Vec<TodoItem>) { for item in items { println!("{} - {} ({})", item.id, item.notes, item.completed); } } /* |------------------------------------------------------------------------------ | Definitions |------------------------------------------------------------------------------ | | Any structs and implementations are to be defined here. This also includes | type aliases. | */
{ "domain": "codereview.stackexchange", "id": 45060, "lm_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, to-do-list", "url": null }
rust, to-do-list // NOTE 7) Is this a common practice for IDs? // Coming from a Laravel background, the ID field was always passed into // the database as ->id() rather than the data type under the hood. type TodoId = u32; struct TodoItem { id: TodoId, notes: String, completed: bool, } struct TodoListId { value: TodoId, } impl TodoListId { // NOTE 8) Is it good practice to specify the return type, if we are immediately returning that type? fn new() -> TodoListId { TodoListId { value: 0 } } fn increment(&mut self) -> TodoId { self.value += 1; self.value } } struct TodoList { auto_increment: TodoListId, items: Vec<TodoItem>, } impl TodoList { fn new() -> TodoList { TodoList { auto_increment: TodoListId::new(), items: Vec::new(), } } } ``` Answer: NOTE 1) Should I specify the type, even when calling the new function on that type? let mut todo_list: TodoList = TodoList::new(); No, if the type is clear from the expression, TodoList::new(), don't repeat the type. In general, its pretty rare to explicitly label the type except when required because the type cannot be inferred. NOTE 2) This code is repeated a few times, should functions handle OK/Err or not? let name = match read_user_input() { Ok(name) => name, Err(_) => continue, }; It depends on the error. Can the function do something useful with the error? Can the calling function do something useful with the error? In this case, I'd say there really isn't anything useful to do in an error condition. I'd suggest using the color_eyre or anyhow crate to define an error type and having main return a color_eyre::Result<()> or anyhow::Result<()> type. Then you can just use the ? operator to terminate the program and print the error if it happens.
{ "domain": "codereview.stackexchange", "id": 45060, "lm_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, to-do-list", "url": null }
rust, to-do-list NOTE 3) What could cause std::io::read_line to Err? let id: String = match read_user_input() { Not much in practical situations. You could get an error if the standard input was closed or something like that. NOTE 4) Is it acceptable to handle errors within a function, or let the calling code handle the error? It depends on the error, can you do something sensible? In this case, falling back to a default value if the text could not be parsed seem a bit strange. That's rarely a useful way to handle an error. match input.trim().parse::<T>() { Ok(output) => output, Err(_) => default, } I'd do input.trim().parse::<T>().unwrap_or(default) I'd also probably not have a distinct function just for this. // Forgive me for this horror! fn clear_terminal() { print!("{}[2J", 27 as char); } You might be interested in the crossterm crate which gives you functions to manipulate the terminal in cross-platform manner. // NOTE 5) What is the best way to pause a Terminal application. fn pause_terminal() { let _ = Command::new("pause").status(); let _ = Command::new("cmd.exe").arg("/c").arg("pause").status(); } Calling out to the pause command on windows work (on windows), but is a bit of a kludge. You could simply read a line and request the user push enter (instead of any key). If you want to wait for the user to push any key, you'll need to use something like crossterm to get lower level access to the terminal. // NOTE 7) Is this a common practice for IDs? // Coming from a Laravel background, the ID field was always passed into // the database as ->id() rather than the data type under the hood. type TodoId = u32; I myself would use struct TodoId(u32) The distinction is that TodoId and u32 would be different types. Then I can't accidently pass some other u32 as a TodoId // NOTE 8) Is it good practice to specify the return type, if we are immediately returning that type? fn new() -> TodoListId { TodoListId { value: 0 } }
{ "domain": "codereview.stackexchange", "id": 45060, "lm_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, to-do-list", "url": null }
rust, to-do-list You don't have a choice here. Rust won't infer the return type of a function.
{ "domain": "codereview.stackexchange", "id": 45060, "lm_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, to-do-list", "url": null }
c++, time-limit-exceeded, vectors, binary-search-tree Title: Market Portfolio Binary Search Tree Question: I'm trying to solve the following problem here: First line of input contains the number of days D. The next d lines contains a character c and a number x. If c is B, then buy stock . If c is S, then sell stock x if it is present. If c is R, then ask if the stock x was present in his portfolio. For each of the days of type R x, print "YES" (without the quotes) if the stock x is present in the portfolio else print "NO" (without the quotes). The criteria for implementing the above question is to just use the following three ```cpp`` libraries: iostream, cstdlib, vector Thus my question to optimise the time using the binary search tree. My code for the same is: #include <iostream> #include <vector> int main() { int D; std::cin >> D; std::vector<int> portfolio; while (D--) { char c; int x; std::cin >> c >> x; if (c == 'B') { // Buy stock portfolio.push_back(x); } else if (c == 'S') { // Sell stock if it is present for (int i = 0; i < portfolio.size(); ++i) { if (portfolio[i] == x) { portfolio.erase(portfolio.begin() + i); break; // Found and sold the stock, so break the loop } } } else if (c == 'R') { // Check if the stock is present in the portfolio bool found = false; for (int i = 0; i < portfolio.size(); ++i) { if (portfolio[i] == x) { found = true; break; // Found the stock, so break the loop } } if (found) { std::cout << "YES" << std::endl; } else { std::cout << "NO" << std::endl; } } } return 0; }
{ "domain": "codereview.stackexchange", "id": 45061, "lm_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++, time-limit-exceeded, vectors, binary-search-tree", "url": null }
c++, time-limit-exceeded, vectors, binary-search-tree return 0; } I'm maintaining the portfolio here using a vector, but the issue I feel is time complexity will be affected at the stage when we search for the stock in the portfolio. If it is added at the end, the loop will traverse all the way when this can be optimized if we just maintain a binary search tree. I was hoping to get a BST implementation of the same. To add, the exact language of the question is: For each of the d days, Avi meets one person among Bansal, Shrey, or Radha. If he meets Bansal on ith day, he advises him to buy the stock s; and if Avi doesn't already have that stock in his portfolio then he buys it. If he meets Shrey on ith day, he advises him to sell the stock si and if he has that stock in his portfolio, he sells that stock. If he meets Radha on ith day she asks him to check if the stock s; is present in his portfolio. Help Avi maintain his stock portfolio and answer all the queries asked by Radha. Input Format First line of input contains the number of days D. The next d lines contains a character c and a number x. If c is B, then Avi met Bansal and got advice to buy stock x. If c is S, then Avi met Shrey and got advice to sell stock x. If c is R, then Avi met Radha and was asked if the stock x was present in his portfolio. Constraints 1<=d <= 2*10^5 C=B|S|R 1<=x<=10^9 Output Format For each of the days of type R x, print "YES" (without the quotes) if the stock x is present in the portfolio else print "NO" (without the quotes). Answer: #include <iostream> #include <vector> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} };
{ "domain": "codereview.stackexchange", "id": 45061, "lm_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++, time-limit-exceeded, vectors, binary-search-tree", "url": null }
c++, time-limit-exceeded, vectors, binary-search-tree TreeNode* insertIntoBST(TreeNode* root, int val) { if(root == NULL) return new TreeNode(val); TreeNode *curr = root; while(true){ if(val < curr->val){ if(curr->left != NULL) curr = curr->left; else{ curr->left = new TreeNode(val); break; } } else{ if(curr->right != NULL) curr = curr->right; else{ curr->right = new TreeNode(val); break; } } } return root; } bool searchBST(TreeNode* root, int val) { if(root == NULL) return false; if(root->val == val) return true; else if(val < root->val) return searchBST(root->left, val); else return searchBST(root->right, val); return false; } TreeNode* deleteNode(TreeNode* root, int key) { if(root != NULL){ if(key < root->val) root->left = deleteNode(root->left, key); else if(key > root->val) root->right = deleteNode(root->right, key); else{ if(root->left == NULL && root->right == NULL) return NULL; if (root->left == NULL || root->right == NULL) return root->left ? root->left : root->right; TreeNode* temp = root->left; while(temp->right != NULL) temp = temp->right; root->val = temp->val; root->left = deleteNode(root->left, temp->val); } } return root; } int main() { int D; std::cin >> D; TreeNode* portfolio = nullptr; while (D--) { char c; int x; std::cin >> c >> x;
{ "domain": "codereview.stackexchange", "id": 45061, "lm_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++, time-limit-exceeded, vectors, binary-search-tree", "url": null }