text
stringlengths
1
2.12k
source
dict
performance, c, simd // I need a review for this section. __m256d start_v = _mm256_set1_pd(start); __m256d step_size_v = _mm256_set1_pd(step_size); for (int i = 0; i < alignedElementsCount; i += 4) { __m256d temp_v = _mm256_add_pd(start_v, _mm256_set_pd( step_size * (i + 3), step_size * (i + 2), step_size * (i + 1), step_size * (i + 0))); _mm256_store_pd(&data[i], temp_v); } data[elementsCount] = end; return (NativeFixedDArray_t) { elementsCount, data }; } // Here is driver program to test the functions. int main() { NativeFixedDArray_t range1 = generate_range(0, 0.0002, 4.5); NativeFixedDArray_t range2 = generate_range_simd(0, 0.0002, 4.5); for (int i = 0; i < range1.length; ++i) { double value1 = range1.memory_block[i]; double value2 = range2.memory_block[i]; if (value1 != value2) { printf("Not equal!\n"); break; } printf("range1[%d]: %lf, range2[%d]: %lf\n", i, value1, i, value2); } return 0; } Answer: set functions such as _mm256_set_pd here are not efficient when the inputs are variable. That can be OK to do once, but here it's in a loop, and GCC 13.1 (with -O2 -mavx2) generated such code: lea eax, [rsi+2] lea ecx, [rsi+1] vmovd xmm5, esi lea edi, [rsi+3] vmovd xmm3, eax vpinsrd xmm1, xmm5, ecx, 1 vpinsrd xmm3, xmm3, edi, 1 vpunpcklqdq xmm1, xmm1, xmm3 vcvtdq2pd ymm1, xmm1 vmulpd ymm1, ymm1, ymm4 GCC was a bit clever here, vectorizing the multiplication. But not clever enough, this is still expensive. Other compilers may do different things but they don't do a particularly good job with this either. As alternatives, you could consider:
{ "domain": "codereview.stackexchange", "id": 44706, "lm_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, c, simd", "url": null }
performance, c, simd Initializing start_v to 4 successive values (instead of 4 equal values) and adding step_size * 4 to it in every iteration. This is essentially equivalent to how the scalar code implementation works. Using the same integer index to float conversion, multiplied by the step size, but doing the whole thing with vector operations. This is more expensive than the first option, but still better than the current code, and this way there is no build-up of floating point inaccuracy as there is from adding floats in a loop. When using the first option, you may notice that it's not as fast as it looks, that's because the floating point addition is on the critical path. That can be worked around by unrolling the loop by up to a factor of 2 to 4 (you can go higher but there shouldn't be a benefit), using as many separate accumulators as the unroll factor. As an example, after unrolling by 2: __m256d x0_v = _mm256_set_pd( start + step_size * 3, start + step_size * 2, start + step_size * 1, start + step_size * 0); __m256d x1_v = _mm256_set_pd( start + step_size * 7, start + step_size * 6, start + step_size * 5, start + step_size * 4); __m256d step_size_v = _mm256_set1_pd(step_size * 8); for (int i = 0; i < alignedElementsCount; i += 8) { _mm256_storeu_pd(&data[i], x0_v); _mm256_storeu_pd(&data[i + 4], x1_v); x0_v = _mm256_add_pd(x0_v, step_size_v); x1_v = _mm256_add_pd(x1_v, step_size_v); } By the way I changed the stores to unaligned, because the malloc'ed memory may not be sufficiently aligned. It would be better to use an aligned allocation such as _mm_malloc or aligned_alloc etc.
{ "domain": "codereview.stackexchange", "id": 44706, "lm_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, c, simd", "url": null }
python, algorithm, functional-programming Title: Optimizing a function to find the closest multiple of 10 Question: I have written a Python function called closest_multiple_10() which takes an integer as input and returns the closest multiple of 10. The function works as expected, but its execution time is quite long, and I'm looking for ways to optimize it. Below is my current implementation: def closest_multiple_10(i): a = i b = i j = 0 c = 0 while a/10 != a//10: j+=1 a+=1 while b/10 != b//10: c+=1 b-=1 if j>c: return i-c else: return i+j I'm seeking suggestions for improvements in the code to make it more efficient and reduce the execution time. Any tips or alternative solutions would be greatly appreciated. Answer: There is a very easy solution to this problem. The algorithm is: Get remainder of number with modulo by 10 If remainder is less than 5, return number minus remainder Else, return number + (10 - remainder) def closest_multiple_10(x): rem = x % 10 return x - rem if rem < 5 else x + (10 - rem) You can even expand this function to take in any multiple. def closest_multiple(x, mul): rem = x % mul return x - rem if rem < (mul / 2) else x + (mul - rem)
{ "domain": "codereview.stackexchange", "id": 44707, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, functional-programming", "url": null }
c#, xml Title: C# addXmlDefinition method Question: I have this methods that take in a xml file and add XDeclaration for utf-8. I want to optimize the code because it need to XDocument.Parse and then XDeclaration. It also needs to XDocument.save. Any help would be great. private static string addXmlDefinition(string xmlContent) { string xml = Encoding.UTF8.GetString(Encoding.Default.GetBytes(xmlContent)); var wr = new StringWriter(); XDocument xdoc = XDocument.Parse(xml); xdoc.Declaration = new XDeclaration("1.0", "utf-8", null); xdoc.Save(wr); return wr.ToString(); } Answer: Why don't you simply do this? private static readonly string declaration = new XDeclaration("1.0", "utf-8", null).ToString(); private static string addXmlDefinition(string xmlContent) => string.Join(Environment.NewLine, new [] { declaration, xmlContent }); Define the XML Declaration only once and reuse it Concat the declaration string and the content Use new line as a delimiter between them
{ "domain": "codereview.stackexchange", "id": 44708, "lm_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#, xml", "url": null }
r, machine-learning, neural-network Title: Optimize an algorithm for preparing a dataset for machine learning Question: I'm learning how to use R coming from a python background. I'm following Andrej Karpathy's zero-to-hero course, reimplementing it in R. We start with a list of 32033 names. These names have to be broken into a format digestible by the network. For example, if the first name in the dataset is emma, we would represent it as such: X | Y ________ ... | e ..e | m .em | m emm | a mma | . ... | etc Although each character is represented as a number so they can later be stored as a tensor. I've written the following alogrithm to do so: XS <- vector("list",length(data)*block_size*2) YS <- vector("numeric",length(data)+1) stoi <- setNames(0:26,c('.',letters)) i = 1 for (item in data) { context <- rep(0,block_size) for (ch in strsplit(item,"")[[1]]) { ch <- stoi[ch] XS[[i]] <- context YS[[i]] <- ch context <- c(context[-1],ch) i <- i + 1 } } return(list(XS,YS)) } I would really appreciate any feedback on how to write more performant and idiomatic code in R that can accomplish this better than my implementation. Thank you. Answer: Right now your code basically loops through words to process. For each word, it first uses strsplit to split it into characters, and then it loops through each character, maintaining a running vector of the last block_size characters it has encountered. It iteratively stores the running vectors into a list, which it eventually returns. A few thoughts on this code:
{ "domain": "codereview.stackexchange", "id": 44709, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "r, machine-learning, neural-network", "url": null }
r, machine-learning, neural-network Since each of your blocks is of the same size (as determined by your block_size variable), it would make more sense to me to actually build a matrix instead of a list. Probably you will find the matrix easier and faster to work with. In R we strive to identify pre-implemented, vectorized code that does what we are working to accomplish. Usually this involves some amount of searching around to find the correct function. In your case, it turns out that there is a built-in function called embed that does basically what you're asking. For instance, here is the output for your "emma" example, with block size 3, where we separately compute the contributions to X and Y as defined in your question: word <- "emma" block_size <- 3 (wordLetters <- c(rep(".", block_size), strsplit(word, "")[[1]])) # [1] "." "." "." "e" "m" "m" "a" (Xpart <- embed(wordLetters, block_size)[,block_size:1]) # [,1] [,2] [,3] # [1,] "." "." "." # [2,] "." "." "e" # [3,] "." "e" "m" # [4,] "e" "m" "m" # [5,] "m" "m" "a" (Ypart <- c(strsplit(word, "")[[1]], ".")) # [1] "e" "m" "m" "a" "." Once we have things working for one word, we can simply loop to combine them together across all the words we need to process. I'll also include the actual conversion to numbers (via stoi) as you defined in your code: data <- c("emma", "hello") block_size <- 3 stoi <- setNames(0:26,c('.',letters)) (XS <- do.call(rbind, lapply(data, function(word) { wordLetters <- stoi[c(rep(".", block_size), strsplit(word, "")[[1]])] embed(wordLetters, block_size)[,block_size:1] }))) # [,1] [,2] [,3] # [1,] 0 0 0 # [2,] 0 0 5 # [3,] 0 5 13 # [4,] 5 13 13 # [5,] 13 13 1 # [6,] 0 0 0 # [7,] 0 0 8 # [8,] 0 8 5 # [9,] 8 5 12 # [10,] 5 12 12 # [11,] 12 12 15 (YS <- unlist(lapply(data, function(word) { unname(stoi[c(strsplit(word, "")[[1]], ".")]) }))) # [1] 5 13 13 1 0 8 5 12 12 15 0
{ "domain": "codereview.stackexchange", "id": 44709, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "r, machine-learning, neural-network", "url": null }
c++, c++20 Title: Custom binary file format serializer Question: I am creating a binary file format to store a series of vectors alongside some metadata. The vectors will be stored at the start of the file which will have a predetermined size, and the metadata alongside the size of each vector will go to the end. data = {{1, 2, 3}, {5, 6, 7}} metadata = {'1011', '1110'} file: --> 1235670000 0000000000 0000000000 3111031011 <-- So every time I need a new vector I will read the next available metadata block and size, e.g., 31011, that tells me I need to get 3 items from the current position at the top of the file and so I will end up returning ({1, 2, 3}, '1011') The idea I want to test is if storing all my data in contiguous memory addresses will take advantage of caching and speed things up a bit if I have a very large amount of vectors to be used by an off memory algorithm. My implementation is a .h file containing my class: #pragma once #include <fstream> #include <utility> #include <vector> #include <filesystem> #include <bitset>
{ "domain": "codereview.stackexchange", "id": 44710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 #include <fstream> #include <utility> #include <vector> #include <filesystem> #include <bitset> class BinaryFile { public: // TODO: metadataWritePos_{static_cast<std::streamoff>(maxFileSize - metadataSize_ - 1)}, am I wasting one bit? // TODO: store the number of vectors in the file to resume write/read from a different instance BinaryFile(std::string filename, std::size_t maxFileSize, std::size_t metadataSize) : filename_{std::move(filename)}, maxFileSize_{maxFileSize}, metadataSize_{metadataSize + sizeof(long)}, metadataWritePos_{static_cast<std::streamoff>(maxFileSize - metadataSize_)}, metadataReadPos_{static_cast<std::streamoff>(maxFileSize - metadataSize_)} { file_.open(filename_, std::ios::binary | std::ios::in | std::ios::out); if (!file_.is_open()) { // If the file does not exist, create it. file_.open(filename_, std::ios::binary | std::ios::out); file_.close(); // Re-open the file in binary mode for both reading and writing. file_.open(filename_, std::ios::binary | std::ios::in | std::ios::out); } } // TODO: accept a vector of `T` as the data type. template <std::size_t N> bool write(const std::vector<int> &data, std::bitset<N> metadata) { if (file_.is_open()) { // Check if there is enough space at the beginning and end of the file. const auto dataSize = data.size() * sizeof(int); const auto totalSize = dataSize + metadataSize_; const auto curPos = dataWritePos_; const auto spaceAvailable = static_cast<std::size_t>(metadataWritePos_ - curPos); if (spaceAvailable < totalSize) { return false; } // Write the data to the file. file_.seekp(curPos); file_.write(reinterpret_cast<const char *>(data.data()), static_cast<std::streamoff>(dataSize));
{ "domain": "codereview.stackexchange", "id": 44710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 // Write the metadata to the end of the file. const std::streampos metadataPos = metadataWritePos_; file_.seekp(metadataPos); file_.write(reinterpret_cast<const char*>(&metadata), static_cast<std::streamoff>(metadataSize_ - sizeof(long))); file_.write(reinterpret_cast<const char*>(&dataSize), sizeof(long)); // Update the data & metadata position for the next write. metadataWritePos_ -= static_cast<std::streamoff>(metadataSize_); dataWritePos_ += static_cast<std::streamoff>(dataSize); return true; } return false; } template <std::size_t N> std::pair<std::vector<int>, std::bitset<N>> readNext() { std::pair<std::vector<int>, std::bitset<N>> result; if (file_.is_open()) { const std::streampos curPos = file_.tellg(); if (metadataWritePos_ <= metadataReadPos_) { // Read the metadata hash and vector size from the end of the file. std::size_t dataSize; const auto metadataPos = metadataReadPos_; file_.seekg(metadataPos); file_.read(reinterpret_cast<char *>(&result.second), static_cast<std::streamoff>(metadataSize_ - sizeof(long))); file_.read(reinterpret_cast<char *>(&dataSize), sizeof(long)); // Read the data from the current position. const std::size_t elementCount = dataSize / sizeof(int); result.first.resize(elementCount); file_.seekg(dataReadPos_); file_.read(reinterpret_cast<char *>(std::get<0>(result).data()), static_cast<std::streamoff>(dataSize)); // Update the metadata position for the next read. metadataReadPos_ -= static_cast<std::streamoff>(metadataSize_); dataReadPos_ += static_cast<std::streamoff>(dataSize); } } return result; }
{ "domain": "codereview.stackexchange", "id": 44710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 // TODO: is there a better way to keep track of these values between instance? std::streamoff getLastWritenPosition() const { return metadataWritePos_; } void setLastWritenPosition(std::streamoff pos) { metadataWritePos_ = pos; } private: std::string filename_; std::size_t maxFileSize_; std::size_t metadataSize_; std::streamoff metadataWritePos_; std::streamoff metadataReadPos_; std::streamoff dataWritePos_{}; std::streamoff dataReadPos_{}; std::fstream file_; }; and I am using it in this way: #include <iostream> #include <vector> #include <numeric> #include "serializer.h" #define HASH_SIZE 4 void test_write_multiple() { // Create a binary writer with some data. const std::string filename = "test.bin"; const std::size_t maxFileSize = 1024; BinaryFile writer(filename, maxFileSize, sizeof(std::bitset<HASH_SIZE>)); const std::vector<std::vector<int>> data = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {3, 2, 1} }; const std::vector<std::bitset<HASH_SIZE>> metadata = { std::bitset<4>("0101"), // equivalent to decimal value 5 std::bitset<4>("1100"), // equivalent to decimal value 12 std::bitset<4>("0000"), // equivalent to decimal value 0 std::bitset<4>("1111") // equivalent to decimal value 15 }; for (std::size_t i = 0; i < data.size(); ++i) { if (!writer.write(data[i], metadata[i])) { std::cout << "::Write failed due to max writer size.\n"; return; } } // Create a reader to get the original data back. BinaryFile reader(filename, maxFileSize, sizeof(std::bitset<HASH_SIZE>)); reader.setLastWritenPosition(writer.getLastWritenPosition());
{ "domain": "codereview.stackexchange", "id": 44710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 for (std::size_t i = 0; i < data.size(); ++i) { const auto [readData, readMetadata] = reader.readNext<HASH_SIZE>(); // Check that the read data matches the original data. if (readData != data[i]) { std::cout << "::Read data does not match original data.\n"; return; } // Check that the read metadata matches the original metadata. if (readMetadata != metadata[i]) { std::cout << "::Read metadata does not match original metadata.\n"; return; } } std::cout << "Multiple write test done.\n"; } Are there any obvious mistakes, any optimizations I could have performed. Is the design even any good, or should I structure the class and the data it handles differently? Answer: It's hard to create unit tests for this code, as we can't separate out the use of actual filesystem files from the logic. A more testable implementation would accept an open seekable stream, so that we could use a string-stream in the unit tests. That's something we'd naturally end up with if we wrote some tests before starting the implementation. Speaking of file streams, I can't see where we check that writes and reads are successful. We seem to report success if the file can be merely opened, regardless of whether any subsequent operations succeed or not. Perhaps we should be calling the stream's exceptions() to cause it to throw on failure?
{ "domain": "codereview.stackexchange", "id": 44710, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, networking, bitwise Title: Access integer field in network packet Question: I see three complexities in accessing (reading/writing) integer field in network packet. Handle endianness. Integer in network packet is big-endian (BE). The host may be either big-endian or little-endian (LE). The integer may have a bit width that is not a multiple of 8. E.g., IPv4 fragment offset has 13 bits. The integer may not align to byte boundary. I authored a group of functions to help with the task. I'm not quite confident in this and seeking comments in terms of interface design (you may find my current one odd), correctness, performance. Pertaining to correctness, I know my code fails for cases like "4 bits + 7 bytes + 4 bits". It's a legit input for the payload fits into a 64-bit uint. I cannot come up with an algorithm that handles this without sacrificing too much performance. So I decided not to support it. As an example, for IPv4 fragment offset, we have len = 2, hishf = 3, and loshf = 0. #include <cstdint> #include <cstring> #include <bit> #include <ostream> #include <format> namespace net { using byte_t = std::uint8_t; using uint_t = std::uint64_t; static_assert( std::endian::native == std::endian::little || std::endian::native == std::endian::big ); // Network byte order (big-endian) // // +------------+------+------------+ // | hishf bits | uint | loshf bits | // ^------------+------+------------^ // | | // data (data + len) in byte constexpr unsigned hishf_lead = (sizeof(unsigned) - 1) * 8; template <unsigned len, unsigned hishf = 0, unsigned loshf = 0> struct uint_view { byte_t* data; operator uint_t() const noexcept { if constexpr (std::endian::native == std::endian::big) { return parse_uint_be(); } else { return parse_uint_le(); } }
{ "domain": "codereview.stackexchange", "id": 44711, "lm_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++, networking, bitwise", "url": null }
c++, networking, bitwise void operator=(uint_t uint) const noexcept { if constexpr (std::endian::native == std::endian::big) { write_uint_be(uint); } else { write_uint_le(uint); } } private: static_assert(2 <= len && len <= sizeof(uint_t)); static_assert(hishf <= 7 && loshf <= 7); constexpr static unsigned hi_uint_mask = unsigned(-1) << hishf_lead << hishf >> hishf >> hishf_lead; constexpr static unsigned hi_data_mask = ~hi_uint_mask << hishf_lead >> hishf_lead; constexpr static unsigned lo_uint_mask = unsigned(-1) << hishf_lead >> hishf_lead >> loshf << loshf; constexpr static unsigned lo_data_mask = ~lo_uint_mask << hishf_lead >> hishf_lead; uint_t parse_uint_le() const noexcept { uint_t uint{}; auto dst = (byte_t*)(&uint); auto src = data + (len - 1); do { *dst++ = *src--; } while (src > data); *dst = *src & hi_uint_mask; return uint >> loshf; } uint_t parse_uint_be() const noexcept { uint_t uint{}; auto dst = (byte_t*)(&uint) + (sizeof(uint_t) - len); auto src = data; *dst++ = *src++ & hi_uint_mask; std::memcpy(dst, src, len - 1); return uint >> loshf; } void write_uint_le(uint_t uint) const noexcept { uint <<= loshf; auto dst = data + (len - 1); auto src = (byte_t const*)(&uint); *dst = (*dst & lo_data_mask) | (*src & lo_uint_mask); --dst; ++src; while (dst > data) { *dst-- = *src++; } *dst = (*dst & hi_data_mask) | (*src & hi_uint_mask); }
{ "domain": "codereview.stackexchange", "id": 44711, "lm_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++, networking, bitwise", "url": null }
c++, networking, bitwise void write_uint_be(uint_t uint) const noexcept { uint <<= loshf; auto dst = data; auto src = (byte_t const*)(&uint) + (sizeof(uint_t) - len); *dst = (*dst & hi_data_mask) | (*src & hi_uint_mask); std::memcpy(++dst, ++src, len - 2); dst += len - 2; src += len - 2; *dst = (*dst & lo_data_mask) | (*src & lo_uint_mask); } }; template <unsigned hishf, unsigned loshf> struct uint_view<1, hishf, loshf> { byte_t* data; operator uint_t() const noexcept { return (*data & uint_mask) >> loshf; } void operator=(uint_t uint) const noexcept { uint <<= loshf; *data = (*data & data_mask) | (uint & uint_mask); } private: static_assert(hishf <= 7 && loshf <= 7); static_assert(hishf + loshf <= 7); constexpr static unsigned uint_mask = unsigned(-1) << hishf_lead << hishf >> hishf >> hishf_lead >> loshf << loshf; constexpr static unsigned data_mask = ~uint_mask << hishf_lead >> hishf_lead; }; // _ _ _ _ _ _ _ _ // pos 0 1 2 3 4 5 6 7 template <unsigned pos> using bit_view = uint_view<1, pos, 7 - pos>; template <unsigned len, unsigned hishf, unsigned loshf> inline std::ostream& operator<<(std::ostream& os, uint_view<len, hishf, loshf> view) { return os << uint_t(view); } } // namespace net template <unsigned len, unsigned hishf, unsigned loshf> struct std::formatter<net::uint_view<len, hishf, loshf>>: formatter<net::uint_t> { auto format(net::uint_view<len, hishf, loshf> view, format_context& ctx) { return formatter<net::uint_t>::format(view, ctx); } }; Answer: Handling corner cases Pertaining to correctness, I know my code fails for cases like "4 bits + 7 bytes + 4 bits". It's a legit input for the payload fits into a 64-bit uint.
{ "domain": "codereview.stackexchange", "id": 44711, "lm_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++, networking, bitwise", "url": null }
c++, networking, bitwise This is something that probably will not ever happen. Protocols are usually designed such that values naturally align as best as possible, so in a sane design the two 4 bit fields would be packed together in one byte, and also likely so the 7 byte field would only need to have a mask applied, and not a shift. That said: I cannot come up with an algorithm that handles this without sacrificing too much performance. So I decided not to support it. First of all, your class uint_view is templated, so you can just use if constexpr to keep the fast code fast, so there is no need to sacrifice any performance. Second, it should not be a problem to support this. It's just a shift and a mask of 64-bit values. The issue you are having is that you are calculating the mask in the wrong way: Calculating masks The way you are calculating the masks is way too complicated. Instead of using unsigned(-1), use UINT64_MAX to get a 64-bit value with all one-bits, and shift that as necessary. You should also need just one mask: constexpr std::uint64_t mask = (UINT64_MAX << (loshf + hishf)) >> hishf;
{ "domain": "codereview.stackexchange", "id": 44711, "lm_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++, networking, bitwise", "url": null }
c++, networking, bitwise You just apply that mask to the whole 64-bit value, and then shift the value left or right as necessary. To get the inverse of the mask, just write ~mask. Don't create aliases for standard types Creating a type alias uint_t is not helpful. It sounds like "unsigned integer", so if I didn't know any better I would assume it's only 32 bits on most platforms. I now have to look at the definition to find out it's actually 64 bits. I recommend you use std::uint64_t everywhere instead; it's not that much more to type, and now there is no chance of any confusion. The same goes for byte_t. Even better than using std::uint8_t though, there is a std::byte since C++17. Avoid code duplication You have two versions of the parse_*() and write_*() functions. I think it would be nicer to split the byte swapping from the shifting and masking. In particular, see if you can write those functions like so: // Do things before swapping uint64_t value; … // Do the swap if constexpr (std::endian::native == std::endian::little) { value = std::byteswap(value); } // Do things needed after swapping … Here I'm using C++23's std::byteswap(), if you can't use that yet you can provide your own function that swaps bytes. Const issues Your write_*() member functions are marked const. While technically you are not modifying any member variable of uint_view itself, consider what happens if you parse a value, write to it, then parse it again. Can the compiler optimize out the second call to the parse function and assume it returns the same value is the first time it was called? Your class also doesn't handle views of const network packets. While you could create a class const_uint_view, that would result in a lot of duplication. Another option would be to make it a template, like std::span, where the constness of the data viewed is captured by the template parameter.
{ "domain": "codereview.stackexchange", "id": 44711, "lm_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++, networking, bitwise", "url": null }
python, algorithm, array Title: Determine whether two arrays have the same elements with the same multiplicities Question: I have written a Python function called comp that checks whether two given arrays have the same elements, with the same multiplicities. The multiplicity of a member is the number of times it appears in the array. I would like to post my code here for review, so that I can optimize it and receive any advice on how to improve it. Here's the code for the function: def comp(array1, array2): c = 0 ta = [] if len(array1) == 0 or len(array2) == 0: return None for i in range(len(array2)): for j in range(len(array2)): if array2[i] != array1[j] * array1[j]: c += 1 ta.append(c) c = 0 if len(array1) in ta: return False else: return True I would appreciate any suggestions or advice on how to improve the code's efficiency, readability, or any other best practices that I might be missing. Answer: for i in range(len(array2)): for j in range(len(array2)): if array2[i] != array1[j] * array1[j]: c += 1 The multiplicity of a member is the number of times it appears in the array. Either the problem is ill-specified, or the code is wrong. When the lengths of array{1,2} differ, we either ignore many entries or we raise IndexError. It is very surprising for a bool predicate to return None. Consider using mypy to help you lint this code.
{ "domain": "codereview.stackexchange", "id": 44712, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, array", "url": null }
python, algorithm, array The identifier c apparently means "count". Take the opportunity to spell that out more fully. What were you thinking when you chose the identifier ta?? What should I think when I read it? No idea what's behind that decision. Rename it before merging down to main. You chose a list datastructure for something that we only do an in test on. Ordinarily I would encourage switching it to a set, for O(1) constant lookup speed. But given the crazy quadratic complexity of that loop, it's lost in the noise. Instead you should focus on choosing a sensible algorithm with complexity O(N log N) or better. Given the lack of unit tests and poor level of specification / documentation, I would not be willing to delegate or accept maintenance tasks on this code base.
{ "domain": "codereview.stackexchange", "id": 44712, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, array", "url": null }
c++, algorithm, simd Title: Search function using SIMD Question: I wrote a search function, similar to std::find, that uses SIMD instructions. Since I am new to SIMD, I would appreciate comments on other SIMD instructions I have missed that would be useful for this use case, possible corner cases I have overlooked, and best practices in using SIMD and C++ in general. #pragma once #include <immintrin.h> #include <cstddef> #include <cstdint> #include <iterator> #include <memory> #include <type_traits> namespace simd { using vec256i = __m256i; using vec256f = __m256; using vec256d = __m256d; template <std::size_t WIDTH> [[nodiscard]] inline __attribute__((always_inline)) vec256i compare(const vec256i& lhs, const void* const rhs) { static_assert(WIDTH == 1 || WIDTH == 2 || WIDTH == 4 || WIDTH == 8); if constexpr (WIDTH == 1) { return _mm256_cmpeq_epi8(lhs, _mm256_loadu_epi8(rhs)); } else if (WIDTH == 2) { return _mm256_cmpeq_epi16(lhs, _mm256_loadu_epi16(rhs)); } else if (WIDTH == 4) { return _mm256_cmpeq_epi32(lhs, _mm256_load_epi32(rhs)); } else if (WIDTH == 8) { return _mm256_cmpeq_epi64(lhs, _mm256_load_epi64(rhs)); } else { return vec256i{0}; } } template <std::size_t WIDTH> [[nodiscard]] inline __attribute__((always_inline)) std::uint32_t compress_mask(const vec256i& mask) { static_assert(WIDTH == 1 || WIDTH == 2 || WIDTH == 4 || WIDTH == 8); if constexpr (WIDTH == 1 || WIDTH == 2) { return _mm256_movemask_epi8(mask); } else if (WIDTH == 4) { return _mm256_movemask_ps(reinterpret_cast<vec256f>(mask)); } else if (WIDTH == 8) { return _mm256_movemask_pd(reinterpret_cast<vec256d>(mask)); } else { return 0; } }
{ "domain": "codereview.stackexchange", "id": 44713, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, simd", "url": null }
c++, algorithm, simd template <std::size_t WIDTH> [[nodiscard]] inline __attribute__((always_inline)) std::uint32_t ctz_ui128(const std::uint32_t& mask4, const std::uint32_t& mask3, const std::uint32_t& mask2, const std::uint32_t& mask1) { static_assert(WIDTH == 1 || WIDTH == 2); if (mask1 != 0) { return __builtin_ctz(mask1) / WIDTH; } else if (mask2 != 0) { return (__builtin_ctz(mask2) + 32) / WIDTH; } else if (mask3 != 0) { return (__builtin_ctz(mask3) + 64) / WIDTH; } else if (mask4 != 0) { return (__builtin_ctz(mask4) + 96) / WIDTH; } else { return 128; } } template <std::size_t WIDTH> const void* find(const void* const current_void, const void* const value_void); template <> [[nodiscard]] inline __attribute__((always_inline)) const void* find<1>(const void* const current, const void* const value) { const auto* const current_i8{reinterpret_cast<const std::uint8_t*>(current)}; const auto* const value_i8{reinterpret_cast<const std::uint8_t*>(value)}; const auto value_vec{_mm256_set1_epi8(*value_i8)}; const auto mask1{compare<1>(value_vec, current_i8)}; const auto mask2{compare<1>(value_vec, current_i8 + 32)}; const auto mask3{compare<1>(value_vec, current_i8 + 64)}; const auto mask4{compare<1>(value_vec, current_i8 + 96)}; const auto mask12{_mm256_or_si256(mask1, mask2)}; const auto mask34{_mm256_or_si256(mask3, mask4)}; const auto mask1234{_mm256_or_si256(mask12, mask34)};
{ "domain": "codereview.stackexchange", "id": 44713, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, simd", "url": null }
c++, algorithm, simd if (_mm256_testz_si256(mask1234, mask1234) == 0) { const auto first_occurrence{ctz_ui128<1>(compress_mask<1>(mask4), compress_mask<1>(mask3), compress_mask<1>(mask2), compress_mask<1>(mask1))}; return reinterpret_cast<const void*>(current_i8 + first_occurrence); } return nullptr; } template <> [[nodiscard]] inline __attribute__((always_inline)) const void* find<2>(const void* const current, const void* const value) { const auto* const current_i16{reinterpret_cast<const std::uint16_t*>(current)}; const auto* const value_i16{reinterpret_cast<const std::uint16_t*>(value)}; const auto value_vec{_mm256_set1_epi16(*value_i16)}; const auto mask1{compare<2>(value_vec, current_i16)}; const auto mask2{compare<2>(value_vec, current_i16 + 16)}; const auto mask3{compare<2>(value_vec, current_i16 + 32)}; const auto mask4{compare<2>(value_vec, current_i16 + 48)}; const auto mask12{_mm256_or_si256(mask1, mask2)}; const auto mask34{_mm256_or_si256(mask3, mask4)}; const auto mask1234{_mm256_or_si256(mask12, mask34)}; if (_mm256_testz_si256(mask1234, mask1234) == 0) { const auto first_occurrence{ctz_ui128<2>(compress_mask<2>(mask4), compress_mask<2>(mask3), compress_mask<2>(mask2), compress_mask<2>(mask1))}; return reinterpret_cast<const void*>(current_i16 + first_occurrence); } return nullptr; } template <> [[nodiscard]] inline __attribute__((always_inline)) const void* find<4>(const void* const current, const void* const value) { const auto* const current_i32{reinterpret_cast<const std::uint32_t*>(current)}; const auto* const value_i32{reinterpret_cast<const std::uint32_t*>(value)}; const auto value_vec{_mm256_set1_epi32(*value_i32)};
{ "domain": "codereview.stackexchange", "id": 44713, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, simd", "url": null }
c++, algorithm, simd const auto mask1{compare<4>(value_vec, current_i32)}; const auto mask2{compare<4>(value_vec, current_i32 + 8)}; const auto mask3{compare<4>(value_vec, current_i32 + 16)}; const auto mask4{compare<4>(value_vec, current_i32 + 24)}; const auto mask12{_mm256_or_si256(mask1, mask2)}; const auto mask34{_mm256_or_si256(mask3, mask4)}; const auto mask1234{_mm256_or_si256(mask12, mask34)}; if (_mm256_testz_si256(mask1234, mask1234) == 0) { const auto compressed_mask{(compress_mask<4>(mask4) << 24) + (compress_mask<4>(mask3) << 16) + (compress_mask<4>(mask2) << 8) + compress_mask<4>(mask1)}; return reinterpret_cast<const void*>(current_i32 + __builtin_ctz(compressed_mask)); } return nullptr; } template <> [[nodiscard]] inline __attribute__((always_inline)) const void* find<8>(const void* const current, const void* const value) { const auto* const current_i64{reinterpret_cast<const std::uint64_t*>(current)}; const auto* const value_i64{reinterpret_cast<const std::uint64_t*>(value)}; const auto value_vec{_mm256_set1_epi64x(*value_i64)}; const auto mask1{compare<8>(value_vec, current_i64)}; const auto mask2{compare<8>(value_vec, current_i64 + 4)}; const auto mask3{compare<8>(value_vec, current_i64 + 8)}; const auto mask4{compare<8>(value_vec, current_i64 + 12)}; const auto mask12{_mm256_or_si256(mask1, mask2)}; const auto mask34{_mm256_or_si256(mask3, mask4)}; const auto mask1234{_mm256_or_si256(mask12, mask34)}; if (_mm256_testz_si256(mask1234, mask1234) == 0) { const auto compressed_mask{(compress_mask<8>(mask4) << 12) + (compress_mask<8>(mask3) << 8) + (compress_mask<8>(mask2) << 4) + compress_mask<8>(mask1)}; return reinterpret_cast<const void*>(current_i64 + __builtin_ctz(compressed_mask)); } return nullptr; }
{ "domain": "codereview.stackexchange", "id": 44713, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, simd", "url": null }
c++, algorithm, simd return nullptr; } template <std::contiguous_iterator ITERATOR_T> [[nodiscard]] ITERATOR_T find(ITERATOR_T begin_it, ITERATOR_T end_it, const typename std::iterator_traits<ITERATOR_T>::value_type& value) { using value_t = typename std::iterator_traits<ITERATOR_T>::value_type; static_assert(std::is_scalar_v<value_t>); constexpr auto WIDTH{sizeof(value_t)}; const value_t* const begin{std::to_address(begin_it)}; const value_t* const end{std::to_address(end_it)}; const value_t* current{std::to_address(begin_it)}; // Scalar comparison until the pointer is aligned to 32 bytes. while (current != end && reinterpret_cast<std::uintptr_t>(current) % 32 != 0) { if (*current == value) { return begin_it + (current - begin); } ++current; } // SIMD comparison. while (current + (128 / WIDTH) <= end) { const auto* const current_void{reinterpret_cast<const void*>(current)}; const auto* const value_void{reinterpret_cast<const void*>(&value)}; if (const auto* const found{find<WIDTH>(current_void, value_void)}; found != nullptr) { return begin_it + (reinterpret_cast<const value_t*>(found) - begin); } current += 128 / WIDTH; } // Scalar tail comparison. while (current != end) { if (*current == value) { return begin_it + (current - begin); } ++current; } return end_it; } } // namespace simd Example usage: #include <cassert> #include <algorithm> #include <numeric> #include <vector> #include "find.hpp" int main() { std::vector<int> elements(1'000'000, 0); std::iota(elements.begin(), elements.end(), 0); const auto simd_it{simd::find(elements.cbegin(), elements.cend(), 1337)}; const auto std_it{std::find(elements.cbegin(), elements.cend(), 1337)}; assert(simd_it == std_it); }
{ "domain": "codereview.stackexchange", "id": 44713, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, simd", "url": null }
c++, algorithm, simd Answer: Sneaky AVX512 dependence Note that _mm256_loadu_epi8 and such ("typed integer loads" or whatever you want to call them) are AVX512. It looks like this code is aimed at AVX2 though, and the corresponding AVX2 load is _mm256_loadu_si256 regardless of the size of the element. _mm256_loadu_epi8 and friends probably exist (I think) because there are masked versions of them, the element size matters for the masked versions but not the "basic" version that just loads 32 bytes. Passing vectors by const-reference That's unnecessary. Think of vectors as "slightly bigger integers", they fit in registers, you can copy them for almost free. Passing them by const-reference is fine as long as the compiler optimizes away the indirection, but it's not really a good thing, more of an "not necessarily a bad thing, when the compiler cooperates". Passing uint32_t by const-reference is even more unusual, and once again the best you can hope for is that the compiler doesn't do what you told it to do, which is not a great position to be in. reinterpret_cast<vec256f> Does that work? The usual way to express vector reinterpretation is with the "cast" family of intrinsics such as _mm256_castsi256_ps. __builtin_ctz __builtin_ctz is fine but you may like to know that as of C++20 there is a <bit> header that defines std::countr_zero .. or, looking at your user name, perhaps that's not your preference ;) Head and tail handling This is a common problem when working with SIMD, and there is nothing inherently wrong with using some scalar code at the start and end, but it's not the only option. You can also consider one of these tricks:
{ "domain": "codereview.stackexchange", "id": 44713, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, simd", "url": null }
c++, algorithm, simd Use an unaligned load at the start. Once upon a time unaligned loads used to be really quite bad, worth avoiding at significant cost, but not today, and there would be only a couple of them. You're not stuck with unaligned loads throughout, because it's fine if the first aligned(*) load (in the main loop) partially overlaps the unaligned load. There is some wasted work there, but also the potential to still be faster than a scalar loop. By the way, be careful with this: this technique does not handle an input array that's shorter than a vector. Similarly, use an unaligned load at the end, also partially overlapping, with the last aligned load. You can use aligned loads, but then ignore/discard the data that was loaded from before the start of the input and after the end of the input. Be careful with zeroing out the invalid parts when searching for a zero. *: by "aligned load" I mean that the address is aligned. Back in the old days, it used to be that the unaligned load instruction was always slow, even if the address was actually aligned. That hasn't been the case for over a decade. A load can be considered aligned if the address is aligned, the type of instruction doesn't really matter. Some compilers refuse to emit the aligned instruction even when use its intrinsic, opting to always emit the unaligned instruction.
{ "domain": "codereview.stackexchange", "id": 44713, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, simd", "url": null }
php, html5, classes, php7 Title: PHP Class to render HTML div styled tables v1 Question: This class aims to render an HTML compliant div styled table. I added a help() method that provides usage and styling in a more user-friendly way. Besides the review of the code and every advice I will receive I would like to hear your thoughts about the fact __construct() method taking all arguments. Thanks in advance. <?php
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 /** * * This class produces a DIV styled table in HTML * * @author julio * @date 04/05/2023 * * IMPORTANT NOTE: this class is written for PHP 7.0.33. Even though I tried to * accomplish as much as possible PSR-12 and standard conventions. So you may * notice that some methods return a bool value when it could be a void value. * Also, I am not allowed to set visibility for class constants. Among others. * However, I check my codes in webcodesniffer.net to accomplish PSR-12. * * Upon instantiation this class can take the following optional parameters: * * - string $orientation: sets table orientation: "hz" (default) for * horizontal or "vt" for vertical * * - string $table_title: the title for the table * * - array $headers: a simple array where each element is a column header * * - array $data: a multidimensional array where first level is each row * and each subarray contains cells data. Note that first level keys are * ignored so they are not used and are dismissed * * - array $footers: a simple array where each element is a column footer * * - int $tabs: the number of tabs (4 spaces) for the first element. Subsequent * elements are indented properly to provide a correctly indented output * * * Each parameter can be set explicitly with their corresponding method. * * When $headers are set, the number of headers will be the number of columns. * Otherwise the number of columns will be set to the number of elements of * first $data subarray. Any data beyond the number of columns will be * dismissed. * * There is a help() method that prints the basic usage and styling. * * Full copy-paste example:
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 $title = "Testing Table"; $orientation = "hz"; $headers = ["Col1", "Col2", "Col3", "Col4", "Col5"]; $data = array( "r1" => ["dato11", "dato12", "dato13"], "r2" => ["dato21", "dato22", "", "dato24"], "r3" => ["dato31", "dato32", "dato33", "dato34", "dato35"], "r4" => ["dato41"] ); $footers = ["", "foot2", "", "foot4"]; $tabs = 3; $html_classes = []; require("Table.php"); $table = new Table(); $table->setTitle($title); $table->setOrientation($orientation); $table->setHeaders($headers); $table->setData($data); $table->setFooters($footers); $table->setTabs($tabs); $html = $table->get($html_classes); echo $html; * This example should output something like this:
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 <div class='table'> <div class='table-title'>Testing Table</div> <div class='table-header'> <div class='table-header-cell'>Col1</div> <div class='table-header-cell'>Col2</div> <div class='table-header-cell'>Col3</div> <div class='table-header-cell'>Col4</div> <div class='table-header-cell'>Col5</div> </div> <div class='table-body'> <div class='table-row'> <div class='table-row-cell'>dato11</div> <div class='table-row-cell'>dato12</div> <div class='table-row-cell'>dato13</div> <div class='table-row-cell'></div> <div class='table-row-cell'></div> </div> <div class='table-row'> <div class='table-row-cell'>dato21</div> <div class='table-row-cell'>dato22</div> <div class='table-row-cell'></div> <div class='table-row-cell'>dato24</div> <div class='table-row-cell'></div> </div> <div class='table-row'> <div class='table-row-cell'>dato31</div> <div class='table-row-cell'>dato32</div> <div class='table-row-cell'>dato33</div> <div class='table-row-cell'>dato34</div> <div class='table-row-cell'>dato35</div> </div> <div class='table-row'> <div class='table-row-cell'>dato41</div> <div class='table-row-cell'></div> <div class='table-row-cell'></div> <div class='table-row-cell'></div> <div class='table-row-cell'></div> </div> </div> <div class='table-footer'> <div class='table-footer-cell'></div> <div class='table-footer-cell'>foot2</div> <div class='table-footer-cell'></div>
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 <div class='table-footer-cell'></div> <div class='table-footer-cell'>foot4</div> <div class='table-footer-cell'></div> </div> </div>
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 <h4>CSS3 example for styling the table</h4> <pre> <code> .table { width:100%; display:table; } .table-title { display: table-caption; text-align: center; font-size: 20px; font-weight: bold; } .table-header { display: table-header-group; background-color: gray; font-weight: bold; font-size: 15px; background-color: #D1D1D1; } .table-header-cell { display: table-cell; padding:10px; border-bottom:1px solid black; font-weight:bold; text-align:justify; } .table-body { display:table-row-group; } .table-row { display:table-row; } .table-row-cell { display:table-cell; padding:5px 10px 5px 10px; } .table-footer { display: table-footer-group; background-color: gray; font-weight: bold; font-size: 15px; color:#FFF; } .table-footer-cell { display: table-cell; padding: 10px; text-align: justify; border-bottom: 1px solid black; } .table-row:hover { background-color:#d9d9d9; } </code> </pre> * You can also achieve the same results with: require("Table.php"); $table = new Table($orientation, $title, $headers, $data, $footers, $tabs); $html = $table->get($html_classes); echo $html; * As you can see, any cell can be left empty. * You can also add HTML markup. * */ class Table {
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 * As you can see, any cell can be left empty. * You can also add HTML markup. * */ class Table { private $orientation = "hz"; // "vt" not implemented yet private $table_title = ""; private $headers = array(); private $data = array(); private $footers = array(); private $tabs = 0; public function __construct( string $orientation = "", string $table_title = "", array $headers = [], array $data = [], array $footers = [], int $tabs = 0 ) { if (strlen($orientation) !== 0) { $this->setOrientation($orientation); } if (strlen($table_title) !== 0) { $this->setTitle($table_title); } if (count($headers) > 0) { $this->setHeaders($headers); } if (count($data) > 0) { $this->setData($data); } if (count($footers) > 0) { $this->setFooters($footers); } if ($tabs !== 0) { $this->setTabs($tabs); } } /** * Set table orientation * @param string $orientation "hz" for horizontal (default), "vt" for vertical * @return bool */ public function setOrientation(string $orientation = "hz"): bool { if ($orientation === "vt") { $this->orientation = "vt"; } return true; } public function setTitle(string $table_title = ""): bool { if (strlen($table_title) !== 0) { $this->table_title = $table_title; } return true; } public function setHeaders(array $headers = []): bool { if (count($headers) > 0) { if (count($headers) !== count($headers, COUNT_RECURSIVE)) { throw new Exception("Headers array should be a simple array"); } $this->headers = $headers; } return true; }
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 /** * Sets the table cells data * @param array $data Multidimensional non-associative array * @return bool * * This function takes a multidimensional array as parameter where each * key is an array where each element is a cell data. * * Empty cells are filled with "&nbsp;" to keep table format from breaking. * * So, the array format: * * array( * "header1" => ["data11", "data12", "data13", ...], * "header2" => ["data21", "data22", "data23", ...], * ... * ) * * Note that first level keys can be indexed, so this is also valid: * * array( * ["data11", "data12", "data13", ...], * ["data21", "data22", "data23", ...], * ... * ) * */ public function setData(array $data = []): bool { $this->checkData($data); $this->data = $data; return true; } private function checkData(array $data = []): bool { if (count($data) < 1) { throw new Exception("With no data there is no table to render"); } if (count($data) === count($data, COUNT_RECURSIVE)) { throw new Exception("Table data array has the wrong format: it must be a multidimensional array"); } return true; } public function setFooters(array $footers = []): bool { if (count($footers) > 0) { if (count($footers) !== count($footers, COUNT_RECURSIVE)) { throw new Exception("Footers should be a simple array"); } $this->footers = $footers; } return true; } /** * Sets the number of tabs for first element so indentation is correct * Note that 1 tab is considered as 4 spaces * @param int $tabs * @return bool */ public function setTabs(int $tabs = 0): bool { $this->tabs = ($tabs > 0) ? $tabs : 0; return true; }
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 /** * Renders the table * * @param array $html_attrs [optional] Associative array with HTML * classes and table id * @return string * * This method takes un optional array as parameter which holds * HTML ids and classes for rows, columns and cells. * It can take none or any of the following keys: * * table_id: HTML id for table container. * table_class: HTML class for table container. Mandatory. * title_class: HTML class for title. Mandatory. * header_class: HTML class for header row. Mandatory. * header_cell_class: HTML class for header cells. Mandatory. * body_class: HTML class for table body. Mandatory. * row_class: HTML class for rows. Mandatory. * row_cell_class: HTML class for row's cells. Mandatory. * footer_class: HTML class for footer. Mandatory * footer_cell_class: HTML class for footer cells. Mandatory. * * */ public function get(array $html_classes = []): string { $this->checkData($this->data); $output = null; /** * When orientation is horizontal (hz) column count is set by * the number of headers. When vertical (vt) column count in set by * the number of elements of first subarray * @var integer $col_count */ $col_count = 0; $counter = 1; if ( array_key_exists("table_id", $html_classes) && (strlen($html_classes['table_id']) !== 0) ) { $html_table_id = $html_classes['table_id']; } else { $html_table_id = ""; }
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 // mandatory if ( array_key_exists("table_class", $html_classes) && (strlen($html_classes['table_class']) !== 0) ) { $html_table_class = $html_classes['table_class']; } else { $html_table_class = "table"; } // mandatory if ( array_key_exists("title_class", $html_classes) && (strlen($html_classes['title_class']) !== 0) ) { $html_title_class = $html_classes['title_class']; } else { $html_title_class = "table-title"; } // mandatory if ( array_key_exists("header_class", $html_classes) && (strlen($html_classes['header_class']) !== 0) ) { $html_header_class = $html_classes['header_class']; } else { $html_header_class = "table-header"; } // mandatory if ( array_key_exists("header_cell_class", $html_classes) && (strlen($html_classes['header_cell_class']) !== 0) ) { $html_header_cell_class = $html_classes['header_cell_class']; } else { $html_header_cell_class = "table-header-cell"; } // mandatory if ( array_key_exists("body_class", $html_classes) && (strlen($html_classes['body_class']) !== 0) ) { $html_table_body_class = $html_classes['body_class']; } else { $html_table_body_class = "table-body"; } // mandatory if ( array_key_exists("row_class", $html_classes) && (strlen($html_classes['row_class']) !== 0) ) { $html_row_class = $html_classes['row_class']; } else { $html_row_class = "table-row"; }
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 // mandatory if ( array_key_exists("row_cell_class", $html_classes) && (strlen($html_classes['row_cell_class']) !== 0) ) { $html_cell_class = $html_classes['row_cell_class']; } else { $html_cell_class = "table-row-cell"; } // mandatory if ( array_key_exists("footer_class", $html_classes) && (strlen($html_classes['footer_class']) !== 0) ) { $html_footer_class = $html_classes['footer_class']; } else { $html_footer_class = "table-footer"; } // mandatory if ( array_key_exists("footer_cell_class", $html_classes) && (strlen($html_classes['footer_cell_class']) !== 0) ) { $html_footer_cell_class = $html_classes['footer_cell_class']; } else { $html_footer_cell_class = "table-footer-cell"; } // open table: begin $output = "\n" . str_repeat(" ", $this->tabs) . "<div"; if (strlen($html_table_id) != 0) { $output .= " id='$html_table_id'"; } $output .= " class='$html_table_class'"; $output .= ">"; // open table: end if (strlen($this->table_title) !== 0) { $output .= "\n" . str_repeat(" ", $this->tabs + 1) . "<div class='$html_title_class'>" . $this->table_title . "</div>"; } if ($this->orientation === "hz") { /** * column count: if $this->headers is set it takes its count. * Otherwise it takes the count of first data subarray */ if (count($this->headers) > 0) { $col_count = count($this->headers); // header row: begin $output .= "\n" . str_repeat(" ", $this->tabs + 1) . "<div class='$html_header_class'>";
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 foreach ($this->headers as $header) { $output .= "\n" . str_repeat(" ", $this->tabs + 2) . "<div class='$html_header_cell_class'>$header</div>"; } $output .= "\n" . str_repeat(" ", $this->tabs + 1) . "</div>"; // header row: end } else { $col_count = count($this->data[array_keys($this->data)[0]]); } // open table body $output .= "\n" . str_repeat(" ", $this->tabs + 1) . "<div class='$html_table_body_class'>"; // process cells foreach ($this->data as $data) { // open row $output .= "\n" . str_repeat(" ", $this->tabs + 2) . "<div class='$html_row_class'>"; $counter = 1; foreach ($data as $cell_data) { if ($counter <= $col_count) { $output .= "\n" . str_repeat(" ", $this->tabs + 3) . "<div class='$html_cell_class'>"; $output .= $cell_data ?? ""; // <-- $output .= "</div>"; $counter++; } } // complete empty cells to preserve row:hover on full row while ($counter <= $col_count) { $output .= "\n" . str_repeat(" ", $this->tabs + 3) . "<div class='$html_cell_class'>"; $output .= ""; // <-- $output .= "</div>"; $counter++; } // close row $output .= "\n" . str_repeat(" ", $this->tabs + 2) . "</div>"; } // close table body $output .= "\n" . str_repeat(" ", $this->tabs + 1) . "</div>";
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 // footer: begin $counter = 1; if (count($this->footers) > 0) { $output .= "\n" . str_repeat(" ", $this->tabs + 1) . "<div class='$html_footer_class'>"; foreach ($this->footers as $footer_cell) { $output .= "\n" . str_repeat(" ", $this->tabs + 2) . "<div class='$html_footer_cell_class'>"; $output .= (strlen($footer_cell) != 0) ? $footer_cell : ""; // <-- $output .= "</div>"; $counter++; } // complete empty footer cells to have footer as long as table while ($counter <= $col_count) { $output .= "\n" . str_repeat(" ", $this->tabs + 2) . "<div class='$html_footer_cell_class'>"; $output .= ""; // <-- $output .= "</div>"; $counter++; } $output .= "\n" . str_repeat(" ", $this->tabs + 1) . "</div>"; } // footer: end } // close table $output .= "\n" . str_repeat(" ", $this->tabs) . "</div>"; return $output; } /** * Renders a sample table where you can see the HTML generated code and * the CSS3 styling * @return string */ public function help(): string { $output = <<<'EOT' <h1>Class Table usage</h1> <h2>How to render a table</h2> <p>There are two ways for rendering a table. You can pass all arguments when the class is instantiated or you can call the desired method. Below you have two examples that render the exact same HTML code:</p> <pre> <code> // parameter setting
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 <pre> <code> // parameter setting $title = "Testing Table"; $orientation = "hz"; $headers = ["Col1", "Col2", "Col3", "Col4", "Col5"]; $data = array( "r1" => ["dato11", "dato12", "dato13"], "r2" => ["dato21", "dato22", "", "dato24"], "r3" => ["dato31", "dato32", "dato33", "dato34", "dato35"], "r4" => ["dato41"] ); $footers = ["", "foot2", "", "foot4"]; $tabs = 3; $html_classes = []; // Method 1: require("Table.php"); $table = new Table($orientation, $title, $headers, $data, $footers, $tabs); $html = $table->get($html_classes); echo $html; // Method 2:
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 require("Table.php"); $table = new Table(); $table->setTitle($title); $table->setOrientation($orientation); $table->setHeaders($headers); $table->setData($data); $table->setFooters($footers); $table->setTabs($tabs); $html .= $table->get($html_classes); echo $html; </code> </pre> <h3>Output:</h3> <pre> <code> EOT; $output .= htmlspecialchars(" <div class='table'> <div class='table-title'>Testing Table</div> <div class='table-header'> <div class='table-header-cell'>Col1</div> <div class='table-header-cell'>Col2</div> <div class='table-header-cell'></div> <div class='table-header-cell'>Col4</div> <div class='table-header-cell'>Col5</div> </div> <div class='table-body'> <div class='table-row'> <div class='table-row-cell'>dato11</div> <div class='table-row-cell'>dato12</div> <div class='table-row-cell'>dato13</div> <div class='table-row-cell'></div> <div class='table-row-cell'></div> </div> <div class='table-row'> <div class='table-row-cell'>dato21</div> <div class='table-row-cell'>dato22</div> <div class='table-row-cell'></div> <div class='table-row-cell'>dato24</div> <div class='table-row-cell'></div> </div> <div class='table-row'> <div class='table-row-cell'>dato31</div> <div class='table-row-cell'>dato32</div> <div class='table-row-cell'>dato33</div> <div class='table-row-cell'>dato34</div> <div class='table-row-cell'>dato35</div> </div>
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 <div class='table-row-cell'>dato35</div> </div> <div class='table-row'> <div class='table-row-cell'>dato41</div> <div class='table-row-cell'></div> <div class='table-row-cell'></div> <div class='table-row-cell'></div> <div class='table-row-cell'></div> </div> </div> <div class='table-footer'> <div class='table-footer-cell'></div> <div class='table-footer-cell'>foot2</div> <div class='table-footer-cell'></div> <div class='table-footer-cell'>foot4</div> <div class='table-footer-cell'></div> </div> </div>"); $output .= <<<'EOT' </code> </pre> <h2>The CSS3 styling</h2> <p>This code allows you to style the table. Take into consideration that HTML classes, if changed, should be updated. Read forward to learn how to set your own HTML classes</p> <pre> <code> .tabla, .table { width:100%; display:table; } .tabla-titulo, .table-title { display: table-caption; text-align: center; font-size: 20px; font-weight: bold; } .tabla-encabezado, .table-header { display: table-header-group; background-color: gray; font-weight: bold; font-size: 15px; background-color: #D1D1D1; } .tabla-celda-encabezado, .table-header-cell { display: table-cell; padding:10px; border-bottom:1px solid black; font-weight:bold; text-align:justify; } .tabla-body, .table-body { display:table-row-group; } .tabla-fila, .table-row { display:table-row; } .tabla-fila-celda, .table-row-cell { display:table-cell;
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 .tabla-fila-celda, .table-row-cell { display:table-cell; padding:5px 10px 5px 10px; } .tabla-footer, .table-footer { display: table-footer-group; background-color: gray; font-weight: bold; font-size: 15px; color:#FFF; } .tabla-footer-celda, .table-footer-cell { display: table-cell; padding: 10px; text-align: justify; border-bottom: 1px solid black; } .tabla-fila:hover, .table-row:hover { background-color:#d9d9d9; } </code> </pre>
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 <h2>How to set your own HTML classes</h2> <p>Classes for table elements are passed to get() method. It must be an array that that has none or any of the following keys:</p> <pre> <code> table_id: HTML id for table container. table_class: HTML class for table container. Mandatory. title_class: HTML class for title. Mandatory. header_class: HTML class for header row. Mandatory. header_cell_class: HTML class for header cells. Mandatory. body_class: HTML class for table body. Mandatory. row_class: HTML class for rows. Mandatory. row_cell_class: HTML class for row's cells. Mandatory. footer_class: HTML class for footer. Mandatory footer_cell_class: HTML class for footer cells. Mandatory. </code> </pre> <p>So if you want to specify your own classes, you should do something like this:</p> <pre> <code> $html_classes = ["table_id"=>"mytable01", "table_class"=>"mytable-class", ...]; $table->get($html_classes); </code> </pre> <p>When HTML classes are not present, defaults will be used (the ones in the styling example).</p> <br> <br> <p>If you need further information read the class' docblock's</p> EOT; return $output; } } Answer: I'm not overly bothered by the amount of arguments in your __construct() method. It looks fine to me. There are however some classic coding problems: Repetition There is a lot of repeated code in your class. Repetition is bad because it makes your code unnecessarily long. There must be a way to program this more elegantly. For instance, this code is repeated 10 times in get(): if ( array_key_exists("table_class", $html_classes) && (strlen($html_classes['table_class']) !== 0) ) { $html_table_class = $html_classes['table_class']; } else { $html_table_class = "table"; }
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 You could create a separate method for this: private function getClass($classes, $className, $defaultClass) { if (array_key_exists($className, $classes) && (strlen($classes[$className]) !== 0)) { return $classes[$className]; } else { return $defaultClass; } } Which can then be used as: $html_table_class = $this->getClass($html_classes, "table_class", "table"); so that you only need 10 lines where you now use 10 times as much. This is the DRY principle. Use modern PHP features With modern PHP you could also write the code above as: $html_table_class = $html_classes["table_class"] ?? "table"; and you don't need an extra method at all. See: Null coalescing operator. I do notice that you used this operator elsewhere, so you are aware of its existence. One method with all the code in it I think we both can agree that your get() method does all the heavy lifting in this class. The rest of the class is just used make this method into a class. This doesn't make for pleasant reading and debugging. Methods should be short pieces of code. Your getters and setters are such methods, but the get() method is not. It sets all the classes and does everything to generate the HTML output. Apart from checkData() it doesn't use any other method in this class. I wouldn't yet call this spagetti code, but it is getting close. Why does your class not have a general method for generating a html <div>...</div> tag, and then use that in a method to create a table cell, and that in a row method, ending in a table method? Something like: private function getDivHtml($content = '', $class = '', $tabCount = 0) { $whiteSpace = "\n" . str_repeat(" ", $tabCount + 3); $startTag = "<div" . (empty($class) ? "" : " class=\"$class\"") . ">"; $endTag = "</div>"; return $whiteSpace . $startTag . $content . $endTag; }
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 private function getTableCellHtml($content = '', $tabCount = 0) { return $this->getDivHtml($content, $this->cellClass, $tabCount); } private function getTableRowHtml($rowData = [], $tabCount = 0) { $content = ''; foreach ($rowData as $cellData) { $content .= $this->getTableCellHtml($cellData, $tabCount + 1); } return $this->getDivHtml($content, $this->rowClass, $tabCount); }
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 And so on. This isn't complete, but I hope you get the idea? Short, easy to understand, methods, each responsible for a very small part of what the class needs to accomplish. Notice how I can reuse the getDivHtml() method. Help and length of script Your script contains a long comment at the start, and a help function that basically contains the same information. This makes the script for this class very long, and difficult to read and use. There is such a thing as too much help. In principle, the class should be self-explanatory, without any comments or help. In practice some extra information can be useful, but this should be kept to a minimum. If you need to explain too much you didn't write a very good class. Code flexibility Each class should have a clear reason to exist. Your aim seems to be to make it easier to create tables. Does it do that? What if I want color rows to indicate the status of the data in that row? What if I want to attach a click event to a row? Your class makes those things impossible: It is inflexible. I have no short answer on how to to make this class more flexible. You could argue that you didn't want your tables to have these features, but that's ignoring what I'm trying to say here. You might very well need those features in the future. I've written similar code myself in the past, but ran into its limitation. So I know what I'm talking about. I now either use plain HTML, or I fully generate the HTML using all it's features. To get an idea what that could look like see: Document Object Model. I'm using my own code to do something similar. It's only aim is to generating HTML output, and is therefore simpler than this model. It's basic class, to create a HTML tag looks like this: class HTML { public function __construct($parent = null, $tagName = '', $content = '', $attributes = []) }
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
php, html5, classes, php7 and everything follows from that. Perhaps you can create something similar?
{ "domain": "codereview.stackexchange", "id": 44714, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, html5, classes, php7", "url": null }
python, algorithm, functional-programming, mathematics Title: Removing Elements from an Array Based on a Second Array Question: I've written a function that takes two arrays of integers as input and removes all the elements in the first array that are also present in the second array. I would like to share my code with you and kindly request your feedback for potential improvements. Please find my code implementation below, and any suggestions or alternative solutions would be greatly appreciated. def remove_(array1, array2): to_remove = [] for i in array2: for j in array1: if i == j: to_remove.append(i) for r in to_remove: array1.remove(r) return to_remove # Example usage: array1 = [1, 2, 3, 4, 5] array2 = [2, 4] result = remove_(array1, array2) print("Removed elements:", result) print("Updated array1:", array1) This function works by first iterating through both arrays and appending the elements that need to be removed to a new list called to_remove. It then iterates through the to_remove list and removes each element from array1. The function returns the removed elements. I'm interested in suggestions for optimizing the code or making it more Pythonic. Answer: When feasible, use specific names. Your function and variable names are generic. Help your reader out by selecting more communicative names. A second problem is that the current names are easily misread: array1 and array2 look similar when scanned quickly, and nothing intuitive links i to array1 and j to array2. Even in a fully generic context, one can do much better. For example, the following names are more compact, less easily confused, and more meaningful because single values are linked to their collection. for x in xs: for y in ys: ...
{ "domain": "codereview.stackexchange", "id": 44715, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, functional-programming, mathematics", "url": null }
python, algorithm, functional-programming, mathematics Use sets to determine what should be removed [but see below]. Selecting appropriate data structures is one of the keys to successful programming. Before writing code, put some real thought behind each collection you need: should it be a tuple, list, dict, or set? Good choices tend to simplify coding logic greatly. By switching to sets in this example, most of the need for our own algorithm disappears. Reconsider your function's design. There are many advantages that flow from building programs out of functions that don't modify their inputs. Do you really need to modify the original list, or would it be fine to return a new list? If possible, opt for the latter. A second drawback for your current approach is its co-mingling of mutation and return values. In Python, a close analogue for your function is list.remove(), which returns None. It could have returned true/false, but the language designers opted against that -- an approach often taken in Python. These considerations don't lead to hard and fast rules, but in the abstract I would favor a no-mutation approach. # Mutation. def remove_all(xs, discard): removed = set(xs).intersection(set(discard)) xs[:] = [x for x in xs if x not in removed] return list(removed) # No mutation. def remove_all(xs, discard): removed = set(xs).intersection(set(discard)) return ( [x for x in xs if x not in removed], list(removed), ) Addendum: the code above does not do exactly what your code does. The set logic eliminates duplicates from removed. If you don't want to do that, you can adjust things along these lines. # No mutation. def remove_all(xs, discard): discard = set(discard) return ( [x for x in xs if x not in discard], [x for x in xs if x in discard], )
{ "domain": "codereview.stackexchange", "id": 44715, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, functional-programming, mathematics", "url": null }
algorithm, c, mathematics Title: Efficient N-Dimensional AABB Subdivision Algorithm Question: This is supposed to subdivide a n-dimensional aabb (axis aligned bounding box) into 2ⁿ equal pieces as if sliced by n planes that are perpendicular to only one axis and parallel to the rest of the axes at a time. The code: CGL_bool CGL_aabb_subdivide_ndim(CGL_int n, CGL_float* aabb_min, CGL_float* aabb_max, CGL_float* aabbs_min_out, CGL_float* aabbs_max_out) { static CGL_float aabb_mid_pos[1024], aabb_axis_deltas[1024]; // I don't think we'll ever need more than 1024 dimensions CGL_float nth_dim_val_holder = 0.0f, *pm_a[2]; CGL_int result_count = 1 << n, nth_dim_val_holder_index = 0; for (CGL_int i = 0; i < n; i++) { aabb_mid_pos[i] = (aabb_min[i] + aabb_max[i]) * 0.5f; aabb_axis_deltas[i] = aabb_mid_pos[i] - aabb_min[i]; } for (CGL_int j = 0; j < n; j++) { pm_a[0] = &aabb_min[j]; pm_a[1] = &aabb_mid_pos[j]; nth_dim_val_holder = *pm_a[nth_dim_val_holder_index = 0]; for (CGL_int i = 0; i < result_count; i++) { aabbs_min_out[i * n + (n - j - 1)] = nth_dim_val_holder; if ((i - 1) % (1 << j) == 0) nth_dim_val_holder = *pm_a[nth_dim_val_holder_index = (nth_dim_val_holder_index + 1) % 2]; } } for (CGL_int i = 0; i < result_count; i++) { for (CGL_int j = 0; j < n; j++) { aabbs_max_out[i * n + j] = aabbs_min_out[i * n + j] + aabb_axis_deltas[j]; } } return CGL_TRUE; }
{ "domain": "codereview.stackexchange", "id": 44716, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, mathematics", "url": null }
algorithm, c, mathematics return CGL_TRUE; } Here CGL_float, CGL_int, etc are just standard C types renamed with typedefs. aabb_min is the min point of the n-dim box (it's an array of n elements) Similar for aabb_max. aabb_min_out and aabb_max_out are pre-allocated float arrays of size (2ⁿ * n) to store the result aabb min and max values for all the resulting aabb. I tested this using: CGL_float test_for_n_dim(CGL_int n) { CGL_float* aabb_minn = (CGL_float*)malloc(sizeof(CGL_float) * n); if (!aabb_minn) return; CGL_float* aabb_maxn = (CGL_float*)malloc(sizeof(CGL_float) * n); if (!aabb_maxn) return; for (CGL_int i = 0; i < n; i++) { aabb_minn[i] = 0; aabb_maxn[i] = 1; } CGL_float* aabb_out_minn = (CGL_float*)malloc(sizeof(CGL_float) * n * (1 << n)); if (!aabb_out_minn) return; CGL_float* aabb_out_maxn = (CGL_float*)malloc(sizeof(CGL_float) * n * (1 << n)); if (!aabb_out_maxn) return; CGL_float time_before = CGL_utils_get_time(); CGL_aabb_subdivide_ndim(n, aabb_minn, aabb_maxn, aabb_out_minn, aabb_out_maxn); CGL_float time_after = CGL_utils_get_time(); if (n <= 3) { CGL_info("For %dD", n); for (CGL_int i = 0; i < (1 << n); i++) { CGL_printf_green("{("); for (CGL_int j = 0; j < n; j++) { CGL_printf_green("%f", aabb_out_minn[i * n + j]); if (j != n - 1) CGL_printf_green(", "); } CGL_printf_green(") -> ("); for (CGL_int j = 0; j < n; j++) { CGL_printf_green("%f", aabb_out_maxn[i * n + j]); if (j != n - 1) CGL_printf_green(", "); } CGL_printf_green(")}\n"); } } free(aabb_minn); free(aabb_maxn);free(aabb_out_minn); free(aabb_out_maxn); return time_after - time_before; }
{ "domain": "codereview.stackexchange", "id": 44716, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, mathematics", "url": null }
algorithm, c, mathematics Results: [INTERNAL] [Tue May 9 22:04:28 202] : Started Logger Session [INFO] [Tue May 9 22:04:28 202] : Testing NDIM AABB Subdivision [INFO] [Tue May 9 22:04:28 202] : For 1D {(0.000000) -> (0.500000)} {(0.500000) -> (1.000000)} [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000002 (1D) [INFO] [Tue May 9 22:04:28 202] : For 2D {(0.000000, 0.000000) -> (0.500000, 0.500000)} {(0.000000, 0.500000) -> (0.500000, 1.000000)} {(0.500000, 0.000000) -> (1.000000, 0.500000)} {(0.500000, 0.500000) -> (1.000000, 1.000000)} [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000000 (2D) [INFO] [Tue May 9 22:04:28 202] : For 3D {(0.000000, 0.000000, 0.000000) -> (0.500000, 0.500000, 0.500000)} {(0.000000, 0.000000, 0.500000) -> (0.500000, 0.500000, 1.000000)} {(0.500000, 0.500000, 0.000000) -> (1.000000, 1.000000, 0.500000)} {(0.500000, 0.500000, 0.500000) -> (1.000000, 1.000000, 1.000000)} {(0.500000, 0.000000, 0.000000) -> (1.000000, 0.500000, 0.500000)} {(0.500000, 0.000000, 0.500000) -> (1.000000, 0.500000, 1.000000)} {(0.000000, 0.500000, 0.000000) -> (0.500000, 1.000000, 0.500000)} {(0.000000, 0.500000, 0.500000) -> (0.500000, 1.000000, 1.000000)} [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000000 (3D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000001 (4D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000001 (5D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000001 (6D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000002 (7D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000005 (8D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000010 (9D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000030 (10D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000091 (11D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000207 (12D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.000394 (13D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.001144 (14D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.001890 (15D)
{ "domain": "codereview.stackexchange", "id": 44716, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, mathematics", "url": null }
algorithm, c, mathematics [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.001890 (15D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.004921 (16D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.009553 (17D) [INFO] [Tue May 9 22:04:28 202] : Time taken: 0.092833 (18D) [INFO] [Tue May 9 22:04:29 202] : Time taken: 0.201626 (19D) [INFO] [Tue May 9 22:04:29 202] : Time taken: 0.657279 (20D) [INFO] [Tue May 9 22:04:30 202] : Time taken: 1.104113 (21D) [INFO] [Tue May 9 22:04:32 202] : Time taken: 1.859703 (22D) [INFO] [Tue May 9 22:04:36 202] : Time taken: 3.357090 (23D) [INFO] [Tue May 9 22:04:43 202] : Time taken: 7.311569 (24D) [INFO] [Tue May 9 22:05:09 202] : Time taken: 25.260529 (25D)
{ "domain": "codereview.stackexchange", "id": 44716, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, mathematics", "url": null }
algorithm, c, mathematics Answer: Please don't hide important code off the right-hand side of the screen like this: CGL_float* aabb_minn = (CGL_float*)malloc(sizeof(CGL_float) * n); if (!aabb_minn) return; CGL_float* aabb_maxn = (CGL_float*)malloc(sizeof(CGL_float) * n); if (!aabb_maxn) return; One line per statement, please! And make the return value consistent with the function's declaration - getting away with this is a clear sign that you didn't enable enough warning options when you compiled. There's no need to cast the void* which malloc() returns. Also, it's generally clearer to use the assigned-to pointer in the sizeof expression rather than its type (this matters more when the declaration is far away): CGL_float* aabb_minn = malloc((sizeof *aabb_min) * n); Did you see the bug in these lines? When the allocation for aabb_maxn fails, we leak the memory pointed to by aabb_minn. That's why we don't hide the clean-up code off the right-hand margin! We really need something more like CGL_float *const aabb_minn = malloc((sizeof *aabb_minn) * n); CGL_float *const aabb_maxn = malloc((sizeof *aabb_maxn) * n); if (!aabb_minn || !aabb_maxn) { free(aabb_minn); free(aabb_maxn); return 0.0/0.0; /* NaN */ }
{ "domain": "codereview.stackexchange", "id": 44716, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, mathematics", "url": null }
go, lock-free, atomic Title: Implementation of a lock free queue using CompareAndSwap in Go Question: Here is my implementation of a lock free queue using CompareAndSwap operation. type LockFreeQueue struct { capacity int list []int top int32 numPopOps int32 } func (lfq *LockFreeQueue) Pop() (value int, empty bool) { for { top := atomic.LoadInt32(&lfq.top) if top == -1 { return -1, true } if top == atomic.LoadInt32(&lfq.top) { val := lfq.list[lfq.top] if atomic.CompareAndSwapInt32(&lfq.top, top, top-1) { atomic.AddInt32(&lfq.numPopOps, 1) return val, top-1 == -1 } } } } The Pop function is working as I intend it to. Is there any improvements that I can do in the code to make it more efficient? I have intentionally not posted the code for Push function as I think it is not needed for the context. Answer: Could top-1 == -1 be replaced by top==0? top == atomic.LoadInt32(&lfq.top) is likely not needed: LoadInt was already done before and it could have changed before and it could have changed after this line anyways. There is also API contract question: empty == true is returned when there was nothing to read... but also when the last element was read. I would propose that empty is replaced by "nothing_to_read" and return val, top-1 == -1 should become ..., false. Is the assumption that Pop can be called from one thread only? If not then val := lfq.list[lfq.top] is not safe. lfq.top may be updated just before this line is executed to -1 which would result in out of bounds read. lfq.list[top] would probably work.
{ "domain": "codereview.stackexchange", "id": 44717, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "go, lock-free, atomic", "url": null }
python, python-3.x Title: Python data class that is a mixture of dict and namedtuple Question: I wanted to create a data class that is strongly typed, and behaves both like a namedtuple and dict. It should check the data types of the variables used to initialize it, and should support indexing in the style of sequences, therefore it should also be iterable and support type casting to list. It should also support retrieving values of the fields by using the field as attributes, in this regard it acts like a namedtuple. However it should also support indexing in the style of mappings, by using the field names as keys, so it should be able to type cast to dict and JSON serializable. I asked a question on StackOverflow when I almost finished my code, but it got closed for being unfocused. Now I have finished writing it, but I really don't know if this is a bad idea. I intend to use the data class to hold data retrieved from an SQLite3 database, where each row corresponds to an instance of the class, to make the results of queries strongly typed. And there are literally millions of rows in the database. I also wanted to make it immutable, but I only partly succeeded doing so. My code: import json import time from json import JSONEncoder from typing import Any, Deque, Generator, Iterable, Mapping script_start = time.time() def json_default(self, obj): return getattr(obj.__class__, "__json__", json_default.default)(obj) json_default.default = JSONEncoder().default JSONEncoder.default = json_default NoneType = type(None) Network_Fields = ( ('slash', str), ('start_integer', int), ('end_integer', int), ('start_string', str), ('end_string', str), ('count', int), ('ASN', (int, NoneType)), ('country_code', (str, NoneType)), ('is_anonymous_proxy', bool), ('is_anycast', bool), ('is_satellite_provider', bool), ('bad', bool) ) Network_Main_Fields = ( 'slash', 'start_string', 'end_string', 'ASN', 'country_code', 'bad' )
{ "domain": "codereview.stackexchange", "id": 44718, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x class DotDictTuple: def __init__(self, *args, **kwargs) -> None: self.__dict__['_values'] = [] if args: assert not kwargs data = args if len(args) != 1 else args[0] self.from_dict(data) if isinstance(data, dict) else self.from_list(data) else: assert kwargs self.from_dict(kwargs) def from_list(self, sequence: Iterable) -> None: assert len(sequence) == self.__class__._field_count for item, (field, datatype) in zip(sequence, self.__class__._fields): assert isinstance(item, datatype) self.__dict__[field] = item self._values.append(item) def from_dict(self, mapping: Mapping) -> None: assert len(mapping) == self.__class__._field_count for field, datatype in self.__class__._fields: assert isinstance((item := mapping.get(field)), datatype) self.__dict__[field] = item self._values.append(item) def __getitem__(self, key: int | str | slice) -> Any: return self._values[key] if isinstance(key, (int, slice)) else self.__dict__[key] def __repr__(self) -> str: return f'{self.__class__.__name__}(' + ', '.join( f'{field}={self[field]!r}' for field in self.__class__._main_fields )+')' def __full_repr__(self) -> str: return f'{self.__class__.__name__}(' + ', '.join( f'{field}={self[field]!r}' for field in self.__class__._field_list )+')' def __len__(self) -> int: return self.__class__._field_count def __iter__(self) -> Generator: yield from self._values def __json__(self) -> dict: return {k: self.__dict__[k] for k in self.keys()} def values(self) -> tuple: return self._values def keys(self) -> tuple: return self.__class__._field_list def items(self) -> list:
{ "domain": "codereview.stackexchange", "id": 44718, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x return self.__class__._field_list def items(self) -> list: return [(k, self.__dict__[k]) for k in self.keys()]
{ "domain": "codereview.stackexchange", "id": 44718, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x class Network(DotDictTuple): _field_count = len(Network_Fields) _fields = Network_Fields _main_fields = Network_Main_Fields _field_list = [k for k, _ in Network_Fields] def __init__(self, *args, **kwargs) -> None: super(Network, self).__init__(*args, **kwargs) self.__dict__['_values'] = tuple(self._values) def __str__(self) -> str: return self.slash def __setattr__(self, *_, **__) -> None: raise TypeError __delattr__ = __setattr__ Example usage Network(['1.0.0.0/24', 16777216, 16777471, '1.0.0.0', '1.0.0.255', 256, 13335, 'AU', False, True, False, False]) Network(slash='1.0.0.0/24', start_integer=16777216, end_integer=16777471, start_string='1.0.0.0', end_string='1.0.0.255', count=256, ASN=13335, country_code='AU', is_anonymous_proxy=False, is_anycast=True, is_satellite_provider=False, bad=False) Network(*['1.0.0.0/24', 16777216, 16777471, '1.0.0.0', '1.0.0.255', 256, 13335, 'AU', False, True, False, False]) Network('1.0.0.0/24', 16777216, 16777471, '1.0.0.0', '1.0.0.255', 256, 13335, 'AU', False, True, False, False) Network({'slash': '1.0.0.0/24', 'start_integer': 16777216, 'end_integer': 16777471, 'start_string': '1.0.0.0', 'end_string': '1.0.0.255', 'count': 256, 'ASN': 13335, 'country_code': 'AU', 'is_anonymous_proxy': False, 'is_anycast': True, 'is_satellite_provider': False, 'bad': False}) network = Network(['1.0.0.0/24', 16777216, 16777471, '1.0.0.0', '1.0.0.255', 256, 13335, 'AU', False, True, False, False]) network.ASN network['ASN'] network[0] network['slash'] len(network) list(network) dict(network) for i in network: print(i) All the examples work. But I really don't think my solution is concise and elegant. How to make it more Pythonic? If I didn't make it clear, the base class is intended to be subclassed by a few other classes, the bulk of the logic should be implemented in the base class, while the subclasses have different numbers of fields and type requirements.
{ "domain": "codereview.stackexchange", "id": 44718, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x My idea is to only use the SQLite3 database as a way to persist the data between sessions of the program, in other words serializing the data. I have millions of rows in the data, and json is terribly inefficient for this purpose, and is csv. I need a binary serialization library, but pickle is unsafe and more importantly a pkl generated by one Python version cannot be used by another version. I don't know what other alternative there is. I intend to retrieve all rows from the database upfront when the class to query it initializes, so all data is in memory, because I have tested that retrieving a single value from the database using where takes milliseconds, I need to do it repeatedly. Answer: I dislike that you can't discern the fields/attributes of class Network from looking at it. You need to look at Network_Fields, which in this case is not near where class Network is defined. As @Kache suggested, it might make sense to try to use dataclasses. We just need to add some methods to get the desired behaviors. dataclass with a base class One way to do that us to use a base class to add the methods. The difficulty is that the class isn't a "dataclass" until after the @dataclass decorator processes the class. So any base class or meta class can't use functions like dataclasses.fields() to find all the fields in the dataclass. This can be handled by testing if the class is fully initialized when an instance method is called. For example: class Base: def __getitem__(self, key): if isinstance(key, str): return getattr(self, key) else: if not hasattr(self.__class__, '_name'): self.__class__._name = [f.name for f in fields(self)] if isinstance(key, slice): return [getattr(self, name) for name in self.__class__._name[key]] else: return getattr(self, self.__class__._name[key])
{ "domain": "codereview.stackexchange", "id": 44718, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x def __len__(self): return len(self.__class__._name) @dataclass class Bar(Base): field1: str field2: int field3: bool When an attempt is made to access a field of Bar using an index or a slice, the class is checked for a _name attribute. If it doesn't exist one is created containing a list of the dataclass fields in order. The enables one to get the field names corresponding to the index or slices. It works but seems a little "hacky". use a decorator Another option is to use a decorator to add the methods. Because, the dataclass decorator has already processed the class, the dataclasses.fields() function can be used to get information about the fields, such as names, types, defaults, etc. # needed because None may be a valid value for a dataclass field SENTINEL = object() def makedictuple(cls): """decorator to add tuple-like and dict-like methods to a dataclass """ # list mapping indexes to field names cls._name = [f.name for f in fields(cls)] def __getitem__(self, key): if isinstance(key, str): return getattr(self, key) elif isinstance(key, slice): return [getattr(self, name) for name in cls._name[key]] else: return getattr(self, cls._name[key]) cls.__getitem__ = __getitem__ def from_sequence(sequence): "a classmethod to construct cls from a sequence" for arg, field in zip(sequence, fields(cls)): if not isinstance(arg, field.type): raise TypeError(f"'{arg}' not of type '{field.type}'.") return cls(*sequence) cls.from_sequence = from_sequence
{ "domain": "codereview.stackexchange", "id": 44718, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
python, python-3.x def from_dict(mapping): "a classmethod to construct cls from a mapping" for field in fields(cls): value = mapping.get(field.name, SENTINEL) if value != SENTINEL and not isinstance(value, field.type): raise TypeError(f"Field ''{field.name}' value '{value}' not of type '{field.type}'.") return cls(**mapping) cls.from_dict = from_dict cls.__len__ = lambda self: len(cls._name) cls.__iter__ = lambda self: (getattr(self, name) for name in self._name) cls.keys = lambda self: asdict(self).keys() cls.values = lambda self: asdict(self).values() cls.items = lambda self: asdict(self).items() return cls Used like this: NoneType = type(None) @makedictuple @dataclass(frozen=True) class Network: prefix: str start_integer: int end_integer: int start_string: str end_string: str count: int ASN: (int , NoneType) country_code: (str, NoneType) is_anonymous_proxy: bool is_anycast: bool is_satellite_provider: bool bad: bool Everything is defined in one place, and the @dataclass decorator creates __init__, __repr__, as_dict and other methods.
{ "domain": "codereview.stackexchange", "id": 44718, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x", "url": null }
perl Title: Python Package Index recursive package dependency resolver Question: My work has an isolated network that developers write applications to run inside of. These developers often write Python code. This Python code often requires modules from the Python Package Index (PyPi) to be downloaded using something like pip. In order to allow these developers to run their software on this isolated network, I need to provide them with a PyPi mirror so they can get the modules their software depends upon. To accomplish this, I setup a bandersnatch mirror on a VM in my DMZ and configured our VMs to use this mirror instead of the (unreachable from their perspective) internet. So far, so good. Policy dictates that software coming into our isolated network must be approved first, meaning I cannot simply do a full mirror of the entire Python Package Index (if I even had the disk space for such a thing... I'm not sure I do) and let people have whatever they want. Bandersnatch supports this no problem; by including this in it's config file, I essentially have a list of ONLY the approved packages that will show up on the mirror: [allowlist] packages = absl-py astunparse caproto confluent_kafka ConfigArgParse ess-streaming-data-types flatbuffers gast gpytorch ...<and so on>... Unfortunately, Bandersnatch does not do any dependency resolution on this list of packages to allow mirroring of and it does not seem likely they will implement that feature. It does not seem any other PyPi mirror servers are setup to allow this either, but if I have missed something, please let me know. So I find myself having a list of Python Packages that I need to know all of their dependencies of, recursively, so I can mirror that whole list. I am not a Python programmer, so I wrote it in Perl. I think it works, but I'd really appreciate another set of eyes on it. My Code: https://pastebin.com/hR6Yru4W #!/usr/bin/env perl use strict; use warnings;
{ "domain": "codereview.stackexchange", "id": 44719, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "perl", "url": null }
perl # This script is a (probably naive) attempt at writing a recursive dependency resolver for the Python package index (PyPi) # A list of (space seperated) Python Package names provided on the command line are the starting point # Each package in that list is added to a graph, then every node(vertex) in that graph has edges defined between the node itself # and each of it's dependencies (which become their own nodes as a result) # Every node in the graph is iterated through, has it's dependencies(edges) defined, and the process is repeated until # the graph stops changing. Once there are no more dependencies to find, it prints out a (alphabetically sorted) list # of every package that would be required to install every package given as an argument to this script. Note that this list # WILL INCLUDE the packages that were initially provided as part of the list. use JSON; use Graph; # Our main dependency graph objects # We need two so we can check if the graph changed between dependency runs # When the two graphs stay the same after a dependency run, we know our graph is complete my $Agraph = Graph->new(); my $Bgraph = Graph->new(); # Accepts a list of python packages to check dependencies for # Returns a list of python packages the arguments depend upon # Note that this function is NOT RECURSIVE. It ONLY provides the direct dependencies. sub get_deps { my $ret = []; my $json = JSON->new; foreach my $package ( @_ ) { my $curl = `curl -s "https://pypi.org/pypi/$package/json"`; my $reqs = $json->decode($curl)->{info}->{requires_dist}; if (defined($reqs)) { foreach my $dep (@$reqs) { $dep =~ s/[^a-zA-Z0-9-].*$//; push(@$ret, $dep); } } } return $ret; } # @ARGV is a list of packages we need to find all dependencies for and is the roots of our dependency graph foreach my $package (@ARGV) { $Agraph->add_vertex($package); }
{ "domain": "codereview.stackexchange", "id": 44719, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "perl", "url": null }
perl # A list of packages we have already gotten dependnecies for so we don't check twice my $checked = []; # Loop until our graphs stop changing between dependency runs while ( $Agraph ne $Bgraph ) { $Bgraph = $Agraph->deep_copy(); # Check every single vertice in our graph my @vertlist = $Agraph->vertices; foreach my $package (@vertlist) { # If we haven't checked this package before, get it added to the graph with all of it's dependencies if (! grep( /^$package$/, @$checked )) { my $deplist = get_deps($package); foreach my $dep (@$deplist) { $Agraph->add_edge($package, $dep); } # Add this package to our list of already checked packages so we don't waste time push(@$checked, $package); } } } my @fulldeplist = sort $Agraph->vertices; foreach my $package (@fulldeplist) { print "$package\n"; } Answer: The layout of the code is very good, with nice use of vertical whitespace and consistent indentation. It also makes good use of comments. It is great that you used strict and warnings. In the grep line, it would be a good idea to use \Q and \E to escape any potential regular expression metacharacters that might be in your $package variable. See also quotemeta The remaining suggestions are mostly for good coding style, and some are my personal preference. When I use modules like JSON, I like to only import what is being used by the code so as to not clutter up the namespace. In your case, since you use the object-oriented interface, you can specify an empty list; I'll show this below. When I have header comments, I like to place them inside Perl POD (=head, etc.). This provides a command-line manpage for you when you use the perldoc command: perldoc script.pl When dereferencing an array reference, I prefer to use extra braces: @{ $ret }
{ "domain": "codereview.stackexchange", "id": 44719, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "perl", "url": null }
perl When dereferencing an array reference, I prefer to use extra braces: @{ $ret } Refer to this perlcritic policy for further details: Perl::Critic::Policy::References::ProhibitDoubleSigil. Since backticks (``) can be easily missed, I prefer to use the qx quoting operator; it stands out more in the code. Here is the code with modifications. I also ran your code through a spell checker and fixed some typos in your comments (dependnecies, seperated). #!/usr/bin/env perl use strict; use warnings; =head1 Description This script is a (probably naive) attempt at writing a recursive dependency resolver for the Python package index (PyPi) A list of (space separated) Python Package names provided on the command line are the starting point Each package in that list is added to a graph, then every node(vertex) in that graph has edges defined between the node itself and each of it's dependencies (which become their own nodes as a result) Every node in the graph is iterated through, has it's dependencies(edges) defined, and the process is repeated until the graph stops changing. Once there are no more dependencies to find, it prints out a (alphabetically sorted) list of every package that would be required to install every package given as an argument to this script. Note that this list WILL INCLUDE the packages that were initially provided as part of the list. =cut use JSON qw(); use Graph qw(); # Our main dependency graph objects # We need two so we can check if the graph changed between dependency runs # When the two graphs stay the same after a dependency run, we know our graph is complete my $Agraph = Graph->new(); my $Bgraph = Graph->new();
{ "domain": "codereview.stackexchange", "id": 44719, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "perl", "url": null }
perl # Accepts a list of python packages to check dependencies for # Returns a list of python packages the arguments depend upon # Note that this function is NOT RECURSIVE. It ONLY provides the direct dependencies. sub get_deps { my $ret = []; my $json = JSON->new; foreach my $package ( @_ ) { my $curl = qx(curl -s "https://pypi.org/pypi/$package/json"); my $reqs = $json->decode($curl)->{info}->{requires_dist}; if (defined($reqs)) { foreach my $dep (@{ $reqs }) { $dep =~ s/[^a-zA-Z0-9-].*$//; push(@{ $ret }, $dep); } } } return $ret; } # @ARGV is a list of packages we need to find all dependencies for and is the roots of our dependency graph foreach my $package (@ARGV) { $Agraph->add_vertex($package); } # A list of packages we have already gotten dependencies for so we don't check twice my $checked = []; # Loop until our graphs stop changing between dependency runs while ( $Agraph ne $Bgraph ) { $Bgraph = $Agraph->deep_copy(); # Check every single vertice in our graph my @vertlist = $Agraph->vertices; foreach my $package (@vertlist) { # If we haven't checked this package before, get it added to the graph with all of it's dependencies if (! grep( /^\Q$package\E$/, @{ $checked } )) { my $deplist = get_deps($package); foreach my $dep (@{ $deplist }) { $Agraph->add_edge($package, $dep); } # Add this package to our list of already checked packages so we don't waste time push(@{ $checked }, $package); } } } my @fulldeplist = sort $Agraph->vertices; foreach my $package (@fulldeplist) { print "$package\n"; } I like to use this line for warnings, but it can be too restrictive for some people's tastes: use warnings FATAL => 'all'; FATAL
{ "domain": "codereview.stackexchange", "id": 44719, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "perl", "url": null }
performance, julia, simd Title: Implementing a 1D Convolution SIMD Friendly in Julia Question: I want to implement a 1D convolution in Julia using the direct calculation since the conv() function in DSP.jl uses DFT (fft) based methods. In order to make it fast, I'd like the code to be SIMD friendly (I am OK with using LoopVectorization.jl). The trivial code is: using BenchmarkTools; function _Conv1D!( vO :: Array{T, 1}, vA :: Array{T, 1}, vB :: Array{T, 1} ) :: Array{T, 1} where {T <: Real} lenA = length(vA); lenB = length(vB); fill!(vO, zero(T)); for idxB in 1:lenB @simd for idxA in 1:lenA @inbounds vO[idxA + idxB - 1] += vA[idxA] * vB[idxB]; end end return vO; end function _Conv1D( vA :: Array{T, 1}, vB :: Array{T, 1} ) :: Array{T, 1} where {T <: Real} lenA = length(vA); lenB = length(vB); vO = Array{T, 1}(undef, lenA + lenB - 1); return _Conv1D!(vO, vA, vB); end numSamplesA = 1000; numSamplesB = 15; vA = rand(numSamplesA); vB = rand(numSamplesB); vO = rand(numSamplesA + numSamplesB - 1); @benchmark _Conv1D($vA, $vB) I get: BenchmarkTools.Trial: 10000 samples with 9 evaluations. Range (min … max): 2.522 μs … 558.844 μs ┊ GC (min … max): 0.00% … 99.28% Time (median): 3.333 μs ┊ GC (median): 0.00% Time (mean ± σ): 4.321 μs ± 13.718 μs ┊ GC (mean ± σ): 10.38% ± 3.67% ██▆ ▂ ▃▄▃███▆▅▇▆▄▂▃▇██▄▂▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▂▂▃▃▃▃▂▂▁▁▁▁▁▁▁▁ ▂ 2.52 μs Histogram: frequency by time 8.51 μs < Memory estimate: 8.06 KiB, allocs estimate: 1. I read Chris Elrod's post Orthogonalize Indices. Basically I tried removing the inner loop and got something like: function Conv1D!( vO :: Array{T, 1}, vA :: Array{T, 1}, vB :: Array{T, 1} ) :: Array{T, 1} where {T <: Real}
{ "domain": "codereview.stackexchange", "id": 44720, "lm_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, julia, simd", "url": null }
performance, julia, simd lenA = length(vA); lenB = length(vB); lenO = length(vO); vC = view(vB, lenB:-1:1); @simd for ii in 1:lenO # Rolling vB over vA startIdxA = max(1, ii - lenB + 1); endIdxA = min(lenA, ii); startIdxC = max(lenB - ii + 1, 1); endIdxC = min(lenB, lenO - ii + 1); # println("startA = $startIdxA, endA = $endIdxA, startC = $startIdxC, endC = $endIdxC"); @inbounds vO[ii] = sum(view(vA, startIdxA:endIdxA) .* view(vC, startIdxC:endIdxC)); end return vO; end function Conv1D( vA :: Array{T, 1}, vB :: Array{T, 1} ) :: Array{T, 1} where {T <: Real} lenA = length(vA); lenB = length(vB); vO = Array{T, 1}(undef, lenA + lenB - 1); return Conv1D!(vO, vA, vB); end numSamplesA = 1000; numSamplesB = 15; vA = rand(numSamplesA); vB = rand(numSamplesB); vO = rand(numSamplesA + numSamplesB - 1); @benchmark Conv1D($vA, $vB) Yet I get much much slower results. Is there anything I can do to improve results any farther? Maybe something to make the code much more SIMD friendly? A Godbold link for _Conv1D!(): https://godbolt.org/z/e8W7e473h. Remark: Originally, in Conv1D!(), I used @inbounds vO[ii] = dot(view(vA, startIdxA:endIdxA), view(vC, startIdxC:endIdxC));. It was slower. Answer: Based on code by Chris Elrod I managed to come to this: function Conv1D!( vO :: Vector{T}, vA :: Vector{T}, vB :: Vector{T} ) where {T <: Real}
{ "domain": "codereview.stackexchange", "id": 44720, "lm_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, julia, simd", "url": null }
performance, julia, simd J = length(vA); K = length(vB); #<! Assumed to be the Kernel # Optimized for the case the kernel is in vB (Shorter) J < K && return Conv1D!(vO, vB, vA); I = J + K - 1; #<! Output length @turbo for ii in 1:(K - 1) #<! Head sumVal = zero(T); for kk in 1:K ib0 = (ii >= kk); oa = ib0 ? vA[ii - kk + 1] : zero(T); sumVal += vB[kk] * oa; end vO[ii] = sumVal; end @turbo inline=true for ii in K:(J - 1) #<! Middle sumVal = zero(T); for kk in 1:K sumVal += vB[kk] * vA[ii - kk + 1]; end vO[ii] = sumVal; end @turbo for ii in J:I #<! Tail sumVal = zero(T); for kk in 1:K ib0 = (ii < J + kk); oa = ib0 ? vA[ii - kk + 1] : zero(T); sumVal += vB[kk] * oa; end vO[ii] = sumVal; end return vO end This code will efficiently use the SIMD capabilities of the CPU (Assuming x64 CPU). The main idea is to replace the series of if with 3 optimized cases for beginning of the signal, middle and the end. This makes the code SIMD friendly. Pay attention that it won't work well with @simd instead of @turbo.
{ "domain": "codereview.stackexchange", "id": 44720, "lm_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, julia, simd", "url": null }
strings, swift Title: Swift-function, which checks if all letters in a string are unique Question: The task is writing a function, which checks if a string contains only unique characters. Means: is each character is included only one time. Here's the solution, I have developed: func areAllLettersUnique(_ str: String) -> Bool { let arr = str.split(separator: "") for (i, chr) in arr.enumerated() { if arr[i + 1..<arr.count].contains(chr) { return false } } return true } assert(areAllLettersUnique("No duplicates") == true, "Challenge 1.1 failed") assert(areAllLettersUnique("abcdefghijklmnopqrstuvwxyz") == true, "Challenge 1.2 failed") assert(areAllLettersUnique("AaBbCc") == true, "Challenge 1.3 failed") assert(areAllLettersUnique("Hello, world") == false, "Challenge 1.4 failed") print("All assertions successful") It has passed the provided asserts and I think it works correct. But: Is there a better, perhaps more "swifty" solution? Can I expect my code to work correctly or are there flaws? Answer: This let arr = str.split(separator: "") creates an array of one-element substrings of the original string. It is simpler to create an array of Characters with let arr = Array(str) It might also be a bit more efficient to compare characters instead of substrings. Also this works not only for strings but for arbitrary Sequences. if arr[i + 1..<arr.count].contains(chr) can be simplified slightly using a RangeExpression, in this case ... if arr[(i + 1)...].contains(chr) The variable name arr does not indicate what it contains, a better choice might be something like allCharacters. Your method is not very efficient, the complexity is \$ O(N^2) \$ where \$ N \$ is the length of the string. One can use a Set to store the distinct characters of the string. A very short and simple implementation would be func areAllLettersUnique(_ str: String) -> Bool { let allCharacters = Set(str) return allCharacters.count == str.count }
{ "domain": "codereview.stackexchange", "id": 44721, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, swift", "url": null }
strings, swift but this does not “short-circuit”: The entire string is processed even if a duplicate character has been found. But one can enumerate the characters and keep track of all characters seen to far: func areAllLettersUnique(_ str: String) -> Bool { var charactersSeenSoFar = Set<Character>() for chr in str { if charactersSeenSoFar.contains(chr) { return false } charactersSeenSoFar.insert(chr) } return true } The insert operation of a Set returns a value which indicates whether the element was newly inserted or already present, so this can be further simplified to func areAllLettersUnique(_ str: String) -> Bool { var charactersSeenSoFar = Set<Character>() for chr in str { if !charactersSeenSoFar.insert(chr).inserted { return false } } return true } Finally note that this method can be made generic with minor changes, so that it can be used with arbitrary sequences of (hashable) elements func areAllElementsUnique<C>(_ seq: C) -> Bool where C: Sequence, C.Element: Hashable { var elementsSeenSoFar = Set<C.Element>() for elem in seq { if !elementsSeenSoFar.insert(elem).inserted { return false } } return true }
{ "domain": "codereview.stackexchange", "id": 44721, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "strings, swift", "url": null }
c#, object-oriented, snake-game Title: C# Snake in Console Question: I've created Snake in Console. I've tried to make my code as good as I possibly could. (Code on github: https://github.com/bartex-bartex/SnakeCSharp) Question Is my coding style good enough, so I can move to creating another project while not repeating some blunders I've made here? Program.cs using SnakeGame; Game game = new Game(40, 30); game.Start(); Game.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SnakeGame { public class Game { public Board Board { get; set; } public Snake Snake { get; set; } public Apple Apple { get; set; } public Score Score { get; set; } private const int scoreTextHeight = 1; private const int FPS = 16; public Game(int width, int height) { Board = new Board(width, height); Snake = new Snake(width, height); Apple = new Apple(width, height, Snake.Position); Score = new Score(); Console.CursorVisible = false; Console.SetWindowSize(width, height + scoreTextHeight); } public void Start() { Point previousSnakeTail = new Point(Snake.GetSnakeTail().x, Snake.GetSnakeTail().y); while (true) { Board.Draw(Snake.Position, previousSnakeTail, Apple.Position); previousSnakeTail = Snake.GetSnakeTail(); // Snake Movement Direction direction = KeyboardManager.GetDirection(); bool isBodyCollision = Snake.Move(direction, Board.Width, Board.Height); if (isBodyCollision) break; // Handle apple eat if (Apple.CheckIfEaten(Snake.GetSnakeHead())) { Snake.IncreaseLength(); Score.IncreasePoints();
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game Apple = new Apple(Board.Width, Board.Height, Snake.Position); } Score.PrintScore(Board.Height); Thread.Sleep(1000 / FPS); } Messages.GameOverMessage(Board.Width, Board.Height, Score.GetPoints()); Console.ReadLine(); } } } Snake.cs using System; using System.Collections.Generic; using System.Linq; using System.Security; using System.Text; using System.Threading.Tasks; namespace SnakeGame { public struct Point { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } public static bool operator== (Point p1, Point p2) { if(p1.x == p2.x && p1.y == p2.y) { return true; } return false; } public static bool operator !=(Point p1, Point p2) { if (p1.x != p2.x || p1.y != p2.y) { return true; } return false; } } public enum Direction { previousDirection, up, right, down, left } public class Snake { public List<Point> Position { get; private set; } private Direction currentDirection; public Snake(int mapWidth, int mapHeight) { Position = new List<Point>(); //Spawn snake head in the middle Position.Add(new Point(mapWidth / 2, mapHeight / 2)); //Initiate movement currentDirection = Direction.up; } public bool Move(Direction newDirection, int mapWidth, int mapHeight) { currentDirection = UpdateCurrentDirection(newDirection);
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game switch (currentDirection) { case Direction.up: UpdateSnakePositionList(Direction.up, mapWidth, mapHeight, new Point(Position[0].x, mapHeight - 2), new Point(Position[0].x, Position[0].y - 1)); break; case Direction.right: UpdateSnakePositionList(Direction.right, mapWidth, mapHeight, new Point(1, Position[0].y), new Point(Position[0].x + 1, Position[0].y)); break; case Direction.down: UpdateSnakePositionList(Direction.down, mapWidth, mapHeight, new Point(Position[0].x, 1), new Point(Position[0].x, Position[0].y + 1)); break; case Direction.left: UpdateSnakePositionList(Direction.left, mapWidth, mapHeight, new Point(mapWidth - 2, Position[0].y), new Point(Position[0].x - 1, Position[0].y)); break; default: break; } return CheckIfCollisionWithTail(); } private Direction UpdateCurrentDirection(Direction newDirection) { if (newDirection != Direction.previousDirection) { if (Position.Count == 1) { return newDirection; } if (CheckIfOppositeDirection(newDirection) == true) { return currentDirection; } else { return newDirection; } } else { return currentDirection; } }
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game private bool CheckIfOppositeDirection(Direction newDirection) { if (currentDirection == Direction.left && newDirection == Direction.right || currentDirection == Direction.right && newDirection == Direction.left || currentDirection == Direction.up && newDirection == Direction.down || currentDirection == Direction.down && newDirection == Direction.up) { return true; } return false; } private bool CheckIfCollisionWithBoundary(Direction direction, int mapWidth, int mapHeight) { switch (direction) { case Direction.up: if (Position[0].y - 1 == 0) { return true; } return false; case Direction.right: if (Position[0].x + 1 == mapWidth - 1) { return true; } return false; case Direction.down: if (Position[0].y + 1 == mapHeight - 1) { return true; } return false; case Direction.left: if (Position[0].x - 1 == 0) { return true; } return false; default: return false; } }
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game private void UpdateSnakePositionList(Direction direction, int mapWidth, int mapHeight, Point newHeadPointIfBorderHit, Point newHeadPointIfNormalMove) { if (CheckIfCollisionWithBoundary(direction, mapWidth, mapHeight) == true) { Position.Insert(0, newHeadPointIfBorderHit); } else { Position.Insert(0, newHeadPointIfNormalMove); } Position.RemoveAt(Position.Count - 1); } private bool CheckIfCollisionWithTail() { if (Position.Skip(1).Contains(Position[0])) { return true; } return false; } public void IncreaseLength() { Position.Add(Position[Position.Count - 1]); } public Point GetSnakeHead() { return Position[0]; } public Point GetSnakeTail() { return Position[^1]; } } } Board.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SnakeGame { public class Board { public readonly int Width; public readonly int Height; public Board(int width, int height) { Width = width; Height = height; } public void Draw(List<Point> snakePosition, Point previousSnakeTail, Point applePosition) { DrawBoard(); DrawSnake(snakePosition, previousSnakeTail); DrawApple(applePosition); } private static void DrawApple(Point applePosition) { Console.SetCursorPosition(applePosition.x, applePosition.y); Console.BackgroundColor = ConsoleColor.Red; Console.Write("@"); Console.BackgroundColor = ConsoleColor.Black; }
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game private static void DrawSnake(List<Point> snakePosition, Point previousSnakeTail) { for (int i = 0; i < snakePosition.Count; i++) { Console.SetCursorPosition(snakePosition[i].x, snakePosition[i].y); if (i == 0) { Console.ForegroundColor = ConsoleColor.Blue; Console.Write("O"); Console.ForegroundColor = ConsoleColor.White; } else { Console.Write("o"); } } // Instead of redrawing whole Board just clear previous Snake tail Console.SetCursorPosition(previousSnakeTail.x, previousSnakeTail.y); Console.Write(" "); } private void DrawBoard() { Console.SetCursorPosition(0, 0); for (int i = 0; i < Width; i++) { Console.Write("#"); } Console.WriteLine(); for (int i = 0; i < Height - 2; i++) { Console.Write("#"); Console.SetCursorPosition(Width - 1, i + 1); Console.WriteLine("#"); } for (int i = 0; i < Width; i++) { Console.Write("#"); } } } } Apple.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SnakeGame { public class Apple { public Point Position { get; private set; } public bool IsEaten { get; private set; } public Apple(int mapWidth, int mapHeight, List<Point> snakePosition) { IsEaten = false; SpawnApple(mapWidth, mapHeight, snakePosition); }
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game SpawnApple(mapWidth, mapHeight, snakePosition); } private void SpawnApple(int mapWidth, int mapHeight, List<Point> snakePosition) { Random rand = new Random(); Point applePosition; do { applePosition = new Point(rand.Next(1, mapWidth - 2), rand.Next(1, mapHeight - 2)); } while (snakePosition.Contains(applePosition) != false); Position = applePosition; } public bool CheckIfEaten(Point SnakeHeadPosition) { if(SnakeHeadPosition == Position) { IsEaten = true; return true; } return false; } } } KeyboardManager.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SnakeGame { public static class KeyboardManager { public static Direction GetDirection() { if (Console.KeyAvailable) { ConsoleKeyInfo pressedKey = Console.ReadKey(true); ClearBuffer(); switch (pressedKey.Key) { case ConsoleKey.D: case ConsoleKey.RightArrow: return Direction.right; case ConsoleKey.S: case ConsoleKey.DownArrow: return Direction.down; case ConsoleKey.A: case ConsoleKey.LeftArrow: return Direction.left; case ConsoleKey.W: case ConsoleKey.UpArrow: return Direction.up; default: return Direction.previousDirection; } } return Direction.previousDirection; }
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game private static void ClearBuffer() { while (Console.KeyAvailable) { Console.ReadKey(true); } } } } Score.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SnakeGame { public class Score { private int points = 0; public void PrintScore(int mapHeight) { Console.SetCursorPosition(0, mapHeight); Console.Write($"Your score: {points}"); } public void IncreasePoints() { points++; } public int GetPoints() { return points; } } } Messages.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SnakeGame { public static class Messages { public static void GameOverMessage(int mapWidth, int mapHeight, int score) { Console.SetCursorPosition(mapWidth / 4, mapHeight / 2); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("GAME OVER"); Console.SetCursorPosition(mapWidth / 4, mapHeight / 2 + 1); Console.WriteLine($"Your score was: {score}"); Console.ForegroundColor = ConsoleColor.White; } } } Answer: Program.cs Well done! Rare in the extreme to see good OO with appropriate abstraction level, and decoupling the application from the environment entry point. No public setters public class Game { public Board Board { get; protected set; } public Snake Snake { get; protected set; } public Apple Apple { get; protected set; } public Score Score { get; protected set; } A good class exposes functionality and hides state. The way the code is already written you doesn't need them. NEVER publicly expose internal state.
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game Not this: if (Position[0].y - 1 == 0) { return true; } return false; This: return (Position[0].y - 1 == 0); also the operator overload methods: return (p1.x == p2.x && p1.y == p2.y) Easy Complexity Reduction Technique Return immediately on terminating conditions. Use the ternary operator. This reduces technical complexity scores because those are mainly about the total possible branches. private Direction UpdateCurrentDirection(Direction newDirection) { if (newDirection == Direction.previousDirection) return currentDirection; if (Position.Count == 1) return newDirection; return CheckIfOppositeDirection(newDirection)) ? currentDirection : newDirection; } One line if w/out brackets super-sizes comprehension speed. The secret to getting away with that is to leave white space above & below. BEFORE: private Direction UpdateCurrentDirection(Direction newDirection) { if (newDirection != Direction.previousDirection) { if (Position.Count == 1) { return newDirection; } if (CheckIfOppositeDirection(newDirection) == true) { return currentDirection; } else { return newDirection; } } else { return currentDirection; } } as long as true is true this truthy true is true public void Start() { // ... while (true) { // ... bool isBodyCollision = Snake.Move(direction, Board.Width, Board.Height); if (isBodyCollision) break; // ... }
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game Name the rules controlling game play. Move isBodyCollision declaration out of the loop. bool isBodyCollision = false while (! isBodyCollision) { // ... isBodyCollision = Snake.Move(direction, Board.Width, Board.Height); if (isBodyCollision) continue; // ... } Let the loop conditional control execution. It tends to help prevent temperal coupling as code changes and complexity increases. Leaky Abstraction I like the variable name "Position" public class Snake { ... Position = new List<Point>(); ... } Playing the game we talk about the Snake's position, not a collection of positions. But then the abstraction leaks its implementation somewhat with a method name: UpdateSnakePositionList Change that to UpdateSnakePosition Abstracting - It's Turtles All the Way Down Each layer of code structure, method, and class is an opportunity for abstraction into actual Snake Game terminology, concepts, and game play. As a general rule use names and verbs abstracting away, not hanging onto, actual code implementaiton. Below requires reading the loop code and often reading deeper to make sure I understand what is "true"ly going on: while (true) { // .... } All that effort goes away when: while (! isBodyCollision) { // .... } Class name gives context to methods This: Draw Not: DrawBoard Concise reading enjoyment: Board snakeMaze = new Board(...); snakeMaze.Draw(); switch case & fall-through formatting Always put space between a case break/return and the next case. Fall-through cases in particular stand out much better. case ConsoleKey.D: case ConsoleKey.RightArrow: return Direction.right; case ConsoleKey.S: case ConsoleKey.DownArrow: return Direction.down; case ConsoleKey.A:
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game Check 'check' in method names "Check" is such a generic term that it means nothing. But I'll admit I can't help myself sometimes. Try very hard to replace "check" with something else. It is easier to fix when returning boolean, prefix with "is" CheckIfEaten - IsEaten CheckIfOppositeDirection - ChangedDirection CheckIfCollisionWithBoundary - IsBoundryCollision Concise reading enjoyment: if ( Apple.IsEaten()) if (ChangedDirection()) Get is a given Methods like this: GetSnakeHead(). After about 7,602 GET-prefixed methods, you will realize it is superfluous. SnakeHead() is better. Make it a property - Snake.Head is better still. Concise reading enjoyment: if (Apple.IsEaten(Snake.Head)) Uh, oh. I now see a problem. Not kidding - I thought of it only after I wrote that. The code feels "backwards" and I think "inversion of control" Inversion of Control (IOC) public class Start { ..... if (Apple.CheckIfEaten(Snake.GetSnakeHead())) .... } // Start The Apple should not be responsible for determining if the snake ate it. That's for the snake to do. Due to the "inverted" (backward, inside-out) referencing (dependencies) the Start class must know Snake internal details, head vs tail vs otherParts. Apple also, for it's part. In other words Start must know how the snake eats because Snake does not know how to eat - it has no eating behavior (method). If you have ever experienced a waiter suddenly shoving any part of your body into a plate of food, then you understand the issue here. Concise reading enjoyment: if (Snake.Eats(Apple))
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
c#, object-oriented, snake-game Decouple the game from the UI There should be a new class that makes console calls for UI interaction. There will be no console code anywhere in the Snake Game classes. Then make Game class methods/properties for score, board, etc. The UI class talks to Game object and no others. This is the principle of least knowledge. Suggestion: Board.ToString() returns the board/grid as a string with/n separating rows. Same thing for Score.ToString() and any other UI bound output. Then Game has the interface used by UI objects. public class Game { public string Score() { return Score.ToString(); } public string Board() { return Board.ToString(); } public override string ToString() { return Score() + `/n/n` + Board(); } } Concise reading enjoyment: console.WriteLine(mySnakeGame); // implicit ToString call
{ "domain": "codereview.stackexchange", "id": 44722, "lm_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#, object-oriented, snake-game", "url": null }
python, algorithm, complexity Title: Finding whether there exists a pair of numbers in a set having a given product Question: Devise an algorithm that will operate on a number x and a set of n distinct numbers such that in \$O(n \lg n)\$ time, the algorithm indicates whether or not there are two numbers in the set that have a product of x. Explain why your algorithm works. My algorithm: Sort the set //\$ O(n \lg n)\$ For every element in the set check if x % element =0 // \$O(n)\$ If so check if the dividend x/element exists in the set // \$O(\lg n)\$ If dividend exists and is not equal to element, the two numbers in the set (element and dividend) have a product of x. This algorithm works because it only returns true when the condition(x=element*dividend where element and dividend are in the set) to be satisfied is met. And upon quick Analysis we can see that the algorithm is running at \$O(n\lg n)\$ for the sort and \$O(n)*(\lg n)\$ for checking if the two elements exists. Therefore it is running at \$O(n \lg n) + O(n \lg n) = O(2n \lg n) = O(n \lg n)\$ Can I have some feedback on my solution — whether you think it is correct or not and where you think it can be improved? def findIfProdExists(x,items): items = mergeSort(items) # O(nlgn) for item in items: if(item!=0): if x%item ==0: if(find(x/item,items)and item!=x/item): #binary Search O(lgn) return True return False def mergeSort(aList): size = len(aList) first = aList[:int(size/2)] second = aList[int(size/2):]
{ "domain": "codereview.stackexchange", "id": 44723, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, complexity", "url": null }
python, algorithm, complexity if(size ==1): return aList if(size ==2): if(aList[1]<aList[0]): return list([aList[1],aList[0]]) else: return aList else: return merge(mergeSort(first),mergeSort(second)) def merge(list1,list2): newList =[] i1 =0 i2 =0 while(i1<len(list1) and i2 <len(list2)): if(list1[i1] <list2[i2]): newList.append(list1[i1]) i1+=1 elif(list1[i1]>list2[i2]): newList.append(list2[i2]) i2+=1 newList.extend(list1[i1:] +list2[i2:]) return newList def find(x,items): size = len(items) mid = int(size/2) if(size == 1): if(x == items[0]): return True return False elif(x==items[mid]): return True elif x> items[mid]: return find(x,items[mid:]) else: return find(x,items[:mid]) Answer: The algorithm description is good, but the implementation of find is \$ O(n) \$, so the overall runtime is actually \$ O(n^2) \$. Detailed review follows: There are no docstrings. What does each function do? How do I call it? What does it return? Are there any constraints on the parameters, for example do the inputs have to be sorted? or do they have to be free of duplicates? It's not necessary in Python to have parentheses around the condition of if statement, and it's best to omit them. According to the analysis, find needs to be \$ O(\log n) \$, but the actual implementation is \$ O(n) \$. Here's a demonstration: >>> from timeit import timeit >>> for p in range(2, 8): ... items = list(range(10**p)) ... '{:f}'.format(timeit(lambda:find(0, items), number=1)) ... 0.000012 0.000022 0.000077 0.001386 0.038858 0.417670
{ "domain": "codereview.stackexchange", "id": 44723, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, complexity", "url": null }
python, algorithm, complexity The reason for this is the copying in the recursive calls. In Python, the list slice items[mid:] has to be copied, and the time taken to do this is proportional to the number of items in the copy. See the time complexity page on the Python wiki. In order to avoid copying in find, it's best to keep indexes into the part of the sequence which might contain the item we're looking for: def find(x, items): """Return True if x is an element of the sequence items, assuming items is sorted. """ lo = 0 hi = len(items) while lo < hi: mid = (lo + hi) // 2 if x == items[mid]: return True elif x < items[mid]: hi = mid else: lo = mid + 1 return False Python has a built-in module bisect for binary search of sorted sequences, and using this module it's possible to write find like this: from bisect import bisect_left def find(x, items): """Return True if x is an element of the sequence items, assuming items is sorted. """ i = bisect_left(items, x) return i < len(items) and items[i] == x
{ "domain": "codereview.stackexchange", "id": 44723, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, complexity", "url": null }
python, algorithm, complexity """ i = bisect_left(items, x) return i < len(items) and items[i] == x The corrected version of find locates an element in a sorted list in time \$ O(\log n) \$. But it's possible to do better than that using a set. Set lookup has average complexity \$ O(1) \$. The implementation of merge goes into an infinite loop if list1 and list2 have a common item. This was easy for me to spot because there is an if … elif with no else at the end. When code has a sequence of conditions like this, it's always worth asking, "what happens if none of the conditions apply?" Python has a built-in function heapq.merge for merging sorted iterables into a single sorted iterator, and a built-in function sorted for sorting an iterable (using a variant of mergesort, as it happens). These are fast and well-tested implementations, and (except as an exercise) they should be used in preference to writing your own. In findIfProdExists the division x/item is computed twice in some cases. It would be better to compute it once and remember the value. In findIfProdExists the cheap test item!=x/item is computed after the expensive test find(x/item,items). It's usually best to compute cheap cases first so that if they fail the expensive test can be avoided altogether. Putting all this together, I'd implement the algorithm like this: def product_pair(x, items): """Return True if there is a pair of distinct elements in the iterable items whose product is x. Return False otherwise. """ items = set(items) for item in items: if item != 0 and x % item == 0: y = x / item if y != item and y in items: return True return False
{ "domain": "codereview.stackexchange", "id": 44723, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, algorithm, complexity", "url": null }
python, performance, pygame Title: 2d minecraft with infinite chunk system Question: I've made a python game called 2d minecraft (guess where I got the idea) that has an infinite chunk system. I believe the idea I have is alright but my coding is bad and I have tried to improve it as much as I can before posting here. Here is the code: import pygame # set up variables title, size = "2d_MC", (1365, 705) pygame.init() screen, window_rect, clock = pygame.display.set_mode(size), pygame.Rect((0, 0), size), pygame.time.Clock() pygame.display.set_caption(title) pygame.event.set_allowed([pygame.QUIT]) block_size = 64 block_texture_names = ["textures\\void.png", "textures\\air.png", "textures\\grass_block.png", "textures\\dirt.png", "textures\\stone.png", "textures\\sandstone.png", "textures\\sand.png", "textures\\bedrock.png", "textures\\oak_log.png", "textures\\oak_leaves.png", "textures\\cobblestone.png"] block_textures = [] def block_texture(texture): # does the image loading return pygame.transform.scale(pygame.image.load(texture), (block_size, block_size)).convert_alpha() def convert(pos, convert_value_x, convert_value_y): # converts coordinate systems nx, rx = divmod(pos.x, convert_value_x) ny, ry = divmod(pos.y, convert_value_y) return ((nx, ny), (rx, ry)) class chunk(): width, height = 8, 8 def __init__(self, pos): self.pos = pygame.Vector2(pos) self.blocks = {} # sets up the range and blocks self.range = (range(0, self.width), range(0, self.height)) for x in self.range[0]: for y in self.range[1]: self.blocks[(x, y)] = 0 def load(self): # will be of more use in the future self.generate()
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
python, performance, pygame def load(self): # will be of more use in the future self.generate() def generate(self): # simple generation for now for x in self.range[0]: for y in self.range[1]: x_pos, y_pos = int(self.pos.x)+x, int(self.pos.y)+y surface = 0 bedrock = 16 soil_amount = 3 if y_pos == surface: block = 2 elif y_pos > surface and y_pos <= surface + soil_amount: block = 3 elif y_pos > surface + soil_amount and y_pos < bedrock: block = 4 elif y_pos == bedrock: block = 7 elif y_pos > bedrock: block = 0 else: block = 1 self.blocks[(x, y)] = block def blocks_str(self): # string representation of the blocks in the chunk, for testing purposes return [self.blocks[(x, y)] for x in self.range[0] for y in self.range[1]] def save(self): # will be used in furture pass def unload(self): # will be of more use in the future for x in self.range[0]: for y in self.range[1]: self.blocks[(x, y)] = 0 class world(): def __init__(self, loader_pos, loader_distance): self.loaded_chunks = {} self.loader_pos = loader_pos self.loader_chunk_pos = pygame.Vector2(convert(loader_pos, chunk.width*block_size, chunk.height*block_size)[0]) self.loader_distance = loader_distance self.rendered = pygame.Surface((1, 1)).convert_alpha()
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
python, performance, pygame def handle_chunk_loader(self): # get chunks needed and unloads and loads acordingly chunks_needed = [chunk_pos for chunk_pos in self.chunks_to_load(self.loader_chunk_pos)] chunks_currently_loaded = [chunk_pos for chunk_pos in self.loaded_chunks] self.load_chunks([chunk_pos for chunk_pos in chunks_needed if chunk_pos not in chunks_currently_loaded]) self.unload_chunks([chunk_pos for chunk_pos in chunks_currently_loaded if chunk_pos not in chunks_needed]) def load_chunks(self, chunks_pos): for chunk_pos in chunks_pos: self.loaded_chunks[(chunk_pos.x, chunk_pos.y)] = chunk(chunk_pos) self.loaded_chunks[(chunk_pos.x, chunk_pos.y)].load() def unload_chunks(self, chunks_pos): for chunk_pos in chunks_pos: chunk = self.loaded_chunks.pop(chunk_pos) # chunk.save() chunk.unload() def get_block(self, pos): # will be of more use in the future chunk_pos, block_pos = convert(pos, chunk.width, chunk.height) try: return self.loaded_chunks[chunk_pos].blocks[block_pos] except Exception as e: return 0 def chunks_to_load(self, loader_pos): return [pygame.Vector2(chunk_pos_x*chunk.width, chunk_pos_y*chunk.height) for chunk_pos_x in range(int(loader_pos.x)-self.loader_distance, int(loader_pos.x)+self.loader_distance+1) for chunk_pos_y in range(int(loader_pos.y)-self.loader_distance, int(loader_pos.y)+self.loader_distance+1)] def change_pos(self, pos): self.loader_pos += pos self.loader_chunk_pos = pygame.Vector2(convert(self.loader_pos, chunk.width*block_size, chunk.height*block_size)[0])
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
python, performance, pygame def set_pos(self, pos): self.loader_pos = pos self.loader_chunk_pos = pygame.Vector2(convert(pos, chunk.width*block_size, chunk.height*block_size)[0]) def render(self, screen, use_pos, other_offset=0): for chunk_pos, ch in self.loaded_chunks.items(): chunk_screen_pos = pygame.Vector2(chunk_pos[0], chunk_pos[1])*block_size for block_pos, block in ch.blocks.items(): screen.blit(block_textures[block], ((chunk_screen_pos + pygame.Vector2(block_pos)*block_size) - self.loader_pos*int(use_pos))+other_offset) def handle_events(): for e in pygame.event.get(): if e.type == pygame.QUIT: return 1 keys = pygame.key.get_pressed() if keys[pygame.K_UP]: overworld.change_pos(pygame.Vector2(0, -2)) if keys[pygame.K_DOWN]: overworld.change_pos(pygame.Vector2(0, 2)) if keys[pygame.K_LEFT]: overworld.change_pos(pygame.Vector2(-2, 0)) if keys[pygame.K_RIGHT]: overworld.change_pos(pygame.Vector2(2, 0)) return 0 def draw(): screen.fill((255, 255, 255)) overworld.render(screen, True, other_offset=window_rect.center) #screen.blit(overworld.rendered, (0, 0)) def game_logic(): overworld.handle_chunk_loader() def run_game(): # set up textures for texture in block_texture_names: block_textures.append(block_texture(texture)) while 1: game_logic() if handle_events(): break draw() pygame.display.update(window_rect) clock.tick() print(clock.get_fps()) pygame.quit() overworld = world(pygame.Vector2(0, 0), 2) run_game() It runs at a minimum of 30 fps and maximum of 50 and I would like to get it to 60 at least. I would also not mind reducing the code. Answer: Yay, minecraft! # set up variables title, size = "2d_MC", (1365, 705) pygame.init()
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
python, performance, pygame Answer: Yay, minecraft! # set up variables title, size = "2d_MC", (1365, 705) pygame.init() Delete the vacuous # comment, as it doesn't tell us anything beyond what the code is clearly explaining. Break the tuple assign into two lines, as they are unrelated variables. Similarly for the ..., ..., clock = assignment. In contrast, the width, height = 8, 8 assignment further down is perfect as-is, since it helpfully points out that there is a single concept (with two values) being assigned. That .init() call is troublesome. Protect it within an if __name__ == "__main__": guard. Why? At some point you, or another maintainer, will want to import this module, for example when running unit tests. And there should be no interesting side effects at import time. We should be able to run headless, without a display. Some related calls should be moved along with the init call. block_texture_names = ["textures\\void.png", ... Consider spelling it "textures/void.png", so the code will portably run on more than one OS. If that is infeasible, at least spell it r"textures\void.png". def convert(...): # converts coordinate systems That is a valuable comment. I thank you for it. But python has a special way of explaining what a function does: def convert(...): """Converts coordinate systems.""" Recommend you prefer a """docstring""" over # comments. class chunk(): Pep-8 asks that you spell it class Chunk. And also World. No need for those extra ( ) parens, as you're not inheriting from anything. def __init__(self, pos): self.pos = pygame.Vector2(pos) I don't understand what's going on there. An optional type hint of ...(self, pos: tuple[int, int]): would go a long way toward helping me out. As it stands, I believe we're getting a Vector2 position passed in, and then we turn it into an identical Vector2. Couldn't we have simply assigned it, without creating a copy? self.range = (range(0, self.width), range(0, self.height))
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
python, performance, pygame This is nice enough. Consider breaking it into a pair of assignments so you instead have x_range and y_range. The [0] / [1] subscripts aren't terrible, but they're not super convenient either -- names would improve clarity. self.blocks[(x, y)] = 0 Usually zero (and one) get a pass when it comes to magic numbers. But here it seems like you should define an enum or manifest constant of TEXTURE_VOID to denote the zeroth index into that array. Oh, and we see it a little farther down in generate(), where 1, 2, 3, 4, & 7 are similarly mysterious / magical. The generate() function is not too long. But consider breaking out the inner if's as a trivial helper method. def blocks_str(self): # string representation of the blocks in the chunk, for testing purposes return [self.blocks[(x, y)] for x in self.range[0] for y in self.range[1]] I don't understand that at all. It clearly isn't a string. That is, both the identifier and the comment are lying to us. Do consider def __str__(self):, so that str(my_chunk) and print(my_chunk) will offer nice debugging behaviors. Your self.blocks is a dict, which is nice enough. Consider turning it into a numpy ndarray. You would save on the overhead of storing 962_325 object pointers. More importantly you could linearly scan those ~ 1 M elements without random reads, so the code runs at closer to memory bandwidth speed. And then unload() would become a simple self.blocks = np.zeros(self.range) def get_block(self, pos): # will be of more use in the future chunk_pos, block_pos = convert(pos, chunk.width, chunk.height) try: return self.loaded_chunks[chunk_pos].blocks[block_pos] except Exception as e: return 0
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
python, performance, pygame This "more code coming in future!" seems to be a theme. Resist it. YAGNI. Wait until some future time when new code is needed, and refactor at that point. Some of the implemented methods don't seem to be called, and could be safely removed until needed. Catching Exception is worrisome. Apparently the Author's Intent was to catch IndexError, so specify just that. Habitually catching "too broadly" is an easy way to accidentally mask bugs, which then become hard to diagnose. You say you want this to run ~ twice as fast. There's no profiler output in this submission that would help to pinpoint where the bulk of the time is being spent. I imagine it is probably in the render() loop. I wonder if tracking "screen update deltas" would speed it up? That is, if you're scrolling horizontally and a row is usually TEXTURE_BEDROCK both before / after the scroll, would it help to not re-render it? (I don't know -- time it!) An obvious thing to do would be choose lower resolution, that is, bigger texture blocks. Then you're blit'ing fewer blocks. A less obvious thing to do is inspired by the progressive rendering of e.g. PNG and JPEG images, and by the fact that sometimes the user is rapidly scrolling across blocks and sometimes not. During rapid scrolling with e.g. pygame.K_LEFT depressed, query the current FPS and if it is "slow" (e.g. 30 FPS) then reduce resolution so you're blit'ing fewer blocks. When the arrow key is released we're no longer scrolling so there are zero deltas and FPS should be "fast". At that point we can afford to render at maximum resolution, so the scrolling effect is low-res "blur" and when we halt then all the detailed blocks will progressively render to show a hi-res image.
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
python, performance, pygame EDIT Suppose you can only do K block blits per frame if you want to stay at 60 FPS. Init a list of all (x, y) block positions. At start of each frame, shuffle it, and blit just the initial K locations. (Use the sorted() initial locations to take better advantage of the memory hierarchy. Or equivalently, instead of shuffle use random draws compared against threshold so that, in expectation, you blit about K blocks.) During rapid scrolling there will be visual artifacts, but upon halting the screen will rapidly update and stabilize. Actually, no need to shuffle each time, doing that at init suffices. Just keep walking your index circularly through the scheduled block coordinates, and on next frame pick up where you left off. Randomizing at the horizontal raster level, rather than the block level, would be enough. Better, let's assume you can do about K blits and "little" or "big" blits have about the same cost. Then we want to cache giant pre-rendered multi-block regions. Remove the K_LEFT / K_RIGHT actions for the moment, so now we have an app which can only scroll up / down. We render a raster of blocks near the middle of the screen. Notice that the same raster will be horizontally displayed at one of the {above, below, same} rows on next frame, according to whether the keyboard demands scrolling or is idle. So upon laboriously looping over the whole raster and rendering each block, we finish up by creating a cached raster by blit'ing the screen result into the cache. On the next render(), we probe the cache and either do a single giant blit or else we render block-by-block. Now suppose we only honor K_LEFT / K_RIGHT events. Same thing, pretty much, just cache vertical columns of pre-rendered blocks. Now combine those behaviors, where rendering is aware of the recent scroll direction. We don't need to cache a full raster -- using quarter rasters might still be helpful, and would more robustly handle diagonal scrolling.
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
python, performance, pygame might still be helpful, and would more robustly handle diagonal scrolling. Caching larger regions, say 16 x 16, might also work well.
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
python, performance, pygame This code achieves most of its objectives. It would benefit from some minor refactoring. The structure is solid, as the two classes nicely reflect Separation of Concerns. I would be willing to delegate or accept maintenance tasks on this codebase.
{ "domain": "codereview.stackexchange", "id": 44724, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, performance, pygame", "url": null }
javascript, strings, unit-testing, regex Title: Attempt at Perl transliteration function in JavaScript with flags
{ "domain": "codereview.stackexchange", "id": 44725, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, strings, unit-testing, regex", "url": null }
javascript, strings, unit-testing, regex Question: I've been trying to rewrite the perl transliteration function in javascript. This isn't a complete replication, and I haven't looked at the perl source code... I took inspiration from this question for my source code. some unit tests (not all): describe('without flags', () => { it('should produce a function that transliterates abcd to dcba when search is abcd and replacement is dcba', () => { let text = 'abcd'; let search = 'abcd'; let replace = 'dcba'; let expected = 'dcba'; let actual = tr(text, search, replace); expect(actual).to.be.equal(expected); }); it('should produce a function that transliterates ruby to perl when search is bury and replacement is repl', () => { let text = 'ruby'; let search = 'bury'; let replace = 'repl'; let expected = 'perl'; let actual = tr(text, search, replace); expect(actual).to.be.equal(expected); }); }); describe('with s flag', () => { before(() => { flags = 's'; }); it('should produce a function that transliterates abba to pop when search is ab and replacement is pop', () => { let text = 'abba'; let search = 'ab'; let replace = 'po'; let expected = 'pop'; let actual = tr(text, search, replace, flags); expect(actual).to.be.equal(expected); }); }); }); describe('with d flag', () => { before(() => { flags = 'd'; }); it('should produce a function that transliterates abba to aa when search is b and replacement is null', () => { let text = 'abba'; let search = 'b'; let replace = ''; let expected = 'aa'; let actual = tr(text, search, replace, flags); expect(actual).to.be.equal(expected); }); it('should produce a function that transliterates adam to eve when search is adm and replacement is ev', () => { let text = 'adam'; let search = 'adm'; let replace = 'ev';
{ "domain": "codereview.stackexchange", "id": 44725, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, strings, unit-testing, regex", "url": null }