text
stringlengths
1
2.12k
source
dict
c++, recursion, reinventing-the-wheel, template, c++20 Simplify variadic templates You have two versions of pixelwiseOperation(), one which takes exactly 3 arguments, and one which takes 3 + a variable number of arguments. However, note that parameter packs are allowed to be empty, so you don't need the version which takes exactly 3 arguments at all. Furthermore, the only reason you need to have both input1 and inputs is to get the size of the first image. The rest of the code doesn't care about input1, but now you have to pass it to everything explicitly. Instead, I would suggest you remove input1 from the argument list, and use a helper function function to get the first element of the parameter pack, like so: template<typename Arg, typename... Args> constexpr static auto& first_of(Arg& first, Args&...) { return first; }
{ "domain": "codereview.stackexchange", "id": 42579, "lm_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++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c++, recursion, reinventing-the-wheel, template, c++20 template<typename Op, class... Args, std::size_t unwrap_level = 1> constexpr static auto pixelwiseOperation(Op op, const Args&... inputs) { return TinyDIP::Image( recursive_transform<unwrap_level>( op, inputs.getImageData()... ), first_of(inputs...).getWidth(), first_of(inputs...).getHeight() ); } Since you don't care whether it's the first or last input you take the size of (they should all have the same after all), you could even use a trick like this: (inputs, ...).getWidth(), (inputs, ...).getHeight() But this will produce lots of compiler warnings about left hand sides of comma operators having no effect. The unwrap_level can't be changed If you have a template parameter pack, any template parameters after that pack cannot be manually changed anymore. Furthermore, it's very cumbersome to first have to specify all other types first when those can be deduced from the input. So make sure unwrap_level is the first template parameter. Or in this case, you could also make it the only one, and use auto for the function arguments, like so: template<std::size_t unwrap_level = 1> constexpr static auto pixelwiseOperation(auto op, const auto&... inputs) { ... } If it shouldn't be changed to begin with, then unwrap_level should not be a template argument, instead just pass 1 directly as the template argument of the call to recursive_transform() (or don't specify it at all, since the latter function has it defaulted to 1 itself). Consider adding friend arithmetic operators You already have member operators like operator+=(), but there is no operator+(). Consider implementing them as well, as friend functions. Incorrect behavior of difference() The function difference() first calls subtract(), then calls abs() on it. However, if ElementT is an unsigned type, then the result of subtract() will always be positive, so abs() will do nothing. You have to calculate the absolute difference for each element indivually.
{ "domain": "codereview.stackexchange", "id": 42579, "lm_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++, recursion, reinventing-the-wheel, template, c++20", "url": null }
c#, json, .net-core Title: Achieving same abstraction by replacing JObject's implementation with System.Text.Json alternative Question: I'm trying to improve this wrapper by replacing the Newtonsoft.Json with System.Text.Json in its BinanceWebSocketClient class and more specifically the HandleObjectMessage method. It is a message handler, which is supposed to parse the JSON results returned by the combined stream. Combined stream events are wrapped as follows: {"stream":"","data":} The stream field is telling us what the stream name is. For ex. !miniTicker@arr. And data is the actual data corresponding to the stream name. The handler HandleObjectMessage must recognize the JSON returned and parse it to the corresponding stream name object. If it's a kline, it should parse it to the KlineResponse class and so on. GitHub (original HandObjectMessage) GitHub (original BookTickerResponse) Here are my changes to System.Text.Json. This is what I want to be reviewed. There were developers who actually used switch like here instead of that abstraction. public class BookTickerResponse : ResponseBase<BookTicker> { internal static bool TryHandle(JsonDocument response, ISubject<BookTickerResponse?> subject) { var stream = response.RootElement.GetProperty("stream").GetString() ?? string.Empty; if (!stream.ToLower().EndsWith("@bookTicker")) return false; var parsed = response.ToObject<BookTickerResponse>(); subject.OnNext(parsed); return true; } } public sealed class BinanceWebSocketClient : IDisposable { ... private bool HandleObjectMessage(string msg) { using var response = JsonDocument.Parse(msg);
{ "domain": "codereview.stackexchange", "id": 42580, "lm_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#, json, .net-core", "url": null }
c#, json, .net-core // Add object handlers return AggregateTradeResponse.TryHandle(response, Streams.TradeBinSubject) || TradeResponse.TryHandle(response, Streams.TradesSubject) || MiniTickerResponse.TryHandle(response, Streams.MiniTickerSubject) || BookTickerResponse.TryHandle(response, Streams.BookTickerSubject) || KlineResponse.TryHandle(response, Streams.KlineSubject); } } Answer: TryHandle First of all I would not trust the input parameters. I suggest to make sure that they are not null before you start accessing their members (like response.RootElement) As far as I know the GetProperty throws KeyNotFoundException if a given key is not present The GetString might throw an InvalidOperationException if the JsonElement's ValueKind is neither String nor Null ToLower().EndsWith: Depending on how often this method is called, a complied regex might provide better performance As far I know JsonDocument does not have neither ToObject method nor extension method. Is it a custom built solution, like this? HandleObjectMessage At the first glance the single return statement seems a bit weird Let me show you an alternative where the actions and their relation are separated var probes = new Func<bool>[] { () => AggregateTradeResponse.TryHandle(response, Streams.TradeBinSubject), () => TradeResponse.TryHandle(response, Streams.TradesSubject), () => MiniTickerResponse.TryHandle(response, Streams.MiniTickerSubject), () => BookTickerResponse.TryHandle(response, Streams.BookTickerSubject), () => KlineResponse.TryHandle(response, Streams.KlineSubject) }; return probes.Any(probe => probe()); So, here we have defined several probe methods Then we iterate through them until we find one where the probe passes or until we run out of options With this approach the return statement is simple and easy to understand.
{ "domain": "codereview.stackexchange", "id": 42580, "lm_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#, json, .net-core", "url": null }
c#, json, .net-core UPDATE #1: avoid closure In order to capture the response in a closure you can do the following: var probes = new Func<JsonDocument, bool>[] { (res) => AggregateTradeResponse.TryHandle(res, Streams.TradeBinSubject), (res) => TradeResponse.TryHandle(res, Streams.TradesSubject), (res) => MiniTickerResponse.TryHandle(res, Streams.MiniTickerSubject), (res) => BookTickerResponse.TryHandle(res, Streams.BookTickerSubject), (res) => KlineResponse.TryHandle(res, Streams.KlineSubject) }; return probes.Any(probe => probe(response));
{ "domain": "codereview.stackexchange", "id": 42580, "lm_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#, json, .net-core", "url": null }
c++, performance, stack Title: Optimization suggestions for my Stack Question: stack.hpp class Stack { public: Stack(float incFactor = 1.5f); ~Stack(); template<typename T> inline void push(T value) { validate(sizeof(T)); *(reinterpret_cast<T*>(top)) = value; top += sizeof(T); size += sizeof(T); } void push(char* value); void push(char* value, int size); template<typename T> inline T pop() { validate(sizeof(T)); top -= sizeof(T); size -= sizeof(T); return *(reinterpret_cast<T*>(top)); } char* pop_str(); char* pop(int size = 1); void print(const char* end = "\n"); void print_int(const char* end = "\n"); int length(); void* get_data(); void revalidate(int size); private: float incFactor; char* top; char* data; int size; int capacity; }; stack.cpp Stack::Stack(float incFactori) { incFactor = incFactori; capacity = STACK_SIZE; size = 0; data = (char*)malloc(capacity); top = data; } Stack::~Stack() { if(data) free(data); } void Stack::print(const char* end) { printf("[ "); for(int i = 0; i < size; i++) printf("%d ", (int)data[i]); printf("]"); printf("%s", end); } void Stack::print_int(const char* end) { printf("[ "); int count = size / sizeof(int); for(int i = 0; i < count; i++) printf("%d ", ((int*)data)[i]); printf("]"); printf("%s", end); } void Stack::revalidate(int sizei) { if(sizei + size > capacity) { capacity = (int)(capacity * incFactor); char* datat = (char*)malloc(capacity); memcpy(datat, data, size); free(data); data = datat; top = data + size; } } void Stack::push(char* value) { validate(strlen(value) + 1); *top = '\0'; memcpy(top + 1, value, strlen(value)); top += strlen(value) + 1; size += strlen(value) + 1; }
{ "domain": "codereview.stackexchange", "id": 42581, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, stack", "url": null }
c++, performance, stack void Stack::push(char* value, int sizei) { validate(sizei); memcpy(top, value, sizei); top += sizei; size += sizei; } char* Stack::pop_str() { char* value = top - 1; int sizei = 0; while(*value != '\0') { value--; sizei++; } char* outStr = (char*)malloc((top - value) + 1); memset(outStr, '\0', (top - value) + 1); memcpy(outStr, value + 1, top - value); outStr[top - value] = '\0'; top -= sizei + 1; size -= sizei + 1; return outStr; } char* Stack::pop(int sizei) { char* value = top - sizei; char* outStr = (char*)malloc((top - value)); memset(outStr, '\0', (top - value)); memcpy(outStr, value, top - value); top -= sizei; size -= sizei; return outStr; } int Stack::length() { return size; } void* Stack::get_data() { return data; } Repo : https://github.com/Jaysmito101/tovie/blob/master/include/stack.hpp https://github.com/Jaysmito101/tovie/blob/master/src/stack.cpp Answer: You're implementing a growable collection like vector and only using it for this Stack. Don't use raw pointers, malloc, etc. If you are implementing your own low-level memory management (instead of just using vector), at least use unique_ptr for the data. You should not need to write a destructor for the class! Writing inline for a member function defined inside the class doesn't do anything.
{ "domain": "codereview.stackexchange", "id": 42581, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, stack", "url": null }
c++, performance, stack Writing inline for a member function defined inside the class doesn't do anything. So Stack is not a template based on the element type, but push and pop are templates? This is weird and dangerous. How do you you know what the next element is supposed to be in order to pop it correctly? You are not respecting the alignment of the objects you push. That can fail on some architectures. You are not calling destructors of all the stacked stuff when you destroy the stack. The Pop function copies the element into the return value, but never calls the destructor of the location on the stack. Try stacking std::string objects and watch the memory leaks! The autogenerated copy constructor and assignment operator will not work properly, and will simply copy the data pointer and now the two instances can fight over it! If you write any of the special member functions (e.g. the destructor, as you have), you probably need to write all of them. You're using malloc, printf; you don't appreciate that objects have constructors/destructors even though your class needs it; is seems like this has a "C" mentality and just dresses it up in a class but it's not really. What are your design requirements for this? How is it different from the std::stack? What is your goal in writing it: is it something you need, or is it to learn how such data structures can be implemented? Start with documentation. Let others help spot gaps and inconsistencies (like the copy constructor) in the design first. You should not be worrying about optimization at this point: first make it correct. Deeper than that, make it do something sensible in the first place.
{ "domain": "codereview.stackexchange", "id": 42581, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance, stack", "url": null }
python Title: Get data from nfo file with functions Python Question: I am learning python and I have made a function to get text from a .nfo file, improving on this block of code: # Book Author _author = ["Author:", "Author.."] logger_nfo.info('Searching Author book...') with open(nfofile, "r+", encoding='utf-8') as file1: fileline1 = file1.readlines() for x in _author: # <--- Loop through the list to check for line in fileline1: # <--- Loop through each line line = line.casefold() # <--- Set line to lowercase if x.casefold() in line: logger_nfo.info('Line found with word: %s', x) nfo_author = line if nfo_author == '': logger_nfo.warning('Author not found.') I've made this function: nfofile_link = "The Sentence.nfo" search_for = ["Author:", "Author.."] def search_nfo(nfofile_link, search_for): logger_nfo.info('Searching nfo') with open(nfofile_link, "r+", encoding='utf-8') as file1: fileline1 = file1.readlines() for x in search_for: # <--- Loop through the list to check for line in fileline1: # <--- Loop through each line line = line.casefold() # <--- Set line to lowercase if x.casefold() in line: logger_nfo.info('Line found with word: %s', x) global nfo_author nfo_author = line search_nfo(nfofile_link, search_for) print(nfo_author)
{ "domain": "codereview.stackexchange", "id": 42582, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python search_nfo(nfofile_link, search_for) print(nfo_author) This works, but I'd like to improve it, how can I do that? An example of the .nfo file's content: General Information =================== Title: Agent in Berlin Author: Alex Gerlis Read By: Duncan Galloway Copyright: 2021 Audiobook Copyright: 2021 Genre: Audiobook Publisher: Canelo Series Name: Wolf Pack Spies Position in Series: 01 Abridged: No Original Media Information ========================== Media: Downloaded Source: Audible Condition: New File Information ================ Number of MP3s: 42 Total Duration: 11:33:05 Total MP3 Size: 319.23 MB Encoded At: 64 kbit/s 22050 Hz Mono ID3 Tags: Set, v1.1, v2.3
{ "domain": "codereview.stackexchange", "id": 42582, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Answer: Embrace functions, not global variables. It's good that you put your code in a function. However, you are not taking full advantage of the power of functions because you use the function to modify a global variable. Except under very rare circumstances, that is not a good idea. Instead, functions should take arguments and returns values. Organize your programs around that basic model. Push algorithmic details into easily testable functions. A function that requires a file to exist is more awkward to test and debug than a function that takes text and returns a value. A simple data-oriented function, for example, can be pasted into a Python REPL and experimented with. An automated test for such a function is easy to write because you only need to define a list/tuple of strings and pass them into the function. For such reasons, I would reduce search_nfo() to the bare minimum: open the file, read the lines, and do any needed logging. That's it. Delegate most of the work -- in particular, the algorithmic details that might contain bugs, that might require debugging, testing, or future modification -- to a separate function. Don't lowercase more often than you need to. Currently you are lowercasing values inside of nested for-loops. That's not a huge problem if the volume of data is moderate or small. Nonetheless, it's a decent idea to practice good habits of editing your code to weed out unnecessary operations. Don't take that virtue to unreasonable extremes, but keep it in mind. def main(): nfo_author = search_nfo('foobar.nfo', ('Author:', 'Author..')) print(nfo_author) def search_nfo(nfofile_link, search_for): with open(nfofile_link) as fh: nfo_author = search_nfo_lines(fh.readlines(), search_for) return nfo_author
{ "domain": "codereview.stackexchange", "id": 42582, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python def search_nfo_lines(lines, search_for): targets = tuple(s.casefold() for s in search_for) for line in lines: lower_line = line.casefold() if any(t in lower_line for t in targets): # Do you want to return the original line # or the lowercase line? Adjust as needed. return line return None if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 42582, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
c++, event-handling Title: Event Dispatching System Question: Below you can see my implementation of a simple event dispatcher. I would like to get some feedback or improvement tips regarding the design and maybe an idea how to get rid of the static_cast. Thank you very much. Classes Event.h #pragma once #include <cstdint> enum class EventType : uint8_t { ButtonPress, FactoryReset }; class Event { public: Event() = default; explicit Event(EventType type) : mType(type) {} virtual ~Event() = default; inline const EventType Type() const { return this->mType; }; protected: EventType mType; }; ButtonPressEvent.h #pragma once #include "Event.h" class ButtonPressEvent final : public Event { public: ButtonPressEvent(uint8_t pin) : Event(EventType::ButtonPress), mPin(pin) {}; uint8_t mPin; }; FactoryResetEvent.h #pragma once #include "Event.h" class FactoryResetEvent final : public Event { public: FactoryResetEvent() : Event(EventType::FactoryReset) {}; }; Subscriber.h #pragma once #include <functional> #include <map> #include <memory> #include "Event.h" using EventHandlerType = std::function<void(std::unique_ptr<Event>&)>; class Subscriber { public: virtual ~Subscriber() = default; virtual std::map<EventType, EventHandlerType> GetSubscribedEvents() = 0; }; Dispatcher.h #pragma once #include <map> #include <memory> #include <vector> #include "Event.h" #include "Subscriber.h" class Dispatcher { public: Dispatcher(); void Listen(EventType type, const EventHandlerType &funct); void Subscribe(Subscriber *subscriber); void Post(std::unique_ptr<Event> &ptr); void Process(); private: std::map<EventType, std::vector<EventHandlerType>> mObservers; std::vector<std::unique_ptr<Event>> mEvents; }; Dispatcher.cpp #include "Dispatcher.h"
{ "domain": "codereview.stackexchange", "id": 42583, "lm_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++, event-handling", "url": null }
c++, event-handling Dispatcher.cpp #include "Dispatcher.h" void Dispatcher::Listen(EventType type, const EventHandlerType &funct) { this->mObservers[type].push_back(funct); } void Dispatcher::Subscribe(Subscriber *subscriber) { for (auto&& event : subscriber->GetSubscribedEvents()) { this->Listen(event.first, event.second); } } void Dispatcher::Post(std::unique_ptr<Event> &ptr) { this->mEvents.push_back(std::move(ptr)); } void Dispatcher::Process() { if (this->mEvents.empty()) { return; } for (auto&& event : this->mEvents) { // call listener functions for (auto&& observer : this->mObservers.at(event->Type())) { observer(event); } } this->mEvents.clear(); } Usage App.h #pragma once #include "Subscriber.h" class App : public Subscriber { public: std::map<EventType, EventHandlerType> GetSubscribedEvents(); void OnButtonPressEvent(std::unique_ptr<Event> &event); }; App.cpp #include <functional> #include <stdio.h> #include "App.h" #include "Event.h" #include "ButtonPressEvent.h" std::map<EventType, EventHandlerType> App::GetSubscribedEvents() { return { { EventType::ButtonPress, std::bind(&App::OnButtonPressEvent, this, std::placeholders::_1) } }; } void App::OnButtonPressEvent(std::unique_ptr<Event> &event) { ButtonPressEvent *b = static_cast<ButtonPressEvent*>(event.get()); printf("Button pin %d pressed", b->mPin); } main.cpp #include "Dispatcher.h" #include "ButtonPressEvent.h" #include "App.h" void main(void) { App app; Dispatcher dispatcher; dispatcher.Subscribe(&app); // simulate event std::unique_ptr<Event> ptr(new ButtonPressEvent(11)); dispatcher.Post(ptr); while (true) { dispatcher.Process(); } }
{ "domain": "codereview.stackexchange", "id": 42583, "lm_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++, event-handling", "url": null }
c++, event-handling while (true) { dispatcher.Process(); } } Answer: Delete the default constructor of Event The default constructor of Event doesn't initialize mType, leaving it in an undefined state. You probably never want to create a default initialized Event object, so it would be best to delete it to catch any incorrect use: Event() = delete; Make mType const Assuming you never want to change the type of an event after creating it, you should make the member variable mType const. Use std::unordered_map instead of std::map where possible Since you don't require mObservers to be ordered in any way, use std::unordered_map, as it has \$O(1)\$ lookups instead of \$O(\log N)\$. Consider the overhead of returning a std::map GetSubscribedEvents() is a very costly operation, since it returns a std::map by value. In this case, it is more efficient to let the subscriber call Listen() instead of the dispatcher. So instead of GetSubscribedEvents(), you could instead have a member function Subscribe() like so: void App::Subscribe(Dispatcher& dispatcher) { dispatcher.Listen(EventType::ButtonPress, std::bind(&App::OnButtonPressEvent, this, std::placeholders::_1)); } And instead of: dispatcher.Subscribe(&app); Call: app.Subscribe(dispatcher); Lifetime management of events There are several issues with how you manage the lifetime of Event objects. It is a good idea to use std::unique_ptr, as this avoids memory management issues. However, you still need to consider how and when ownership is transferred. The function Post() takes a reference to a std::unique_ptr<Event>, and then internally std::move()s it into the vector mEvents. While this is legal, it is hard to see just from the API that Post() is taking over ownership. It is better to make this explicit, by having Post() take a forwarding reference: void Dispatcher::Post(std::unique_ptr<Event>&& ptr) { mEvents.push_back(std::move(ptr)); }
{ "domain": "codereview.stackexchange", "id": 42583, "lm_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++, event-handling", "url": null }
c++, event-handling This now forces the caller to use std::move() as well, which makes it clear at the call site that ownership is transferred: std::unique_ptr<Event> ptr(new ButtonPressEvent(11)); dispatcher.Post(std::move(ptr)); While it looks like more work, it now actually supports passing in a temporary variable, like so: dispatcher.Post(std::make_unique<ButtonPressEvent>(11)); In fact, since it is likely that you want to create and post the event in one go, you could make Post() a template that does this: template<typename T, typename... Args> void Post(Args&&... args) { mEvents.push_back(std::make_unique<T>(std::forward<Args>(args)...)); } And then the caller can do: dispatcher.Post<ButtonPressEvent>(11); Another lifetime issue happens when the observers are called. Again, you pass the event as a reference to a std::unique_ptr<Event>, since you defined the type of an observer as: using EventHandlerType = std::function<void(std::unique_ptr<Event>&)>; However, this allows an observer to modify the event, and even std::move() the event out of the std::unique_ptr. This is clearly very undesirable, as there might be multiple observers, and they all should see the same event. Instead, you should pass a const reference to the Event: using EventHandlerType = std::function<void(const Event&)>; Call the observers like so: for (auto& event : mEvents) for (auto& observer : mObservers.at(event->Type())) observer(*event); And then the observer looks like: void App::OnButtonPressEvent(const Event& event) { auto& b = static_cast<const ButtonPressEvent&>(event); std::cout << "Button pin " << b.mPin << " pressed\n"; }
{ "domain": "codereview.stackexchange", "id": 42583, "lm_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++, event-handling", "url": null }
python, python-3.x, numpy, pandas Title: Calculate a time weighted average of a feature Question: I'm trying to calculate a time weighted average of a feature (feat) based on previous rows by date for a given class. Below is a sample output: +------------+-------+------+---------------------+ | date | class | feat | time_weight_av_feat | +------------+-------+------+---------------------+ | 11/11/2000 | 2 | 9 | 3.98144991 | | 10/06/2000 | 2 | 3 | 4.520009579 | | 17/03/2000 | 2 | 7 | 2 | | 01/03/2000 | 2 | 2 | NaN | | 11/07/2000 | 1 | 2 | 2.730337656 | | 08/05/2000 | 1 | 4 | 2.03150533 | | 04/03/2000 | 1 | 3 | 1 | | 01/01/2000 | 1 | 1 | NaN | +------------+-------+------+---------------------+ time_weight_av_feat is calculated for each row by assigning a time weighted value to each of the previous rows for a given class. These are then multiplied by the feat for that row and summed. This total is this divided by a sum of the time weighted values to produce an average. My current code is as follows: import datetime as dt import pandas as pd import numpy as np from tqdm import tqdm pd.options.mode.chained_assignment = None df = pd.DataFrame( { 'date': ( dt.datetime(2000, 1, 1), dt.datetime(2000, 3, 4), dt.datetime(2000, 5, 8), dt.datetime(2000, 7, 11), dt.datetime(2000, 3, 1), dt.datetime(2000, 3, 17), dt.datetime(2000, 6, 10), dt.datetime(2000, 11, 11), ), 'class': (1, 1, 1, 1, 2, 2, 2, 2), 'feat': (1, 3, 4, 2, 2, 7, 3, 9), } )
{ "domain": "codereview.stackexchange", "id": 42584, "lm_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, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas df_sorted = df.sort_values("date", ascending=False) classes = list(pd.unique(df_sorted["class"])) discount_constant = 0.999 dfs = [] for _, c in enumerate(tqdm(classes), 1): df_class = df_sorted[df_sorted["class"] == c] df_class.reset_index(drop=True, inplace=True) for idx, row in df_class.iterrows(): df_prev = df_class.iloc[idx + 1:].copy() df_prev["days_diff"] = [int((row["date"] - d).days) for d in df_prev["date"]] df_prev["time_weight"] = discount_constant ** df_prev["days_diff"] sum_time_weight_feat = (df_prev["feat"] * df_prev["time_weight"]).sum() sum_time_weight = df_prev["time_weight"].sum() df_class.at[idx, "time_weight_av_feat"] = sum_time_weight_feat / sum_time_weight dfs.append(df_class) This works fine. However, if I scale up to a data frame of 1.5m rows: def random_dates(start, end, n): divide_by = 24*60*60*10**9 start_u = start.value // divide_by end_u = end.value // divide_by return pd.to_datetime(np.random.randint(start_u, end_u, n), unit="D") num_rows = 15000000 start = pd.to_datetime('1990-01-01') end = pd.to_datetime('2021-01-01') dates = random_dates(start, end, num_rows) classes = np.random.randint(1, 80000, num_rows) feats = np.random.randint(1, 10, num_rows) df = pd.DataFrame({'date': dates, "class": classes, "feat": feats}) Then the forecast is 10 hrs+ and I now get a RuntimeWarning. I've now read enough about replacing for loops with numpy vectorisation to thoroughly confuse myself. Would anyone be able to get me onto the right path?
{ "domain": "codereview.stackexchange", "id": 42584, "lm_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, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas Edit: As the answer by Reinderien suggested moving the time_weight_av_feat backwards by one date to avoid the NaNs I thought it would be useful to explain the context of the real use case. Each of the rows in the data frame is actually a sports match with class being a player ID and feat being a performance metric that was recorded after the match was played. time_weight_av_feat, along with lots of other similar variants is fed into a model that predicts the outcome of the match. As such, it is key that the time_weight_av_feat for a row does not include the feat for that row in its calculation. If the easiest way to write the code is to move the time_weight_av_feat backwards by one date then this is simple enough to handle as I'll just move all the time_weight_av_feat forward again before submitting them to the predictive model. However, I thought I'd mention it... Answer: I still don't think that your NaNs are appropriate, but since you sound determined: my proposed code includes them. Importantly: your two loops for idx, row in df_class.iterrows(): and [int((row["date"] - d).days) for d in df_prev["date"]] imply an O(nΒ²) time complexity. There is a mathematically equivalent implementation which is to apply a discrete differential over the date series, and update your sums in O(n) time. Unfortunately I see no easy way to vectorise that part. The following suggested code shows a simpler and probably faster way to express your geometric weighted expanding mean. from datetime import datetime import pandas as pd import numpy as np DISCOUNT = 1e-3 ONE_DAY = pd.to_timedelta(1, 'd') def geomean(df: pd.DataFrame) -> pd.Series: # Change the first value in the group's weight from a negative # value produced by diff() crossing a group boundary to 0. df.weight.iloc[0] = 0 weight_sum = 0 feat_sum = 0
{ "domain": "codereview.stackexchange", "id": 42584, "lm_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, numpy, pandas", "url": null }
python, python-3.x, numpy, pandas # Target numpy array: same length as the group dataframe; uninitialised means = np.empty_like(df.feat.values, dtype=np.float64) means[0] = float('NaN') # Co-evolve the weight and feature sums based on pre-calculated weights # This is an O(n) calculation equivalent to the full-form O(nΒ²) calculation # In its current form it will be difficult (impossible?) to vectorise. for index, row in enumerate(df.iloc[:-1].itertuples()): weight_sum = weight_sum*row.weight + 1 feat_sum = feat_sum*row.weight + row.feat means[index + 1] = feat_sum / weight_sum return pd.Series(name='mean', data=means, index=df.index) def grouped_geomean(df: pd.DataFrame) -> pd.Series: sorted = df.sort_values(by=['class', 'date']) # Calculate weight based on discrete differential over date column as fractional days sorted['weight'] = (1 - DISCOUNT)**(sorted.date.diff() / ONE_DAY) # apply() here is non-vectorised. droplevel() is required to drop the outer index # which is the class number. return sorted.groupby('class').apply(geomean).droplevel(0) def test() -> None: df = pd.DataFrame( { 'date': ( datetime(2000, 1, 1), datetime(2000, 3, 4), datetime(2000, 5, 8), datetime(2000, 7, 11), datetime(2000, 3, 1), datetime(2000, 3, 17), datetime(2000, 6, 10), datetime(2000, 11, 11), ), 'class': (1, 1, 1, 1, 2, 2, 2, 2), 'feat': (1, 3, 4, 2, 2, 7, 3, 9), } ) feat_mean = grouped_geomean(df) assert np.all(np.isclose( feat_mean[1:4], (1.000000, 2.031505, 2.730338), )) assert np.all(np.isclose( feat_mean[5:8], (2.000000, 4.520010, 3.981450), )) if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 42584, "lm_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, numpy, pandas", "url": null }
programming-challenge, rust Title: 2021 Advent of Code, Day 1 Part 2: Keeping error-handling simple while chaining iterators with Rust Question: This question is with respect to Day 1, Part 2 of the 2021 Advent Of Code challenge, which requires comparing values from a rolling window taken from integers streamed as input. This answer is correct, insofar as it emits the intended output, but I'm unclear as to the quality of the code. (This challenge is no longer scored for points, making it within the rules to post/submit/stream/discuss/otherwise share answers). My overall goal here is to learn to write reasonably good Rust code; all advice towards that end will be gratefully accepted. use std::collections::VecDeque; use std::error; use std::error::Error; use std::io; use std::io::BufRead; use std::ops::{Add, AddAssign, Sub}; use std::result::Result; pub struct WindowedSumIter<'a, T, E> where T: Default + Add<Output = T> + Sub<Output = T> + AddAssign + Copy, { source: &'a mut dyn Iterator<Item = Result<T, E>>, window: VecDeque<T>, sum: T, finished: bool, }
{ "domain": "codereview.stackexchange", "id": 42585, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, rust", "url": null }
programming-challenge, rust impl<'a, T, E> WindowedSumIter<'a, T, E> where T: Default + Add<Output = T> + Sub<Output = T> + AddAssign + Copy, { pub fn new( source: &'a mut dyn Iterator<Item = Result<T, E>>, window_size: u32, ) -> Result<Self, E> { let mut sum: T = T::default(); let mut window: VecDeque<T> = VecDeque::new(); let mut finished: bool = false; // fill the window at initialization time for _ in 0..window_size { let item = source.next(); match item { None => { finished = true; } Some(maybe_value) => match maybe_value { Ok(value) => { sum = sum + value; window.push_back(value); } Err(e) => { return Result::Err(e); } }, } } Ok(WindowedSumIter { source, window, sum, finished, }) } }
{ "domain": "codereview.stackexchange", "id": 42585, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, rust", "url": null }
programming-challenge, rust impl<'a, T, E> Iterator for WindowedSumIter<'a, T, E> where T: Default + Add<Output = T> + Sub<Output = T> + AddAssign + Copy, { type Item = Result<T, E>; fn next(&mut self) -> Option<Self::Item> { if self.finished { None } else { let old_value = self.window.pop_front().unwrap(); let maybe_new_value = self.source.next(); match maybe_new_value { None => { self.finished = true; Some(Result::Ok(self.sum)) } Some(new_value_or_error) => match new_value_or_error { Ok(new_value) => { let orig_sum = self.sum; self.sum += new_value - old_value; self.window.push_back(new_value); Some(Result::Ok(orig_sum)) } Err(e) => Some(Result::Err(e)), }, } } } } fn main() -> Result<(), Box<dyn Error>> { let stdin = io::stdin(); let mut depth_increase_count: i32 = 0; { let mut integers = stdin.lock().lines().map(|result| { result .map_err(|e| Box::<dyn error::Error>::from(e)) .and_then(|s| { s.parse::<i32>() .map_err(|e| Box::<dyn error::Error>::from(e)) }) }); let mut rolling_totals = WindowedSumIter::new(&mut integers, 3)?; let mut last_depth = rolling_totals.next().unwrap().unwrap(); for maybe_integer in rolling_totals { let current_depth = maybe_integer.unwrap(); if current_depth > last_depth { depth_increase_count += 1; } last_depth = current_depth; } } println!("{}", depth_increase_count); return Result::Ok(()); }
{ "domain": "codereview.stackexchange", "id": 42585, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, rust", "url": null }
programming-challenge, rust While all this code should be considered in-scope, I'm particularly curious as to whether there's a better way to generate an iterator over integers parsed from stdin (the statement starting with let mut integers =) while keeping the error handling fairly flat (avoiding the need to have std::io::Errors and std::num::ParseIntErrors handled separately by consumers of that iterator, with distinct levels of unwrapping). For the record: There is another Advent of Code Day 1 solution at Advent of Code 2021: day 1 however, the linked question does not try to create an iterator to generate rolling windows, so I believe the new question has enough novelty to justify its creation. Answer: Errors Your code is good, I don't see any room for improvement in error handling. Idiomatic Rust code may feel verbose, but it's good. I would use if let in both places to reduce verbosity. Less complexity in WindowedSumIter Let's reduce the complexity a little by collecting to an intermediate Result<Vec<i32>, Box<dyn Error>> in main. That's because you have unseparated concerns -- that is, WindowedSumIter handles both sums and errors. Unseparated concerns make it harder to modify and reuse code in other tasks if one stumbles upon your solution. Ideally, we would use something like itertools::process_results here. However, we can do the same thing with a few lines in main, possibly with a tiny difference in performance. FromIterator used by collect has a nifty impl that allows you to collect an iterator of Results into a single Result that wraps a container. use std::collections::VecDeque; use std::error::Error; use std::io; use std::io::BufRead; use std::ops::{Add, AddAssign, Sub}; use std::result::Result; pub struct WindowedSumIter<'a, T> where T: Default + Add<Output = T> + Sub<Output = T> + AddAssign + Copy, { source: &'a mut dyn Iterator<Item = T>, window: VecDeque<T>, sum: T, finished: bool, }
{ "domain": "codereview.stackexchange", "id": 42585, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, rust", "url": null }
programming-challenge, rust impl<'a, T> WindowedSumIter<'a, T> where T: Default + Add<Output = T> + Sub<Output = T> + AddAssign + Copy, { pub fn new( source: &'a mut dyn Iterator<Item = T>, window_size: u32, ) -> Self { let mut sum: T = T::default(); let mut window: VecDeque<T> = VecDeque::new(); let mut finished: bool = false; // fill the window at initialization time for _ in 0..window_size { let item = source.next(); match item { None => { finished = true; } Some(value) => { sum = sum + value; window.push_back(value); }, } } WindowedSumIter { source, window, sum, finished, } } } impl<'a, T> Iterator for WindowedSumIter<'a, T> where T: Default + Add<Output = T> + Sub<Output = T> + AddAssign + Copy, { type Item = T; fn next(&mut self) -> Option<Self::Item> { if self.finished { None } else { let old_value = self.window.pop_front().unwrap(); let maybe_new_value = self.source.next(); match maybe_new_value { None => { self.finished = true; Some(self.sum) } Some(new_value) => { let orig_sum = self.sum; self.sum += new_value - old_value; self.window.push_back(new_value); Some(orig_sum) }, } } } }
{ "domain": "codereview.stackexchange", "id": 42585, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, rust", "url": null }
programming-challenge, rust fn main() -> Result<(), Box<dyn Error>> { let stdin = io::stdin(); let mut depth_increase_count: i32 = 0; { let integers: Vec<i32> = stdin.lock().lines().map(|result| { result .map_err(|e| Box::<dyn Error>::from(e)) .and_then(|s| { s.parse() .map_err(|e| Box::<dyn Error>::from(e)) }) }).collect::<Result<_, _>>()?; let mut iter = integers.iter().cloned(); let mut rolling_totals = WindowedSumIter::new(&mut iter, 3); let mut last_depth = rolling_totals.next().unwrap(); for maybe_integer in rolling_totals { let current_depth = maybe_integer; if current_depth > last_depth { depth_increase_count += 1; } last_depth = current_depth; } } println!("{}", depth_increase_count); return Result::Ok(()); } My solution using itertools::process_results and TupleWindows I attempted a solution out of curiosity. use std::error::Error; use std::io; use std::io::BufRead; use std::mem; use std::result::Result; use itertools::{process_results, Itertools};
{ "domain": "codereview.stackexchange", "id": 42585, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, rust", "url": null }
programming-challenge, rust use itertools::{process_results, Itertools}; fn main() -> Result<(), Box<dyn Error>> { let stdin = io::stdin(); let depth_increase_count: usize; { let integers = stdin.lock().lines().map(|result| { result .map_err(|e| Box::<dyn Error>::from(e)) .and_then(|s| { s.parse::<i32>() .map_err(|e| Box::<dyn Error>::from(e)) }) }); depth_increase_count = process_results(integers, |iter| { let mut sums = iter.tuple_windows().map(|(a, b, c)| a + b + c); let mut prev_sum = sums.next().expect("empty input"); sums.filter(|&sum| { sum > mem::replace(&mut prev_sum, sum) }).count() })?; } println!("{}", depth_increase_count); return Result::Ok(()); }
{ "domain": "codereview.stackexchange", "id": 42585, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "programming-challenge, rust", "url": null }
c++, performance Title: Reading from large binary files Question: I am reading data out of some large (~2GB each) binary files; these have a well defined structure: - Header (info about the next chunk of data) - Chunk of data (any type) - Repeat I am using the following function to extract data from the files: template<class T> std::vector<T> getFromBin(std::ifstream& ifs, int num); template<class T> std::vector<T> getFromBin(std::ifstream& ifs, int num) { std::vector<T> output; output.reserve(num); T* buffer = new T[num]; ifs.read((char*)buffer, sizeof(T) * num); for(int i = 0; i < num; ++i) { output.push_back(buffer[i]); } delete[] buffer; return output; } If I want to read e.g. 2 unsigned short int followed by 100000 unsigned int from the binary file, I can do: std::ifstream ifs(file_name, std::ios::binary | std::ios::ate); std::streampos total_bytes(ifs.tellg()); ifs.seekg(0, std::ios::beg); std::vector<unsigned short int> h(getFromBin<unsigned short int>(ifs, 2)); std::vector<unsigned int> b(getFromBin<unsigned int>(ifs, 100000));
{ "domain": "codereview.stackexchange", "id": 42586, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance", "url": null }
c++, performance std::vector<unsigned int> b(getFromBin<unsigned int>(ifs, 100000)); This works perfectly. It gives me the exact results I want, and I get them fast. Does the code above have any problems allocating/releasing memory? Are there any obvious ways I can make it run faster? I have 1 problem: If I run my code in Valgrind, I get over 10000000 errors detected. This is the only function in my code that handles memory by hand, so I am confused. To be clear, by code doesn't crash, it runs perfectly. Message from Valgrind: ==8613== More than 10000000 total errors detected. I'm not reporting any more. ==8613== Final error counts will be inaccurate. Go fix your program! ==8613== Rerun with --error-limit=no to disable this cutoff. Note ==8613== that errors may occur in your program without prior warning from ==8613== Valgrind, because errors are no longer being displayed. ==8613== ==8613== Warning: client switching stacks? SP change: 0x1ffe8ffa90 --> 0x1fff0007d0 ==8613== to suppress, use: --max-stackframe=7343424 or greater ==8613== ==8613== HEAP SUMMARY: ==8613== in use at exit: 0 bytes in 0 blocks ==8613== total heap usage: 54,917,047 allocs, 54,917,047 frees, 5,703,921,853 bytes allocated ==8613== ==8613== All heap blocks were freed -- no leaks are possible ==8613== ==8613== For lists of detected and suppressed errors, rerun with: -s ==8613== ERROR SUMMARY: 10000000 errors from 92 contexts (suppressed: 0 from 0) Answer: This works perfectly. It gives me the exact results I want… This code only β€œworks perfectly” on your particular machine. It is not portable. Consider reading in a bunch of unsigned longs. The core of your code (pretending we’re only reading a single unsigned long and not a bunch of them) is basically this: auto i = 0uL; ifs.read(reinterpret_cast<char*>(&i), sizeof(unsigned long)); There are two problems here:
{ "domain": "codereview.stackexchange", "id": 42586, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance", "url": null }
c++, performance There are two problems here: sizeof(unsigned long) is implementation-defined. I believe it is 4 on Windows; it’s 8 on Linux. The same data file will read differently on different machines. The endianness of unsigned long is also implementation-defined. If the data in your file is big-endian, and your machine is big-endian, then (probably) no problem. But if the endianness is not the same, you’re going to get garbage. There are also other issues you will run into if you try to read into more complex types. And β€œmore complex” doesn’t mean all that complex. Just consider the humble int. Even if you get endianness right, there’s no guarantee that the sign bit will be in the same place across different implementations. Once you get into doubles and such, all bets are off. Does the code above have any problems allocating/releasing memory? Yes, because you are using naked new and delete. That is bad C++. So long as you stick to simple types like unsigned int you will probably never have a problem. However, look at the structure of your code: T* buffer = new T[num]; ifs.read((char*)buffer, sizeof(T) * num); // <--- for(int i = 0; i < num; ++i) { output.push_back(buffer[i]); // <--- } delete[] buffer; What happens if that call to push_back() throws? You may argue that it can’t, because you’ve already reserved the memory. But allocation failures are not the only way a push_back() can fail. Not only that, but ifs.read() might throw as well. If a throw happens, that buffer is leaked. This is so easily fixed by just using a smart pointer: T* buffer = std::make_unique_for_overwrite<T[]>(num); // or std::unique_ptr<T[]>{new T[num]}; ifs.read((char*)buffer.get(), sizeof(T) * num); for(int i = 0; i < num; ++i) { output.push_back(buffer[i]); } // buffer automatically deletes Are there any obvious ways I can make it run faster? The most obvious way I can see is to forgo the buffer. Just do:
{ "domain": "codereview.stackexchange", "id": 42586, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance", "url": null }
c++, performance The most obvious way I can see is to forgo the buffer. Just do: template<class T> std::vector<T> getFromBin(std::ifstream& ifs, int num) { std::vector<T> output; output.resize(num); ifs.read(reinterpret_cast<char*>(output.data()), sizeof(T) * num); return output; } This is still the wrong way to read binary data for the reasons I mentioned above… but it is the exact same behaviour of your current code, without the unnecessary buffer. (As an aside, even if the buffer were necessary, manually writing a loop and doing a bunch of push_back()s would be silly in this situation. Just do output.assign(buffer, buffer * num);.) Incidentally: std::ifstream ifs(file_name, std::ios::binary | std::ios::ate); std::streampos total_bytes(ifs.tellg()); ifs.seekg(0, std::ios::beg); This is not the right way to determine the size of a file. I’ve actually written articles about this, it’s such a common error. Simply put: The number returned by tellg() is absolutely useless for any purpose other than to seekg() to the same location. In particular, if you tellg(), then write some data, then tellg() again, the difference between those two results is not necessarily the same as the number of bytes written. The β€œend” of the file is not necessarily what you think it is. On some platforms, particularly those with record-based file systems, there can be a chunk of extra data at the β€œend” of the file. So, for example, even if tellg() could actually tell you the correct number of bytes, if you seekg() to the end of the file, you would still get the wrong number for the size. There is no portable way to determine the file size other than by trying to actually read to the end, and counting the bytes you read. In other words, this is the only portable way to get the file size using IOstreams: auto pos = ifs.tellg(); if (not ifs.ignore(std::numeric_limits<std::streamsize>::max())) throw "read failure";
{ "domain": "codereview.stackexchange", "id": 42586, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance", "url": null }
c++, performance auto total_bytes = ifs.gcount(); if (not ifs.seekg(pos)) throw "seek failure"; // total_bytes now has the actual, correct number of bytes you can read // between the current position and the end of the file. As you can imagine, for a huge file, manually reading through the whole thing just to count bytes is a colossal waste of time. That’s why the pattern of checking the whole file’s size is not a good fit for IOstreams. If you don’t need to know the whole file’s size up frontβ€”and your use case, where you are reading chunk-by-chunk doesn’t seem to require knowing the whole file’s sizeβ€”then don’t bother with it. As a side note, if you want to know a file’s size portably, you can use std::filesystem::file_size(). But don’t do this: auto total_bytes = std::filesystem::file_size(path); auto ifs = std::ifstream{path, std::ios_base::binary}; // now assume the file size is total_bytes
{ "domain": "codereview.stackexchange", "id": 42586, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance", "url": null }
c++, performance There is a race condition between reading the file size and opening it. In short: you may read the file size, then the OS may pause your program to give time to another program, that program may delete the file and replace it with a totally new one, then the OS switches back to your program and you open the file stream. The bottom line is that a stream interface is not really designed for the use pattern of getting the total size, and then reading it. A stream may not even know the total size… for example, if it is a network stream, and it is giving you data as it downloads without knowing the total download size. Yeah, sure, it should usually work for a file, on a local filesystem (but not always!), but the stream interface is for much more than just that. The biggest issue I see with your current interface is that it doesn’t seem to have any idea that errors might occur, nor does it have a sensible way of handling them. For example, let’s consider this simplified form: template<class T> std::vector<T> getFromBin(std::ifstream& ifs, int num) { std::vector<T> output; output.resize(num); ifs.read(reinterpret_cast<char*>(output.data()), sizeof(T) * num); return output; } What happens if the read fails? You will happily return a vector half-full of data, and half-full of random garbage. The user has to write: auto b = getFromBin<unsigned int>(ifs, 100000); // is b good? don't know, have to check here: if (not ifs) throw "problem"; It would make much more sense to do the checking in the function: template<class T> std::vector<T> getFromBin(std::ifstream& ifs, int num) { std::vector<T> output; output.resize(num); if (not ifs.read(reinterpret_cast<char*>(output.data()), sizeof(T) * num)) throw ...; return output; }
{ "domain": "codereview.stackexchange", "id": 42586, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance", "url": null }
c++, performance return output; } That way you always know that when the function successfully returns, the data is good. As for those Valgrind errors, as far as I can see, they are not related to any problems with memory allocation. As it says: All heap blocks were freed -- no leaks are possible. There is no way I can even begin to guess what’s going on without seeing the rest of your program, knowing the compiler and standard library you are using, and knowing the way you called Valgrind.
{ "domain": "codereview.stackexchange", "id": 42586, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance", "url": null }
java, game, adventure-game, battle-simulation Title: Text-based adventure game where you fight two enemies per round Question: This is a text based adventure game, where you need to fight against 2 enemy in every round. The damage dealt and potion heal is a random number. How can I improve? Game class: package textbasedadventuregame; import java.util.Scanner; public class Game { public static void main(String[] args) { String[] enemyTypes = {"Skeleton", "Giant", "Goblin", "Demon", "Defeated Knight", "Warrior", "Demon Lord"}; String[] enemyStatsText = createEnemyStats(enemyTypes); Player player = new Player(150, 3); System.out.println("How many rounds do you want to play?"); int maxRound = new Scanner(System.in).nextInt(); int roundCount = 0; for (roundCount = 1; roundCount < maxRound; roundCount++) { roundStart(chooseEnemys(enemyStatsText), player, roundCount); } } private static String[] chooseEnemys(String[] enemyStatsText) { String[] enemies = new String[2]; enemies[0] = enemyStatsText[randomNumber(0, enemyStatsText.length - 1)]; enemies[1] = enemyStatsText[randomNumber(0, enemyStatsText.length - 1)]; return enemies; } private static String[] createEnemyStats(String[] enemyType) { String[] enemyStatsText = new String[enemyType.length]; int minHealth = 25; int maxHealth = 70; int minDamage = 15; int maxDamage = 25; for (int i = 0; i < enemyStatsText.length; i++) { enemyStatsText[i] = enemyType[i] + ";" + randomNumber(minHealth, maxHealth) + ";" + randomNumber(minDamage, maxDamage); } return enemyStatsText; } public static int randomNumber(int min, int max) { int range = (max - min) + 1; int stats = (int) (Math.random() * range) + min; return stats; }
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation private static void roundStart(String[] enemies, Player player, int roundCount) { System.out.println(enemies[0] + " " + enemies[1]); String[] enemyOne = enemies[0].split(";"); String enemyOneName = enemyOne[0]; int enemyOneHP = Integer.parseInt(enemyOne[1]); int enemyOneDamage = Integer.parseInt(enemyOne[2]); boolean enemyOneDead = false; String[] enemyTwo = enemies[1].split(";"); String enemyTwoName = enemyTwo[0]; int enemyTwoHP = Integer.parseInt(enemyTwo[1]); int enemyTwoDamage = Integer.parseInt(enemyTwo[2]); boolean enemyTwoDead = false; int stopLoop = 1; while (stopLoop == 1) { System.out.println(" \n \n \n Round " + roundCount + " is starting!"); System.out.println("Player HP: " + player.getPlayerHP()); System.out.println(" \n 1: I want to fight \n 2: I want to drink a potion. I have " + player.getPotionCount() + " potions." + "\n 3: Escape"); int input = new Scanner(System.in).nextInt(); if (input == 1) { System.out.println("So, you choose to fight!"); stopLoop = 2; chooseEnemyToFight(player, enemyOneName, enemyOneHP, enemyOneDamage, enemyOneDead, enemyTwoName, enemyTwoHP, enemyTwoDamage, enemyTwoDead, roundCount); } else if (input == 2) { potionDrink(player); System.out.println("You have drinked a potion. Potions remaining: " + player.getPotionCount() + ". Your hp is: " + player.getPlayerHP()); stopLoop = 2; } else if (input == 3) { System.out.println("You are escaped. Your score is: " + roundCount); stopLoop = 2; } else { System.out.println("Invaild number!"); } } }
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation private static void chooseEnemyToFight(Player player, String enemyOneName, int enemyOneHP, int enemyOneDamage, boolean enemyOneDead, String enemyTwoName, int enemyTwoHP, int enemyTwoDamage, boolean enemyTwoDead, int roundCount) { while (enemyOneDead == false || enemyTwoDead == false) { int input = 0; if (enemyOneDead == false && enemyTwoDead == false) { System.out.println("The two enemy is: " + enemyOneName + " with " + enemyOneHP + " health and " + enemyOneDamage + " attack DMG and a " + enemyTwoName + " with " + enemyTwoHP + " health and " + enemyTwoDamage + " attack DMG"); System.out.println("Which one do you want to hit? The other one can attack you!"); System.out.println("If you want to fight with the " + enemyOneName + ", type number 1. If you want to fight with the " + enemyTwoName + ", type number 2."); input = new Scanner(System.in).nextInt(); } else if (enemyOneDead == false && enemyTwoDead == true) { System.out.println("You will fight with the " + enemyOneName + " who has " + enemyOneHP + " HP and " + enemyOneDamage + " attack damage."); input = 1; } else if (enemyOneDead == true && enemyTwoDead == false) { System.out.println("You will fight with the " + enemyTwoName + " who has " + enemyTwoHP + " HP and " + enemyTwoDamage + " attack damage."); input = 2; } if (input == 1) { if (enemyTwoDead == false) { System.out.println("So you want to fight with the " + enemyOneName + " first \n"); } enemyOneHP = attackEnemy(enemyOneName, enemyOneHP, enemyOneDamage, player); if (enemyOneHP <= 0) { System.out.println(enemyOneName + " is died. \n"); enemyOneDead = true; }
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation playerDamageRecived(player, enemyTwoDamage, enemyTwoName, roundCount); } else if (input == 2) { if (enemyOneDead == false) { System.out.println("So you want to fight with the " + enemyTwoName + " first \n"); } enemyTwoHP = attackEnemy(enemyTwoName, enemyTwoHP, enemyTwoDamage, player); if (enemyTwoHP <= 0) { System.out.println(enemyTwoName + " is died. \n"); enemyTwoDead = true; } playerDamageRecived(player, enemyOneDamage, enemyOneName, roundCount); } } } private static void playerDamageRecived(Player player, int enemyOneDamage, String enemyOneName, int roundCount) { player.setPlayerHP(enemyAttack(player, enemyOneDamage)); if (player.getPlayerHP() > 0) { System.out.println(enemyOneName + " attacked you! Your hp is: " + player.getPlayerHP()); } else if (player.getPlayerHP() <= 0) { System.out.println("You are dead! Your score is: " + roundCount); System.exit(0); } }
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation private static int attackEnemy(String enemyName, int enemyHP, int enemyDamage, Player player) { System.out.println("Which attack do you want to use, your knife (1) or your gun (2)? If you use your knife, you can use a heal potion too, or attack twice! \n"); int input1 = new Scanner(System.in).nextInt(); if (input1 == 1) { enemyHP = enemyHP - player.getPlayerKnifeDamage(); System.out.println("The enemy hp is: " + enemyHP + ". Do you want to attack again with the knife(1), or do you want to use a potion(2). You have " + player.potionCount + " potions."); int input2 = new Scanner(System.in).nextInt(); if (input2 == 1) { enemyHP = enemyHP - player.getPlayerKnifeDamage(); System.out.println("The enemy hp is: " + enemyHP); } else if (input2 == 2) { potionDrink(player); System.out.println("You have drinked a potion. Potions remaining: " + player.getPotionCount() + ". Your hp is: " + player.getPlayerHP() + "\n"); } } else if (input1 == 2) { enemyHP = enemyHP - player.getPlayerGunDamage(); } return enemyHP; } private static void potionDrink(Player player) { player.setPotionCount(player.getPotionCount() - 1); player.setPlayerHP(player.getPlayerHP() + player.getPotionHeal()); if (player.getPlayerHP() > 100) { player.setPlayerHP(100); } } private static int enemyAttack(Player player, int enemyDamage) { return player.getPlayerHP() - enemyDamage; } } Player class: package textbasedadventuregame; import static textbasedadventuregame.Game.randomNumber; public class Player { int playerHP; int playerKnifeDamage; int playerGunDamage; int potionCount; int potionHeal;
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation public Player(int playerHP, int potionCount) { this.playerHP = playerHP; this.potionCount = potionCount; } public int getPlayerHP() { return playerHP; } public void setPlayerHP(int playerHP) { this.playerHP = playerHP; } public int getPlayerKnifeDamage() { return playerKnifeDamage = randomNumber(15, 25); } public void setPlayerKnifeDamage(int playerKnifeDamage) { this.playerKnifeDamage = playerKnifeDamage; } public int getPlayerGunDamage() { return playerGunDamage = randomNumber(20, 60); } public void setPlayerGunDamage(int playerGunDamage) { this.playerGunDamage = playerGunDamage; } public int getPotionCount() { return potionCount; } public void setPotionCount(int potionCount) { this.potionCount = potionCount; } public int getPotionHeal() { return potionHeal = randomNumber(50, 80); } public void setPotionHeal(int potionHeal) { this.potionHeal = potionHeal; } }
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation Answer: Java is idiomatically very object-oriented, and the current code doesn't quite get there - it has too many statics, and doesn't properly encapsulate the classes that it should. Particularly, Enemy should get a class. Game can also be instantiated from main(). roundStart isn't particularly well-named, since it doesn't just start the round - it runs the entire round. chooseEnemys should be spelled chooseEnemies. Don't pack your enemy stats into semicolon-separated strings - you aren't serializing them to disk or sending them over the network. Just put those stats as members on objects. You should generalise your code so that it's easy to change the number of enemies per round, not hard-coding everything to two enemies. Don't write your own randomNumber - ThreadLocalRandom has what you want. Don't make a new Scanner every time that you need to get input - just make a single instance. If you want to make this testable you can accept it as a parameter to the class constructor, though I haven't shown this. Avoid writing \n as it isn't portable. Use %n in format strings instead. The score is a strange calculation. You get the same score if you run away from every single fight as when you win every single fight. This probably needs refinement. You have drinked should just be You drank, and You are escaped should just be You escaped. The two enemy is should be The two enemies are. Is died should just be died. Recived is spelled Received. Consider use of switch rather than your repeated ifs when checking input. Also, your input validation is a good start but is not comprehensive - for instance, if the user enters a letter instead of a number your loop will not catch it. The easy way around this is to work with strings and don't bother calling nextInt. Avoid calling System.exit(). Instead, let the round logic pick up on the fact that the player is dead. Remove the word Player from all of your methods on the player class, since it's redundant.
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation Remove the word Player from all of your methods on the player class, since it's redundant. Your damage should not be represented as variables on the player class. Delete those and keep your damage calculation functions. Remove basically all of your set methods and constrain your state manipulation to supported operations like taking damage and drinking potions. Health and damage are continuous quantities. Why not represent them as doubles instead of ints? Suggested Game.java package textbasedadventuregame;
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation import java.util.Iterator; import java.util.Scanner; import static java.lang.System.out; public class Game implements Iterator<Round> { public final int nRounds; private int roundIndex = 0; private final Player player = new Player(); public static void main(String[] args) { System.out.println("How many rounds do you want to play?"); int nRounds = new Scanner(System.in).nextInt(); new Game(nRounds).run(); } public Game(int nRounds) { this.nRounds = nRounds; } @Override public boolean hasNext() { return roundIndex < nRounds && player.isAlive(); } @Override public Round next() { roundIndex++; out.printf("%n%n%nRound %d is starting!%n", roundIndex); return new Round(player); } public void run() { forEachRemaining(Round::run); } } Round.java package textbasedadventuregame; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import static java.lang.System.out; public class Round { private final List<Enemy> enemies = List.of( new Enemy(), new Enemy() ); private final Player player; private static final Scanner scanner = new Scanner(System.in); public Round(Player player) { this.player = player; } public String enemyDescriptions() { // Return a string with all enemy descriptions separated by spaces. return enemiesAlive() .map(Enemy::toString) .collect(Collectors.joining(", ")); } public void run() { out.printf( "%s%n" + "Player HP: %.0f%n", enemyDescriptions(), player.getHealth()); while (true) { out.printf( "1: I want to fight!%n" + "2: I want to drink a potion. I have %d potions.%n" + "3: Escape.%n", player.getPotionCount());
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation String input = scanner.next(); switch (input) { case "1" -> fight(); case "2" -> drinkPotion(); case "3" -> out.println("You have escaped."); default -> { out.println("Invalid choice!"); continue; } } break; } } public Stream<Enemy> enemiesAlive() { return enemies.stream().filter(Enemy::isAlive); } private void fight() { out.println("So, you choose to fight!"); while (player.isAlive() && enemiesAlive().findAny().isPresent()) { Enemy toFight = chooseEnemy(); attackEnemy(toFight); enemiesAlive() .filter(enemy -> enemy != toFight) .forEach(this::receiveDamage); } } public Enemy chooseEnemy() { List<Enemy> alive = enemiesAlive().collect(Collectors.toList()); Enemy enemy; if (alive.size() == 1) enemy = alive.get(0); else { out.println("The enemies are:"); out.println( IntStream.range(0, alive.size()) .mapToObj(index -> String.format( "%d. %s", index + 1, alive.get(index) )) .collect(Collectors.joining(System.lineSeparator())) ); out.println("Which one do you want to hit? The others can attack you!"); enemy = alive.get(scanner.nextInt() - 1); } out.printf("So you want to fight with the %s.%n", enemy.name); return enemy; } private void receiveDamage(Enemy enemy) { player.takeDamage(enemy.damage); out.printf("%s attacked you! Your health is: %.0f%n", enemy.name, player.getHealth()); if (!player.isAlive()) out.println("You are dead!"); }
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation private void attackEnemy(Enemy enemy) { out.println("Which attack do you want to use, your knife (1) or your gun (2)? If you use your knife, you can use a heal potion too, or attack twice!"); boolean bonusAction; double damage; while (true) { switch (scanner.next()) { case "1" -> { bonusAction = true; damage = player.getKnifeDamage(); } case "2" -> { bonusAction = false; damage = player.getGunDamage(); } default -> { out.println("Invalid choice!"); continue; } } break; } damageEnemy(enemy, damage); if (bonusAction) { out.println("Do you want to attack again with the knife(1), or do you want to use a potion(2)?"); switch (scanner.next()) { case "1" -> damageEnemy(enemy, player.getKnifeDamage()); case "2" -> drinkPotion(); } } } public void damageEnemy(Enemy enemy, double damage) { enemy.takeDamage(damage); out.printf("The enemy health is: %.0f%n", enemy.getHealth()); if (!enemy.isAlive()) out.printf("%s died.%n", enemy.name); } private void drinkPotion() { player.drinkPotion(); out.printf( "You drank a potion. Potions remaining: %d. Your health is: %.0f.%n", player.getPotionCount(), player.getHealth()); } } Body.java package textbasedadventuregame; public class Body { public final double startingHealth; protected double health; protected Body(double health) { startingHealth = health; this.health = health; } public double getHealth() { return health; } public boolean isAlive() { return health > 0; }
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation public double getHealth() { return health; } public boolean isAlive() { return health > 0; } public void takeDamage(double damage) { health = Math.max(0, health - damage); } public void heal(double amount) { health = Math.min(startingHealth, health + amount); } } Player.java package textbasedadventuregame; import java.util.concurrent.ThreadLocalRandom; public class Player extends Body { private static final ThreadLocalRandom rand = ThreadLocalRandom.current(); private int potionCount; public Player(double health, int potionCount) { super(health); this.potionCount = potionCount; } public Player() { this(150, 3); } public int getPotionCount() { return potionCount; } public void drinkPotion() { if (potionCount > 0) { potionCount--; heal(rand.nextDouble(50, 80)); } } public double getKnifeDamage() { return rand.nextDouble(15, 25); } public double getGunDamage() { return rand.nextDouble(20, 60); } } Enemy.java package textbasedadventuregame; import java.util.concurrent.ThreadLocalRandom; public class Enemy extends Body { private static final ThreadLocalRandom rand = ThreadLocalRandom.current(); public static final String[] names = { "Skeleton", "Giant", "Goblin", "Demon", "Defeated Knight", "Warrior", "Demon Lord", }; public final double damage; public final String name; public Enemy(String name, double health, double damage) { super(health); this.name = name; this.damage = damage; } public Enemy() { // Random enemy this( names[rand.nextInt(names.length)], rand.nextDouble(25, 70), rand.nextDouble(15, 25) ); }
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
java, game, adventure-game, battle-simulation @Override public String toString() { return String.format( "%s with %.0f health and %.0f attack damage", name, health, damage ); } }
{ "domain": "codereview.stackexchange", "id": 42587, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "java, game, adventure-game, battle-simulation", "url": null }
python, python-3.x Title: Get data from a dict
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 Question: I have been trying to figure out what is the best performance wise and also best practice to get data from a dict using Python. I currently have a data that looks like this: data = { "cart": { "id": 123456, "currency": "GBP", "name": None, "rows": [ { "id": 7079540, "unitPrice": 1089, "unitVat": 217.8, "quantity": 1, "pass": None, "extraData": { "isLoggedIn": True, "source": "product" }, "product": { "id": 279533, "thumbnail": "\/images\/product\/279533?trim&h=80", "name": "Seagate Game Drive f\u00f6r PS4 4TB", "subTitle": "Extern H\u00e5rddisk 2,5\" \/ USB 3.0 \/ 4 TB", "shippingClass": { "id": 1, "order": 1, "prices": [ { "price": 0, "shippingMethodId": 1, "isFixedPrice": False, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 2, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 3, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 4,
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 "price": 0, "shippingMethodId": 4, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 19, "isFixedPrice": True, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 20, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 21, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 22, "isFixedPrice": True, "maximumPackageSizeId": None }, { "price": 0, "shippingMethodId": 25, "isFixedPrice": True, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 26, "isFixedPrice": True, "maximumPackageSizeId": 7 }, { "price": 0,
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 { "price": 0, "shippingMethodId": 27, "isFixedPrice": True, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 28, "isFixedPrice": True, "maximumPackageSizeId": 2 } ] }, "packageSizeId": 1, "isShippable": True, "release": { "timestamp": 1512450000, "format": "Y-m-d" }, "regularPrice": { "price": "1199.00", "currency": "SEK", "vat": 239.8, "type": None, "endAt": "2022-03-12", "maxQtyPerCustomer": None }, "isRevenue": True, "stock": { "web": 51, "supplier": None, "displayCap": "50", "1": 51, "2": 0, "5": 10, "8": 4, "9": 4, "10": 10, "11": 7, "14": 2, "15": 23, "16": 0, "19": 0, "20": 0, "21": 0, "22": 4, "23": 0, "26": 4, "27": 18, "28": 1 }, "meta": [
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 ], "statusCodes": [ ], "packageVolume": 879750, "packageWeight": 340, "minimumRankLevel": 0, "packageMeasurements": [ 170, 115, 45 ] }, "insurance": { "id": 339702, "name": "testing Care Pack (12 m\u00e5nader)", "price": 289, "provider": 1, "length": 12 } } ] }, "corrections": [ { "type": "PRICE_CHANGED", "rowId": None, "price": { "was": 0, "shouldBe": "1089.00" } } ], "errors": [ ] } and I am currently trying to get specific data that I store into a dict and return the dict data. This is what I have done: import pendulum TESTING_STORES = { 'web': 'Webblager', 'supplier': 'Hos leverantΓΆr', '1': 'Hello World', }
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 data = { "cart": { "id": 2656218, "currency": "SEK", "name": None, "rows": [ { "id": 7079540, "unitPrice": 1089, "unitVat": 217.8, "quantity": 1, "pass": None, "extraData": { "isLoggedIn": True, "source": "product" }, "product": { "id": 279533, "thumbnail": "\/images\/product\/279533?trim&h=80", "name": "Seagate Game Drive f\u00f6r PS4 4TB", "subTitle": "Extern H\u00e5rddisk 2,5\" \/ USB 3.0 \/ 4 TB", "shippingClass": { "id": 1, "order": 1, "prices": [ { "price": 0, "shippingMethodId": 1, "isFixedPrice": False, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 2, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 3, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 4, "isFixedPrice": False, "maximumPackageSizeId": 7 }, {
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 }, { "price": 0, "shippingMethodId": 19, "isFixedPrice": True, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 20, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 21, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 22, "isFixedPrice": True, "maximumPackageSizeId": None }, { "price": 0, "shippingMethodId": 25, "isFixedPrice": True, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 26, "isFixedPrice": True, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 27, "isFixedPrice": True, "maximumPackageSizeId": 2 }, {
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 }, { "price": 0, "shippingMethodId": 28, "isFixedPrice": True, "maximumPackageSizeId": 2 } ] }, "packageSizeId": 1, "isShippable": True, "release": { "timestamp": 1512450000, "format": "Y-m-d" }, "regularPrice": { "price": "1199.00", "currency": "SEK", "vat": 239.8, "type": None, "endAt": "2022-03-12", "maxQtyPerCustomer": None }, "isRevenue": True, "stock": { "web": 51, "supplier": None, "displayCap": "50", "1": 51, "2": 0, "5": 10, "8": 4, "9": 4, "10": 10, "11": 7, "14": 2, "15": 23, "16": 0, "19": 0, "20": 0, "21": 0, "22": 4, "23": 0, "26": 4, "27": 18, "28": 1 }, "meta": [
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 ], "statusCodes": [ ], "packageVolume": 879750, "packageWeight": 340, "minimumRankLevel": 0, "packageMeasurements": [ 170, 115, 45 ] }, "insurance": { "id": 339702, "name": "testing Care Pack (12 m\u00e5nader)", "price": 289, "provider": 1, "length": 12 } } ] }, "corrections": [ { "type": "PRICE_CHANGED", "rowId": None, "price": { "was": 0, "shouldBe": "1089.00" } } ], "errors": [ ] } # --------------------------------------------------------------- # # GET JSON DATA # --------------------------------------------------------------- # pageData = { 'title': 'Unknown', 'image': 'Not found', 'price': 'Not found', 'sizes': {} } def get_data(): if doc := data.get('cart', {}).get('rows')[0].get('product', {}): # ---------------------------- ALL ---------------------------- # pageData.update({ 'title': doc.get('name'), 'image': f"https://cdn.testing.com/images/product/{doc.get('id')}?trim&w=231", 'price': doc.get('regularPrice', {}).get('price', {}), }) # ---------------------------- Release date ---------------------------- # if release_date := doc.get('release', {}).get('timestamp', {}): if not pendulum.from_timestamp(release_date, tz='Europe/Stockholm').is_past(): pageData['release_date'] = release_date # ---------------------------- Sizes ---------------------------- #
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 # ---------------------------- Sizes ---------------------------- # if sizes := doc.get('stock'): pageData['sizes'] = {TESTING_STORES[store]: stock for store, stock in sizes.items() if store in TESTING_STORES and stock} if status := sizes.get('orders', {}).get('CL', {}): if not status.get('status', 0) == -1: pageData['sizes']['Potential InStock'] = status.get('ordered') # ---------------------------- Campaign ---------------------------- # if doc.get('regularPrice', {}).get('type', '') == 'campaign': pageData['sizes']['InStock'] = None # ---------------------------- minimumRankLevel ---------------------------- # if minimumRankLevel := doc.get('minimumRankLevel', {}): pageData['minimumRankLevel'] = minimumRankLevel return pageData if __name__ == '__main__': data = get_data() print(data) The script itself works but I do also feel like I have done it incorrectly by not applying the best practice and I do know that using .get() is not the best performance compare to if in but also I do not know e.g. what if its a nested data I want to use.. how to apply it etc etc... my goal is to make the script to have the best performance wise and trying to keep it as simple as possible as well. I wonder, if there is anything I could improve in my code?
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 Answer: Your code relies on dictionary soup, and if my memory serves correctly it's been like this for a long time. Concern about optimization should be secondary to concern about correctness; a.k.a. current concern about optimization is premature when this code has no strong types and has few to no guarantees about the structure of your data. As Akash suggests, you should move toward classes. data should not be global and should be made a local of a test routine. pageData should be called page_data, and should be made a local of your get_data() routine. Add PEP484 type hints. The words "unknown" and "not found" are presentation strings that are prematurely baked into your data. Use None instead. In expressions like this: if doc := data.get('cart', {}).get('rows')[0].get('product', {}): I don't find the walrus to be helpful and you should probably just separate the assignment from the test. Also, your final get should not pass a default of {} and should just accept the default of None. Your update() can use the new kwargs-style instead of the old dictionary literal style. if not status.get('status', 0) == -1 should just be if status.get('status') != -1. if minimumRankLevel := doc.get('minimumRankLevel', {}): does not save the minimum rank level if it's 0, since 0 is falsy. Don't pass {}, and use is not None. Don't leave the price as a string; cast it to a Decimal. You call from_timestamp (good!) but then throw it away (ungood) and for some reason forget the time entirely if it's in the past (also ungood). Save the deserialized datetime object regardless of whether it's in the past on not. Leave the past check for a separate logic-processing function. Suggested This implements some (not all) of the above. from decimal import Decimal from pprint import pprint from typing import Dict, Any TESTING_STORES = { 'web': 'Webblager', 'supplier': 'Hos leverantΓΆr', '1': 'Hello World', }
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 get_data(data: Dict[str, Any]) -> Dict[str, Any]: page_data = { 'title': None, 'image': None, 'price': None, 'sizes': {}, } doc = data.get('cart', {}).get('rows')[0].get('product') if doc: page_data.update( title=doc.get('name'), image=f"https://cdn.testing.com/images/product/{doc.get('id')}?trim&w=231", ) price = doc.get('regularPrice', {}).get('price') if price is not None: page_data['price'] = Decimal(price) release_date = doc.get('release', {}).get('timestamp') if release_date: if not pendulum.from_timestamp(release_date, tz='Europe/Stockholm').is_past(): page_data['release_date'] = release_date sizes = doc.get('stock') if sizes: page_data['sizes'] = { TESTING_STORES[store]: stock for store, stock in sizes.items() if store in TESTING_STORES and stock } status = sizes.get('orders', {}).get('CL') if status and status.get('status') != -1: page_data['sizes']['Potential InStock'] = status.get('ordered') if doc.get('regularPrice', {}).get('type') == 'campaign': page_data['sizes']['InStock'] = None minimum_rank_level = doc.get('minimumRankLevel') if minimum_rank_level is not None: page_data['minimumRankLevel'] = minimum_rank_level return page_data
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 test() -> None: data = { "cart": { "id": 2656218, "currency": "SEK", "name": None, "rows": [ { "id": 7079540, "unitPrice": 1089, "unitVat": 217.8, "quantity": 1, "pass": None, "extraData": { "isLoggedIn": True, "source": "product" }, "product": { "id": 279533, "thumbnail": "\/images\/product\/279533?trim&h=80", "name": "Seagate Game Drive f\u00f6r PS4 4TB", "subTitle": "Extern H\u00e5rddisk 2,5\" \/ USB 3.0 \/ 4 TB", "shippingClass": { "id": 1, "order": 1, "prices": [ { "price": 0, "shippingMethodId": 1, "isFixedPrice": False, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 2, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 3, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 4,
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 "shippingMethodId": 4, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 19, "isFixedPrice": True, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 20, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 21, "isFixedPrice": False, "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 22, "isFixedPrice": True, "maximumPackageSizeId": None }, { "price": 0, "shippingMethodId": 25, "isFixedPrice": True, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 26, "isFixedPrice": True, "maximumPackageSizeId": 7
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 "maximumPackageSizeId": 7 }, { "price": 0, "shippingMethodId": 27, "isFixedPrice": True, "maximumPackageSizeId": 2 }, { "price": 0, "shippingMethodId": 28, "isFixedPrice": True, "maximumPackageSizeId": 2 } ] }, "packageSizeId": 1, "isShippable": True, "release": { "timestamp": 1512450000, "format": "Y-m-d" }, "regularPrice": { "price": "1199.00", "currency": "SEK", "vat": 239.8, "type": None, "endAt": "2022-03-12", "maxQtyPerCustomer": None }, "isRevenue": True, "stock": { "web": 51, "supplier": None, "displayCap": "50", "1": 51, "2": 0, "5": 10, "8": 4, "9": 4, "10": 10, "11": 7, "14": 2, "15": 23, "16": 0, "19": 0,
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 "16": 0, "19": 0, "20": 0, "21": 0, "22": 4, "23": 0, "26": 4, "27": 18, "28": 1 }, "meta": [
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 ], "statusCodes": [ ], "packageVolume": 879750, "packageWeight": 340, "minimumRankLevel": 0, "packageMeasurements": [ 170, 115, 45 ] }, "insurance": { "id": 339702, "name": "testing Care Pack (12 m\u00e5nader)", "price": 289, "provider": 1, "length": 12 } } ] }, "corrections": [ { "type": "PRICE_CHANGED", "rowId": None, "price": { "was": 0, "shouldBe": "1089.00" } } ], "errors": [ ] } page_data = get_data(data) pprint(page_data) if __name__ == '__main__': test()
{ "domain": "codereview.stackexchange", "id": 42588, "lm_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 }
performance, programming-challenge, haskell, functional-programming Title: Efficiently calculating perfect powers in Haskell Question: I'm trying to calculate perfect powers to solve this code wars challenge: https://www.codewars.com/kata/55f4e56315a375c1ed000159/haskell The number 81 has a special property, a certain power of the sum of its digits is equal to 81 (nine squared). Eighty one (81), is the first number in having this property (not considering numbers of one digit). The next one, is 512. Let's see both cases with the details \$8 + 1 = 9\$ and \$9^2\$ = 81 \$512 = 5 + 1 + 2 = 8\$ and \$8^3\$ = 512 We need to make a function, power_sumDigTerm(), that receives a number n and may output the n-th term of this sequence of numbers. The cases we presented above means that power_sumDigTerm(1) == 81 power_sumDigTerm(2) == 512 The initial brute force approach where I check the digits sum for every number could only get up to the 11th term in the sequence in reasonable time. I was able to improve on this by only checking numbers that are perfect powers Using this approach I was able to get up to the 17th number in the sequence. This is the code that I am using (apologies for the poor coding style, I'm a Haskell beginner with an imperative programming background): module Codewars.G964.Powersumdig where import qualified Data.Vector.Unboxed as V import Data.Vector.Unboxed (Vector, fromList, (!), snoc, foldl', findIndex, accum) import Data.Int (Int64) import Data.Maybe (fromJust) v1 (a,_,_) = a v2 (_,a,_) = a v3 (_,_,a) = a
{ "domain": "codereview.stackexchange", "id": 42589, "lm_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, programming-challenge, haskell, functional-programming", "url": null }
performance, programming-challenge, haskell, functional-programming v1 (a,_,_) = a v2 (_,a,_) = a v3 (_,_,a) = a inc_exp :: (Int64, Int, Int) -> Int -> (Int64, Int, Int) inc_exp (_, b, c) _ = ((fromIntegral c)^nb, nb, c) where nb = succ b -- next_pp : get the next "perfect power" -- The vector input contains a tuple of potential next perfect powers -- With the base and exponents used to calculate them -- Returns a tuple of the next perfect power, the exponent used to calculate the power -- and the updated Vector state to get the next perfect power next_pp :: Vector (Int64, Int, Int) -> (Int64, Int, Vector (Int64, Int, Int)) next_pp v = let next = foldl' ((. v1) . min) maxBound v i = fromJust $ findIndex ((next ==) . v1) v -- fromJust should be safe as vector should contain it upd_v = accum inc_exp v [(i,0)] last = upd_v ! ((V.length upd_v)-1) -- (last upd_v) doesn't work?? new_v = if v2 last == 3 then upd_v `snoc` ((fromIntegral (succ (v3 last)))^2, 2, succ (v3 last)) else upd_v in (next, v2 (v ! i), new_v) get_next :: Int64 -> Int -> Vector (Int64, Int, Int) -> Int64 get_next n d v | is_valid && d == 1 = np | is_valid = get_next np (d-1) nps | otherwise = get_next np d nps where (np, e, nps) = next_pp v is_valid = (sum_digits np)^e == np sumd 0 acc = acc sumd x acc = sumd d (acc + m) where (d,m) = x `divMod` 10 sum_digits x = sumd x 0 powerSumDigTerm :: Int -> Integer -- 16 is the first perfect power with 2 or more digits -- the vector is initialised with values to generate the next perfect power (which happens to also be 16) powerSumDigTerm n = toInteger $ get_next 16 n (fromList [(maxBound,0,0),(maxBound,0,1),(32,5,2),(27,3,3),(16,2,4)]) I used ghc profiling tools to find which parts of the code are the bottlenecks. From this I can tell that:
{ "domain": "codereview.stackexchange", "id": 42589, "lm_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, programming-challenge, haskell, functional-programming", "url": null }
performance, programming-challenge, haskell, functional-programming 99.8% of the time is spent in the next_pp function. 39.6% of time is spent calculating i 39.2% of time is spent calculating next 12.4% of time is spent calculating upd_v 8.3% of time is spent calculating new_v I need to be able to calculate up to the 40th code in the sequence, so this code is woefully inadequate, but I'm stuck for where to go next with it. Any suggestions? Code style suggestions are also welcome. Perhaps there is a better set of numbers to check that is more specific than perfect powers? I also tried using sequences and boxed vectors but unboxed vectors performed best out of the ones I tried. (I am worried that later terms in the sequence could overflow a 64 bit int) I tried using sequences unstableSort to sort the list each time and find the smallest power but this ended up being slower than using unboxed vectors and folds to find the smallest power. Edit: my second attempt using Data.Heap (unfortunately codewars doesn't support Data.Heap though) module Codewars.G964.Powersumdig where import Data.Heap import Data.Maybe (fromJust) inc_exp :: (Int, Int) -> (Integer, (Int, Int)) inc_exp (e, b) = ((fromIntegral b)^ne, (ne, b)) where ne = succ e next_pp :: MinPrioHeap Integer (Int, Int) -> (Integer, Int, MinPrioHeap Integer (Int, Int)) next_pp v = let next = fromJust $ viewHead h tmp_h = fromJust $ viewTail h base = snd $ snd next exp = fst $ snd next upd_h = insert (inc_exp $ snd next) tmp_h new_h = if exp == 2 then insert ((fromIntegral $ succ base)^2, (2, succ base)) upd_h else upd_h in (fst next, base, new_h)
{ "domain": "codereview.stackexchange", "id": 42589, "lm_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, programming-challenge, haskell, functional-programming", "url": null }
performance, programming-challenge, haskell, functional-programming get_next :: Integer -> Int -> MinPrioHeap Integer (Int, Int) -> Integer get_next n d h | n < 10 = get_next np d nps | is_valid && d == 1 = np | is_valid = get_next np (d-1) nps | otherwise = get_next np d nps where (np, b, nps) = next_pp h is_valid = fromIntegral (sum_digits np) == b sumd 0 acc = acc sumd x acc = sumd d (acc + m) where (d,m) = x `divMod` 10 sum_digits x = sumd x 0 powerSumDigTerm :: Int -> Integer powerSumDigTerm n = toInteger $ get_next 1 n (fromList [(4, (2,2))]) Answer: So, it turns out that there really isn't a nice way to solve this in the general case as far as I can tell. If you know an upper bound for the values of the base (b) and the exponent (e) then you can generate an (unsorted) list of all perfect powers, which only takes O(b*e) time. Then you only have to sort the list once and filter the list once. import Data.List sumd 0 acc = acc sumd x acc = sumd d (acc + m) where (d,m) = x `divMod` 10 sum_digits x = sumd x 0 perfect_powers :: Int -> Int -> [(Integer,Int)] perfect_powers b e = go 2 2 [] where go x y l | x == b && y == e = l | y == e = go (x+1) 2 (((toInteger x)^y,y):l) | otherwise = go x (y+1) (((toInteger x)^y,y):l) powerSumDigTerm :: Int -> Integer powerSumDigTerm n = fst $ (filter (\(x,y) -> (sum_digits x)^y == x) $ sortOn fst $ perfect_powers 200 100) !! (n-1) Overall, I'm kind of unsatisfied with this solution, if anyone knows one that works in the general case (i.e without bounds on base and exponent) please let me know
{ "domain": "codereview.stackexchange", "id": 42589, "lm_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, programming-challenge, haskell, functional-programming", "url": null }
python, performance, programming-challenge, time-limit-exceeded, pathfinding Title: BFS shortest path for Google Foobar challenge "Prepare the Bunnies' Escape" Question: This is the Google Foobar challenge "Prepare the Bunnies' Escape": You have maps of parts of the space station, each starting at a prison exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the prison is at the top left \$(0,0)\$ and the door into an escape pod is at the bottom right \$(w-1,h-1)\$. Write a function answer(map) that generates the length of the shortest path from the prison door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed. Test cases Input: maze = [[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]] Output: 7 Input: maze = [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]] Output: 11 I found a couple solutions but none seem to be optimal enough. Solution in Python: BFS shortest path for Google Foobar "Prepare the Bunnies' Escape" I tried the recommendations in this answer but I am still getting a "time-limit-exceeded" error and I did not have any means to confirm whether the optimisations happened and to what extent they worked. I am fairly new to Python so I might have missed some basic details. Is there any more room for optimisation? My code after following the instructions is as follows: from collections import deque
{ "domain": "codereview.stackexchange", "id": 42590, "lm_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, programming-challenge, time-limit-exceeded, pathfinding", "url": null }
python, performance, programming-challenge, time-limit-exceeded, pathfinding def memodict(f): """ Memoization decorator for a function taking a single argument """ class memodict(dict): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__ @memodict def adjacent_to((maze_dim, point)): neighbors = ( (point[0] - 1, point[1]), (point[0], point[1] - 1), (point[0], point[1] + 1), (point[0] + 1, point[1])) return [p for p in neighbors if 0 <= p[0] < maze_dim[0] and 0 <= p[1] < maze_dim[1]] def removable(maz, ii, jj): counter = 0 for p in adjacent_to(((len(maz), len(maz[0])), (ii, jj))): if not maz[p[0]][p[1]]: if counter: return True counter += 1 return False def answer(maze): path_length = 0 if not maze: return dims = (len(maze), len(maze[0])) end_point = (dims[0]-1, dims[1]-1) # list of walls that can be removed passable_walls = set() for i in xrange(dims[0]): for j in xrange(dims[1]): if maze[i][j] == 1 and removable(maze, i, j): passable_walls.add((i, j)) shortest_path = 0 best_possible = dims[0] + dims[1] - 1 path_mat = [[None] * dims[1] for _ in xrange(dims[0])] # tracker matrix for shortest path path_mat[dims[0]-1][dims[1]-1] = 0 # set the starting point to destination (lower right corner) for wall in passable_walls: temp_maze = maze if wall: temp_maze[wall[0]][wall[1]] = 0 stat_mat = [['-'] * dims[1] for _ in xrange(dims[0])] # status of visited and non visited cells q = deque() q.append(end_point) while q: curr = q.popleft() if curr == (0,0): break
{ "domain": "codereview.stackexchange", "id": 42590, "lm_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, programming-challenge, time-limit-exceeded, pathfinding", "url": null }
python, performance, programming-challenge, time-limit-exceeded, pathfinding if curr == (0,0): break for next in adjacent_to((dims, curr)): if temp_maze[next[0]][next[1]] == 0: # Not a wall temp = path_mat[curr[0]][curr[1]] + 1 if temp < path_mat[next[0]][next[1]] or path_mat[next[0]][next[1]] == None: # there is a shorter path to this cell path_mat[next[0]][next[1]] = temp if stat_mat[next[0]][next[1]] != '+': # Not visited yet q.append(next) stat_mat[curr[0]][curr[1]] = '+' # mark it as visited if path_mat[0][0]+1 <= best_possible: break if shortest_path == 0 or path_mat[0][0]+1 < shortest_path: shortest_path = path_mat[0][0]+1 return shortest_path Answer: The algorithm in the post is to iterate over the walls, and for each wall, to remove that wall from the maze, and then solve the maze using breadth-first-search. If the maze is \$nΓ—n\$, then there are \$Θ(n^2)\$ walls, and it takes \$Θ(n^2)\$ to do a breadth-first search on the resulting maze, for \$Θ(n^4)\$ overall runtime. No wonder you are exceeding the time limit. Instead, consider the following approach: Run a breadth-first search starting at the prison door, to find the distance of each passable space from the prison door. Run another breadth-first search starting at the escape pod, to find the distance of each passable space from the escape pod. Now iterate over the walls, and consider removing each wall in turn. You know the distance of each passable space from the prison door and the escape pod, so you can immediately work out the length of the shortest route that passes through the space left by the wall you just removed. This would have runtime \$Θ(n^2)\$.
{ "domain": "codereview.stackexchange", "id": 42590, "lm_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, programming-challenge, time-limit-exceeded, pathfinding", "url": null }
python, programming-challenge, time-limit-exceeded, pathfinding Title: BFS shortest path for Google Foobar "Prepare the Bunnies' Escape" Question: This is the Google Foobar puzzle "Prepare the Bunnies' Escape": You have maps of parts of the space station, each starting at a prison exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the prison is at the top left \$(0,0)\$ and the door into an escape pod is at the bottom right \$(w-1,h-1)\$. Write a function answer(map) that generates the length of the shortest path from the prison door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed. Test cases Input: maze = [[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]] Output: 7 Input: maze = [[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]] Output: 11 My approach is to make a list of removable walls and then by removing them one at a time in a loop, do a BFS for the shortest path. At the end, I return the shortest path overall. I have the following code that works. However, when I deal with larger matrices, it becomes very slow and I can't get past the test code due to exceeding the time limit. I was wondering if there is a problem in my algorithm or there would be a better approach to this problem. class Queue: def __init__(self): self.items = [] def isEmpty(self): return self.items == [] def enqueue(self, item): self.items.insert(0,item)
{ "domain": "codereview.stackexchange", "id": 42591, "lm_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, programming-challenge, time-limit-exceeded, pathfinding", "url": null }
python, programming-challenge, time-limit-exceeded, pathfinding def enqueue(self, item): self.items.insert(0,item) def dequeue(self): return self.items.pop() def size(self): return len(self.items) def adjacent_to(maze_dim, point): neighbors = ( (point[0]-1, point[1]), (point[0], point[1]-1), (point[0], point[1]+1), (point[0]+1, point[1])) for p in neighbors: if 0 <= p[0] < maze_dim[0] and 0 <= p[1] < maze_dim[1]: yield p def removable(maz, ii, jj): counter = 0 for p in adjacent_to((len(maz),len(maz[0])), (ii, jj)): if maz[p[0]][p[1]] == 0: counter += 1 if counter >= 2: return True else: return False def answer(maze): path_length = 0 if not maze: return dims = (len(maze), len(maze[0])) end_point = (dims[0]-1, dims[1]-1) # list of walls that can be removed passable_walls = [0] for i in xrange(dims[0]): for j in xrange(dims[1]): if maze[i][j] == 1 and removable(maze, i, j): passable_walls.append((i, j)) shortest_path = 0 best_possible = dims[0] + dims[1] - 1 path_mat = [[None] * dims[1] for _ in xrange(dims[0])] # tracker matrix for shortest path path_mat[dims[0]-1][dims[1]-1] = 0 # set the starting point to destination (lower right corner) for i in xrange(len(passable_walls)): temp_maze = maze if passable_walls[i] != 0: temp_maze[passable_walls[i][0]][passable_walls[i][1]] = 0 stat_mat = [['-'] * dims[1] for _ in xrange(dims[0])] # status of visited and non visited cells q = Queue() q.enqueue(end_point) while not q.isEmpty(): curr = q.dequeue()
{ "domain": "codereview.stackexchange", "id": 42591, "lm_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, programming-challenge, time-limit-exceeded, pathfinding", "url": null }
python, programming-challenge, time-limit-exceeded, pathfinding while not q.isEmpty(): curr = q.dequeue() if curr == (0,0): break for next in adjacent_to(dims, curr): if temp_maze[next[0]][next[1]] == 0: # Not a wall temp = path_mat[curr[0]][curr[1]] + 1 if temp < path_mat[next[0]][next[1]] or path_mat[next[0]][next[1]] == None: # there is a shorter path to this cell path_mat[next[0]][next[1]] = temp if stat_mat[next[0]][next[1]] != '+': # Not visited yet q.enqueue(next) stat_mat[curr[0]][curr[1]] = '+' # mark it as visited if path_mat[0][0]+1 <= best_possible: break if shortest_path == 0 or path_mat[0][0]+1 < shortest_path: shortest_path = path_mat[0][0]+1 return shortest_path maze = [ [0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0] ] # maze = [ # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # ]
{ "domain": "codereview.stackexchange", "id": 42591, "lm_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, programming-challenge, time-limit-exceeded, pathfinding", "url": null }
python, programming-challenge, time-limit-exceeded, pathfinding # maze = [ # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] # ] print answer(maze) Answer: One problem might be your custom Queue class. The list you use as underlying data structure has O(n) behaviour for list.insert(0, item). It would be better to use a collections.deque, for which insertion and poping from both sides is O(1). You would use it like this: q = collections.deque() for value in range(10): q.append(value) ... while q: next_value = q.popleft() # Do something with `next_value` In removable your return logic can be short-circuited: def removable(maze, ii, jj): zeros = 0 for y, x in adjacent_to((len(maze),len(maze[0])), (ii, jj)): if not maze[y][x]: if zeros: return True zeros += 1 return False This way you exit early after finding the second 0 already. I also used the more readable name maze, split up p into an x and y coordinate and used the fact that 0 == False in Python.
{ "domain": "codereview.stackexchange", "id": 42591, "lm_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, programming-challenge, time-limit-exceeded, pathfinding", "url": null }
python, programming-challenge, time-limit-exceeded, pathfinding When looping over passable_walls you should directly loop over the elements, not the indices: for wall in passable_walls: temp_maze = maze if wall: temp_maze[wall[0]][wall[1]] = 0 ... Here I also used the fact that 0 == False in Python. Implementing these first two changes, the running time changes for the medium size maze from 89492 function calls in 0.042 seconds to 61763 function calls in 0.035 seconds, so not really a lot of improvement. The large maze takes about 30s. Profiling the code (run it with python -m cProfile maze.py) yields that 42761 of those calls are a call to adjacent_to. So it might make sense to speed that function up. One possibility for this is caching the results of the function, because with 40k calls for less than 300 cells for the large maze there are bound to be repeated calls. The fastest cache for a single valued function I know is this one: def memodict(f): """ Memoization decorator for a function taking a single argument """ class memodict(dict): def __missing__(self, key): ret = self[key] = f(key) return ret return memodict().__getitem__ This could be modified to allow for multiple values, or we could just always supply the arguments as a tuple: @memodict def adjacent_to((maze_dim, (i, j))): neighbors = ( (i - 1, j), (i, j - 1), (i, j + 1), (i + 1, j)) return [p for p in neighbors if 0 <= p[0] < maze_dim[0] and 0 <= p[1] < maze_dim[1]] def removable(maze, i, j): counter = 0 for x, y in adjacent_to(((len(maze), len(maze[0])), (i, j))): if not maze[x][y]: if counter: return True counter += 1 return False def answer(maze): ... while q: ... for next in adjacent_to((dims, curr)): ...
{ "domain": "codereview.stackexchange", "id": 42591, "lm_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, programming-challenge, time-limit-exceeded, pathfinding", "url": null }
python, programming-challenge, time-limit-exceeded, pathfinding Here I had to remove the generator from adjacent_to as well, because it messes with the caching. This solves the medium maze with 28616 function calls in 0.020 seconds and the large maze with 22233918 function calls in 14.493 seconds. So it is a speed-up of about a factor 2. At this time most of the time spent is in the logic of answer (12 out of the 14s). The rest is equally shared by dict.__getitem__, deque.append and deque.popleft. For further speed improvement, consider again passable_walls. Currently it is a list. But it might as well be a set, because it is enough to note that a wall is removable, having a pair (i,j) in there twice does not add any information: def answer(maze): ... passable_walls = set() for i in xrange(dims[0]): for j in xrange(dims[1]): if maze[i][j] == 1 and removable(maze, i, j): passable_walls.add((i, j)) ... for wall in passable_walls: temp_maze = maze if wall: temp_maze[wall[0]][wall[1]] = 0 ... This, finally, executes with 5470021 function calls in 3.590 seconds for the large maze.
{ "domain": "codereview.stackexchange", "id": 42591, "lm_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, programming-challenge, time-limit-exceeded, pathfinding", "url": null }
c++, performance Title: Is this snippet of code following all the best practices? The code is intended to capitalize the first letter of a word Question: How can I improve this so that it follows all the best practices? #include <iostream> int main() { std::string userInput{ " " }; std::cin >> userInput; if( int( userInput[ 0 ] ) > 96 && int( userInput[ 0 ] ) < 123 ) { userInput[ 0 ] = char( int( userInput[ 0 ] ) - 32 ); } std::cout << userInput << "\n"; return 0; } 32,96 and 123 used are ascii character codes. Answer: No, your code can and should be improved: You are missing the include for std::string. Default-constructing the string is sufficient. You fail to check whether reading from std::cin succeeded. Converting a char to int before comparison with int constants has no effect. If any of the values compared against were outside the common range of char and unsigned char (a minimum of 0 to 127 inclusive), conversion to unsigned char would have an effect. Use character-literals for respective constants. While the portability concerns for character codes are largely academic as long as you restrict yourself to ASCII, it's still needless obfuscation. Also, in this case a close range would be appropriate. Writing your own toupper() might be cute, but that implementation is restricted to pure ASCII. The true toupper() is restricted to SBCSs (no unicode), which might suffice for a toy-program. return 0; is implied for main(). Fixed code: #include <cctype> #include <cstdlib> #include <iostream> #include <string> int main() { std::string input; if (!(std::cin >> input)) { std::cerr << "Could not read from STDIN.\n"; return EXIT_FAILURE; } input[0] = std::toupper((unsigned char)input[0]); std::cout << input << "\n"; }
{ "domain": "codereview.stackexchange", "id": 42592, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, performance", "url": null }
python, matplotlib Title: Euler Method Harmonic Oscillator Question: I have written very simple Python code to solve the simple harmonic oscillator using Euler method, but I am not sure if the program is correct or not. I would be very grateful if anyone can look at my code and suggest further improvements since I am very new to this programming thing. import matplotlib.pyplot as plt v=0.0 #initial velocity h=0.01 #time step x=5.0 #initial position t=0.0 ta,xa=[],[] while t<1.0: ta.append(t) xa.append(x) v=v-(10.0/1.0)*x*h #k=10.0, m=1.0 x=x+v*h t=t+h plt.figure() plt.plot(ta,xa,'--') plt.xlabel('$t(s)$') plt.ylabel('$x(m)$') plt.show() Answer: The code is quite monolithic: calculation and presentation are separate concerns, and while I appreciate the context given by showing the presentation, it would be better to make clear that they're separate concerns by separating them with whitespace and commenting briefly. Also on structure: separate constants (h) from variables (v, x, t). v=v-(10.0/1.0)*x*h #k=10.0, m=1.0 x=x+v*h t=t+h Two things: firstly, what are k and m? It seems that they should be constants with comments explaining their physical significance. Secondly, this isn't Euler's method. Euler's method is \$\vec{x}_{n+1} = \vec{x}_n + hf(t_n, \vec{x}_n)\$ where \$f = \frac{d\vec{x}}{dt}\$. Here \$\vec{x} = (v, x)\$ and \$f(t, v, x) = (\frac{dv}{dt}, \frac{dx}{dt}) = (-\frac{k}{m}x, v)\$. In other words, to be Euler's method you should update x according to the previous value of v, not the updated value of v. Since you're using Python, you can take advantage of simultaneous assignment: v,x=v-(k/m)*x*h,x+v*h t=t+h (As it happens your buggy implementation works better than Euler's method, but if it was intended to implement Euler's method then it's still technically buggy).
{ "domain": "codereview.stackexchange", "id": 42593, "lm_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, matplotlib", "url": null }
bash, file-structure, sed Title: Bash script to clone directory structure with renaming Question: I've written a script to aid in creating new watchfaces for the awesome AsteroidOS project. A watchface there typically consists of directory structure like this: digital-shifted/ └── usr └── share β”œβ”€β”€ asteroid-launcher β”‚ β”œβ”€β”€ watchface-img β”‚ β”‚ β”œβ”€β”€ asteroid-logo.svg β”‚ β”‚ β”œβ”€β”€ digital-shifted-0.png β”‚ β”‚ β”œβ”€β”€ digital-shifted-1.png β”‚ β”‚ β”œβ”€β”€ digital-shifted-2.png β”‚ β”‚ β”œβ”€β”€ digital-shifted-3.png β”‚ β”‚ β”œβ”€β”€ digital-shifted-4.png β”‚ β”‚ β”œβ”€β”€ digital-shifted-5.png β”‚ β”‚ β”œβ”€β”€ digital-shifted-6.png β”‚ β”‚ β”œβ”€β”€ digital-shifted-7.png β”‚ β”‚ β”œβ”€β”€ digital-shifted-8.png β”‚ β”‚ β”œβ”€β”€ digital-shifted-9.png β”‚ β”‚ └── digital-shifted-ring.svg β”‚ └── watchfaces β”‚ └── digital-shifted.qml └── fonts β”œβ”€β”€ OpenSans-CondLight.ttf └── OpenSans-Light.ttf If we want to clone this watchface, named digital-shifted to a new watchface, let's say digital-swirl we need to copy that complete directory tree, but everywhere digital-shifted appears in a file name, we need to change it to digital-swirl and finally, the lines within the QML file that refers to those files should also be changed to refer to the renamed files. This is a fairly common operation for creating a new watchface from an existing one, so this script is intended to perform that task. It must be invoked in the same top-level directory that contains digital-shifted and the new digital-swirl must not already exist. The copying is fairly straightforward, but then find is used and the script runs itself with a third argument which is the name of each individual file that contains the original name. That part is not so obvious and is, in particular, the place I'd like comments and suggestions. #!/bin/bash # clone watchface changing names where required
{ "domain": "codereview.stackexchange", "id": 42594, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, file-structure, sed", "url": null }
bash, file-structure, sed # remember source and dest, trimming trailing / if needed SOURCE=$(echo $1 | sed 's:/*$::') DEST=$(echo $2 | sed 's:/*$::') function showHelp { cat << EOF ./clone.sh source destination Clone a existing "source" watchface to a new "destination" watchface. The script copies and renames files that contain the "source" name and updates the watchface qml file to point to the renamed sources. EOF } # the three-argument form is only intended to be used internally if [ -f "$3" ] ; then if [[ "$3" == *.qml ]] ; then sed "s/$SOURCE/$DEST/g" "$3" > "${3//$SOURCE/$DEST}" rm "$3" else mv "$3" "${3//$SOURCE/$DEST}" fi exit fi if [ "$#" != "2" ] ; then showHelp exit fi if [ ! -d "$SOURCE" ] ; then echo "Error: $SOURCE does not exist, exiting program" exit fi if [ -e "$DEST" ] ; then echo "Error: $DEST already exists, exiting program" exit fi # copy all of the files cp -r "${SOURCE}" "${DEST}" # rename any file that contains the source dir name find "${DEST}" -type f -iname "*${SOURCE}*" -execdir "$(pwd)/cloner.sh" "${SOURCE}" "${DEST}" '{}' \; Answer: SOURCE=$(echo $1 | sed 's:/*$::') DEST=$(echo $2 | sed 's:/*$::') We don't need an external sed for this transformation, I think. Are we really likely to be invoked with multiple trailing /? If we only ever need to remove a single /, then it's a trivial parameter substitution: source=${1%/} dest=$2{%/} Note also use of lower-case for variable names - that's a good practice, since all-caps environment variable names are often used for communicating with child processes, and we don't want to accidentally collide with them. This is worrying: sed "s/$SOURCE/$DEST/g" "$3" > "${3//$SOURCE/$DEST}"
{ "domain": "codereview.stackexchange", "id": 42594, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, file-structure, sed", "url": null }
bash, file-structure, sed This is worrying: sed "s/$SOURCE/$DEST/g" "$3" > "${3//$SOURCE/$DEST}" The source variable is being interpreted both as regular expression and as a shell pattern. The two substitutions could give different results, unless we constrain the allowed characters, and I see no validation that will do that. And what if a name is given that contains / somewhere (not at the end)? if [ "$#" != "2" ] ; then showHelp exit fi I think that's a user error, so would expect showHelp >&2 exit 1 Similarly with the other error conditions - write the message to standard error stream and exit with a non-zero status value.
{ "domain": "codereview.stackexchange", "id": 42594, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "bash, file-structure, sed", "url": null }
c#, asp.net-web-api Title: ASP.NET Web API 2 reading values from config file or database or elsewhere Question: In my asp.net web API 2, I am reading values from web.config from the controller into my DTO as a response to the client. It is working as expected, I wonder if there are any improvements to make it better. Should I read it from a database or elsewhere? So I would be glad if you can share your comments. Here is the controller related part: [HttpGet] [Route("reconciliation")] public async Task<IHttpActionResult> GameReconciliation(ReconciliationDto reconciliationDto) { if (!ModelState.IsValid) return BadRequest(ModelState); using var recon = await _gameServices.GameReconciliation(reconciliationDto); switch (recon.StatusCode) { case HttpStatusCode.NotFound: { return NotFound(); } case HttpStatusCode.InternalServerError: { return InternalServerError(); } case HttpStatusCode.OK: { var responseStream = await recon.Content.ReadAsStringAsync(); var resultResponse = JsonConvert.DeserializeObject<ReconciliationResponse>(responseStream);
{ "domain": "codereview.stackexchange", "id": 42595, "lm_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#, asp.net-web-api", "url": null }
c#, asp.net-web-api //Transform ReconciliationResponse into DTO for returning result var config = new MapperConfiguration(cfg => { cfg.CreateMap<ReconciliationResponse, ReconciliationResponseDto>().ForMember(x => x.ReconDateTime, opt => opt.MapFrom(src => (src.ReconciliationResponseDateTime.ToString("yyyy-MM-dd")))); }); var iMapper = config.CreateMapper(); var resultDto = iMapper.Map<ReconciliationResponse, ReconciliationResponseDto>(resultResponse); //EAN Barcode Added **resultDto.Ean = WebConfigurationManager.AppSettings["000000001570"];** return Ok(resultDto); } case HttpStatusCode.Unauthorized: { return Unauthorized(); } case HttpStatusCode.RequestTimeout: { return InternalServerError(); } } recon.Dispose(); return Ok(recon); } Here is web.config related part: <appSettings> <!--TEST EAN--> <add key="000000001570" value="9799753293685" /> Answer: Honestly, it is impossible for us to answer your question. If this is the same value on all environments and it will likely never change, why not hardcode it in the C# code as a const in some appropriately named class? If it changes per environment: put it in the .config. If this is a value that might change regularly and you don't want to do a deploy each time: put it in the DB. WRT your code: Keep controllers and the methods therein small. Use something like MediatR to move logic to specific classes.
{ "domain": "codereview.stackexchange", "id": 42595, "lm_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#, asp.net-web-api", "url": null }
c#, asp.net-web-api Don't needlessly abbreviate. Sure, the next maintainer of this code can figure out what recon means and/or what it is, but they shouldn't need to spend time on this: your code should make it clear what it is/does. Don't use meaningless prefixes. I guess iMapper is an IMapper, but that doesn't mean you need to call it that. Plus, I assume CreateMapper returns an actual mapper, not simply an interface. Why is your mapping logic inside this class, even inside this method? I'd expect that kind of logic to be in a separate class, and that class to be injected. For instance via your API's Startup class by using the AddAutoMapper method (if you're using AutoMapper). I'm not a fan of seeing things like WebConfigurationManager.AppSettings["000000001570"]; in the middle of code. I usually put all the configuration settings in a specific static class (named e.g. "WebApiConfiguration") and all of the settings would be in that class as public static properties, e.g. public static string EnvironmentName => ConfigurationManager.AppSettings["EnvironmentName"];. This also allows me to have typed settings if necessary, e.g. public static bool LogDetails => _lazyLogDetails.Value; uses private static readonly Lazy<bool> _lazyLogDetails = new Lazy<bool>(() => ConfigurationHelper.GetBool("LogDetails")); which itself uses a method from this class.
{ "domain": "codereview.stackexchange", "id": 42595, "lm_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#, asp.net-web-api", "url": null }
python, json Title: Very slow work with data analysis in JSON using Python Question: I'll put my complete code below so that anyone who can help won't have any difficulty running, just copy it and it's 100% functional, just very very slow. To register the data I need, I make several requests on different API links, a tangle of calls. This makes it very slow and takes forever to parse each of the ID's. I need help improving my code as I only know how to work this way it currently is. import requests import csv
{ "domain": "codereview.stackexchange", "id": 42596, "lm_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, json", "url": null }
python, json headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } with open("SofaScore/Goals_Mommentum.csv", "a", newline="", encoding="UTF-8") as f: datasparaurl = ["2021-01-01","2021-01-02","2021-01-03","2021-01-04","2021-01-05"] for dataparaurl in datasparaurl: url1 = f'https://api.sofascore.com/api/v1/sport/football/scheduled-events/{dataparaurl}' response1 = requests.get(url1, headers=headers).json() events = response1['events'] for event in events: nometimeA = event['homeTeam']['shortName'] nometimeB = event['awayTeam']['shortName'] nomedojogo = str(nometimeA) + " x " + str(nometimeB) description = event['status']['description'] identidade = event['id'] jogofinalizado = event['status']['type'] if (jogofinalizado == 'finished'): url2 = f'https://api.sofascore.com/api/v1/event/{identidade}/incidents' response2 = requests.get(url2, headers=headers).json() if 'incidents' in response2: incidents = response2['incidents'] for incident in incidents: if (incident['incidentType'] == 'goal'): dadosdogol = [] dadosdogol.append(nomedojogo) dadosdogol.append(identidade) goalminute = incident['time'] if(goalminute >=0 and goalminute <=44 or goalminute >=46 and goalminute <=89): dadosdogol.append(goalminute) url3 = f'https://api.sofascore.com/api/v1/event/{identidade}/graph' response3 = requests.get(url3, headers=headers).json() if 'graphPoints' in response3:
{ "domain": "codereview.stackexchange", "id": 42596, "lm_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, json", "url": null }
python, json if 'graphPoints' in response3: graphs = response3['graphPoints'] for graph in graphs: if(graph['minute'] == goalminute-5): dadosdogol.append(abs(graph['value'])) if(graph['minute'] == goalminute-4): dadosdogol.append(abs(graph['value'])) if(graph['minute'] == goalminute-3): dadosdogol.append(abs(graph['value'])) if(graph['minute'] == goalminute-2): dadosdogol.append(abs(graph['value'])) if(graph['minute'] == goalminute-1): dadosdogol.append(abs(graph['value'])) print(dadosdogol) a = csv.writer(f) a.writerow(dadosdogol) print(dataparaurl) f.close()
{ "domain": "codereview.stackexchange", "id": 42596, "lm_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, json", "url": null }
python, json Answer: very, very slow This is unavoidable - you're sending up to three HTTP requests for every single row of your output. Also note that it's "at least immoral" to hammer this site; the owners have tried to protect it with CloudFlare and want you to ask them for permission: The system identified you as a scraper and banned the IP. To use the data on the website contact the owner and request permission. That aside, for your code itself, Write some functions; don't write one giant blob of global code Separate downloading, filtering and serialising concerns Don't write code in Portuguese - write it in English, which is an international de-facto standard for coding Mommentum is spelled Momentum Refactor your goal-minutes statements into a loop Don't f.close(); you've already done this in your with Maintain a session object for your requests Use PEP484 type hints Suggested from csv import DictWriter from datetime import date, timedelta from typing import Iterator, Any, Dict, Iterable, Tuple, List from urllib.parse import urljoin from requests import Session JsonDict = Dict[str, Any] EventsAndGoals = Tuple[JsonDict, JsonDict] EventsGoalsGraphs = Tuple[JsonDict, JsonDict, List[JsonDict]] def get_sofascore(session: Session, path: str) -> JsonDict: url = urljoin('https://api.sofascore.com', path) with session.get(url, headers={'Accept': 'application/json'}) as response: response.raise_for_status() return response.json() def get_events(session: Session, start_date: date, days: int) -> Iterator[Dict[str, Any]]: for day in range(days): when = start_date + timedelta(days=day) response = get_sofascore( session=session, path=f'/api/v1/sport/football/scheduled-events/{when}', ) for event in response['events']: if event['status']['type'] == 'finished': yield event
{ "domain": "codereview.stackexchange", "id": 42596, "lm_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, json", "url": null }
python, json def get_goals(session: Session, events: Iterable[JsonDict]) -> Iterator[EventsAndGoals]: for event in events: response = get_sofascore( session=session, path=f'/api/v1/event/{event["id"]}/incidents', ) for incident in response.get('incidents', ()): if ( incident['incidentType'] == 'goal' and incident['time'] < 90 and incident['time'] != 45 # why? ): yield event, incident def get_graphs(session: Session, events_and_goals: Iterable[EventsAndGoals]) -> Iterator[EventsGoalsGraphs]: for event, goal in events_and_goals: response = get_sofascore( session=session, path=f'https://api.sofascore.com/api/v1/event/{event["id"]}/graph', ) graph = response.get('graphPoints') if graph: yield event, goal, graph def make_row( event: JsonDict, goal: JsonDict, graph: List[JsonDict], ) -> Dict[str, Any]: row = { 'name': f'{event["homeTeam"]["shortName"]} x {event["awayTeam"]["shortName"]}', 'id': event['id'], 'minutes': goal['time'], } for point in graph: delta = goal['time'] - point['minute'] if 0 < delta <= 5 and float(delta).is_integer(): row[f'tminus{delta}'] = abs(point['value']) return row def main() -> None: with Session() as session: events = get_events( session=session, start_date=date(2021, 1, 1), days=5, ) events_and_goals = get_goals(session, events) all_sources = get_graphs(session, events_and_goals) rows = (make_row(*source) for source in all_sources)
{ "domain": "codereview.stackexchange", "id": 42596, "lm_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, json", "url": null }
python, json with open("Goals_Momentum.csv", "w", newline="", encoding="UTF-8") as f: writer = DictWriter( f=f, fieldnames=( 'name', 'id', 'minutes', *(f'tminus{i}' for i in range(5, 0, -1)), ), ) writer.writerows(rows) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 42596, "lm_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, json", "url": null }
r Title: Assign 0 or 1 with different probabilities conditional on another column in R Question: I am trying to assign a 0 or 1 with some stochasticity based on another column in a data frame (outcome). If outcome == 1, the new column exposure should equal 1 about 90% of the time. Conversely if outcome == 0 it should equal 1 about 20% of the time. I am currently doing this with a for loop but wondering if there are more efficient/elegant ways to accomplish this (i.e. via vectorization). To be clear, though the data frame is labeled example_data this is not an example - its the test data I am generating to test a series of functions related to GEE models. set.seed(05062020) example_data <- data.frame(id = as.factor(rep(sprintf("Record %s",seq(1:50)), each = 2)), outcome = as.factor(rep(sample(0:1, 50, prob = c(0.8,0.2), replace = TRUE), each = 2))) for (i in 1:nrow(example_data)){ example_data$exposure[i] <- ifelse(example_data$outcome[i] == 1, sample(0:1, 1, prob = c(0.1, 0.9)), sample(0:1, 1, prob = c(0.8, 0.2))) } Answer: example_data$exposure <- ifelse(example_data$outcome == 1, sample(0:1, nrow(example_data), prob = c(0.1, 0.9), replace = T), sample(0:1, nrow(example_data), prob = c(0.8, 0.2), replace = T)) ifelse is vectorized, so we can do this with one function call.
{ "domain": "codereview.stackexchange", "id": 42597, "lm_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", "url": null }
c#, random, shuffle Title: Improving performance of 'Prioritized left shuffle algorithm' Question: I wrote a prioritized left shuffle algorithm (the code is copied from my open source C# project Fluent Random Picker). That means: You've got some values and each of them has a priority (a number). The higher the priority is, the higher are the chances of the value being far on the left after the shuffle. The algorithm pretty much runs in linear time. It works with "stochastic acceptance" (see method RouletteWheelSelection). But: It can get slower if one or multiple priorities are much higher than others. E.g. (1.000.000.000, 1, 1, 1, 1, 1, 1, 1). Why? Because the max is only calculated once (see first line in Shuffle) and calculating it n time would make the performance worse.
{ "domain": "codereview.stackexchange", "id": 42598, "lm_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#, random, shuffle", "url": null }
c#, random, shuffle Any ideas for improvements? The best solution would be an always O(n) algorithm that can run in parallel, but especially the "parallel" part is probably not possible. Idea 1: Using this O(n) algorithm to get the max values of some intervals (e.g. in an array with 1.000 priorities I get the largest value, the 100th largest, the 200th largest, ... and the 900th largest) in the beginning and keep track of them to be able to replace one max priority with the next one as soon as there is no priority higher than the next one remaining. Idea 2: Keeping track of the pairs[randomIndex].Priority / (double)max calculations in RouletteWheelSelection and if the last x results of that calculation are all lower than 0.000..., then the max will be calculated again. /// <summary> /// Shuffles the first n elements and respects the probabilities in O(n) time. /// </summary> /// <param name="elements">The elements (value and probability) to shuffle.</param> /// <param name="firstN">Limits how many of the first elements to shuffle.</param> /// <returns>The shuffled elements.</returns> public IEnumerable<ValuePriorityPair<T>> Shuffle(IEnumerable<ValuePriorityPair<T>> elements, int firstN) { var max = elements.Max(v => v.Priority); var list = new List<ValuePriorityPair<T>>(elements); var lastIndex = firstN < elements.Count() ? firstN - 1 : firstN - 2; for (int i = 0; i <= lastIndex; i++) { int randomIndex = RouletteWheelSelection(list, i, max); Swap(list, i, randomIndex); } return list; } private static void Swap<TEelment>(IList<TEelment> elements, int index1, int index2) { var tmp = elements[index1]; elements[index1] = elements[index2]; elements[index2] = tmp; }
{ "domain": "codereview.stackexchange", "id": 42598, "lm_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#, random, shuffle", "url": null }
c#, random, shuffle private int RouletteWheelSelection(IList<ValuePriorityPair<T>> pairs, int startIndex, int max) { while (true) { var randomDouble = _rng.NextDouble(); var randomIndex = _rng.NextInt(startIndex, pairs.Count); if (randomDouble <= pairs[randomIndex].Priority / (double)max) return randomIndex; } } Answer: Without a doubt, RouletteWheelSelection could take a very long time, i.e. loop hundreds, thousands, or more times when you the max is very high. For a set like { 1_000_000_000, 1, 1, 1, 1, 1, 1, 1 } you have 7 elements with a Priority of 1, which means that randomDouble must be less than or equal to 0.000000001 for the method to return. So it might loop for a long time. And it would do it 7 times over. I can't help you with how you could improve that. Other than that, you code is fairly easy to read with decent enough variable naming. There is a typo in Swap in that TElement is spelled wrong. The signature should be: private static void Swap<TElement>(IList<TElement> elements, int index1, int index2) In the Shuffle method, it sounds like your input collection may be small but there is some inefficiencies with it if you ever plan to have a large collection. Right off the bat, you make 2 or 3 full collection enumerations based on these lines: var max = elements.Max(v => v.Priority); var list = new List<ValuePriorityPair<T>>(elements); var lastIndex = firstN < elements.Count() ? firstN - 1 : firstN - 2;
{ "domain": "codereview.stackexchange", "id": 42598, "lm_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#, random, shuffle", "url": null }
c#, random, shuffle If your input is actually an IList<ValuePriorityPair<T>>, then elements.Count() will just provide the IList.Count. If you do not input a list or array, then Count() will enumerate over the full collection. Max() and well as defining a new List also enumerates over the whole collection. Worst case, is 2 times but it could be 3. And then later you loop over the collection up to firstN. You could skip LINQ for the first 2 lines and loop once to both find max and add items to list. Then lastIndex could become: var lastIndex = Math.Min(firstN, list.Count) - 1; Observe this does 2 things differently. (1) It uses list.Count which does not require enumerating over the collection to perform the count, and (2) it clamps the end at list.Count just in case you input a firstN that is greater than list.Count. VERY Minor things I would do differently regarding naming and types in RouletteWheelSelection. I would want max to accept a double in the signature rather than cast repeatedly in the while loop. And I would change the name pairs to be elements to be consistent with its usage elsewhere. private int RouletteWheelSelection(IList<ValuePriorityPair<T>> elements, int startIndex, double max) Again, those are very minor so take it with a grain of salt.
{ "domain": "codereview.stackexchange", "id": 42598, "lm_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#, random, shuffle", "url": null }
c++, casting Title: How to not clutter intended casts with static_cast<>? Question: have the following struct with one method: struct CaveData { int tunnel_radius; int min_cave_edge_points; int max_cave_edge_points; int min_surface_points; int max_surface_points; int min_random_points; int max_random_points; int chunk_seem_connector_cave_range_quotient; int chunk_seem_min_points; int chunk_seem_max_points; inline void addWithFactor(float factor, CaveData & other) { tunnel_radius += factor * other.tunnel_radius; min_cave_edge_points += factor * other.min_cave_edge_points; max_cave_edge_points += factor * other.max_cave_edge_points; min_surface_points += factor * other.min_surface_points; max_surface_points += factor * other.max_surface_points; min_random_points += factor * other.min_random_points; max_random_points += factor * other.max_random_points; chunk_seem_connector_cave_range_quotient += factor * other.chunk_seem_connector_cave_range_quotient; chunk_seem_min_points += factor * other.chunk_seem_min_points; chunk_seem_max_points += factor * other.chunk_seem_max_points; } }; It is intended that all those values are ints and possible inaccuracies are ignored. However Visual Studio is showing me a literal ton of warnings regarding: "conversion from 'float' to 'int', possible loss of data" I understand that I can avoid those by adding static_cast() to every line but that feels like cluttering the code (coming from C# and Java) because it just looks like adding another function call. Is there an alternative way of avoiding the warnings appropriately? Answer: With MSVC you can disable the warning for a block of code like the following: inline void addWithFactor(float factor, CaveData& other) { #pragma warning( push ) #pragma warning( disable : 4244 ) tunnel_radius += factor * other.tunnel_radius;
{ "domain": "codereview.stackexchange", "id": 42599, "lm_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++, casting", "url": null }
c++, casting min_cave_edge_points += factor * other.min_cave_edge_points; max_cave_edge_points += factor * other.max_cave_edge_points; min_surface_points += factor * other.min_surface_points; max_surface_points += factor * other.max_surface_points; min_random_points += factor * other.min_random_points; max_random_points += factor * other.max_random_points; chunk_seem_connector_cave_range_quotient += factor * other.chunk_seem_connector_cave_range_quotient; chunk_seem_min_points += factor * other.chunk_seem_min_points; chunk_seem_max_points += factor * other.chunk_seem_max_points; #pragma warning( pop ) } You can also disable the warning for the whole project or a specific file in the settings: It might be better to properly cast the conversion. Using floor or ceil may add some clutter but it makes your intentions more clear. You can also consider std::lround which converts to the nearest integer.
{ "domain": "codereview.stackexchange", "id": 42599, "lm_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++, casting", "url": null }
javascript, html, css Title: Grade Calculator Tool Code Improvement Question: I am just looking for code improvements as I believe that it is done, and would like to see it expanded. I mainly want code improvements to make it more efficient, but any and all constructive criticisms are enjoyed If the snippet is broken the link to the fiddle is here: https://jsfiddle.net/BOSS2342/q18z037w/ What my code does is it take the two inputs, Current and Total Grade, and it uses that to give you some information about it, such as your letter grade and grade percentage, along with the amount you need to go up and down a letter grade. document.addEventListener("keyup", function(event) { //Used so you can press enter if (event.keyCode === 13) { Calc() } }); function Calc() { var g = /\d+$/.test(document.getElementById('g').value) ? Math.round(parseFloat(document.getElementById('g').value) * 100) / 100 : `You did not input your Current Points correctly`, //Testing and getting the value of Current Grade t = /\d+$/.test(document.getElementById('t').value) ? Math.round(parseFloat(document.getElementById('t').value) * 100) / 100 : `You did not input your Total Points correctly`, // Getting and testing the value of Total Grade m = Math.round((g / t) * 10000) / 100, //Using this for percentage calculations n = [], //empty var for later grade = (m) => { return m >= 90 ? 'A' : m < 90 && m >= 80 ? 'B' : m < 80 && m >= 70 ? 'C' : m < 70 && m >= 60 ? 'D' : 'F' }, //Used to convert Percentage into letter grade x = grade(m), cgrade = (m) => { return m == 'A' ? 90 : m == 'B' ? 80 : m == 'C' ? 70 : m == 'D' ? 60 : 50 } //Does the inverse of that for (i = 0; i <= t; i++) { n.push(Math.round(i / t * 10000) / 100) } //This is used to find all the possible percentages with the Total Grade
{ "domain": "codereview.stackexchange", "id": 42600, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, html, css", "url": null }
javascript, html, css //This is used to find all the possible percentages with the Total Grade findProx = (m) => { c = n[0] d = Math.abs(m - c) for (i = 0; i < n.length; i++) { if (n[i] === m) { return i } f = Math.abs(m - n[i]) if (f < d) { d = f c = i } } return c; } //Used to find the closest to the number I want var down = x == 'F' ? g : cgrade(x) == g / t * 100 || g == t ? Math.round((g - findProx(cgrade(x)) + 1)*10)/10 : Math.round((g - findProx(cgrade(x)))*10)/10, //Used to find the closest letter grade down, this is just a lot of if statements up = x == 'A' ? t - g : Math.round((Math.abs(g - findProx(cgrade(x+10))))*10)/10 //Used to find the closet letter grade up, this is just one more if statement document.getElementById('r1').innerHTML = typeof(g) == 'string' || typeof(t) == 'string' ? `Error` : `Your grade is: ${x} ${m}%` //Used to display the Grade and Percentage, along with an error document.getElementById('r2').innerHTML = typeof(g) == 'string' && typeof(t) == 'string' ? `You did not input either options correctly` : typeof(g) == 'string' ? g : typeof(t) == 'string' ? t : Math.sign(up) == -1 ? `You have ${Math.round((g-t)*100)/100} points of extra credit` : g == t ? `You have a 100% congrats!` : x == 'A' ? `If you gain ${Math.round((t-g)*100)/100} points you will have a 100%` : `If you gain ${up} points you'll go up to the next letter grade: ${grade(m+10)}` // A lot of stuff used for user information for the amount of points you need to go up a letter grade
{ "domain": "codereview.stackexchange", "id": 42600, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, html, css", "url": null }