text
stringlengths
1
2.12k
source
dict
algorithm, c, comparative-review, generics, c-preprocessor FIFO_CONFIG_ADD_LOCK(); pHandle->Buffer[FIFO_Head(&pHandle->Control)] = *pElement; FIFO_AdvanceHead(&pHandle->Control, pHandle->Size, 1); FIFO_CONFIG_ADD_UNLOCK(); return true; } static bool FIFO_Take(FIFO_CONFIG_TAG, FIFO_t(FIFO_CONFIG_TAG) *const pHandle, FIFO_CONFIG_TYPE *const pElement) { if (FIFO_IsEmpty(FIFO_CONFIG_TAG, pHandle)) { return false; } FIFO_CONFIG_TAKE_LOCK(); *pElement = pHandle->Buffer[FIFO_Tail(&pHandle->Control)]; FIFO_AdvanceTail(&pHandle->Control, pHandle->Size, 1); FIFO_CONFIG_TAKE_UNLOCK(); return true; } static void FIFO_Seek(FIFO_CONFIG_TAG, FIFO_t(FIFO_CONFIG_TAG) *const pHandle, const size_t offset) { FIFO_CONFIG_TAKE_LOCK(); FIFO_AdvanceTail(&pHandle->Control, pHandle->Size, offset); FIFO_CONFIG_TAKE_UNLOCK(); } static FIFO_CONFIG_TYPE * FIFO_Peek(FIFO_CONFIG_TAG, const FIFO_t(FIFO_CONFIG_TAG) *const pHandle, const size_t offset) { size_t index = FIFO_Tail(&pHandle->Control); FIFO_AdvanceIndex(&index, pHandle->Size, offset); return &pHandle->Buffer[index]; } #undef FIFO_CONFIG_TAG #undef FIFO_CONFIG_TYPE #undef FIFO_CONFIG_SIZE #undef FIFO_CONFIG_OVERWRITE_FULL #undef FIFO_CONFIG_ADD_LOCK #undef FIFO_CONFIG_ADD_UNLOCK #undef FIFO_CONFIG_TAKE_LOCK #undef FIFO_CONFIG_TAKE_UNLOCK main.c #include <stdio.h> #define FIFO_CONFIG_TAG MyFIFO #define FIFO_CONFIG_TYPE int #define FIFO_CONFIG_SIZE 10 #include "FIFO.h" static FIFO_t(MyFIFO) gFIFO = FIFO_STATIC_DEFINE(gFIFO); static FIFO_t(MyFIFO) gFIFO2 = FIFO_STATIC_DEFINE(gFIFO2); // Same FIFO instance // By reconfiguring and reincluding FIFO.h another different FIFO instance can be created #define FIFO_CONFIG_TAG OtherFIFO #define FIFO_CONFIG_TYPE float #define FIFO_CONFIG_SIZE 3 #include "FIFO.h" static FIFO_t(OtherFIFO) gFIFO3 = FIFO_STATIC_DEFINE(gFIFO3);
{ "domain": "codereview.stackexchange", "id": 44601, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, comparative-review, generics, c-preprocessor", "url": null }
algorithm, c, comparative-review, generics, c-preprocessor static FIFO_t(OtherFIFO) gFIFO3 = FIFO_STATIC_DEFINE(gFIFO3); int main(void) { for (int i = 0; i < 10; i++) { FIFO_Add(MyFIFO, &gFIFO, &i); } int x; while (FIFO_Take(MyFIFO, &gFIFO, &x)) { printf("%d\n", x); } FIFO_Add(OtherFIFO, &gFIFO3, &x); FIFO_Take(OtherFIFO, &gFIFO3, &x); printf("%d\n", x); return 0; } Benefits Using functions instead of macros provide type safety Because functions are used instead of macros means we can cleanly return and pass in variables Functions not necessary to be inlined at place of call which reduces overall code size Simple to integrate any user provided functions using through macros (see example for FIFO_CONFIG_ADD_LOCK, FIFO_CONFIG_ADD_UNLOCK) Code not relevant for specific configuration can be #ifdef'd out of compilation Weaknesses Debugging is somewhat clumsy because placing breakpoint inside of function will result in breakpoint being placed in one of randomly selected generated function or in all functions (that's my guess) Functions required to be passed in the FIFO Tag (or call the tagged function) Unconventional (? I haven't seen anyone use this) C coding practice which feels a bit out of place Need to include FIFO header for every instance (unconventional C coding practice) Macro magic can be hard to follow Need separate macros to define the instance (for example #define FIFO_STATIC_DEFINE(handle) and #define FIFO_DYNAMIC_DEFINE() if instance types are different enough that they require different initializations Cannot include header inside a function which means that all FIFOs must be delcared at global scope #2 Function-like macro code implementation Queue.h #if !defined(QUEUE_H_) #define QUEUE_H_ #include <stdbool.h> #include <stddef.h> #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
{ "domain": "codereview.stackexchange", "id": 44601, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, comparative-review, generics, c-preprocessor", "url": null }
algorithm, c, comparative-review, generics, c-preprocessor #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) /** * Queue control structure. */ typedef struct Queue_Control { size_t Head; /**< Head index. */ size_t Tail; /**< Tail index. */ size_t TotalPushed; /**< Total number of elements pushed to queue. */ size_t TotalPopped; /**< Total number of elements popped from queue. */ } Queue_Control_s; /** * Declare statically allocated queue. */ #define QUEUE_DECLARE_STATIC(type, size) \ struct \ { \ Queue_Control_s Control; /**< Queue control. */ \ const size_t Size; /**< Queue size (number of elements). */ \ type Buffer[size]; /**< Statically allocated element buffer. */ \ } /** * Define statically allocated queue. */ #define QUEUE_DEFINE_STATIC(handle) {.Control = {0}, .Size = ARRAY_SIZE((handle).Buffer)} inline static size_t Queue_Generic_AdvanceIndex(const size_t index, const size_t size, const size_t n) { return ((index < (size - n)) ? index + n : index - (size - n)); } inline static void Queue_Generic_AdvanceHead(Queue_Control_s *const pControl, const size_t size, const size_t n) { pControl->Head = Queue_Generic_AdvanceIndex(pControl->Head, size, n); pControl->TotalPushed += n; } inline static void Queue_Generic_AdvanceTail(Queue_Control_s *const pControl, const size_t size, const size_t n) { pControl->Tail = Queue_Generic_AdvanceIndex(pControl->Tail, size, n); pControl->TotalPopped += n; } inline static size_t Queue_Generic_Count(const Queue_Control_s control) { return (control.TotalPushed - control.TotalPopped); } inline static size_t Queue_Generic_Free(const Queue_Control_s control, const size_t size) { return (size - Queue_Generic_Count(control)); }
{ "domain": "codereview.stackexchange", "id": 44601, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, comparative-review, generics, c-preprocessor", "url": null }
algorithm, c, comparative-review, generics, c-preprocessor inline static bool Queue_Generic_IsFull(const Queue_Control_s control, const size_t size) { return (Queue_Generic_Count(control) == size); } inline static bool Queue_Generic_IsEmpty(const Queue_Control_s control) { return (Queue_Generic_Count(control) == 0); } #define Queue_Count(handle) Queue_Generic_Count((handle).Control) #define Queue_Free(handle) Queue_Generic_Free((handle).Control, (handle).Size) #define Queue_IsFull(handle) Queue_Generic_IsFull((handle).Control, (handle).Size) #define Queue_IsEmpty(handle) Queue_Generic_IsEmpty((handle).Control) #define Queue_Push(handle, element) \ do \ { \ (handle).Buffer[(handle).Control.Head] = (element); \ Queue_Generic_AdvanceHead(&(handle).Control, (handle).Size, 1); \ } while(0) #define Queue_Pop(handle, pElement) \ do \ { \ *(pElement) = (handle).Buffer[(handle).Control.Tail]; \ Queue_Generic_AdvanceTail(&(handle).Control, (handle).Size, 1); \ } while (0) #define Queue_Seek(handle, offset) Queue_Generic_AdvanceTail(&(handle).Control, (handle).Size, offset) #define Queue_Peek(handle, offset) (&(handle).Buffer[Queue_Generic_AdvanceIndex(Queue_Generic_Tail(handle), size, offset)]) #endif /* QUEUE_H_ */ main.c #include <stdio.h> static QUEUE_DECLARE_STATIC(int, 10) gQueue = QUEUE_DEFINE_STATIC(gQueue); static QUEUE_DECLARE_STATIC(float, 3) gQueue2 = QUEUE_DEFINE_STATIC(gQueue2); int main(void) { for (int i = 0; i < 10; i++) { Queue_Push(gQueue, i); }
{ "domain": "codereview.stackexchange", "id": 44601, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, comparative-review, generics, c-preprocessor", "url": null }
algorithm, c, comparative-review, generics, c-preprocessor int main(void) { for (int i = 0; i < 10; i++) { Queue_Push(gQueue, i); } int x; while (!Queue_IsEmpty(gQueue)) { Queue_Pop(gQueue, &x); printf("%d\n", x); } return 0; } Benefits Header is included only once regardless of how many queue instances are used in single source file (conventional C coding practice) More conventional C code compared to #1 approach Pass into function-like macros queue handle directly (no pointers) One single function definition for all types of queues (dont' need Tag) Queue configuration (type, size) is in the declaration of queue so don'te need to #define the configuration and include the header Weaknesses Can result in long macros Debugging macros can be painful Because macros are used instead of functions they sometimes need to rely on do{} while(0) and comma operator constructs which have their drawbacks especially when returning values (which is really easy with functions) Macros are always inlined at place of call so code size can blow up Compiler warnings and errors related to macros can sometimes appear as incoherent and not understandable All possible functions for different instance configuration must be provided by the header even if the specific instance does not use it, which means that multiple functions-like macros (with different names) will have to be provided to achieve some functionality in different ways (adding/taking multiple elements described at start of this post) Cannot have easily accessible user provided functions (like thread lock and unlock from previous example) depending on the configuration
{ "domain": "codereview.stackexchange", "id": 44601, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, comparative-review, generics, c-preprocessor", "url": null }
algorithm, c, comparative-review, generics, c-preprocessor For a mental excercise try to imagine how both of the approaches would implement adding and taking multiple elements from FIFO/Queue using either element-by-element copy or standard memcpy(). FIFO would implement only one set of functions: FIFO_AddMultiple(), FIFO_TakeMultiple() while queue would have to implement two set of functions: Queue_PushMultipleElementWise(), Queue_PushMultipleMemoryWise(), Queue_PopMultipleElementWise(), Queue_PopMultipleMemoryWise(). Which one would you use and why? I am leaning towards #1 but am also afraid that if our code base will use approach #1 heavily then it will not be easy for new employees to grasp and maintain the code. Also, and more importantly, I am not sure how the approach #1 integrates and plays nicely with testing, static analysis and automotive standards. Any improvements, changes or comments to either approach is welcome. Answer: Enable compiler warnings and fix all of them Your first approach compiles, but my compiler shows a lot of warnings, including const-correctness issues and pointers to incorrect types being passed. Usage is more important than the implementation When it comes to libraries and utilities, the primary goal is to make their usage safe, easy and reliable. How it is implemented is of secondary concern. So if I had to choose between the two approaches, I will definitely go with the second one, mainly because it is much less error-prone: there is no chance I can forget a #define or #include "FIFO.h", and I cannot accidentally pass the wrong tag. About the benefits and weaknesses There are several things you mention in your benefits and weaknesses analysis that are incorrect. For example Using functions instead of macros provide type safety You still rely on macros to call those functions. Also, functions are not necessarily more type safe than macros. You can have functions take void pointers and be type unsafe.
{ "domain": "codereview.stackexchange", "id": 44601, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, comparative-review, generics, c-preprocessor", "url": null }
algorithm, c, comparative-review, generics, c-preprocessor Functions not necessary to be inlined at place of call which reduces overall code size Macros are always inlined at place of call so code size can blow up This is wrong. Macros are expanded at the place of call, but that doesn't mean the compiler cannot see that it expands the same code over and over, and decide to un-inline it (this is sometimes called "outlining"). Also, compilers nowadays inline functions heavily, because it makes other optimizations work much better. Debugging is somewhat clumsy because placing breakpoint inside of function will result in breakpoint being placed in one of randomly selected generated function or in all functions (that's my guess) Putting a breakpoint in a macro is not possible. However, there is a clear definition of what a function is, and there is no function overloading in C, so setting a breakpoint for a given function name should be unambiguous. In your first approach, there is no function FIFO_Add() for example, but there will be a function FIFO_MyFIFO_Add() that you can set a breakpoint for. Cannot have easily accessible user provided functions (like thread lock and unlock from previous example) depending on the configuration Why not? You could easily put pointers to those functions in struct Queue_Control, and create a version of QUEUE_DEFINE_STATIC() that takes those function pointers as arguments to store in the control block. Consider using C++ Writing type-safe generic code in C is hard or impossible. However, nowadays there is almost no excuse not to consider to migrate to C++: the compilers are very good, and it is easy to port C to C++. The C++ standard library even comes with a queue type, so you could write this: import std; int main() { std::queue<int> gQueue; for (int i = 0; i < 10; i++) { gQueue.push(i); } while (!gQueue.empty()) { std::print("{}\n", gQueue.front()); gQueue.pop(); } }
{ "domain": "codereview.stackexchange", "id": 44601, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, comparative-review, generics, c-preprocessor", "url": null }
algorithm, c, comparative-review, generics, c-preprocessor There are no macros here, everything is type-safe, and gQueue.front() returns a value, so no need to pass a pointer to a variable. (I've used C++23 here to show off import and std::print(), but the std::queue part has been around since C++98.) std::queue uses a dynamic array under the hood, so you don't specify a size, and it can grow unbounded. You could also implement your own statically-sized queue type as a templated class: template<typename T, std::size_t Size> class Queue { size_t Head = 0; size_t Tail = 0; size_t TotalPushed = 0; size_t TotalPopped = 0; T Buffer[Size]; static std::size_t AdvanceIndex(const std::size_t index, const std::size_t n) { return ((index < (Size - n)) ? index + n : index - (Size - n)); } void AdvanceHead(const std::size_t n = 1) { Head = AdvanceIndex(Head, n); TotalPushed += n; } … public: void Push(const T& element) { Buffer[Head] = element; AdvanceHead(); } … }; Note how all the functions you had in your C version are there, just without any macros and almost no pointers, resulting in much cleaner code. You would use it like so: Queue<int, 10> gQueue; for (int i = 0; i < 10; i++) { gQueue.Push(i); } …
{ "domain": "codereview.stackexchange", "id": 44601, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, comparative-review, generics, c-preprocessor", "url": null }
c#, regex, oauth, json.net Title: Algorithm to compare OAuth2 Rich Authorization Requests Question: Authorization Requests spec defines new authorization_details parameter. The authorization server have to somehow compare this parameter to decide whether client wants less, more or the same access. My way to achieve this is to except two JSON arrays, but I feel my algorithm is not clear and not efficient. My code looks as below: public static Dictionary<string, JObject> ReadAuthorizationDetailsArray(this JArray jArray) { return jArray .Where(p => p is JObject) .ToDictionary(k => ((JObject)k).Property("type")!.Value.ToString(), v => (JObject)v); } public static JArray ExceptAuthorizationDetailArrays(this JArray firstArray, JArray secondArray) { Func<JValue, string> getJsonValueIdentifier = (JValue jValue) => $"{Regex.Replace(jValue.Path, "\\[\\d+\\]", string.Empty)}:{jValue.Value?.ToString()}"; var firstAuthorizationDetails = firstArray.ReadAuthorizationDetailsArray(); var secondAuthorizationDetails = secondArray.ReadAuthorizationDetailsArray(); foreach (var firstAuthorizationDetail in firstAuthorizationDetails) { if (!secondAuthorizationDetails.ContainsKey(firstAuthorizationDetail.Key)) continue; var secondAuthorizationDetailObject = secondAuthorizationDetails[firstAuthorizationDetail.Key]; var firstAuthorizationDetailValuesIdentifiers = firstAuthorizationDetail.Value.Descendants() .Where(p => p is JValue) .ToDictionary(k => getJsonValueIdentifier((JValue)k), v => v); var secondAuthorizationDetailValuesIdentifiers = secondAuthorizationDetailObject.Descendants() .Where(p => p is JValue) .Select(p => getJsonValueIdentifier((JValue)p));
{ "domain": "codereview.stackexchange", "id": 44602, "lm_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#, regex, oauth, json.net", "url": null }
c#, regex, oauth, json.net var exceptedIdentifiers = firstAuthorizationDetailValuesIdentifiers.Keys.Except(secondAuthorizationDetailValuesIdentifiers); if (!exceptedIdentifiers.Any()) { firstArray.Remove(firstAuthorizationDetail.Value); continue; } var toRemove = firstAuthorizationDetailValuesIdentifiers.ExceptBy(exceptedIdentifiers, k => k.Key).Where(p => p.Key != $".type:{p.Value}"); foreach (var removable in toRemove.Select(p => p.Value)) { if (removable.Parent is JProperty) removable.Parent.Remove(); else removable.Remove(); } var emptyDescendants = firstAuthorizationDetail.Value.Descendants().Where(p => (p is JObject || p is JArray) && (p is null || !p.Any())).ToList(); foreach (var descendant in emptyDescendants) { if (descendant.Parent is JProperty prop) { if (prop.Value is null || ((prop.Value is JObject || prop.Value is JArray) && !prop.Value.Any())) descendant.Parent.Remove(); } else descendant.Remove(); } } return firstArray; } When firstArray looks as below: var thirtyJson = @"[ { ""type"": ""payment_initiation"", ""actions"": [ ""initiate"", ""status"", ""cancel"" ], ""locations"": [ ""https://example.com/payments"" ], ""instructedAmount"": { ""currency"": ""EUR"", ""amount"": 123.50 }, ""creditorName"": ""Merchant A"", ""creditorAccount"": { ""iban"": ""DE02100100109307118603"" }, ""remittanceInformationUnstructured"": ""Ref Number Merchant"" }, { ""type"": ""account_information"", ""actions"": [ ""list_accounts"", ""read_balances"", ""read_transactions"", ""write_accounts"" ], ""locations"": [ ""https://example.com/accounts"" ] } ]";
{ "domain": "codereview.stackexchange", "id": 44602, "lm_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#, regex, oauth, json.net", "url": null }
c#, regex, oauth, json.net And the secondArray looks like it: var fourtyJson = @"[ { ""type"":""account_information"", ""actions"":[ ""list_accounts"", ""read_balances"", ""read_transactions"" ], ""locations"":[ ""https://example.com/accounts"" ] } ]"; The valid result is: [ { "type": "payment_initiation", "actions": [ "initiate", "status", "cancel" ], "locations": [ "https://example.com/payments" ], "instructedAmount": { "currency": "EUR", "amount": 123.5 }, "creditorName": "Merchant A", "creditorAccount": { "iban": "DE02100100109307118603" }, "remittanceInformationUnstructured": "Ref Number Merchant" }, { "type": "account_information", "actions": [ "write_accounts" ] } ] We can describe this operation like: result = firstArray - secondArray. So result is JSON that contains all firstArray items that are not contained in secondArray. What's more, type property is never removed (unless compared objects with the same type are the equals. Then we remove the entire object from firstArray.) The regex, getting JSON descendants many times, and these nested loops... I feel it's as bad as possible. What shall I refactor in above code to make it very efficient and more readable? Answer: The naming of the parameters in the original implementation is not very descriptive and should be clarified, I think it's requested and actual scopes? I would suggest you perform a recursive comparison of the JSON tokens unless the object tree is very deep: public static class AuthorizationDetailsUtil { public static JArray ScopeDifferences(JArray requested, JArray actual) { var actualTypeMap = CreateTypeMap(actual); var result = new JArray();
{ "domain": "codereview.stackexchange", "id": 44602, "lm_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#, regex, oauth, json.net", "url": null }
c#, regex, oauth, json.net foreach (var requestType in requested.Values<JObject>()) { var type = (string)requestType.Property("type"); if (actualTypeMap.TryGetValue(type, out var actualType)) { var diff = Differences(requestType, actualType); if (diff != null) { diff.AddFirst(new JProperty("type", type)); result.Add(diff); } } else { result.Add(requestType); } } return result; } private static readonly StringComparer PropertyNameComparer = StringComparer.OrdinalIgnoreCase; private static Dictionary<string, JObject> CreateTypeMap(JArray array) { return array.Values<JObject>().ToDictionary(d => (string)d.Property("type"), PropertyNameComparer); } private static JToken Differences(JToken requested, JToken actual) { var diff = (requested, actual) switch { (JObject r, JObject a) => Differences(r, a), (JArray r, JArray a) => Differences(r, a), (JValue r, JValue a) => Differences(r, a), (JToken r, null) => r, (null, JToken a) => a, (null, null) => null, (_, _) => throw new InvalidDataException("Types do not match"), }; return diff; }
{ "domain": "codereview.stackexchange", "id": 44602, "lm_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#, regex, oauth, json.net", "url": null }
c#, regex, oauth, json.net return diff; } private static JObject Differences(JObject requested, JObject actual) { var actualPropertiesMap = actual.Properties().ToDictionary(p => p.Name, PropertyNameComparer); JObject result = null; foreach (var requestedProperty in requested.Properties()) { if (actualPropertiesMap.Remove(requestedProperty.Name, out var actualProperty)) { var diff = Differences(requestedProperty.Value, actualProperty.Value); if (diff != null) { if (result == null) { result = new JObject(); } result.Add(requestedProperty.Name, diff); } } else { result.Add(requestedProperty.Name, requestedProperty.Value); } } return result; } private static JValue Differences(JValue requested, JValue actual) { if (object.Equals(requested.Value, actual.Value)) { return null; } return requested; } private static JArray Differences(JArray requested, JArray actual) { //This only works for JArrays of JValues not JObjects. var diff = requested.Except(actual).ToList(); if (diff.Count > 0) { return new JArray(diff); } return null; } }
{ "domain": "codereview.stackexchange", "id": 44602, "lm_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#, regex, oauth, json.net", "url": null }
c#, regex, oauth, json.net This makes it simpler to tweak how tokens are compared. var requestedDetails = JArray.Parse(@"[ { ""type"": ""payment_initiation"", ""actions"": [ ""initiate"", ""status"", ""cancel"" ], ""locations"": [ ""https://example.com/payments"" ], ""instructedAmount"": { ""currency"": ""EUR"", ""amount"": 123.50 }, ""creditorName"": ""Merchant A"", ""creditorAccount"": { ""iban"": ""DE02100100109307118603"" }, ""remittanceInformationUnstructured"": ""Ref Number Merchant"" }, { ""type"": ""account_information"", ""actions"": [ ""list_accounts"", ""read_balances"", ""read_transactions"", ""write_accounts"" ], ""locations"": [ ""https://example.com/accounts"" ] } ]"); var actualDetails = JArray.Parse(@"[ { ""type"":""account_information"", ""actions"":[ ""list_accounts"", ""read_balances"", ""read_transactions"" ], ""locations"":[ ""https://example.com/accounts"" ] } ]"); var expected = JArray.Parse(@"[ { ""type"": ""payment_initiation"", ""actions"": [ ""initiate"", ""status"", ""cancel"" ], ""locations"": [ ""https://example.com/payments"" ], ""instructedAmount"": { ""currency"": ""EUR"", ""amount"": 123.5 }, ""creditorName"": ""Merchant A"", ""creditorAccount"": { ""iban"": ""DE02100100109307118603"" }, ""remittanceInformationUnstructured"": ""Ref Number Merchant"" }, { ""type"": ""account_information"", ""actions"": [ ""write_accounts"" ] } ]"); var diffs = AuthorizationDetailsUtils.ScopeDifferences(requestedDetails, actualDetails); Debug.Assert(expected.ToString().Equals(diffs.ToString(), StringComparison.OrdinalIgnoreCase), "Failed Comparison");
{ "domain": "codereview.stackexchange", "id": 44602, "lm_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#, regex, oauth, json.net", "url": null }
python, python-3.x, error-handling, pandas, decorator-pattern Title: Protecting functions from empty DataFrames Question: Pandas likes to throw cryptic errors when you feed its functions with empty DataFrames saying nothing that would help you to identify the root cause. In order to avoid this I used to write conditions like this one all over the place: def normalize_null(data: pd.DataFrame) -> pd.DataFrame: """Replaces pd.NaT garbage with None.""" if data.empty: return pd.DataFrame() return data.replace({pd.NaT: None}) I don't even remember if this particular operation fails on an empty DataFrame, but there are many that do so I just add it to every function just in case. Then I thought why making it so ugly? Make it a decorator! So now I do this: @skip_if_empty(default=pd.DataFrame()) def normalize_null(data: pd.DataFrame) -> pd.DataFrame: """Replaces pd.NaT garbage with None.""" return data.replace({pd.NaT: None}) with this decorator: def skip_if_empty(default: Any | None): def decorate(decoratee): def decorator(*decoratee_args, **decoratee_kwargs): if len(decoratee_args) < 1: raise ValueError("The decorated function must have at least one argument.") if type(decoratee_args[0]) is not pd.DataFrame: raise ValueError("The first argument must be a DataFrame.") return default if decoratee_args[0].empty else decoratee(*decoratee_args, **decoratee_kwargs) decorator.__signature__ = inspect.signature(decoratee) return decorator return decorate Now when I use several such methods that modify a DataFrame in a chain I don't have to worry about anything being empty: data = normalize_null(data) data = do_something_else(data) data = ... Would you say it's ok to use decorators this way or mabe there is something else about it that could be improved?
{ "domain": "codereview.stackexchange", "id": 44603, "lm_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, error-handling, pandas, decorator-pattern", "url": null }
python, python-3.x, error-handling, pandas, decorator-pattern Answer: functools.wraps The triple-nested function confused me for a minute, looking at it as a stranger, particularly as the decorator is not documented. You may want to look into functools.wraps which is a convenience function which does what you want with preserving signature, docs, name, etc. while being a standardised method. Names To me, default doesn't immediately tell me what it's doing, default_return would be more obvious to me. Also, skip_if_empty implies that this function would work for any type, but is explicitly limited by: if type(decoratee_args[0]) is not pd.DataFrame to pd.DataFrames. Perhaps skip_if_empty_df might be more clear. Either that, or you could make this more generically useful by allowing a second argument of permitted type: def skip_if_empty(default: Any | None, allowed_types: tuple = (pd.DataFrame,)): ... if type(decoratee_args[0]) is not in allowed_types Pythonic if len(decoratee_args) < 1 unless len(tuple) is liable to return a negative number what you're actually asking is: if len(decoratee_args) == 0 or more pythonically if not decoratee_args Likewise if type(decoratee_args[0]) is not pd.DataFrame might want to be: if not isinstance(decoratee_args[0], pd.DataFrame) which would allow subclasses of pd.DataFrames to work as well. Error messages As a user, I would (and should) be unaware that any of the functions are in any way decorated, so seeing: raise ValueError("The decorated function must have at least one argument.") Is unhelpful. You might instead want: raise ValueError(f"{decoratee.__name__} must have at least one argument.")
{ "domain": "codereview.stackexchange", "id": 44603, "lm_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, error-handling, pandas, decorator-pattern", "url": null }
python, python-3.x Title: Getting and setting dict items via paths Question: I wanted to have something more convenient to work with nested dictionaries that come from yaml files so I wrote this DictIndexter. Its __getitem__ and __setitem__ accept a path instead of a single key. Additionally the getter can also take a tuple with path and default value. The setter on the other hand is able to create new branches, but only when it's a clean branch. This is a branch assigned to a non-existing key. It wont overwrite another value. Implementation class DictIndexer: def __init__(self, source: Dict[str, Any], set_creates_branches: bool = True): self.source = source self.set_creates_branches = set_creates_branches def __getitem__(self, path: str | Tuple[str, Any]) -> Any | None: path, default = path if isinstance(path, tuple) else (path, None) item = self.source for key in DictIndexer._split(path): item = item.get(key, None) if item is None: return default else: return item def __setitem__(self, path: str, value: Any): class Missing: pass names = DictIndexer._split(path) prev = self.source item = self.source for key in names[:-1]: item = item.get(key, Missing()) match item: case dict(): prev = item case Missing(): if self.set_creates_branches: prev[key] = {} else: raise KeyError(f"Cannot create branch '{key}. Disabled") case _: raise KeyError(f"Cannot overwrite '{key}.") else: item[names[-1]] = value @staticmethod def _split(path: str) -> List[str]: return re.split(r"[/\\]", path) Tests With pytest I made sure that the following features work:
{ "domain": "codereview.stackexchange", "id": 44604, "lm_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 Tests With pytest I made sure that the following features work: def test_can_get_item_by_path(): data = { "foo": { "bar": "baz" } } assert DictIndexer(data)["foo/bar"] == "baz" def test_gets_null_when_last_name_does_not_exist(): data = { "foo": { "bar": "baz" } } assert DictIndexer(data)["foo/baz"] is None def test_gets_null_or_default_when_middle_name_does_not_exist(): data = { "foo": { "bar": { "baz": "baz" } } } assert DictIndexer(data)["foo/baz/baz"] is None assert DictIndexer(data)[("foo/baz/baz", "qux")] == "qux" def test_can_set_item(): data = { "foo": { "bar": { "baz": "baz" } } } DictIndexer(data)["foo/bar/baz"] = "qux" assert DictIndexer(data)["foo/bar/baz"] == "qux" def test_can_set_item_on_new_branches(): data = { "foo": { "bar": { "baz": { "foo": "bar" } } } } DictIndexer(data)["foo/bar/baz/qux"] = "qux" assert DictIndexer(data)["foo/bar/baz/qux"] == "qux" def test_does_not_create_new_branches_when_disabled(): data = { "foo": { "bar": { } } } with pytest.raises(KeyError): DictIndexer(data, set_creates_branches=False)["foo/bar/baz/qux"] = "qux" def test_does_not_overwrite_value_with_dict(): data = { "foo": { "bar": { "baz": "baz" } } } with pytest.raises(KeyError): DictIndexer(data)["foo/bar/baz/qux"] = "qux"
{ "domain": "codereview.stackexchange", "id": 44604, "lm_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 with pytest.raises(KeyError): DictIndexer(data)["foo/bar/baz/qux"] = "qux" Example I currently use it to customize the logger cofiguration: def _initialize_logging(): import logging.config config = DictIndexer(assets.cfg("wiretap")) config["formatters/auto/()"] = wiretap.MultiFormatter config["formatters/auto/./values"] = [f"v{app.VERSION}-{os.environ['mode'][0]}"] config["handlers/file/filename"] = assets.home("log", f"{app.ID}.log") config["handlers/sqlserver/insert"] = assets.sql("wiretap", "insert log.sql") logging.config.dictConfig(config.source) Why do you think? What would you improve? Answer: Overview The code looks good, properly typed, tested. This is a great starting point. Here are various details can could be improved. Documentation Your code could definitely be improved with docstrings. Imports This is more about the StackExchange question than about the code itself but providing the imports can make testing/reviewing easier for others. from typing import Dict, Any, Tuple, List import re Tests: splitting the setup from the logic being tested This is mostly a matter of personal preference but I find a line such as assert DictIndexer(data)[("foo/baz/baz", "qux")] == "qux" a bit hard to grasp. The test cases can probably be made easier to read if the DictIndexer was created as an initial step and then used to perform queries. We'd get something like: def test_gets_null_or_default_when_middle_name_does_not_exist(): data = DictIndexer({ "foo": { "bar": { "baz": "baz" } } }) assert data["foo/baz/baz"] is None assert data[("foo/baz/baz", "qux")] == "qux"
{ "domain": "codereview.stackexchange", "id": 44604, "lm_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 assert data["foo/baz/baz"] is None assert data[("foo/baz/baz", "qux")] == "qux" This is even more relevant when with pytest.raises(KeyError) is used as you definitely do not want the constructor of DictIndexer to be the part raising the error. Splitting Your method to split relies on regexp. It seems slightly overkill in this particular case as you are using a single character for splitting and str.split would do the trick. Also, you could make your code slightly more generic by providing the separator in the constructor. def __init__(self, source: Dict[str, Any], set_creates_branches: bool = True, separator='/'): self.source = source self.set_creates_branches = set_creates_branches self.separator = separator (...) def _split(self, path: str) -> List[str]: return path.split(self.separator) Getting elements with default value I find the way the default value can be provided to __getitem__ slightly awkward. My preference would be to rely on how things are done for dict: d[key]: Return the item of d with key key. Raises a KeyError if key is not in the map. get(key[, default]): Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. def get(self, path, default=None): try: return self[path] except KeyError: return default def __getitem__(self, path: str) -> Any | None: item = self.source for key in self._split(path): item = item.get(key, None) if item is None: raise KeyError(f"Key '{key} not found.") else: return item
{ "domain": "codereview.stackexchange", "id": 44604, "lm_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 else for for loop The optional else for for loops is a nice idiom which deserves some love and can be used to perform an operation in the case where break did not occur in the loop and the loops stops in a "normal" way. In our particular case, there is no break involved at all so I'm not so sure that it is relevant. Tuple unpacking using asterisks Instead of messing with indices with names in __setitem__, you could directly unpack it into the parts you are interested in: *names, last_name = self._split(path). Final code At this stage, the code looks like this: from typing import Dict, Any, Tuple, List class DictIndexer: def __init__(self, source: Dict[str, Any], set_creates_branches: bool = True, separator='/'): self.source = source self.set_creates_branches = set_creates_branches self.separator = separator def get(self, path, default=None): try: return self[path] except KeyError: return default def __getitem__(self, path: str) -> Any | None: item = self.source for key in self._split(path): item = item.get(key, None) if item is None: raise KeyError(f"Key '{key} not found.") return item def __setitem__(self, path: str, value: Any): class Missing: pass *names, last_name = self._split(path) prev = self.source item = self.source for key in names: item = item.get(key, Missing()) match item: case dict(): prev = item case Missing(): if self.set_creates_branches: prev[key] = {} else: raise KeyError(f"Cannot create branch '{key}. Disabled") case _: raise KeyError(f"Cannot overwrite '{key}.") item[last_name] = value
{ "domain": "codereview.stackexchange", "id": 44604, "lm_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 _split(self, path: str) -> List[str]: return path.split(self.separator) def test_can_get_item_by_path(): data = DictIndexer({ "foo": { "bar": "baz" } }) assert data["foo/bar"] == "baz" def test_gets_null_when_last_name_does_not_exist(): data = DictIndexer({ "foo": { "bar": "baz" } }) try: data["foo/baz"] except KeyError: pass assert data.get("foo/baz") is None def test_gets_null_or_default_when_middle_name_does_not_exist(): data = DictIndexer({ "foo": { "bar": { "baz": "baz" } } }) try: data["foo/baz/baz"] except KeyError: pass assert data.get("foo/baz/baz", "qux") == "qux" def test_can_set_item(): data = DictIndexer({ "foo": { "bar": { "baz": "baz" } } }) assert data["foo/bar/baz"] != "qux" data["foo/bar/baz"] = "qux" assert data["foo/bar/baz"] == "qux" def test_can_set_item_on_new_branches(): data = DictIndexer({ "foo": { "bar": { "baz": { "foo": "bar" } } } }) data["foo/bar/baz/qux"] = "qux" assert data["foo/bar/baz/qux"] == "qux" def test_does_not_create_new_branches_when_disabled(): data = DictIndexer({ "foo": { "bar": { } } }, set_creates_branches=False) try: data["foo/bar/baz/qux"] = "qux" except KeyError: pass def test_does_not_overwrite_value_with_dict(): data = DictIndexer({ "foo": { "bar": { "baz": "baz" } } }) try: data["foo/bar/baz/qux"] = "qux" except KeyError: pass
{ "domain": "codereview.stackexchange", "id": 44604, "lm_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 try: data["foo/bar/baz/qux"] = "qux" except KeyError: pass Edit Something that I had forgotten: now that __getitem__ throws, one could directly use: def __getitem__(self, path: str) -> Any | None: item = self.source for key in self._split(path): item = item[key] return item Similarly, we could imagine getting rid of the Missing class and work with exceptions directly: def __setitem__(self, path: str, value: Any): *names, last_name = self._split(path) prev = self.source item = self.source for key in names: try: item = item[key] except KeyError: if self.set_creates_branches: prev[key] = {} continue else: raise KeyError(f"Cannot create branch '{key}. Disabled") match item: case dict(): prev = item case _: raise KeyError(f"Cannot overwrite '{key}.") item[last_name] = value
{ "domain": "codereview.stackexchange", "id": 44604, "lm_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, error-handling, logging, decorator-pattern Title: Cancelling function execution with a ContinuationError Question: Although throwing excptions for control flow is a controversial topic there are some quite popular examples of using this anti-pattern like C#'s async routines throwing the OperationCanceledException to cancel a task or python throwing the StopIteration to control iterators. I thought I'll try to use such an exception with my logger decorator package (GitHub). I call it ContinuationError. In general the decorator handles logging of such states as started before entering a function completed when a function successfully executed canceled when a function exited prematurely faulted when something unexpected occured The exception supports the canceled state by replacing spammy logging with an error: Before: logger.canceled(reason="No luck!") return 5 After: raise ContinuationError("No luck!", 5) It expects a reason for why the cancellation was necessary, optionally a return value if the function is expected to return something and also optionally other arguments that are later rendered into a json-message. class ContinuationError(Exception): """Raise this error to gracefully handle a function cancellation.""" def __new__(cls, *args, **details) -> Any: instance = super().__new__(cls) instance.details = details | dict(reason=args[0]) if len(args) > 1: instance.result = args[1] return instance def __init__(self, message: str, result: Optional[Any] = None, **details): super().__init__(message) The decorator takes care of handling it by checking whether a result was provided and returns it if necessary. The decorator also provides a lambda for creating started details or another lambda for logging the result. def telemetry(on_started: Optional[OnStarted] = None, on_completed: Optional[OnCompleted] = None, **kwargs): """Provides flow telemetry for the decorated function."""
{ "domain": "codereview.stackexchange", "id": 44605, "lm_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, error-handling, logging, decorator-pattern", "url": null }
python, python-3.x, error-handling, logging, decorator-pattern on_started = on_started or (lambda _: {}) on_completed = on_completed or (lambda _: {}) def factory(decoratee): @contextlib.contextmanager def logger_scope() -> Logger: logger = Logger( module=inspect.getmodule(decoratee).__name__, scope=decoratee.__name__, attachment=kwargs.pop("attachment", None), parent=_scope.get() ) token = _scope.set(logger) try: yield logger except Exception: logger.faulted() raise finally: _scope.reset(token) def inject_logger(logger: Logger, d: Dict): """ Injects Logger if required. """ for n, t in inspect.getfullargspec(decoratee).annotations.items(): if t is Logger: d[n] = logger def params(*decoratee_args, **decoratee_kwargs) -> Dict[str, Any]: # Zip arg names and their indexes up to the number of args of the decoratee_args. arg_pairs = zip(inspect.getfullargspec(decoratee).args, range(len(decoratee_args))) # Turn arg_pairs into a dictionary and combine it with decoratee_kwargs. return {t[0]: decoratee_args[t[1]] for t in arg_pairs} | decoratee_kwargs
{ "domain": "codereview.stackexchange", "id": 44605, "lm_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, error-handling, logging, decorator-pattern", "url": null }
python, python-3.x, error-handling, logging, decorator-pattern if asyncio.iscoroutinefunction(decoratee): @functools.wraps(decoratee) async def decorator(*decoratee_args, **decoratee_kwargs): with logger_scope() as scope: inject_logger(scope, decoratee_kwargs) scope.started(**on_started(params(*decoratee_args, **decoratee_kwargs))) try: result = await decoratee(*decoratee_args, **decoratee_kwargs) scope.completed(**on_completed(result)) return result except ContinuationError as e: if hasattr(e, "result"): scope.canceled(**(on_completed(e.result) | e.details)) return e.result else: scope.canceled(**e.details) else: @functools.wraps(decoratee) def decorator(*decoratee_args, **decoratee_kwargs): with logger_scope() as scope: inject_logger(scope, decoratee_kwargs) scope.started(**on_started(params(*decoratee_args, **decoratee_kwargs))) try: result = decoratee(*decoratee_args, **decoratee_kwargs) scope.completed(**on_completed(result)) return result except ContinuationError as e: if hasattr(e, "result"): scope.canceled(**(on_completed(e.result) | e.details)) return e.result else: scope.canceled(**e.details) decorator.__signature__ = inspect.signature(decoratee) return decorator return factory
{ "domain": "codereview.stackexchange", "id": 44605, "lm_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, error-handling, logging, decorator-pattern", "url": null }
python, python-3.x, error-handling, logging, decorator-pattern return factory Later one of the logging APIs checks for the exception and decides whether to log a normal message or an actual error: def _log(self, **kwargs): status = inspect.stack()[1][3] details = Logger.serialize_details(**kwargs) with _create_log_record( functools.partial(_set_module_name, name=self.module), functools.partial(_set_func_name, name=self.scope) ): # Ignore the ContinuationError as an actual error. is_error = all(sys.exc_info()) and sys.exc_info()[0] is not ContinuationError self._logger.log(level=self._logger.level, msg=None, exc_info=is_error, extra={ "parent": self.parent.id if self.parent else None, "node": self.id, "status": status, "elapsed": self.elapsed, "details": details, "attachment": self.attachment }) Internally the package is using python's standard logging library. Example I use it like this: import wiretap.src.wiretap as wiretap # becasue it's from the test environment @wiretap.telemetry(on_started=lambda p: {"value": p["value"], "bar": p["bar"]}, on_completed=lambda r: {"count": r}) def foo(value: int, logger: wiretap.Logger = None, **kwargs) -> int: logger.running(test=f"{value}") raise wiretap.ContinuationError("No luck!", 0, foo="bar") return 3 if __name__ == "__main__": print(foo(1, bar="baz")) # <-- prints: 0 What do you think of this idea? I guess I probably should check if the decorated function is expected to return something and throw an invalid operation exception when a return value wasn't provided. Answer: Your decorator has almost no type hints. You can use ParamSpec to hint your code. Here's an example typed closure wrapper decorator: import functools from typing import Callable, ParamSpec, TypeVar P = ParamSpec("P") TRet = TypeVar("TRet")
{ "domain": "codereview.stackexchange", "id": 44605, "lm_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, error-handling, logging, decorator-pattern", "url": null }
python, python-3.x, error-handling, logging, decorator-pattern P = ParamSpec("P") TRet = TypeVar("TRet") def typed_decorator() -> Callable[[Callable[P, TRet]], Callable[P, TRet]]: def wrapper(fn: Callable[P, TRet]) -> Callable[P, TRet]: @functools.wraps(fn) def inner(*args: P.args, **kwargs: P.kwargs) -> TRet: return fn(*args, **kwargs) return inner return wrapper def untyped_decorator(): def wrapper(fn): @functools.wraps(fn) def inner(*args, **kwargs): return fn(*args, **kwargs) return inner return wrapper @typed_decorator() def foo(bar: str) -> int: return 1 @untyped_decorator() def bar(bar: str) -> int: return 1 reveal_type(foo) reveal_type(bar) $ mypy --strict foo.py foo.py:36: note: Revealed type is "def (bar: builtins.str) -> builtins.int" foo.py:37: note: Revealed type is "Any" As you can see, we basically can just say the parameters are P and the return type is just TRet. Next lets get the DI working. I'll be copying and modifying your inject_logger code. Since I'm focusing on type hints at the moment I'm going to have to ask you to ignore the contents of the function. The function does the same thing yours does, DI the logger. I'm going to change foo to take Logger as an argument, with a default. We need to provide a default for the type hints to work as intended. Otherwise you'll attempt to call the function without a logger and get an error. The logger has some nonsense code just to make determining which logger we're interacting with easier to reason with. import functools import inspect from typing import TYPE_CHECKING, Any, Callable, ParamSpec, TypeVar P = ParamSpec("P") TRet = TypeVar("TRet") TArgs = TypeVar("TArgs", bound=tuple) # type: ignore TKwargs = TypeVar("TKwargs", bound=dict) # type: ignore class Logger: ID = 0 id: int def __init__(self) -> None: self.id = self.ID type(self).ID += 1 def __repr__(self) -> str: return f"<{type(self).__name__} {self.id}>"
{ "domain": "codereview.stackexchange", "id": 44605, "lm_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, error-handling, logging, decorator-pattern", "url": null }
python, python-3.x, error-handling, logging, decorator-pattern def __repr__(self) -> str: return f"<{type(self).__name__} {self.id}>" def inject_logger( fn: Callable[..., Any], logger: Logger, args: TArgs, kwargs: TKwargs, ) -> tuple[TArgs, TKwargs]: """ Injects Logger if required.""" sig = inspect.signature(fn) bound = sig.bind_partial(*args, **kwargs) for param in sig.parameters.values(): if issubclass(Logger, param.annotation): bound.arguments.setdefault(param.name, logger) bound.apply_defaults() return bound.args, bound.kwargs # type: ignore def typed_decorator() -> Callable[[Callable[P, TRet]], Callable[P, TRet]]: def wrapper(fn: Callable[P, TRet]) -> Callable[P, TRet]: @functools.wraps(fn) def inner(*args: P.args, **kwargs: P.kwargs) -> TRet: args, kwargs = inject_logger(fn, Logger(), args, kwargs) print(args, kwargs) return fn(*args, **kwargs) inner.__signature__ = fn.__signature__ = inspect.signature(fn) # type: ignore return inner return wrapper @typed_decorator() def foo(bar: str, logger: Logger = Logger(), /) -> int: return 1 if TYPE_CHECKING: reveal_type(foo) if __name__ == "__main__": foo("test") $ python foo.py ('test', <Logger 1>) {} $ mypy --strict foo.py foo.py:58: note: Revealed type is "def (builtins.str, foo.Logger =) -> builtins.int" We can avoid the need specify a default value by using Concatenate. The limitation with Concatenate is the syntax only works with arguments on the left side of the function. def typed_decorator() -> Callable[[Callable[Concatenate[Logger, P], TRet]], Callable[P, TRet]]: def wrapper(fn: Callable[Concatenate[Logger, P], TRet]) -> Callable[P, TRet]: @functools.wraps(fn) def inner(*args: P.args, **kwargs: P.kwargs) -> TRet: return fn(Logger(), *args, **kwargs)
{ "domain": "codereview.stackexchange", "id": 44605, "lm_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, error-handling, logging, decorator-pattern", "url": null }
python, python-3.x, error-handling, logging, decorator-pattern fn.__signature__ = sig = inspect.signature(fn) # type: ignore params = iter(sig.parameters.values()) next(params, None) inner.__signature__ = inspect.Signature(list(params), return_annotation=sig.return_annotation) # type: ignore return inner return wrapper @typed_decorator() def foo(logger: Logger, bar: str) -> int: return 1 if TYPE_CHECKING: reveal_type(foo) $ mypy --strict foo.py foo.py:56: note: Revealed type is "def (bar: builtins.str) -> builtins.int" We can support both of the options by using a Protocol with overload. As you can possibly see from the increased # type: ignore comments the approach is somewhat janky internally. def inject_logger( fn: Callable[..., Any], logger: Logger, args: TArgs, kwargs: TKwargs, ) -> tuple[TArgs, TKwargs]: """ Injects Logger if required.""" sig = inspect.signature(fn) if ((param := next(iter(sig.parameters.values()), None)) is not None and issubclass(param.annotation, Logger) ): args = (logger,) + args # type: ignore bound = sig.bind_partial(*args, **kwargs) for param in sig.parameters.values(): if issubclass(param.annotation, Logger): bound.arguments.setdefault(param.name, logger) bound.apply_defaults() return bound.args, bound.kwargs # type: ignore class PTypedDecorator(Protocol): @overload def __call__(self, /, fn: Callable[Concatenate[Logger, P], TRet]) -> Callable[P, TRet]: ... @overload def __call__(self, /, fn: Callable[P, TRet]) -> Callable[P, TRet]: ... def typed_decorator() -> PTypedDecorator: def wrapper(fn: Callable[Concatenate[Logger, P], TRet] | Callable[P, TRet]) -> Callable[P, TRet]: @functools.wraps(fn) def inner(*args: P.args, **kwargs: P.kwargs) -> TRet: args, kwargs = inject_logger(fn, Logger(), args, kwargs) print(args, kwargs) return fn(*args, **kwargs)
{ "domain": "codereview.stackexchange", "id": 44605, "lm_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, error-handling, logging, decorator-pattern", "url": null }
python, python-3.x, error-handling, logging, decorator-pattern fn.__signature__ = sig = inspect.signature(fn) # type: ignore params = iter(sig.parameters.values()) if ((param := next(params, None)) is not None and issubclass(param.annotation, Logger) ): sig = inspect.Signature(list(params), return_annotation=sig.return_annotation) inner.__signature__ = sig # type: ignore return inner return wrapper @typed_decorator() def foo(logger: Logger, bar: str, /) -> int: return 1 @typed_decorator() def bar(bar: str, *, logger: Logger = Logger()) -> int: return 1 if TYPE_CHECKING: reveal_type(foo) reveal_type(bar) if __name__ == "__main__": print(inspect.signature(foo)) foo("test") print(inspect.signature(bar)) bar("test") $ python foo.py (bar: str, /) -> int (<Logger 1>, 'test') {} (bar: str, *, logger: __main__.Logger = <Logger 0>) -> int ('test',) {'logger': <Logger 2>} $ mypy --strict foo.py foo.py:73: note: Revealed type is "def (bar: builtins.str) -> builtins.int" foo.py:74: note: Revealed type is "def (bar: builtins.str, *, logger: foo.Logger =) -> builtins.int" Review Your existing code doesn't really support type hints. @wiretap.telemetry(on_started=lambda p: {"value": p["value"], "bar": p["bar"]}, on_completed=lambda r: {"count": r}) def foo(value: int, logger: wiretap.Logger = None, **kwargs) -> int: The only reason logger: wiretap.Logger = None would type correctly is if you're not running your static analysis tool in strict mode. By default mypy runs in non-strict mode. The mode is useful for showing glaring typing issues, like passing int to a function for str. The benefit is by hiding some more pedantic static analysis tools users with large Python code bases can ease into static Python. You have a lot of functions in your factory closure which could just be global, look at my inject_logger.
{ "domain": "codereview.stackexchange", "id": 44605, "lm_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, error-handling, logging, decorator-pattern", "url": null }
python, python-3.x, error-handling, logging, decorator-pattern Your current inject_logger cannot support positional only parameters. To add the logger you mutate the kwargs however the logger can be provided before the / to be a positional only argument. Neither on_started or on_completed are properly typed. I can appreciate you may think using * and ** in a lambda can be ugly for on_started. So having an untyped interface may be preferable. >>> (lambda *_, foo, **__: foo)(foo="foo") 'foo' >>> (lambda *_, foo, **__: foo)(bar="foo") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: <lambda>() missing 1 required keyword-only argument: 'foo' If you ignore typing, your code is good. Seems to do the job, doesn't seem to be poorly designed - from what I've seen. As you may be aware in Python using exceptions for control flow is expected. However, I can't really comment on whether using exceptions for control flow is good here. I would need to see real world usage of your library to see if another option would be better. However, your use of exceptions here seem to be a good way to get what you want to achieve with decorators. An alternate would be to return, say, a LogObject which has the exact same interface as ContinuationError.
{ "domain": "codereview.stackexchange", "id": 44605, "lm_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, error-handling, logging, decorator-pattern", "url": null }
c++, functional-programming, monads Title: Monad object in C++ Question: Have I defined a Monad object for C++? Below is a class called var which I created years ago to implement a lambda calculus like interpreter in C++. The class defaults to a value of nothing. If assigned a value, the behavior invoked during runtime is defined by the data type assigned to the value of var. Through polymorphism the correct function is called. Within the function other instances of var can be cast to the desired data type. Resulting in a null pointer if cast to the incorrect type. After reading up on Monads, it looks like the var class defined the behavior associated with Monads. Also, I am very interested in any feedback on how to improve the class. Some aras of concern: Returning a double to manage partial ordering from the comp method. Returning typeid(self).name(); as the default behavior. Should default behaviour be invoked for classes that do not overwrite var friend functions. Is there any way to break up the implimentation from the header? Every time I try, there are always link issues were the associated type's function is missing. Thank you in advance for any help offered! Note: the entire code base is too big to be included here in its entirty; a repo, is here. Class var was renamed from class let in another incarnation, so as to be more meaningful in C++ code context. While it is a WIP, the entire class is below, to ensure the context of this question doesn't change over time. namespace Olly { class var { struct interface_type; public: var(); template <typename T> var(T x); friend std::ostream& operator<<(std::ostream& stream, var n); template <typename T> std::shared_ptr<const T> cast() const; // Cast the object as an instance of the specified type. template <typename T> T copy() const; // Get a copy of the objects as a specified type.
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads Text type() const; // The class generated type name. Text cat() const; // The class generated category name. bool is() const; // Is or is not the object defined. void str(Text_Stream& out) const; // String representation of the object. void repr(Text_Stream& out) const; // Recreatable text representation of an object. operator bool() const; double comp(var n) const; // Compare two objects. 0 = equality, > 0 = grater than, < 0 = less than, NAN = not same type. bool eq(var n) const; // Equal to. bool ne(var n) const; // Not equal to. bool ge(var n) const; // Greater than equal to. bool le(var n) const; // Less than equal to. bool gt(var n) const; // Greater than. bool lt(var n) const; // Less than. bool operator==(var n) const; bool operator!=(var n) const; bool operator>=(var n) const; bool operator> (var n) const; bool operator<=(var n) const; bool operator< (var n) const; var b_and(var n) const; // Binary and. var b_or(var n) const; // Binary or. var b_xor(var n) const; // Binary exclusive or. var b_neg() const; // Binary negation.
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads var operator&(var n) const; var operator|(var n) const; var operator^(var n) const; var operator~() const; var u_add() const; // Addition identity. var u_neg() const; // Unary compliment. var add(var n) const; // Addition. var sub(var n) const; // Subtraction. var mul(var n) const; // Multiplication. var div(var n) const; // Division. var mod(var n) const; // Modulus. var operator+() const; var operator-() const; var operator+(var n) const; var operator-(var n) const; var operator*(var n) const; var operator/(var n) const; var operator%(var n) const; var f_div(var n) const; // Floor divide. var rem(var n) const; // Remainder. var pow(var n) const; // Raise to the power of. var root(var n) const; // Reduce to the root of.
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads bool has(var n) const; // Determine if an object has an element. std::size_t size() const; // Size of an object. var front() const; // Lead element of an object. var back() const; // Last element of an object. var place(var n) const; // Place an object as the front element. var push(var n) const; // Place an object as the front element. var next() const; // Remove the front element from an object. var prev() const; // Remove the front element from an object. var operator>>(std::size_t shift) const; var operator<<(std::size_t shift) const; var get(var key) const; // Get an element from a collection. var set(var key, var val) const; // Set the value of an element in a collection. var del(var key) const; // Delete an element from a collection. var reverse() const; // Reverse the order of an object's elements. std::size_t hash() const; // Get the hash of an object. OP_CODE op_code() const; bool is_nothing() const; bool is_something() const; Text help() const; // Define a string description of the object. // TODO: add capture of arguments to pass to a function. // TODO: figure out how to incorporate expression iteration. private: struct interface_type {
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads private: struct interface_type { /********************************************************************************************/ // // 'interface_type' Class Definition // // A simple interface description allowing redirection of the 'var' data type. // /********************************************************************************************/ virtual ~interface_type() {}; virtual operator bool() const = 0; virtual Text _type() const = 0; virtual Text _cat() const = 0; virtual bool _is() const = 0; virtual void _str(Text_Stream& out) const = 0; virtual void _repr(Text_Stream& out) const = 0; virtual double _comp(var n) const = 0; virtual var _b_and(var n) const = 0; virtual var _b_or(var n) const = 0; virtual var _b_xor(var n) const = 0; virtual var _b_neg() const = 0; virtual var _u_add() const = 0; virtual var _u_neg() const = 0; virtual var _add(var n) const = 0; virtual var _sub(var n) const = 0; virtual var _mul(var n) const = 0; virtual var _div(var n) const = 0; virtual var _mod(var n) const = 0;
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads virtual var _f_div(var n) const = 0; virtual var _rem(var n) const = 0; virtual var _pow(var n) const = 0; virtual var _root(var n) const = 0; virtual bool _has(var n) const = 0; virtual std::size_t _size() const = 0; virtual var _front() const = 0; virtual var _back() const = 0; virtual var _place(var n) const = 0; virtual var _push(var n) const = 0; virtual var _next() const = 0; virtual var _prev() const = 0; virtual var _reverse() const = 0; virtual var _get(var key) const = 0; virtual var _set(var key, var val) const = 0; virtual var _del(var key) const = 0; virtual std::size_t _hash() const = 0; virtual Text _help() const = 0; virtual bool _is_nothing() const = 0; virtual OP_CODE _op_code() const = 0; }; template <typename T> struct data_type : interface_type {
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads template <typename T> struct data_type : interface_type { /******************************************************************************************/ // // 'data_type' Class Definition // // The interface implementation of the 'interface_type' data type. // Defining a shared const pointer of the data type passed to it. // /******************************************************************************************/ data_type(T val); virtual ~data_type(); operator bool() const; Text _type() const; Text _cat() const; bool _is() const; void _str(Text_Stream& out) const; void _repr(Text_Stream& out) const; double _comp(var n) const; var _b_and(var n) const; var _b_or(var n) const; var _b_xor(var n) const; var _b_neg() const; var _u_add() const; var _u_neg() const; var _add(var n) const; var _sub(var n) const; var _mul(var n) const; var _div(var n) const; var _mod(var n) const; var _f_div(var n) const; var _rem(var n) const; var _pow(var n) const; var _root(var n) const;
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads bool _has(var n) const; std::size_t _size() const; var _front() const; var _back() const; var _place(var n) const; var _push(var n) const; var _next() const; var _prev() const; var _get(var key) const; var _set(var key, var val) const; var _del(var key) const; var _reverse() const; std::size_t _hash() const; Text _help() const; bool _is_nothing() const; OP_CODE _op_code() const; T _data; }; std::shared_ptr<const interface_type> _ptr; }; /********************************************************************************************/ // // 'nothing' Class Definition // // A basic class definition of the value of nothing. This is used within // 'var' class implementation to return a result of nothing for results // which have either conflicting types, or in some cases as the default to // return unless overridden. // // This class also demonstrates the basic function methods that should be // over written for proper object behavior. // /********************************************************************************************/ class nothing { public:
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads class nothing { public: friend Text _type_(const nothing& self); friend bool _is_(const nothing& self); friend double _comp_(const nothing& self, var n); friend void _str_(Text_Stream& out, const nothing& self); friend void _repr_(Text_Stream& out, const nothing& self); friend bool _is_nothing_(const nothing& self); }; /********************************************************************************************/ // // Support Function Declarations // // These definitions add a few useful and some necessary support functions. // /********************************************************************************************/ Text str(var a); // Convert any 'var' to a Text. Text repr(var a); // Convert any 'var' to a Text representation of the 'var'. var pop_front(var& exp); // Remove and return the front element from an ordered expression. var pop_back(var& exp); // Remove and return the back element from an ordered expression. /********************************************************************************************/ // // 'var' Class Function Default Template API. // // The following function templates define the over-ridable functions which // may be used to tailor the behavior of any object held within a 'var'. // // Each function defined here defines the default behavior of each function // which is invoked if a function is not overwritten for a defined class. // /********************************************************************************************/ template<typename T> /**** Type Name ****/ Text _type_(const T& self);
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads template<typename T> /**** Type Name ****/ Text _type_(const T& self); template<typename T> Text _type_(const T& self) { return typeid(self).name(); } template<typename T> /**** Category Name ****/ Text _cat_(const T& self); template<typename T> Text _cat_(const T& self) { return "uncategorized"; } template<typename T> /**** Boolean Conversion ****/ bool _is_(const T& self); template<typename T> bool _is_(const T& self) { return false; } template<typename T> /**** String Conversion ****/ void _str_(Text_Stream& out, const T& self); template<typename T> void _str_(Text_Stream& out, const T& self) { // TODO: handle object based on stream availability. // constexpr bool n = is_streamable<std::stringstream, T>::value; //if (n) { // out << self; //} //else { // out << "object<" << &self << "," << _type_(self) << ">"; //} out << "object<" << &self << "," << _type_(self) << ">"; //out << self; } template<typename T> /**** String Representation ****/ void _repr_(Text_Stream& out, const T& self); template<typename T> void _repr_(Text_Stream& out, const T& self) { out << str(nothing()); } template<typename T> /**** Comparison Between Variables ****/ double _comp_(const T& self, var other); template<typename T> double _comp_(const T& self, var other) { return NOT_A_NUMBER; } template<typename T> /**** Logical Conjunction ****/ var _b_and_(const T& self, var other); template<typename T> var _b_and_(const T& self, var other) { return var(); } template<typename T> /**** Logical Inclusive Disjunction ****/ var _b_or_(const T& self, var other);
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads template<typename T> var _b_or_(const T& self, var other) { return var(); } template<typename T> /**** Logical Exclusive Disjunction ****/ var _b_xor_(const T& self, var other); template<typename T> var _b_xor_(const T& self, var other) { return var(); } template<typename T> /**** Negation ****/ var _b_neg_(const T& self); template<typename T> var _b_neg_(const T& self) { return self; } template<typename T> /**** Unary Addition ****/ var _u_add_(const T& self); template<typename T> var _u_add_(const T& self) { return var(); } template<typename T> /**** Unary Compliment ****/ var _u_neg_(const T& self); template<typename T> var _u_neg_(const T& self) { return var(); } template<typename T> /**** Addition or Concatenation ****/ var _add_(const T& self, var other); template<typename T> var _add_(const T& self, var other) { return var(); } template<typename T> /**** Subtraction or Division ****/ var _sub_(const T& self, var other); template<typename T> var _sub_(const T& self, var other) { return var(); } template<typename T> /**** Multiplication ****/ var _mul_(const T& self, var other); template<typename T> var _mul_(const T& self, var other) { return var(); } template<typename T> /**** Division ****/ var _div_(const T& self, var other); template<typename T> var _div_(const T& self, var other) { return var(); } template<typename T> /**** Modulation ****/ var _mod_(const T& self, var other); template<typename T> var _mod_(const T& self, var other) { return var(); }
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads template<typename T> var _mod_(const T& self, var other) { return var(); } template<typename T> /**** Floor Division ****/ var _f_div_(const T& self, var other); template<typename T> var _f_div_(const T& self, var other) { return var(); } template<typename T> /**** Remainder ****/ var _rem_(const T& self, var other); template<typename T> var _rem_(const T& self, var other) { return var(); } template<typename T> /**** Raise to Power of ****/ var _pow_(const T& self, var other); template<typename T> var _pow_(const T& self, var other) { return var(); } template<typename T> /**** Reduce to Power of ****/ var _root_(const T& self, var other); template<typename T> var _root_(const T& self, var other) { return var(); } template<typename T> /**** Check if an object has an element ****/ bool _has_(const T& self, var other); template<typename T> bool _has_(const T& self, var other) { return false; } template<typename T> /**** Length Of ****/ std::size_t _size_(const T& self); template<typename T> std::size_t _size_(const T& self) { return 0; } template<typename T> /**** Lead Element Of ****/ var _front_(const T& self); template<typename T> var _front_(const T& self) { return var(); } template<typename T> /**** Lead Element Of ****/ var _back_(const T& self); template<typename T> var _back_(const T& self) { return var(); } template<typename T> /**** Prepend Lead Element Of ****/ var _place_(const T& self, var other); template<typename T> var _place_(const T& self, var other) { return var(); }
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads template<typename T> var _place_(const T& self, var other) { return var(); } template<typename T> /**** Prepend Lead Element Of ****/ var _push_(const T& self, var other); template<typename T> var _push_(const T& self, var other) { return var(); } template<typename T> /**** Drop The Leading Element ****/ var _next_(const T& self); template<typename T> var _next_(const T& self) { return var(); } template<typename T> /**** Drop The Leading Element ****/ var _prev_(const T& self); template<typename T> var _prev_(const T& self) { return var(); } template<typename T> /**** Reverse The Elements Of ****/ var _reverse_(const T& self); template<typename T> var _reverse_(const T& self) { return var(); } template<typename T> /**** Retrieve A Selection From ****/ var _get_(const T& self, var other); template<typename T> var _get_(const T& self, var other) { return var(); } template<typename T> /**** Set A Selection Of ****/ var _set_(const T& self, var other, var val); template<typename T> var _set_(const T& self, var other, var val) { return var(); } template<typename T> /**** Remove A Selection From ****/ var _del_(const T& self, var other); template<typename T> var _del_(const T& self, var other) { return var(); } template<typename T> /**** Hash Value ****/ std::size_t _hash_(const T& self); template<typename T> std::size_t _hash_(const T& self) { return DEFAULT_HASH_FUNCTION(repr(self)); } template<typename T> /**** Return An Operation Code ****/ OP_CODE _op_code_(const T& self); template<typename T> OP_CODE _op_code_(const T& self) { return OP_CODE::nothing_op; }
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads template<typename T> /**** Determine If A Var Is Undefined ****/ bool _is_nothing_(const T& self); template<typename T> bool _is_nothing_(const T& self) { return false; } template<typename T> /**** Return A Help String ****/ Text _help_(const T& self); template<typename T> Text _help_(const T& self) { return "No object documentation available."; } std::ostream& operator<<(std::ostream& stream, var n) { Text_Stream out; out.copyfmt(stream); n.str(out); stream << out.str(); return stream; } /********************************************************************************************/ // // 'nothing' Class Implementation // /********************************************************************************************/ Text _type_(const nothing& self) { return "nothing"; } bool _is_(const nothing& self) { return false; } double _comp_(const nothing& self, var n) { return NOT_A_NUMBER; } void _str_(Text_Stream& out, const nothing& self) { out << "nothing"; } void _repr_(Text_Stream& out, const nothing& self) { out << "nothing"; } bool _is_nothing_(const nothing& self) { return true; } /********************************************************************************************/ // // 'var' Class Implementation // /********************************************************************************************/ var::var() : _ptr(std::make_shared<data_type<nothing>>(nothing())) { } template <typename T> var::var(T x) : _ptr(std::make_shared<data_type<T>>(x)) { } template <typename T> std::shared_ptr<const T> var::cast() const { auto p = std::dynamic_pointer_cast<const data_type<T>>(_ptr);
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads auto p = std::dynamic_pointer_cast<const data_type<T>>(_ptr); if (p == nullptr) { return nullptr; } return std::shared_ptr<const T>(p, &(p->_data)); } template <typename T> T var::copy() const { auto p = std::dynamic_pointer_cast<const data_type<T>>(_ptr); if (p) { return T{ *p }; } return T{}; } Text var::type() const { return _ptr->_type(); } Text var::cat() const { return _ptr->_cat(); } bool var::is() const { return const_cast<interface_type*>(_ptr.get())->_is(); } void var::str(Text_Stream& out) const { _ptr->_str(out); } void var::repr(Text_Stream& out) const { _ptr->_repr(out); } double var::comp(var n) const { return _ptr->_comp(n); } bool var::eq(var n) const { return (comp(n) == 0.0 ? true : false); } bool var::ne(var n) const { return (comp(n) != 0.0 ? true : false); } bool var::ge(var n) const { return (comp(n) >= 0.0 ? true : false); } bool var::le(var n) const { return (comp(n) <= 0.0 ? true : false); } bool var::gt(var n) const { return (comp(n) > 0.0 ? true : false); } bool var::lt(var n) const { return (comp(n) < 0.0 ? true : false); } var var::b_and(var n) const { return _ptr->_b_and(n); } var var::b_or(var n) const { return _ptr->_b_or(n); } var var::b_xor(var n) const { return _ptr->_b_xor(n); } var var::b_neg() const { return _ptr->_b_neg(); } var var::operator&(var n) const { return b_and(n); } var var::operator|(var n) const { return b_or(n); } var var::operator^(var n) const { return b_xor(n); } var var::operator~() const { return b_neg(); }
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads var var::operator~() const { return b_neg(); } var var::u_add() const { return _ptr->_u_add(); } var var::u_neg() const { return _ptr->_u_neg(); } var var::add(var n) const { return _ptr->_add(n); } var var::sub(var n) const { return _ptr->_sub(n); } var var::mul(var n) const { return _ptr->_mul(n); } var var::div(var n) const { return _ptr->_div(n); } var var::mod(var n) const { return _ptr->_mod(n); } var var::operator+() const { return u_add(); } var var::operator-() const { return u_neg(); } var var::f_div(var n) const { return _ptr->_f_div(n); } var var::rem(var n) const { return _ptr->_rem(n); } var var::pow(var n) const { return _ptr->_pow(n); } var var::root(var n) const { return _ptr->_root(n); } bool var::has(var n) const { return _ptr->_has(n); } std::size_t var::size() const { return _ptr->_size(); } var var::front() const { return _ptr->_front(); } var var::back() const { return _ptr->_back(); } var var::place(var n) const { return _ptr->_place(n); } var var::push(var n) const { return _ptr->_push(n); } var var::next() const { return _ptr->_next(); } var var::prev() const { return _ptr->_prev(); } var var::operator>>(std::size_t shift) const { var a{ *this }; while (shift--) { a = a.next(); } return a; } var var::operator<<(std::size_t shift) const { var a{ *this }; while (shift--) { a = a.prev(); } return a; } var var::reverse() const { return _ptr->_reverse(); } var var::get(var n) const { return _ptr->_get(n); }
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads var var::get(var n) const { return _ptr->_get(n); } var var::set(var n, var val) const { return _ptr->_set(n, val); } var var::del(var n) const { return _ptr->_del(n); } std::size_t var::hash() const { return _ptr->_hash(); } OP_CODE var::op_code() const { return _ptr->_op_code(); } bool var::is_nothing() const { return _ptr->_is_nothing(); } bool var::is_something() const { return !_ptr->_is_nothing(); } Text var::help() const { return _ptr->_help(); } var::operator bool() const { return is(); } bool var::operator==(var n) const { return eq(n); } bool var::operator!=(var n) const { return ne(n); } bool var::operator>=(var n) const { return ge(n); } bool var::operator> (var n) const { return gt(n); } bool var::operator<=(var n) const { return le(n); } bool var::operator< (var n) const { return lt(n); } var var::operator+(var n) const { return add(n); } var var::operator-(var n) const { return sub(n); } var var::operator*(var n) const { return mul(n); } var var::operator/(var n) const { return div(n); } var var::operator%(var n) const { return mod(n); } /********************************************************************************************/ // // 'data_type' Class Implementation // /********************************************************************************************/ template <typename T> var::data_type<T>::data_type(T val) : _data(std::move(val)) { } template<typename T> var::data_type<T>::~data_type() { } template <typename T> var::data_type<T>::operator bool() const { return _is(); }
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads template <typename T> var::data_type<T>::operator bool() const { return _is(); } template <typename T> std::size_t var::data_type<T>::_hash() const { return _hash_(_data); } template <typename T> Text var::data_type<T>::_type() const { return _type_(_data); } template <typename T> Text var::data_type<T>::_cat() const { return _cat_(_data); } template <typename T> bool var::data_type<T>::_is() const { return _is_(_data); } template <typename T> void var::data_type<T>::_str(Text_Stream& out) const { _str_(out, _data); } template <typename T> void var::data_type<T>::_repr(Text_Stream& out) const { _repr_(out, _data); } template <typename T> double var::data_type<T>::_comp(var n) const { return _comp_(_data, n); } template <typename T> var var::data_type<T>::_b_and(var n) const { return _b_and_(_data, n); } template <typename T> var var::data_type<T>::_b_or(var n) const { return _b_or_(_data, n); } template <typename T> var var::data_type<T>::_b_xor(var n) const { return _b_xor_(_data, n); } template <typename T> var var::data_type<T>::_b_neg() const { return _b_neg_(_data); } template<typename T> inline var var::data_type<T>::_u_add() const { return _u_add_(_data); } template<typename T> inline var var::data_type<T>::_u_neg() const { return _u_neg_(_data); } template <typename T> var var::data_type<T>::_add(var n) const { return _add_(_data, n); } template <typename T> var var::data_type<T>::_sub(var n) const { return _sub_(_data, n); } template <typename T> var var::data_type<T>::_mul(var n) const { return _mul_(_data, n); }
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads template <typename T> var var::data_type<T>::_div(var n) const { return _div_(_data, n); } template <typename T> var var::data_type<T>::_mod(var n) const { return _mod_(_data, n); } template <typename T> var var::data_type<T>::_f_div(var n) const { return _f_div_(_data, n); } template <typename T> var var::data_type<T>::_rem(var n) const { return _rem_(_data, n); } template <typename T> var var::data_type<T>::_pow(var n) const { return _pow_(_data, n); } template <typename T> var var::data_type<T>::_root(var n) const { return _root_(_data, n); } template <typename T> bool var::data_type<T>::_has(var n) const { return _has_(_data, n); } template <typename T> std::size_t var::data_type<T>::_size() const { return _size_(_data); } template <typename T> var var::data_type<T>::_front() const { return _front_(_data); } template <typename T> var var::data_type<T>::_back() const { return _back_(_data); } template <typename T> var var::data_type<T>::_place(var n) const { return _place_(_data, n); } template <typename T> var var::data_type<T>::_push(var n) const { return _push_(_data, n); } template <typename T> var var::data_type<T>::_next() const { return _next_(_data); } template <typename T> var var::data_type<T>::_prev() const { return _prev_(_data); } template <typename T> var var::data_type<T>::_reverse() const { return _reverse_(_data); } template <typename T> var var::data_type<T>::_get(var key) const { return _get_(_data, key); } template <typename T> var var::data_type<T>::_set(var key, var val) const { return _set_(_data, key, val); }
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads template <typename T> var var::data_type<T>::_del(var key) const { return _del_(_data, key); } template <typename T> Text var::data_type<T>::_help() const { return _help_(_data); } template <typename T> bool var::data_type<T>::_is_nothing() const { return _is_nothing_(_data); } template <typename T> OP_CODE var::data_type<T>::_op_code() const { return _op_code_(_data); } /********************************************************************************************/ // // Basic Primitive Implementations // /********************************************************************************************/ Text str(var a) { /* Convert a 'var' to its string representation. */ Text_Stream stream; stream << std::boolalpha; if (a.type() == "format") { /* The 'format' data type must be printed using its string representation, else it would only impart its formatting to the stream instead of being printed to it. */ a.repr(stream); } else { a.str(stream); } return stream.str(); } Text repr(var a) { /* Convert a 'var' to its representation as a string. */ Text_Stream stream; stream << std::boolalpha; a.repr(stream); return stream.str(); } var pop_front(var& exp) { var a = exp.front(); exp = exp.next(); return a; } var pop_back(var& exp) { var a = exp.back(); exp = exp.prev(); return a; } } ``` Answer: Answers to your questions. Have I defined a Monad object for C++?
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads Answer: Answers to your questions. Have I defined a Monad object for C++? Yes. Despite the name and its association with pure functional programming languages, it's not really that special. You can write monads in C as well. Since you have a data type that wraps a value, you have a way to construct that data type from a value, and you have functions that act on the wrapped value and returns that data type again, you have fulfilled all the obligations of the definition of a monad. Returning a double to manage partial ordering from the comp method. Yes, that's unusual. I see you wanted a way to signal that two values are unequal but have no particular ordering, and I guess you chose double because it has a NAN value? C++20 introduced std::partial_ordering that you can use as the return value of a comparison function, which would be more appropriate. If you still want to rely on NAN, consider using float instead of double, as it will be a little more efficient. Returning typeid(self).name(); as the default behavior. If you are OK with _type_() returning typeid(self).name(), why do you need to be able to set a custom name? On the other hand, consider that the return value of std::type_info::name() is implementation defined and not guaranteed to be unique. It could return "nothing" for all types and that would be legal. Should default behaviour be invoked for classes that do not overwrite var friend functions. I think that's the definition of default behaviour? However, the default behaviour should of course match what that function claims to do. So an _add_(const T& self, var other) that just does return var() is not what you want. If you cannot provide reasonable default behaviour, don't provide it at all. Is there any way to break up the implimentation from the header? Every time I try, there are always link issues were the associated type's function is missing.
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
c++, functional-programming, monads Concrete types and functions can be forward declared in the header, and their implementation can be put in source files. For templates, that normally doesn't work; they will only be instantiated when they are used, and at that point the whole definition must be available to the compiler. You can use explicit template instantiation, but then you need to know all types you will ever use in your program up front. This doesn't scale I am not sure what the intended use case is of var(), but if you want it to be able to wrap any type and allow any operation on them, this approach just doesn't scale at all. First, you only make available some functions for doing comparisons, arithmatic and list operations. What if you want to wrap a std::fstream and allow read() and write() operations? You'd have to add more member functions to var, to interface_type, and to potentially many classes that derive from interface_type. Second, consider all the possible integer types, from 8 to 64 bits, signed and unsigned. If you want to allow adding any kind of integer to any other kind of integer, you would have to write 64 overloads for each binary operation. Add float and double, and you have to write 100 overloads.
{ "domain": "codereview.stackexchange", "id": 44606, "lm_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++, functional-programming, monads", "url": null }
python, scipy Title: Local solver built into a global one Question: I am trying to optimize writing a script that has 2 minimizations, one dependent on the other. My code is a bit bloated, and I find the global parameters that I am solving for depend quite strongly on the initial guesses for the local parameters (which is quite concerning). So while the code works, I'm looking to optimize it, both for speed and robustness (i.e. the global solutions shouldn't vary so much due to local initial guesses). Let's say you have multiple systems of linear equations: #system of equations 1 equation1=dF*pF+dO*pO+dC*pC equation2=dF*pF2+dO*pO2+dC*pC2 equation3=dF*pF3+dO*pO3+dC*pC3 equation4=dF*pF4+dO*pO4+dC*pC4 #system 2 equation5=dF2*pF+dO2*pO+dC2*pC equation6=dF2*pF2+dO2*pO2+dC2*pC2 equation7=dF2*pF3+dO2*pO3+dC2*pC3 equation8=dF2*pF4+dO2*pO4+dC2*pC4 ... For each system of equations, there are 4 equations, with 15 adjustable parameters (3 of them shared dF, dO, and dC). However, the other 12 are shared across the multiple various systems. There are given experimental values of "equation1, equation2, equation3...." that the above system of equations is minimized against. These 12 parameters can be determined from 4 global parameters (k,k1,k2,k3) [io is a constant that is given] pF=(sqrt(k)*sqrt(k1)*sqrt(kk1+8io(1+k1)-kk1)/(4(1+k1)) pF2=(sqrt(k*k2)*sqrt(k1*k2)*sqrt(kk2k1k2+8io(1+k1*k2)-kk2k1k2)/(4(1+k1k2)) pF3=(sqrt(k*k3)*sqrt(k1*k3)*sqrt(kk3k1k3+8io(1+k1k3)-kk3k1k3)/(4(1+k1*k3)) pF4=(sqrt(k*k2*k3)*sqrt(k1*k2*k3)*sqrt(kk2k3k1k2k3+8io(1+k1k2k3)-kk2k3k1k2k3)/(4(1+k1*k2*k3)) #all other ps can be calculated in the same manner, but they have different equations I won't list here for space reasons
{ "domain": "codereview.stackexchange", "id": 44607, "lm_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, scipy", "url": null }
python, scipy So the idea is the 4 global parameters (k,k1,k2,k3) can be used to calculate the p's. Then with given p's, you go through each system of equation individually and solve for dF, dO, dC. You then minimize the global parameters, using the combined chi2 of the "solved/minimized" local parameters (dF, dO, dC). Here is the code: from scipy.optimize import minimize import numpy as np experimental_data_list=[[117.77, 117.705, 117.843, 117.597], [110.575, 110.258, 110.167, 110.216], [125.691, 125.006, 125.327, 124.481], [107.491, 108.461, 107.804, 109.383], [128.689, 128.383, 128.668, 128.29], [125.969, 126.326, 126.28, 126.257], [122.439, 122.684, 122.859, 122.194], [125.989, 125.998, 125.985, 125.897], [120.916, 120.18, 120.345, 120.567], [126.772, 126.669, 127.006, 127.592], [120.176, 120.153, 119.864, 120.205]] def local_calculation(d,pF,pO,pC,pF2,pO2,pC2,pF3,pO3,pC3,pF4,pO4,pC4,experimental_data): equation1=(d[0]*pF)+(d[1]*pO)+(d[2]*pC) equation2=(d[0]*pF2)+(d[1]*pO2)+(d[2]*pC2) equation3=(d[0]*pF3)+(d[1]*pO3)+(d[2]*pC3) equation4=(d[0]*pF4)+(d[1]*pO4)+(d[2]*pC4) return np.sqrt(np.sum((experimental_data-np.array([equation1,equation2,equation3,equation4]))**2))
{ "domain": "codereview.stackexchange", "id": 44607, "lm_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, scipy", "url": null }
python, scipy def get_populations(k,io): pF=(((np.sqrt(k[0])*np.sqrt(k[1]))*(np.sqrt((8*io*(k[1]+1))+(k[0]*k[1])))-(k[0]*k[1]))/(4*(k[1]+1)))/io pO=((k[1]*((-np.sqrt(k[0])*np.sqrt(k[1]))*(np.sqrt((8*io*(k[1]+1))+(k[0]*k[1])))+(k[0]*k[1])+(4*io*(k[1]+1))))/(4*((k[1]+1)**2)))/io pC=(((-np.sqrt(k[0])*np.sqrt(k[1]))*(np.sqrt((8*io*(k[1]+1))+(k[0]*k[1])))+(k[0]*k[1])+(4*io*(k[1]+1)))/(4*((k[1]+1)**2)))/io pF2=(((np.sqrt((k[0]*k[2]))*np.sqrt((k[1]*k[2])))*(np.sqrt((8*io*((k[1]*k[2])+1))+((k[0]*k[2])*(k[1]*k[2]))))-((k[0]*k[2])*(k[1]*k[2])))/(4*((k[1]*k[2])+1)))/io pO2=(((k[1]*k[2])*((-np.sqrt((k[0]*k[2]))*np.sqrt((k[1]*k[2])))*(np.sqrt((8*io*((k[1]*k[2])+1))+((k[0]*k[2])*(k[1]*k[2]))))+((k[0]*k[2])*(k[1]*k[2]))+(4*io*((k[1]*k[2])+1))))/(4*(((k[1]*k[2])+1)**2)))/io pC2=(((-np.sqrt((k[0]*k[2]))*np.sqrt((k[1]*k[2])))*(np.sqrt((8*io*((k[1]*k[2])+1))+((k[0]*k[2])*(k[1]*k[2]))))+((k[0]*k[2])*(k[1]*k[2]))+(4*io*((k[1]*k[2])+1)))/(4*(((k[1]*k[2])+1)**2)))/io pF3=(((np.sqrt((k[0]*k[3]))*np.sqrt((k[1]*k[3])))*(np.sqrt((8*io*((k[1]*k[3])+1))+((k[0]*k[3])*(k[1]*k[3]))))-((k[0]*k[3])*(k[1]*k[3])))/(4*((k[1]*k[3])+1)))/io pO3=(((k[1]*k[3])*((-np.sqrt((k[0]*k[3]))*np.sqrt((k[1]*k[3])))*(np.sqrt((8*io*((k[1]*k[3])+1))+((k[0]*k[3])*(k[1]*k[3]))))+((k[0]*k[3])*(k[1]*k[3]))+(4*io*((k[1]*k[3])+1))))/(4*(((k[1]*k[3])+1)**2)))/io pC3=(((-np.sqrt((k[0]*k[3]))*np.sqrt((k[1]*k[3])))*(np.sqrt((8*io*((k[1]*k[3])+1))+((k[0]*k[3])*(k[1]*k[3]))))+((k[0]*k[3])*(k[1]*k[3]))+(4*io*((k[1]*k[3])+1)))/(4*(((k[1]*k[3])+1)**2)))/io pF4=(((np.sqrt((k[0]*k[2]*k[3]))*np.sqrt((k[1]*k[2]*k[3])))*(np.sqrt((8*io*((k[1]*k[2]*k[3])+1))+((k[0]*k[2]*k[3])*(k[1]*k[2]*k[3]))))-((k[0]*k[2]*k[3])*(k[1]*k[2]*k[3])))/(4*((k[1]*k[2]*k[3])+1)))/io pO4=(((k[1]*k[2]*k[3])*((-np.sqrt((k[0]*k[2]*k[3]))*np.sqrt((k[1]*k[2]*k[3])))*(np.sqrt((8*io*((k[1]*k[2]*k[3])+1))+((k[0]*k[2]*k[3])*(k[1]*k[2]*k[3]))))+((k[0]*k[2]*k[3])*(k[1]*k[2]*k[3]))+(4*io*((k[1]*k[2]*k[3])+1))))/(4*(((k[1]*k[2]*k[3])+1)**2)))/io
{ "domain": "codereview.stackexchange", "id": 44607, "lm_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, scipy", "url": null }
python, scipy pC4=(((-np.sqrt((k[0]*k[2]*k[3]))*np.sqrt((k[1]*k[2]*k[3])))*(np.sqrt((8*io*((k[1]*k[2]*k[3])+1))+((k[0]*k[2]*k[3])*(k[1]*k[2]*k[3]))))+((k[0]*k[2]*k[3])*(k[1]*k[2]*k[3]))+(4*io*((k[1]*k[2]*k[3])+1)))/(4*(((k[1]*k[2]*k[3])+1)**2)))/io local_chi2=[] for experimental_data in experimental_data_list: arguments=(pF,pO,pC,pF2,pO2,pC2,pF3,pO3,pC3,pF4,pO4,pC4,experimental_data) local_solution=minimize(local_calculation,args=arguments, x0=np.array([120,110,100]),method = 'Nelder-Mead') local_chi2.append(local_solution.fun) return sum(local_chi2)
{ "domain": "codereview.stackexchange", "id": 44607, "lm_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, scipy", "url": null }
python, scipy io=280000 global_parameter_solution=minimize(get_populations,args=io, x0=np.array([1000,0.002,8,20]),method = 'Nelder-Mead') Answer: As a start: Do not write experimental_data_list all in one line; give each row its own line and put it into an np.array. Combine pF0,1,2,3 into one row of a 3x4 matrix, to also include O and C. Remove your redundant parens. There are so, so many. The inner expressions in get_populations are formatted in a truly awful way and I am not going to suggest any further simplifications there until that's cleaned up - for a small example, ((np.sqrt(k[0])*np.sqrt(k[1])) is really just np.sqrt(k0*k1) with k0, k1 unpacked from k. Do not make local_chi2 a list; make it a float starting at 0 and maintain a running total. Do not call an inner minimize. Recognize that your local_calculation is really a matrix multiplication of d @ pFOC. Ask numpy for a least-squares matrix inversion and use the residual it returns for your chi. Suggested Please scrutinize this closely. Add numeric regression tests to make sure that get_populations still works in the same way and step through a few times in a debugger. from scipy.optimize import minimize import numpy as np experimental_data_list = np.array(( [117.770, 117.705, 117.843, 117.597], [110.575, 110.258, 110.167, 110.216], [125.691, 125.006, 125.327, 124.481], [107.491, 108.461, 107.804, 109.383], [128.689, 128.383, 128.668, 128.290], [125.969, 126.326, 126.280, 126.257], [122.439, 122.684, 122.859, 122.194], [125.989, 125.998, 125.985, 125.897], [120.916, 120.180, 120.345, 120.567], [126.772, 126.669, 127.006, 127.592], [120.176, 120.153, 119.864, 120.205], )) def local_calculation( d: np.ndarray, pFOC: np.ndarray, experimental_data: np.ndarray, ): equations = d @ pFOC return np.linalg.norm(experimental_data - equations) def get_populations(k: np.ndarray, io: float) -> float: k0, k1, k2, k3 = k
{ "domain": "codereview.stackexchange", "id": 44607, "lm_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, scipy", "url": null }
python, scipy def get_populations(k: np.ndarray, io: float) -> float: k0, k1, k2, k3 = k pF = ( (((np.sqrt(k0)*np.sqrt(k1))*(np.sqrt((8*io*(k1+1))+(k0*k1)))-(k0*k1))/(4*(k1+1)))/io, (((np.sqrt((k0*k2))*np.sqrt((k1*k2)))*(np.sqrt((8*io*((k1*k2)+1))+((k0*k2)*(k1*k2))))-((k0*k2)*(k1*k2)))/(4*((k1*k2)+1)))/io, (((np.sqrt((k0*k3))*np.sqrt((k1*k3)))*(np.sqrt((8*io*((k1*k3)+1))+((k0*k3)*(k1*k3))))-((k0*k3)*(k1*k3)))/(4*((k1*k3)+1)))/io, (((np.sqrt((k0*k2*k3))*np.sqrt((k1*k2*k3)))*(np.sqrt((8*io*((k1*k2*k3)+1))+((k0*k2*k3)*(k1*k2*k3))))-((k0*k2*k3)*(k1*k2*k3)))/(4*((k1*k2*k3)+1)))/io, ) pO = ( ((k1*((-np.sqrt(k0)*np.sqrt(k1))*(np.sqrt((8*io*(k1+1))+(k0*k1)))+(k0*k1)+(4*io*(k1+1))))/(4*((k1+1)**2)))/io, (((k1*k2)*((-np.sqrt((k0*k2))*np.sqrt((k1*k2)))*(np.sqrt((8*io*((k1*k2)+1))+((k0*k2)*(k1*k2))))+((k0*k2)*(k1*k2))+(4*io*((k1*k2)+1))))/(4*(((k1*k2)+1)**2)))/io, (((k1*k3)*((-np.sqrt((k0*k3))*np.sqrt((k1*k3)))*(np.sqrt((8*io*((k1*k3)+1))+((k0*k3)*(k1*k3))))+((k0*k3)*(k1*k3))+(4*io*((k1*k3)+1))))/(4*(((k1*k3)+1)**2)))/io, (((k1*k2*k3)*((-np.sqrt((k0*k2*k3))*np.sqrt((k1*k2*k3)))*(np.sqrt((8*io*((k1*k2*k3)+1))+((k0*k2*k3)*(k1*k2*k3))))+((k0*k2*k3)*(k1*k2*k3))+(4*io*((k1*k2*k3)+1))))/(4*(((k1*k2*k3)+1)**2)))/io, ) pC = ( (((-np.sqrt(k0)*np.sqrt(k1))*(np.sqrt((8*io*(k1+1))+(k0*k1)))+(k0*k1)+(4*io*(k1+1)))/(4*((k1+1)**2)))/io, (((-np.sqrt((k0*k2))*np.sqrt((k1*k2)))*(np.sqrt((8*io*((k1*k2)+1))+((k0*k2)*(k1*k2))))+((k0*k2)*(k1*k2))+(4*io*((k1*k2)+1)))/(4*(((k1*k2)+1)**2)))/io, (((-np.sqrt((k0*k3))*np.sqrt((k1*k3)))*(np.sqrt((8*io*((k1*k3)+1))+((k0*k3)*(k1*k3))))+((k0*k3)*(k1*k3))+(4*io*((k1*k3)+1)))/(4*(((k1*k3)+1)**2)))/io, (((-np.sqrt((k0*k2*k3))*np.sqrt((k1*k2*k3)))*(np.sqrt((8*io*((k1*k2*k3)+1))+((k0*k2*k3)*(k1*k2*k3))))+((k0*k2*k3)*(k1*k2*k3))+(4*io*((k1*k2*k3)+1)))/(4*(((k1*k2*k3)+1)**2)))/io, ) pFOC = np.array((pF, pO, pC)) local_chi2 = 0
{ "domain": "codereview.stackexchange", "id": 44607, "lm_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, scipy", "url": null }
python, scipy pFOC = np.array((pF, pO, pC)) local_chi2 = 0 for experimental_data in experimental_data_list: # d @ pFOC ~ experimental_data; what is d? d, (residuals,), rank, singular = np.linalg.lstsq(pFOC.T, experimental_data) local_chi2 += np.sqrt(residuals) return local_chi2 io = 280_000 global_parameter_solution = minimize( get_populations, args=io, x0=(1000, 0.002, 8, 20), method='Nelder-Mead', ) There are other improvements possible, but let's get the basics out of the way first. Refactor Pull out common expressions from the pFOC calculation. Further vectorise to a single matrix inverse instead of doing it row-wise. This produces from typing import Iterable from scipy.optimize import minimize import numpy as np experimental_data_list = np.array(( [117.770, 117.705, 117.843, 117.597], [110.575, 110.258, 110.167, 110.216], [125.691, 125.006, 125.327, 124.481], [107.491, 108.461, 107.804, 109.383], [128.689, 128.383, 128.668, 128.290], [125.969, 126.326, 126.280, 126.257], [122.439, 122.684, 122.859, 122.194], [125.989, 125.998, 125.985, 125.897], [120.916, 120.180, 120.345, 120.567], [126.772, 126.669, 127.006, 127.592], [120.176, 120.153, 119.864, 120.205], )) def get_pfoc(k: Iterable[float]) -> np.ndarray: k0, k1, k2, k3 = k ki = np.array((1, k2, k3, k2*k3)) k01ii = k0*k1*ki*ki a = 2*(k1*ki + 1) s = np.sqrt( k01ii*(4*io*a + k01ii) ) - k01ii f = s/io/a/2 c = (2*io*a - s)/io/a/a o = k1*ki*c return np.vstack((f, o, c)) def get_populations(k: np.ndarray) -> float: pFOC = get_pfoc(k) # pFOC.T @ d = edl.T # 4x3 @ 3x11 = 4x11 d, *_ = np.linalg.lstsq(pFOC.T, experimental_data_list.T, rcond=None) error = (d.T@pFOC - experimental_data_list).ravel() return error.dot(error) io = 280_000
{ "domain": "codereview.stackexchange", "id": 44607, "lm_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, scipy", "url": null }
python, scipy io = 280_000 # Regression test for pFOC calculation assert np.allclose( get_pfoc((1000, 0.002, 8, 20)), np.array(( [0.00188615, 0.014887 , 0.03638202, 0.23081748], [0.00199224, 0.01551359, 0.03706223, 0.18646849], [0.9961216 , 0.96959941, 0.92655575, 0.58271403], )), ) global_parameter_solution = minimize( fun=get_populations, x0=(1000, 0.002, 8, 20), bounds=((0, None),)*4, ) print(global_parameter_solution) message: CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL success: True status: 0 fun: 0.23517135040546988 x: [ 9.999e+02 8.614e-01 4.891e+00 2.441e+00] nit: 22 jac: [ 6.384e-07 1.033e-06 2.839e-06 -9.689e-06] nfev: 200 njev: 40 hess_inv: <4x4 LbfgsInvHessProduct with dtype=float64>
{ "domain": "codereview.stackexchange", "id": 44607, "lm_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, scipy", "url": null }
c++, converting, byte Title: General bytes to number converter (c++) Question: I've written a bytes to number converter for cpp similar to the python int.from_bytes. It does not make any assumptions on: The endianness of the input buffer The endianness of the system The endianness consistency of the the system ( = no assumption that all numeric types have the same endianness ) Additionally the source buffer can be smaller than the target. #include <cstdint> #include <span> #include <stdexcept> namespace Binary { // Used to indicate the endianness of a type // Better readability than a simple bool enum class Endianness { Little, Big, }; namespace Int { // Base is the underlying type that will be used to store the eventual result template< typename Base > Base FromBytes( std::span< std::uint8_t > inBuffer, Binary::Endianness inEndianness ) { // Check if we have enough space if( sizeof( Base ) < inBuffer.size() ) { throw std::length_error( "unable to fit data in requested type" ); } // Determine endianness of the Base type on this system union { Base i; char c[ sizeof( Base ) ]; } test = { .i = 1 }; bool tmp = test.c[ sizeof( Base ) - 1 ] == '\1'; Binary::Endianness type_endianness = tmp ? Binary::Endianness::Big : Binary::Endianness::Little; // Always initialize your variables Base result = Base{ 0 }; std::uint8_t * destination = ( std::uint8_t * ) &result; // If we have big endian and we have a smaller buffer the first bytes should // remain zero, meaning we should start filling further back if( type_endianness == Binary::Endianness::Big ) { destination += sizeof( Base ) - inBuffer.size(); }
{ "domain": "codereview.stackexchange", "id": 44608, "lm_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++, converting, byte", "url": null }
c++, converting, byte if( type_endianness == inEndianness ) { // equal endianness => simple copy memcpy( destination, inBuffer.data(), inBuffer.size() ); } else { // differing endianness => copy in reverse for( size_t i = 0; i < inBuffer.size(); i+=1 ) { destination[ i ] = inBuffer[ inBuffer.size() - i - 1 ]; } } return result; } } } Are there any improvements I could make? Answer: I like the enum. Except that it is different from the one C++20 defines. We're missing some review context, like the range of use cases we're trying to address. This submission contains no unit tests or other demo code. It's unclear if caller is likely to call into this repeatedly through an array loop. Perhaps "exotic" 24-bit quantities motivated this code. use constexpr Every call to FromBytes asks about native endianess. It's a nice piece of code, very clear, but we should cache the result as it won't change. Or better, find the result at compile time. Even better, dispense with it and rely on std::endian::native. Or write down the underlying requirements so we understand what systems are being targeted and what language / compiler variants are within scope. nit: Assigning tmp = test.c[0] == '\1'; seems a little more convenient. But perhaps you wanted the order for the ternary to be "big, little" for aesthetic reasons. Consider renaming tmp to is_big. Delete uninformative comments like "Always initialize your variables". I am glad to see that .size() is the first thing we check. Good. nit: I find the second form slightly easier to read. ... inBuffer[ inBuffer.size() - i - 1 ] ... inBuffer[ inBuffer.size() - 1 - i ]
{ "domain": "codereview.stackexchange", "id": 44608, "lm_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++, converting, byte", "url": null }
c++, converting, byte ... inBuffer[ inBuffer.size() - 1 - i ] Why? I read it as "constant minus i" where I can reason about the constant location independent of the loop. Rather than having to puzzle out the numeric relationship between size and i, observe it is always positive, and then decrement to get to the zero-th element. document language version std::reverse_copy has been available since C++17, but we choose not to use it, unclear why. Using a standard routine might yield performance identical to a naïve loop. But maybe a vendor went to some trouble to vectorize it for your target processor, and it will go quicker. Use it for the same reason you prefer memcpy(). Tell us which language variants are acceptable for this project, write it down so future maintainers will know the rules. I was slightly surprised to not see ntohl mentioned, nor be64toh, but maybe {3, 5, 6, 7}-byte inBuffers are just as important for the use case we're addressing. Those standard functions should absolutely appear in your automated test suite. document the sign bit The brief review context explicitly says that we implement a well-known interface. We do support a corresponding endianness parameter. But interpretation of the source sign bit is left implicit. Presumably it matches the Base type. This should be explicitly written down. (Also, "Base" seems a slightly odd name as it suggests "Radix" which isn't relevant here. Maybe "NumericType"?) API design Imagine the caller is assigning a great many 16-bit integers via an array loop. I worry about whether we're giving the compiler a good chance at vectorizing such a bulk assignment. Consider offering a second method that moves K integers of identical size. Imagine the input numbers are already in native order and they have a standard {16, 32, 64}-bit size. Would it help your use case if this routine was given the flexibility to report no-op by returning address of input buffer, avoiding the memcpy() ?
{ "domain": "codereview.stackexchange", "id": 44608, "lm_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++, converting, byte", "url": null }
c++, converting, byte This code achieves its design goals. Before merging it to main it should be better documented and should be accompanied by unit tests. I would be happy to delegate or accept maintenance tasks on this codebase.
{ "domain": "codereview.stackexchange", "id": 44608, "lm_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++, converting, byte", "url": null }
c++, multithreading, thread-safety Title: C++ Thread Pool Implementation using Lock Free Queue Question: Topic: C++ Implementation of Lock-Free Queue and ThreadPool classes In a project I'm currently working on, I need the implementation of ThreadPool along with a thread-safe queue. I've tried implementing the above structures and wonder about their safety and performance. Reason for asking I'm looking for your review to ensure it's bug-free and well-constructed. As far as I know, everything is working well, but I feel like there is much to improve, as I'm a beginner in this field, and probably I can miss something pretty easily. Lock free queue lock_free_queue.hpp: #include <deque> #include <mutex> #include <condition_variable> template<typename T> class LockFreeQueue { private: std::deque<T> queue; std::mutex mutex; std::condition_variable element_available; std::condition_variable space_available; // keep control of queue size std::atomic_uint active_producers; // to throw poison pill when needed size_t max_size{}; public: LockFreeQueue() : max_size(std::numeric_limits<size_t>::max()), active_producers(1) {} explicit LockFreeQueue(size_t max_size, unsigned active_producers = 1) : max_size(max_size), active_producers(active_producers) {} ~LockFreeQueue() = default; LockFreeQueue(const LockFreeQueue &) = delete; LockFreeQueue &operator=(const LockFreeQueue &) = delete; template<typename A> void push(A &&item) { { std::unique_lock<std::mutex> lock(mutex); space_available.wait(lock, [this] { return queue.size() < max_size; }); queue.push_back(std::forward<A>(item)); } element_available.notify_one(); }
{ "domain": "codereview.stackexchange", "id": 44609, "lm_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++, multithreading, thread-safety", "url": null }
c++, multithreading, thread-safety T pop() { T item; { std::unique_lock<std::mutex> lock(mutex); while (queue.empty()) { if (active_producers.load(std::memory_order_acquire) == 0) { return {}; // poison pill } element_available.wait(lock); } item = std::move(queue.front()); queue.pop_front(); } space_available.notify_one(); return item; } bool try_pop(T &item) { std::unique_lock<std::mutex> lock(mutex); if (queue.empty()) { return false; } item = std::move(queue.front()); queue.pop_front(); return true; } void shutdown() { active_producers.fetch_sub(1, std::memory_order_release); element_available.notify_all(); } [[maybe_unused]] bool empty() { std::unique_lock<std::mutex> lock(mutex); return queue.empty(); } [[maybe_unused]] size_t size() { std::unique_lock<std::mutex> lock(mutex); return queue.size(); } [[maybe_unused]] void clear() { std::unique_lock<std::mutex> lock(mutex); queue.clear(); } }; Thread pool thread_pool.hpp: #include "lock_free_queue.hpp" #include <atomic> #include <vector> #include <thread> #include <functional> #include <future> #include <cstddef> using job_t = std::function<void()>; class JoinThreads { std::vector<std::thread> &threads; public: explicit JoinThreads(std::vector<std::thread> &to_join); ~JoinThreads(); }; class ThreadPool { std::atomic_bool done; LockFreeQueue<job_t> jobs; std::vector<std::thread> threads; JoinThreads joiner; std::condition_variable cv; std::mutex cv_m; size_t pending_jobs = 0; void worker_thread(); void job_done(); public: explicit ThreadPool(size_t num_threads); ~ThreadPool();
{ "domain": "codereview.stackexchange", "id": 44609, "lm_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++, multithreading, thread-safety", "url": null }
c++, multithreading, thread-safety void job_done(); public: explicit ThreadPool(size_t num_threads); ~ThreadPool(); template<typename func_T> void submit(func_T &&f) { jobs.push(std::forward<func_T>(f)); ++pending_jobs; } void wait(); }; thread_pool.cpp: #include "thread_pool.hpp" #include <iostream> using job_t = std::function<void()>; JoinThreads::JoinThreads(std::vector<std::thread> &to_join) : threads(to_join) {} JoinThreads::~JoinThreads() { for (auto &thread: threads) { if (thread.joinable()) { thread.join(); } } } void ThreadPool::worker_thread() { while (!done) { job_t job; if (jobs.try_pop(job)) { job(); job_done(); } else { std::this_thread::yield(); } } } void ThreadPool::job_done() { { std::unique_lock<std::mutex> lock(cv_m); --pending_jobs; } cv.notify_all(); } void ThreadPool::wait() { std::unique_lock<std::mutex> lock(cv_m); cv.wait(lock, [this] { return pending_jobs == 0; }); } ThreadPool::ThreadPool(const size_t num_threads): done(false), joiner(threads) { try { for (size_t i = 0; i < num_threads; ++i) { threads.emplace_back(&ThreadPool::worker_thread, this); } } catch (...) { done = true; throw; } } ThreadPool::~ThreadPool() { jobs.shutdown(); wait(); done = true; } Usage example #include "thread_pool.hpp" ThreadPool pool(num_threads); pool.submit([this] { some_method(); }); pool.submit([this] { another_method(); }); Important I'm also particularly curious if I've correctly implemented the wait() mechanism. Thank you! I will be grateful for any advice and comments.
{ "domain": "codereview.stackexchange", "id": 44609, "lm_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++, multithreading, thread-safety", "url": null }
c++, multithreading, thread-safety Answer: Naming things The name LockFreeQueue is a lie, it uses std::mutex to lock so it is not lock-free. However, this class does provide thread-safety, so a more appropriate name would be ThreadSafeQueue. Don't mix atomics and mutexes Avoid mixing atomic variables and mutexes. Doing so will create multiple synchronization scopes. Since you already have a mutex, I suggest that active_producers is only read from and written to while holding mutex, so there is no need to make it atomic. Just lock the mutex in shutdown(). There is an actual problem in your code. Consider a thread that's inside the while-loop in pop(): if (active_producers.load(std::memory_order_acquire) == 0) { return {}; // poison pill } // <-- thread is currently right here element_available.wait(lock); It has just checked active_producers and it was equal to 1. Now another thread calls shutdown(), which decrements active_producers and calls notify_all(). However, since the first thread hasn't started wait() yet, those notifications will have no effect. Now wait() is called, and it will block forever. The correct way to handle this is to use wait() with a predicate, and to ensure everything this predicate checks is guarded by lock: T pop() { T item; { std::unique_lock<std::mutex> lock(mutex); element_available.wait(lock, [&]{ return !active_producers || !queue.empty(); }); if (queue.empty()) { // We can only reach this if there are no active producers left return {}; } item = std::move(queue.front()); queue.pop_front(); } space_available.notify_one(); return item; } void shutdown() { { std::unique_lock<std::mutex> lock(mutex); --active_producers; } element_available.notify_all(); }
{ "domain": "codereview.stackexchange", "id": 44609, "lm_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++, multithreading, thread-safety", "url": null }
c++, multithreading, thread-safety element_available.notify_all(); } About the use of attributes I see you annotated some member functions with [[maybe_unused]]. That's quite unusual, and is unnecessary; compilers don't warn about class members functions that are not used. What you can do is give empty(), size() and try_pop() the [[nodiscard]] attribute. That will ensure the compiler will warn if something calls those functions but doesn't look at their return value, which would almost certainly be an error. Remove JoinThreads I don't see the point of this class. Sure, it will join threads when it is destroyed, but you had to write a destructor to do that. Why not just move that destructor into ThreadPool itself? That would be less code to write, and is slightly more efficient because there is no need to store a reference to a vector of threads anymore. Since C++20 you can use std::jthread: it's a single std::thread that joins when it is destroyed. You can create a vector of those, and that will automatically cause all threads to join when the vector is destroyed. Don't busy-wait Your ThreadPool::worker_thread() busy-waits if there are no jobs. I would just have it call pop() instead of try_pop(), and then check if the returned job_t contains a function: void ThreadPool::worker_thread() { while (true) { job_t job = jobs.pop(); if (!job) break; job(); } }
{ "domain": "codereview.stackexchange", "id": 44609, "lm_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++, multithreading, thread-safety", "url": null }
c++, multithreading, thread-safety Rely on the queue to signal when work is done. You also don't need to track pending_jobs and have a done variable at all; only when the queue is empty and there are no more producers will pop() return {}. That also means there is no need for ThreadPool::wait(). One issue to worry about is what to do when creating worker threads fails. You then need to ensure the queue is shut down properly. You could do that in the constructor of ThreadPool by calling jobs.shutdown() inside the catch-block. Remove empty() and size() While most standard containers provide empty() and size() member functions, there is a problem with those functions in a thread-safe queue. While you take the lock inside those functions, the lock is released right before these functions return. That means that by the time the caller looks at the return value, that value might no longer be representative of the state of the queue anymore; another thread might have come and added or removed items. Since you cannot rely on the return value of these functions, it is better to remove them entirely.
{ "domain": "codereview.stackexchange", "id": 44609, "lm_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++, multithreading, thread-safety", "url": null }
php, object-oriented, factory-method Title: Creating multiple conditions in objects preventing nesting Question: My class is a factory-method that allows to instantiate it only when the parameter $type (string) is "regular or premium" and when parameter $months (integer) is lower than 6. If $months is lower than 6, an error prompts and the subscription instance is not created. I've created an if condition if (class_exists($suscription)) inside another if condition if ($months < 6) knowing it is a bad practice. How can I improve the way I am creating the conditions (maybe creating a different method for $months validation)? <?php class Subscription { protected $months; public function __construct($months) { $this->months = $months; } public static function create($type, $months) { $suscription = ucwords($type); try { if ($months < 6) { throw new Exception("<p style='color: red;'>The minimum must be 6 months</p>"); } else { try { if (class_exists($suscription)) { return new $suscription($months); } else { throw new Exception("<p style='color: red;'>Subscription type " . $type . " not available</p>"); } } catch (Exception $ex) { echo $ex->getMessage(); } } } catch (Exception $ex) { echo $ex->getMessage(); } } // I tried this first, but didn't worked because it never stoped the instantiation of the new $suscription($months); private static function minimumMonths($months) { try { if ($months < 6) { throw new Exception("<p style='color: red;'>The minimum of months must be 6</p>"); } } catch (Exception $ex) { echo $ex->getMessage(); } } }
{ "domain": "codereview.stackexchange", "id": 44610, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, factory-method", "url": null }
php, object-oriented, factory-method class RegularSubscription extends Subscription { public function __construct($months) { parent::__construct($months); print "<p style='color: green;'>Regular subscription has been created, it has " . $this->months . " months</p>"; } } class PremiumSubscription extends Subscription { public function __construct($months) { parent::__construct($months); print "<p style='color: green;'>Premium subscription has been created, it has " . $this->months . " months</p>"; } } $subscription = Subscription::create('Premiumsubscription', 3);
{ "domain": "codereview.stackexchange", "id": 44610, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, factory-method", "url": null }
php, object-oriented, factory-method Answer: You're probably overthinking this. Do you really need multiple classes? Unless those subscriptions have some distinct behaviour, there is no need for more than properties on just one class. Don't just catch exceptions where you throw them. There is no reason to throw them in the first place if you have code that can handle the case right a few lines below. But echoing something really isn't the right logic for handling errors. You should not print/echo anything inside those classes - I get that it's for debugging, but there is no place for this in production code. And it's better to use a proper debugging tool like xdebug. You could use some modern features of PHP to simplify your code a lot. You can use constructor promotion. You can define enum for the types of subscriptions. It will allow you to separate the place where an invalid type error is thrown and where an invalid subscription setup error is thrown. Do not implement the checks in the static factory if your constructor is public. Either make the constructor private or move all necesary checks inside the contructor. Use appropriate typing wherever possible. Make your classes readonly if possible. The more explicit you are about the types and intents of your classes/methods/functions, the better for anyone using them or just reading the code. enum SubscriptionType : string { case regular = 'regular'; case premium = 'premium'; } final class InvalidSubscriptionDurationException extends \InvalidArgumentException { } final readonly class Subscription { public function __construct( public SubscriptionType $type, public int $months, ) { if ($this->months < 6) { throw new InvalidSubscriptionDurationException('Must be at least 6 months'); } } } $subscription = new Subscription(SubscriptionType::regular, 12); $subscription = new Subscription(SubscriptionType::from($typeString), 12);
{ "domain": "codereview.stackexchange", "id": 44610, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, factory-method", "url": null }
php, object-oriented, factory-method If different subscriptions shall have different behaviour, maybe then you could use inheritance, but one could argue you should use composition instead. You should also avoid magically converting strings to classes. Just instantiate the class you want. Maybe different classes will need different constructor arguments... final readonly class SubscriptionDuration { public function __construct(public int $months) { if ($this->months < 6) { throw new InvalidSubscriptionDurationException('Must be at least 6 months'); } } } interface SubscriptionBehaviour { function behaviour(): void; } final readonly class RegularSubscription implements SubscriptionBehaviour { public function __construct(private SubscriptionDuration $duration) { } function behaviour(): void { // whatever } } final readonly class PremiumSubscription implements SubscriptionBehaviour { public function __construct(private SubscriptionDuration $duration) { } function behaviour(): void { // whatever } } final class SubscriptionFactory { private function __construct() {} public static function create(SubscriptionType $type, SubscriptionDuration $duration): SubscriptionBehaviour { return match ($type) { SubscriptionType::regular => new RegularSubscription($duration), SubscriptionType::premium => new PremiumSubscription($duration), }; } } ```
{ "domain": "codereview.stackexchange", "id": 44610, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "php, object-oriented, factory-method", "url": null }
java, lambda, column, inner-class Title: Print columns of text without hard coding the width (attempt 4) Question: If you'd like to print this: One Two Three Four 1 2 3 4 using this: new Columns() .addLine("One", "Two", "Three", "Four") .addLine("1", "2", "3", "4") // .-={ Optional configuration examples }=-. // .separateColumnsWith(" ") .padWith(" ") .padWith(' ') .outputWith(System.out) .alignRight() .alignLeft(0) .alignRight(1) .alignCenter(2) // '-={ Optional configuration examples }=-' // .print() ; all you need is this: import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Collections; import java.util.function.Function; import java.util.function.UnaryOperator; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.io.PrintStream; public class Columns { private final List<Column> columns = new ArrayList<>(); // Defaults private String columnSeparator = " "; private String pad = " "; private PrintStream out = System.out; private Function<String, Function<String, UnaryOperator<String>>> align; { alignLeft(); // Set default alignment } public Columns addLine(String... line) { if ( columns.size() > 0 && columns.size() != line.length) { throw new IllegalArgumentException("Inconsistant arg. count."); } if ( columns.size() == 0 ) { for (int i = 0; i < line.length; i++) { columns.add( new Columns.Column(align) ); } } IntStream .range(0, columns.size()) .forEach( col -> columns.get(col).addWord(line[col]) ) ; return this; } public Columns print(){ out.println( toString() ); return this; }
{ "domain": "codereview.stackexchange", "id": 44611, "lm_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, lambda, column, inner-class", "url": null }
java, lambda, column, inner-class public String toString(){ final StringBuilder result = new StringBuilder(); final int rows = columns.get(0).size(); IntStream .range(0, rows) .forEach( row -> { result .append( columns .stream() .map(col -> col.getCell(row)) .collect( Collectors.joining(columnSeparator) ) ) ; result.append( System.lineSeparator() ); } ) ; return result.toString(); } // .-={ Make defaults overridable }=-. // public Columns outputWith(PrintStream out){ this.out = out; return this; } public Columns separateColumnsWith(String columnSeparator){ this.columnSeparator = columnSeparator; return this; } public Columns padWith(String pad){ if (pad.length() != 1) { throw new IllegalArgumentException("Expected single character"); } this.pad = pad; return this; } public Columns padWith(char pad){ this.pad = "" + pad; return this; } // '-={ Make defaults overridable }=-' // public Columns alignLeft(){ align = getAlignLeft(); columns.forEach(col -> col.setAlign(align)); return this; } public Columns alignCenter(){ align = getAlignCenter(); columns.forEach(col -> col.setAlign(align)); return this; } public Columns alignRight(){ align = getAlignRight(); columns.forEach(col -> col.setAlign(align)); return this; } public Columns alignLeft(int col){ columns.get(col).setAlign( getAlignLeft() ); return this; }
{ "domain": "codereview.stackexchange", "id": 44611, "lm_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, lambda, column, inner-class", "url": null }
java, lambda, column, inner-class public Columns alignCenter(int col){ columns.get(col).setAlign( getAlignCenter() ); return this; } public Columns alignRight(int col){ columns.get(col).setAlign( getAlignRight() ); return this; } private Function<String, Function<String, UnaryOperator<String>>> getAlignLeft(){ return left -> word -> right -> word + left + right; } private Function<String, Function<String, UnaryOperator<String>>> getAlignCenter(){ return left -> word -> right -> left + word + right; } private Function<String, Function<String, UnaryOperator<String>>> getAlignRight(){ return left -> word -> right -> left + right + word; } class Column { private List<String> words = new ArrayList<>(); private int maxLength = 0; private Function<String, Function<String, UnaryOperator<String>>> align;
{ "domain": "codereview.stackexchange", "id": 44611, "lm_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, lambda, column, inner-class", "url": null }
java, lambda, column, inner-class public Column(Function<String, Function<String, UnaryOperator<String>>> align){ this.align = align; } public Columns.Column addWord(String word){ maxLength = Math.max(maxLength, word.length()); words.add(word); return this; } public String getCell(int row){ return padCell( words.get(row), maxLength ); } private String padCell(String word, int newLength){ int padCount = newLength - word.length(); int leftCount = padCount / 2; int rightCount = padCount - leftCount; String left = pad.repeat(leftCount); String right = pad.repeat(rightCount); return align.apply(left).apply(word).apply(right); } public int size(){ return words.size(); } public String toString(){ return words.toString(); } public Column setAlign(Function<String, Function<String, UnaryOperator<String>>> align){ this.align = align; return this; } } } By waiting until all the lines have been added before printing it can figure out the width each column needs. Looking for a code review to reveal problems. Anything from better names to fewer bugs to better ideas. Back on my second attempt @torbenputkonen gave me the idea of using an inner class for each column. As predicted it cleaned up the code and gave the flexibility to manage alignment on each column. The reviews here have inspired a 5th attempt.
{ "domain": "codereview.stackexchange", "id": 44611, "lm_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, lambda, column, inner-class", "url": null }
java, lambda, column, inner-class The reviews here have inspired a 5th attempt. Answer: I’m not wild about the padWith(String), and restricting the string to a single character. Just keep the padWith(char) method. You can separate columns with " | ", but you can’t specify a prefix or suffix, so you can’t make vertical lines at the left and right edges. While we’re at it, it might be nice to have top/bottom lines possible, and perhaps a line after headings. But if you go too far down that rabbit hole, you’d probably want to call the class Table. .print().addLine(…).print() has unexpected behaviour. I don’t see the point of allowing anything to chain after doing a print unless it clears the accumulated buffer. Perhaps it should be void.
{ "domain": "codereview.stackexchange", "id": 44611, "lm_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, lambda, column, inner-class", "url": null }
rust Title: First attempt using Rust, to create a simple API backing onto a JSON file Question: I'm trying to learn Rust, and have taken a stab at it by create a REST API, that stores the data in a local JSON file. Before I get deeper into things I'd like some feedback on if I'm doing things in a "Rusty" sort of way, or if there's a better approach to what I'm doing. https://github.com/TomHart/books-api main.rs mod books; use actix_web::{get, put, web, App, HttpResponse, HttpServer, Responder, http::header}; use std::fs; use json; use crate::books::structs::{Book, Books}; #[get("/books")] async fn books_route() -> impl Responder { let books: Books = books::get(); let string: String = serde_json::to_string(&books).expect("Err"); HttpResponse::Ok() .insert_header(header::ContentType::json()) .body(string) } #[get("/books/{book_id}")] async fn index(path: web::Path<String>) -> impl Responder { let book_id = path.into_inner(); let book_result = books::get_by_id(book_id); let book: Book = match book_result { Ok(book) => book, Err(_err) => return HttpResponse::NotFound().finish() }; let string: String = serde_json::to_string(&book).expect("Err"); HttpResponse::Ok() .insert_header(header::ContentType::json()) .body(string) } #[put("/books")] async fn add_book(form: web::Json<Book>) -> impl Responder { let books: Books = books::add_book(form.into_inner()); let string: String = serde_json::to_string_pretty(&books).expect("Err"); HttpResponse::Ok() .insert_header(header::ContentType::json()) .body(string) } fn init_json() -> bool { let raw_json = fs::read_to_string("data.json").unwrap_or_else(|_error| { return create_json(); }); json::parse(&raw_json).unwrap_or_else(|_error| { return json::parse(&create_json()).unwrap(); }); return true; }
{ "domain": "codereview.stackexchange", "id": 44612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust return true; } fn create_json() -> String { fs::OpenOptions::new().write(true) .create_new(true) .open("data.json").expect("Couldn't create data.json"); fs::write("data.json", "{\"books\": []}").expect("Unable to write to data.json"); return fs::read_to_string("data.json").unwrap(); } #[actix_web::main] async fn main() -> std::io::Result<()> { if !init_json() { println!("Can't create data.json"); } println!("Starting"); HttpServer::new(|| { App::new() .service(books_route) .service(add_book) .service(index) }) .bind(("127.0.0.1", 8080))? .run() .await } books.rs pub mod structs; use std::fs; use uuid::Uuid; use crate::books::structs::{Book, Books, BooksList}; pub fn get() -> Books { let raw_json = fs::read_to_string("data.json").expect("Failed reading data.json").to_owned(); let books: BooksList = serde_json::from_str(&raw_json).unwrap(); books.books } pub fn add_book(mut book: Book) -> Books { println!("Name: {}", book.name); if book.id.is_none() { book.id = Some(Uuid::new_v4().to_string()); } let raw_json = fs::read_to_string("data.json").expect("Failed reading data.json").to_owned(); let mut books: BooksList = serde_json::from_str(&raw_json).unwrap(); let index_of_first_even_number = books.books.0.iter().position(|x| x.id == book.id); if index_of_first_even_number.is_none() { books.books.0.push(book); } else { books.books.0[index_of_first_even_number.unwrap()] = book; } let string: String = serde_json::to_string_pretty(&books).expect("Err"); fs::write("data.json", string).expect("Unable to write to data.json"); books.books }
{ "domain": "codereview.stackexchange", "id": 44612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust books.books } pub fn get_by_id(book_id: String) -> Result<Book, String> { let raw_json = fs::read_to_string("data.json").expect("Failed reading data_.json").to_owned(); let books: BooksList = serde_json::from_str(&raw_json).unwrap(); let tmp: Vec<Book> = books.books.0; for book in tmp { let id = book.id.as_ref(); if !id.is_none() && id.unwrap() == &book_id { return Ok(book); } } Err("Not found".to_string()) } books/structs.rs use chrono::{DateTime, Utc, serde::ts_seconds_option}; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize)] pub struct BooksList { pub books: Books, } #[derive(Serialize, Deserialize)] pub struct Books(pub Vec<Book>); #[derive(Serialize, Deserialize)] pub struct Book { pub name: String, pub id: Option<String>, #[serde(with = "ts_seconds_option")] pub started: Option<DateTime<Utc>>, #[serde(with = "ts_seconds_option")] pub finished: Option<DateTime<Utc>>, } impl std::fmt::Display for Book { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let started = match self.started { Some(date) => format!("started at {}", date.format("%Y-%m-%d %H:%M:%S").to_string()), None => "not started yet".to_string() }; write!(f, "{}, {}", self.name, started) } } impl std::fmt::Display for Books { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { self.0.iter().fold(Ok(()), |result, album| { result.and_then(|_| writeln!(f, "{}", album)) }) } } ```
{ "domain": "codereview.stackexchange", "id": 44612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust Answer: I'd suggest that you try holding the book data in memory, loading it when the program starts, and writing copies as it changes, but using the in memory copy for lookups. The issue is that you've avoided one of the tricky bits that can arise in web applications by not having any state shared between your different invocations. If you want to get a handle on Rust, you should probably do that. You've got lots of trivial duplication, for example: let raw_json = fs::read_to_string("data.json").expect("Failed reading data.json").to_owned(); let mut books: BooksList = serde_json::from_str(&raw_json).unwrap(); Instead of duplicating this, make a function and call it. This bit is confusing, because it has nothing to do with even numbers. let index_of_first_even_number = books.books.0.iter().position(|x| x.id == book.id); Also, you should probably use a dictionary to store the books if you want to lookup and store by id. let raw_json = fs::read_to_string("data.json").unwrap_or_else(|_error| { return create_json(); }); I would suggest checking the error, to make sure it really indicates not found and not some other error. The Display trait is a generic display function, and it doesn't make sense to implement a specific case in there. So its weird that you've define a std::fmt::Display that just prints some of the information. You don't need to create a file before you write to it: fn create_json() -> String { fs::OpenOptions::new().write(true) .create_new(true) .open("data.json").expect("Couldn't create data.json"); fs::write("data.json", "{\"books\": []}").expect("Unable to write to data.json"); return fs::read_to_string("data.json").unwrap(); } fs::write will create the file if it does not exist.
{ "domain": "codereview.stackexchange", "id": 44612, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
c++, c++20 Title: C++ Thread Pool with suspend functionality, Question: This implementation of thread pool that includes support for suspend functionality, which is necessary for refreshing reference data periodically. I would appreciate your review to ensure that there are no bugs and that the implementation is well-structured. Although everything seems to be working fine, I am still a novice in this area and might have overlooked some details that could be improved. class ThreadPool { public: ThreadPool(size_t size = std::thread::hardware_concurrency()) { threads_.reserve(size); for (size_t i = 0; i < size; ++i) { threads_.emplace_back([this, tid = i]() { thread_func(tid); }); } } template <typename F, typename... Args> void push(F &&f, Args &&...args) { { std::unique_lock<std::mutex> lock(mutex_); tasks_.emplace([=]() { f(args...); }); } condition_.notify_one(); } ~ThreadPool() { { std::lock_guard<std::mutex> lock(mutex_); stop_ = true; } condition_.notify_all(); for (auto &thread : threads_) { thread.join(); } } void suspend() { suspend_mutex_.lock(); { std::lock_guard<std::mutex> lock(mutex_); suspender_id_ = std::this_thread::get_id(); suspend_ = true; } } void resume() { std::lock_guard<std::mutex> lock(mutex_); if (suspender_id_ != std::this_thread::get_id()) { return; } suspend_ = false; suspend_mutex_.unlock(); } bool isSuspended() { std::unique_lock<std::mutex> lock(mutex_); return active_threads_ == 0; }
{ "domain": "codereview.stackexchange", "id": 44613, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 private: void thread_func(size_t thread_id) { { std::unique_lock<std::mutex> lock(mutex_); std::cout << "starting: " << thread_id << '\n'; } while (true) { std::function<void()> task; { std::unique_lock<std::mutex> lock(mutex_); condition_.wait(lock, [this] { return !tasks_.empty() || stop_; }); if (stop_ && tasks_.empty()) { --active_threads_; return; } if (suspend_) { continue; } task = std::move(tasks_.front()); tasks_.pop(); ++active_threads_; } if (task) task(); std::unique_lock<std::mutex> lock(mutex_); --active_threads_; } } std::vector<std::thread> threads_; std::queue<std::function<void()>> tasks_; std::mutex mutex_; std::mutex suspend_mutex_; std::condition_variable condition_; std::thread::id suspender_id_; bool stop_ {false}; bool suspend_ {false}; std::size_t active_threads_ {0}; }; Usage example void thread_func(ThreadPool& pool) { int count = 0; // Push some tasks to the thread pool pool.push([&count]() { count += 1; }); pool.push([&count]() { count += 2; }); pool.push([&count]() { count += 3; }); // Suspend the thread pool and wait for a short period of time pool.suspend(); std::cout << "Thread pool suspended\n"; std::this_thread::sleep_for(std::chrono::seconds(1)); // Push some more tasks and verify that they're not executed pool.push([&count]() { count += 4; }); pool.push([&count]() { count += 5; }); pool.push([&count]() { count += 6; }); std::cout << "More tasks pushed, count = " << count << "\n";
{ "domain": "codereview.stackexchange", "id": 44613, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 // Resume the thread pool and wait for another short period of time pool.resume(); std::cout << "Thread pool resumed\n"; std::this_thread::sleep_for(std::chrono::seconds(1)); // Verify that all tasks have executed std::cout << "Final count = " << count << "\n"; if (count == 21) { std::cout << "Test passed\n"; } else { std::cout << "Test failed\n"; } } int main() { ThreadPool pool(8); while(1) for (int i = 0 ; i < 2 ; i++) { std::jthread t(thread_func, std::ref(pool)); // Create a new thread and pass in the thread pool by reference } }
{ "domain": "codereview.stackexchange", "id": 44613, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 Answer: Remove thread_id If there is no good reason why the threads in the pool should know their ID, I would omit this. This simplifies construction. Different threads calling suspend() and resume() If a thread calls resume() but it hasn't called suspend(), that is most definitely a programming error. Instead of just ignoring this, throw or assert(). If you do ignore it anyway, I don't see the point of keeping track of suspender_id_. Also, if multiple thread call suspend(), then all but one of those threads will be suspended themselves. Instead of doing that, consider allowing multiple calls to suspend() to succeed, but keep track of how many threads called it, and decrement that count in resume(). Remove isSuspended() Any function which takes a lock, and then only returns some state but does not modify the queue, is most likely wrong. The reason is that the lock is released right before returning, so when the caller looks at the return value, it might no longer reflect the current state of the queue. Any caller relying on the return value will therefore most likely have a race condition. Even if it is used in a safe way (only after calling suspend() in the same thread), what should the caller do if it return false? Busy-loop until it returns true? I think it would be much better if suspend() waits (using condition variables to avoid busy-looping) until there are no active threads anymore before returning. Busy loop when suspending threads If the queue is not empty but suspend_ is true, the worker threads will start busy-looping. This is undesirable. You might want to use condition_ to signal changes in suspension state. Your main() doesn't run multiple threads It looks like you wanted to create multiple threads that push jobs to the job queue in main(), but it only creates one thread at a time. You have to write: while (true) { std::jthread t1(thread_func, std::ref(pool)); std::jthread t2(thread_func, std::ref(pool)); }
{ "domain": "codereview.stackexchange", "id": 44613, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, c++20 Or if you want even more concurrency, create a std::vector<std::jthread>. Naming things The name of the function isSuspended() is not correct. It doesn't return whether the thread pool is suspended, it returns whether there are no active threads. The thread pool might not be suspended, but if the queue is empty your function might return true. Conversely, suspend() could have been called, but if one of the threads is still executing a task, it will return false. A better name would be noActiveTasks(). While most functions and variables have good names, thread_func() is very generic, and doesn't describe what that function does at all. Furthermore, your test code also has a thread_func(), making it more confusing. A better name for ThreadPool::thread_func() might be consume_tasks(). Prefer using verbs for function names and nouns for variables. Related, while threads_ is a reasonable name for the thing keeping track of the threads in a thread pool, it is also a bit generic. You could call it task_consumers, which is more specific.
{ "domain": "codereview.stackexchange", "id": 44613, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, c++20", "url": null }
c++, object-oriented, socket, wrapper Title: SNTPv4 server based on rfc 4330 in C++ Question: Please review my SNTPv4 server based on rfc 4330 I tested running 3 instances of ntp-check.exe from Galleon systems and 1 instance of Microsoft w32tm - w32tm /stripchart /computer: No crash! This is a Linux implementation. The socket layer uses UDP and select. Points of interest: Use of a callback function to separate low level socket handling logic from protocol logic - the NTP protocol. Address class as wrapper for socket API addresses. Some specific concerns: Is there a nicer way to pass the member function than using bind on line 133 in ntp-server.cpp NTP-server code is fairly grungy, any ideas on how to improve. Address.cpp: #include "address.hpp" #include <iostream> #include <iomanip> std::ostream& operator<<(std::ostream& os, const Address& address) { os << "Address family : AF_INET (Internetwork IPv4)\n"; os << "Port : " << ntohs(address.sock_addr_.sin_port) << '\n'; os << "IP address : " << address.get_ip() << std::endl; return os; } Address::Address(const sockaddr_in& sock_address) : sock_addr_({ sock_address }) {} // use * for INADDR_ANY Address::Address(const char* dotted_decimal, const unsigned short port) : sock_addr_({}) { if (!dotted_decimal || strlen(dotted_decimal) == 0 || strcmp(dotted_decimal, "*") == 0) { sock_addr_.sin_addr.s_addr = INADDR_ANY; // bind to all interfaces } else { if (inet_pton(AF_INET, dotted_decimal, &sock_addr_.sin_addr) != 1) { throw std::invalid_argument("invalid IPv4 address"); } } sock_addr_.sin_family = PF_INET; sock_addr_.sin_port = htons(port); } Address::Address(const uint32_t ipv4_address, const unsigned short port) : sock_addr_({}) { sock_addr_.sin_family = PF_INET; sock_addr_.sin_addr.s_addr = ipv4_address; sock_addr_.sin_port = htons(port); } const sockaddr_in* Address::get() const { return &sock_addr_; } size_t Address::size() const { return sizeof sock_addr_; }
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper size_t Address::size() const { return sizeof sock_addr_; } std::string Address::get_ip() const { char buffer[64]; const char* ipv4 = inet_ntop(PF_INET, &sock_addr_.sin_addr, buffer, 64); return ipv4 ? ipv4 : ""; } Address.hpp: /* C++ wrapper for C socket API sockaddr_in */ #ifndef ADDRESS_HPP_ #define ADDRESS_HPP_ #include <string> #include <cstring> #include <cstdint> #include <stdexcept> #include <iostream> #ifdef _WIN32 #include <winsock2.h> // Windows sockets v2 #include <ws2tcpip.h> // WinSock2 Extension, eg inet_pton, inet_ntop, sockaddr_in6 #elif __linux__ || __unix__ #include <arpa/inet.h> #else #error Unsupported platform #endif class Address { public: //! construct from sockaddr_in Address(const sockaddr_in& sock_address); //! construct from 32 bit unsigned integer and a port Address(const uint32_t ipv4_address, const unsigned short port); //! construct from IP address string and port, use * for INADDR_ANY Address(const char* dotted_decimal, const unsigned short port); //! retrieve socket API sockaddr_in const sockaddr_in* get() const; //! get size of sockaddr_in size_t size() const; //! get IP address as string std::string get_ip() const; friend std::ostream& operator<<(std::ostream& os, const Address& address); private: sockaddr_in sock_addr_; }; //! debug print address std::ostream& operator<<(std::ostream& os, const Address& address); #endif // ADDRESS_HPP_ main.cpp: #include <iostream> #include "ntp-server.hpp" int main(int argc, char* argv[]) { std::cout << "Starting SNTPv4 Server\n"; ntp_server server(123); server.run(); } Makefile: CXX=g++ CXXFLAGS=-Wall -std=c++17 PROJECTNAME=ntpserver SOURCES = main.cpp select-server.cpp ntp-server.cpp address.cpp OBJ = $(SOURCES:.cpp=.o) # $@ is target # $^ is pre-requisites - ie $(OBJ) $(PROJECTNAME): $(OBJ) $(CXX) $(LDFLAGS) $^ $(LDLIBS) -o $@ debug: CPPFLAGS += -DDEBUG debug: CXXFLAGS += -g debug: $(PROJECTNAME)
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper debug: CPPFLAGS += -DDEBUG debug: CXXFLAGS += -g debug: $(PROJECTNAME) # $< is name of first pre-requisite %.o: %.c $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $< clean: $(RM) -rf *.o $(PROJECTNAME) ntp-server.cpp: #include "ntp-server.hpp" #include <stdio.h> #include <time.h> /* for time() and ctime() */ #include <sys/time.h> // gettimeofday namespace { /* unix epoch is 1970-01-01 00:00:00 +0000 (UTC) but start of ntp time is 1900-01-01 00:00:00 UTC, so adjust with difference */ const uint32_t NTP_UTIME_DIFF = 2208988800U; /* 1970 - 1900 */ const uint64_t NTP_SCALE_FRAC = 4294967296; // utility function to print an array in hex void printhex (const void *buf, size_t len) { for (size_t i = 0; i < len; i++) { printf ("%02X", ((uint8_t *)buf)[i]); } fputc ('\n', stdout); } /* get timestamp for NTP in LOCAL ENDIAN, in/out arg is a uint32_t[2] array with most significant 32 bit part no. seconds since 1900-01-01 00:00:00 and least significant 32 bit part fractional seconds */ void gettime64(uint32_t ts[]) { struct timeval tv; gettimeofday(&tv, NULL); ts[0] = tv.tv_sec + NTP_UTIME_DIFF; ts[1] = (NTP_SCALE_FRAC * tv.tv_usec) / 1000000UL; } /* get timestamp for NTP in LOCAL ENDIAN, returns uint64_t with most significant 32 bit part no. seconds since 1900-01-01 00:00:00 and least significant 32 bit part fractional seconds */ uint64_t gettime64() { struct timeval tv_unix; gettimeofday(&tv_unix, NULL); uint64_t ntp_secs = tv_unix.tv_sec + NTP_UTIME_DIFF; uint64_t ntp_usecs = (NTP_SCALE_FRAC * tv_unix.tv_usec) / 1000000UL; return (ntp_secs << 32) | ntp_usecs; } // helper to populate an array at start_index with uint32_t void populate_32bit_value(unsigned char* buffer, int start_index, uint32_t value) { uint32_t* p32 = reinterpret_cast<uint32_t*>(&buffer[start_index]); *p32 = value; }
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper /* create the NTP response message to be sent to client Args: recv_buf - array received from NTP client (should be 48 bytes in length) recv_time - array containing time NTP request received send_buf - byte array to be sent to client */ void make_reply(const unsigned char recv_buf[], uint32_t recv_time[], unsigned char* send_buf) { /* LI VN Mode Leap Indicator = 0 Version Number = 4 (SNTPv4) Mode = 4 = server 0x24 == LI=0, version=4 (SNTPv4), mode=4 (server) 00 100 100 */ send_buf[0] = 0x24; /* Stratum = 1 (primary reference). A stratum 1 level NTP server is synchronised by a reference clock, eg in UK the Anthorn Radio Station in Cumbria. (Not true - next project work out how to sync up with radio signal. Typically in a real world scenario, subsidiary ntp servers at lower levels of stratum would sync with a stratum ntp server. */ send_buf[1] = 0x1; // Poll Interval - - we set to max allowable poll interval send_buf[2] = 0x11; // 17 == 2^17 (exponent) // Precision send_buf[3] = 0xFA; // 0xFA == -6 - 2^(-6) == mains clock frequency // *** below are 32 bit values /* Root Delay - total roundtrip delay to primary ref source in seconds set to zero - simplification */ populate_32bit_value(send_buf, 4, 0); /* Root Dispersion - max error due to clock freq tolerance in secs, svr sets set to zero (simplification) */ populate_32bit_value(send_buf, 8, 0); /* Reference Identifier - reference source, LOCL means uncalibrated local clock We must send in network byte order (we assume we built svr little endian) */ uint32_t refid = htonl(('L' << 24) | ('O' << 16) | ('C' << 8) | 'L'); populate_32bit_value(send_buf, 12, refid); // *** below are 64 bit values
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper // *** below are 64 bit values /* Reference Timestamp - time system clock was last set or corrected investigate - if we assume client is requesting every poll interval 2^17 - just simulate what time was back then 2^17 = 131072 */ uint64_t ntp_now = gettime64(); uint32_t p32_seconds_before = htonl((ntp_now >> 32) - 131072); uint32_t p32_frac_seconds_before = htonl(ntp_now & 0xFFFFFFFF); populate_32bit_value(send_buf, 16, p32_seconds_before); populate_32bit_value(send_buf, 20, p32_frac_seconds_before); /* Originate Timestamp: This is the time at which the request departed the client for the server, in 64-bit timestamp format. We can copy value from client request */ memcpy(&send_buf[24], &recv_buf[40], 4); memcpy(&send_buf[28], &recv_buf[44], 4); // Receive Timestamp - get from time rq received by server uint32_t* p32 = reinterpret_cast<uint32_t*>(&send_buf[32]); *p32++ = htonl(recv_time[0]); // seconds part *p32++ = htonl(recv_time[1]); // fraction of seconds part // Transmit Timestamp - re-use ntp_now time obtained above populate_32bit_value(send_buf, 40, htonl(ntp_now >> 32)); populate_32bit_value(send_buf, 44, htonl(ntp_now & 0xFFFFFFFF)); } } // unnamed namespace // is there any way to do this and not have to use bind. It is a little ugly ntp_server::ntp_server(uint16_t port) : udp_server_(port, std::bind(&ntp_server::read_callback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)) { } void ntp_server::run() { udp_server_.run(); } void ntp_server::read_callback(const char* data, const size_t length, const Address& address) { const size_t ntp_msg_size{48}; std::cout << "new data in\n"; printhex(data, length); std::cout << "Client address:\n" << address << std::endl; uint32_t recv_time[2]; gettime64(recv_time); unsigned char send_buf[ntp_msg_size] {}; make_reply(reinterpret_cast<const unsigned char*>(data), recv_time, send_buf);
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper make_reply(reinterpret_cast<const unsigned char*>(data), recv_time, send_buf); std::cout << "data to send:\n"; printhex(send_buf, ntp_msg_size); ssize_t ret; if ( (ret = udp_server_.send(reinterpret_cast<const char*>(send_buf), ntp_msg_size, address)) != ntp_msg_size) { std::cerr << "Error sending response to client: " << ret; perror("sendto"); } } ntp-server.hpp: /* Basic implementation of v4 SNTP server as per: https://www.rfc-editor.org/rfc/rfc4330 Uses udp_server for low level UDP socket communication Separation of socket and ntp handling via passing a callback function to udp server */ #ifndef NTP_SERVER_HPP_ #define NTP_SERVER_HPP_ #include "select-server.hpp" class ntp_server { public: //! initialise ntp_server with server port, defaults to well known NTP port 123 ntp_server(uint16_t port = 123); //! start NTP server void run(); //! callback to handle data received from NTP client void read_callback(const char* data, const size_t length, const Address& address); private: udp_server udp_server_; }; #endif // NTP_SERVER_HPP_ select-server.cpp: #include "select-server.hpp" #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <iostream> udp_server::udp_server(uint16_t port, client_request_callback request_callback) : port_(port), rq_callback_(request_callback ), s_(0) { std::cout << "udp_server will bind to port: " << port_ << std::endl; } udp_server::~udp_server() { if (s_) { close(s_); } } //! start server void udp_server::run() { // create server socket s_ = socket(PF_INET, SOCK_DGRAM, 0); std::cout << "Socket created: " << s_ << "\n";
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper // bind the server address to the socket sockaddr_in server_addr = {}; // AF_INET server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port_); server_addr.sin_addr.s_addr = INADDR_ANY; socklen_t len_inet = sizeof server_addr; int r = bind(s_, reinterpret_cast<sockaddr*>(&server_addr), len_inet); if ( r == -1) { std::cerr << "bind returned: " << r << strerror(errno) << std::endl; exit(1); } // express interest in socket s for read events fd_set rx_set; // read set FD_ZERO(&rx_set); // init int maxfds = s_ + 1; // start the server loop for (;;) { FD_SET(s_, &rx_set); // sample timeout of 2.03 secs timeval tv; // timeout value tv.tv_sec = 2; tv.tv_usec = 30000; int n = select(maxfds, &rx_set, NULL, NULL, &tv); if ( n == -1) { std::cerr << "select returned: " << n << strerror(errno) << std::endl; exit(1); } else if ( !n ) { // select timeout continue; } // if udp socket is readable receive the message. if (FD_ISSET(s_, &rx_set)) { sockaddr_in sock_address {}; unsigned char buf[48] {}; // I/O buffer socklen_t len_client = sizeof sock_address; // retrieve data received ssize_t recbytes = recvfrom(s_, buf, sizeof(buf), 0, reinterpret_cast<sockaddr*>(&sock_address), &len_client); if (recbytes <= 0) { std::cerr << "recvfrom returned: " << recbytes << std::endl; continue; } // Create an address from client_address and pass to callback function with data Address client_address(sock_address); rq_callback_(reinterpret_cast<const char*>(buf), recbytes, client_address); FD_CLR(s_, &rx_set); } } // for loop } //! returns number of bytes successfully sent ssize_t udp_server::send(const char* data, const size_t length, const Address& address) { return sendto(s_, data, length, 0, (const sockaddr*)address.get(), address.size()); }
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper select-server.hpp: /* Basic implementation of UDP socket server using select User provides callback function to handle client requests */ #ifndef SELECT_SERVER__ #define SELECT_SERVER__ #include <functional> #include <cstdint> #include "address.hpp" // callback signature for user provided function for handling request data from clients using client_request_callback = std::function<void(const char*, const size_t, const Address&)>; class udp_server { public: //! construct with port and callback for custom data handler udp_server(uint16_t port, client_request_callback request_callback); //! destructor virtual ~udp_server(); //! call run to start server void run(); //! send returns number of bytes successfully sent ssize_t send(const char* data, const size_t length, const Address& address); private: uint16_t port_; client_request_callback rq_callback_; int s_; }; #endif // SELECT_SERVER__
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper Answer: General It's better to present the files in a more logical order - headers before implementation files, and lower-level utilities before the higher-level code that depends on them. Address.cpp The operator<<() shouldn't be flushing os - that's really something that should be decided by the caller rather than imposed at this level. The constructors look odd with ({…}) where plain {…} would be sufficient for the initializers. There's no declaration for strlen or strcmp - I think we should be including <cstring> and using std::strlen and std::strcmp here. Or better, ditch the C-style string handling and use a std::string_view instead. Address.hpp This header has unnecessary includes for <cstring> and <stdexcept>, and can be slimmed greatly by using <iosfwd> instead of <iostream>. std::size_t is misspelt (this identifier lives in the std namespace). The one-argument constructor should be explicit. The get() function is lacking any indication of the ownership and lifetime of the returned pointer - prefer not to return pointers unless it's unavoidable. The name is a bit vague, too. main.cpp We could simplify the makefile if we called this ntpserver.cpp instead (so we could use the default %.o rule). argc and argv are unused - perhaps we should be using the int main() signature instead. It probably makes more sense to use std::clog for the status message than std::cout. Makefile I recommend CFLAGS += -Wextra at least, and usually some more diagnostic options (-Wconversion highlights a few places in this program). That will greatly improve code quality (assuming you act on the warnings, of course). SOURCES appears to be used only to define OBJECTS, so perhaps omit that and define OBJECTS only. The comments in this file are useless. They just tell us what every makefile author already knows, and nothing about why the Makefile is written as it is.
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }
c++, object-oriented, socket, wrapper The debug target is problematic. When invoked, it will rebuild the modified sources using different compiler flags, likely resulting in a binary made with a mix of debug and non-debug flags. Much better to have a separate build with debug (we usually do that by building in a separate directory from the same sources, using VPATH). %.o: %.c target is pointless, since it effectively duplicates the built-in rule for this. We're completely missing the dependencies that object files have on the headers. I recommend getting g++ to generate dependency files by supplying one of the -M options. clean target doesn't need -r as none of its arguments should be a directory. And it doesn't need -f because that's included in the definition of $(RM). .PHONY and .DELETE_ON_ERROR targets are missing. ntp-server.cpp Why are we including the deprecated C header <stdio.h> instead of the C++ version <cstdio>? The comment for including <time.h> says we need it for time() and ctime(), but we never use those - either drop it, or change to <ctime> and fix the comment. No definition of uint8_t, uint32_t and uint64_t - presumably we intended to include <cstdint> and use the corresponding names from std. printhex() does more than its comment says, as it writes an additional newline after printing the hex content of the array. The two implementations of gettime64() have quite a lot of duplicated code. It would be better for the second to simply call the first: uint64_t gettime64() { uint32_t ts[2]; gettime64(ts); return (ts[0] << 32) + ts[1]; }
{ "domain": "codereview.stackexchange", "id": 44614, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, object-oriented, socket, wrapper", "url": null }