text
stringlengths
1
2.12k
source
dict
c++, template-meta-programming, variadic Title: C++ variardic universal template for unknown types, used to handle multiple network protocols Question: I am creating a template function with variardic arguments, to handle a specific classes that have some interface, method, member or whatever is specialized in a specialization area. However I came to a solution to handle even types that are not supported, thus avoid exceptions, polymorphism, virtual functions, RTTI, etc. I'd like to hear a suggestions and also a peak to the implementation. The example below shows a simple parsing of known network protocols (pseudo logic), that can handle all relevant types, if not specialized classes are passed, they shall be omitted as it happens. #include <iostream> #include <cstring> template<typename T> struct is_validator { static const bool value = false; }; struct Null { Null(const std::string& res[[maybe_unused]]) {} bool valid() const { return false; } }; struct RtpRFC { std::string m_res; RtpRFC(const std::string& res) : m_res{res}{} bool valid() const { if (!strcmp(m_res.c_str(), "rtp")) return true; return false; } }; struct RtspRFC { public: std::string m_res; RtspRFC(const std::string& res) : m_res{res}{} bool valid() const { if (!strcmp(m_res.c_str(),"rtsp")) return true; return false; } }; struct StunRFC { std::string m_res; StunRFC(const std::string& res) : m_res{res}{} bool valid() const { if (!strcmp("stun", m_res.c_str())) return true; return false; } }; struct NonValid { }; template<> struct is_validator<Null> { static const bool value = true; }; template<> struct is_validator<RtpRFC> { static const bool value = true; }; template<> struct is_validator<StunRFC> { static const bool value = true; }; template<> struct is_validator<RtspRFC> { static const bool value = true; };
{ "domain": "codereview.stackexchange", "id": 43267, "lm_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++, template-meta-programming, variadic", "url": null }
c++, template-meta-programming, variadic /*terminator*/ bool VParse(...) { return false; } template <class T, //typename std::enable_if<is_validator<T>::value>::type, typename...ARgs> bool VParse(T type, ARgs&&... FArgs) { if constexpr (is_validator<T>::value) { if (type.valid()) { return true; } else { return VParse(std::forward<ARgs>(FArgs)...); } } return VParse(std::forward<ARgs>(FArgs)...); } int main(void) { std::string ret{}; const std::string someNetworkData[10] = { "stun", "rtp", "stun", "stun", "rtsp", "rtp", "http", "http2", "udp" }; for(int i=0; i < 10; i++) { auto res = someNetworkData[i]; bool valid = VParse( 10, "test", NonValid{}, RtpRFC{res} , RtspRFC{res}, StunRFC{res}, Null{res}, //dummies Null{res}, Null{res} ); if (valid) { ret += res; ret += "|"; } } std::cout << ret; return 0; } Answer: Avoid C string functions if possible There is no need to use strcmp(), especially not if you are working with std::strings to begin with. For example, you can just write: bool valid() const { return m_res == "rtp"; } Also make sure then to #include <string> instead of #include <cstring>. Simplifying the code Since your code needs C++17 anyway, you can simplify VParse() significantly by using fold expressions and a helper function, like so: template <typename T> bool is_valid(T&& type) { if constexpr(is_validator<T>::value) { return type.valid(); } return false; } template <typename... Args> bool VParse(Args&&... args) { return (is_valid(std::forward<Args>(args)) || ...); }
{ "domain": "codereview.stackexchange", "id": 43267, "lm_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++, template-meta-programming, variadic", "url": null }
c++, template-meta-programming, variadic This splits the code into one self-contained part that checks a single argument, and another part that just iterates over all arguments. Should you allow types that are not validators? I think it's risky to have your function check whether is_validator<T>::value is a valid expression, and ignoring it if not. It's quite easy to make a typo somewhere and turn a valid validator into something that's not, and your code will then explicitly allow that, instead of letting the compiler catch the error. So I would recommend using SFINAE (like the one you commented out), or concepts if you can use C++20, to limit the accepted types, unless you really have a situation where it would be better to allow arbitrary types and ignore those that you can't use. Alternatives I assume the above code is just a toy example, but consider what happens if the list of validators grows a lot more than you have in your example. VParse() will have to call each validator in turn before one returns true. This can be expensive. If it is just matching strings, then you could just use a std::unordered_set<std::string> of valid types and check if a given protocol name is in that set.
{ "domain": "codereview.stackexchange", "id": 43267, "lm_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++, template-meta-programming, variadic", "url": null }
vba, excel Title: Identify Anonymous orders in BOM list & update accordingly, execute time is taking very long Question: Right here, I'm trying to identify whether or not the demand order in my multi-level BOM list is made by an anonymous customer and then update accordingly. -In laymens term, I'm checking if an item in the "BOM list sheet" is an anonymous order. If it is, match the item to the same item in "other sheet" & check whether there is an allocated supply. If no supply allocated, update the "other sheet" accordingly as anonymous, else do nothing. But I'm using arrays instead of worksheets. aRow & bRow refers to current row. value means current column. = vbNullString means no supply allocated For aRow = 2 To UBound(mArray, 1) For bRow = LBound(dArray, 1) + 1 To UBound(dArray, 1) - 1 If dArray(bRow, 15) = "issue SFC-anonymous" Or dArray(bRow, 15) = "issue PRP-anonymous" Then If mArray(aRow, 1) = dArray(bRow, 1) And mArray(aRow, 12) = vbNullString Then mArray(aRow, 12) = "Anonymous" End If ElseIf dArray(bRow, 15) = "add INV-PUR" Or dArray(bRow, 15) = "add INV-SFC" Then If mArray(aRow, 1) = dArray(bRow, 1) And mArray(aRow, 12) = vbNullString Then mArray(aRow, 12) = "Anonymous" End If End If Next bRow Next aRow This code is working, but the time it takes to execute is taking about 4-5 minutes which is very long, I assume one reason for this might be because I'm working with string values. Any advice/criticism to help me improve the code is highly appreciated. Answer: The code cycles thru the remainder of dArray even after meeting the logic condition for setting an mArray element to 'Anonymous'. This is inefficient since replacing the vbNullString once is sufficient. Adding an Exit For statement after replacing the vbNullString value with 'Anonymous' will remove the inefficiency.
{ "domain": "codereview.stackexchange", "id": 43268, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, excel", "url": null }
vba, excel Regardless of the string comparisons, the condition for replacing the mArray value depends directly on the condition that mArray(aRow,12) = vbNullString. This is known prior to entering the dArray loop. Check for this condition and skip iterating thru the nested loop altogether if the condition is not met. Regardless of the string comparisons, the condition for replacing the mArray value depends directly on mArray(aRow, 1) = dArray(bRow, 1). This is known the immediately after entering the dArray loop. If the condition is not met, skip any other checks in the iteration. Also, it looks like there is no reason to have an If and ElseIf based on the code fragment provided. Below is the code with the changes described above. Declarations have been added to make the fragment compile. Sub Test() Dim aRow As Long Dim bRow As Long Dim dArray As Variant Dim mArray As Variant Dim toCheckFor As String For aRow = 2 To UBound(mArray, 1) If Not mArray(aRow, 12) = vbNullString Then For bRow = LBound(dArray, 1) + 1 To UBound(dArray, 1) - 1 If mArray(aRow, 1) = dArray(bRow, 1) Then toCheckFor = dArray(bRow, 15) If toCheckFor = "issue SFC-anonymous" _ Or toCheckFor = "issue PRP-anonymous" _ Or toCheckFor = "add INV-PUR" _ Or toCheckFor = "add INV-SFC" Then mArray(aRow, 12) = "Anonymous" Exit For End If End If Next bRow End If Next aRow End Sub
{ "domain": "codereview.stackexchange", "id": 43268, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, excel", "url": null }
vba, excel End Sub The changes above should improve performance. However, the code contains both nested loops and If statements. This makes the code very hard to read/understand and maintain. The code below eliminates the nested loop, improves readability, and will likely have an unnoticeable impact on performance. Sub Test() Dim aRow As Long Dim dArray As Variant Dim mArray As Variant For aRow = 2 To UBound(mArray, 1) If Not mArray(aRow, 12) = vbNullString Then If MeetsConditionsToSetMArrayValue(dArray, mArray, aRow) Then mArray(aRow, 12) = "Anonymous" Exit For End If End If Next aRow End Sub Private Function MeetsConditionsToSetMArrayValue(ByRef dArray As Variant, _ ByRef mArray As Variant, ByVal aRow As Long) As Boolean Dim bRow As Long For bRow = LBound(dArray, 1) + 1 To UBound(dArray, 1) - 1 If mArray(aRow, 1) = dArray(bRow, 1) Then If ValueMeetsReplacementCriteria(dArray(bRow, 15)) Then MeetsConditionsToSetMArrayValue = True Exit Function End If End If Next bRow MeetsConditionsToSetMArrayValue = False End Function Private Function ValueMeetsReplacementCriteria(ByVal valueToCheck As String) As Boolean ValueMeetsReplacementCriteria = _ valueToCheck = "issue SFC-anonymous" _ Or valueToCheck = "issue PRP-anonymous" _ Or valueToCheck = "add INV-PUR" _ Or valueToCheck = "add INV-SFC" End Function
{ "domain": "codereview.stackexchange", "id": 43268, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "vba, excel", "url": null }
multithreading, sorting, rust, thread-safety Title: Multithreaded bogosort in Rust Question: For some quick context, I'm fairly new to Rust and decided to give myself a difficult-but-attainable task of implementing a sorting algorithm. I chose bogosort (or stupid-sort, shuffle-sort, whatever your preference is) and got it working pretty quickly. I then decided to make it faster by threading it lol. This works pretty well and I can definitely tell there's a performance improvement. However I want to make sure I'm implementing it decently. My biggest concern is making sure all of the other threads die when one of them finishes (i.e. "sorted" the vector). The way I have it implemented below uses a boolean Mutex within an Arc. My understanding is that this way allows every thread to have access to it but also allows it to be modified safely. I use this Mutex as the condition in my while loop. Once any thread "sorts" the vector, it will change the Mutex - effectively telling every other thread to stop. My question is, have I implemented this correctly? Am I stopping the threads correctly? And is the best way to do it? Any feedback (including constructively roasting my code) is immensely appreciated as I'd like to learn as much as I can. use rand::prelude::*; use rand_chacha::ChaCha8Rng; use rand::thread_rng; use std::time::Instant; use std::thread; use std::sync::mpsc; use std::sync::{Mutex,Arc}; const ELEMENT_COUNT: i32 = 5; const THREAD_COUNT: i32 = 5; fn main() { // Initialize a vector with <ELEMENT_COUNT> random numbers from 1-100 let mut rng = ChaCha8Rng::seed_from_u64(31); let mut vec: Vec<i32> = (0..ELEMENT_COUNT).collect(); for x in &mut vec { *x = rng.gen_range(1..100); }
{ "domain": "codereview.stackexchange", "id": 43269, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, sorting, rust, thread-safety", "url": null }
multithreading, sorting, rust, thread-safety // Start a counter to track performance let clock = Instant::now(); let (tx, rx) = mpsc::channel(); let mut handles = vec![]; let done = Arc::new(Mutex::new(true)); // Create a bunch of threads for _i in 0..THREAD_COUNT { let tx = tx.clone(); let done_shared = Arc::clone(&done); let mut vec = Vec::clone(&vec); let handle = thread::spawn(move || { 't_outer: while *done_shared.lock().unwrap() { vec.shuffle(&mut thread_rng()); // println!("\nthread: {}\nvar: {:?}\n", i, *done_shared); let mut counter = 1; // Check if it's sorted 't_inner: for x in &vec { // If the xth element is greater than the element after it: it's not sorted, so give up if x > &vec[counter] { break 't_inner; } counter = counter + 1; // But, if this counter finds itself equal to the length of our vector, then we must be sorted if counter == vec.len() { tx.send(clock.elapsed()).unwrap(); // Set the while loop condition to false (effectively killing every other thread) *done_shared.lock().unwrap() = false; break 't_outer; } } } }); // handle.join(); handles.push(handle); } let b = rx.recv().unwrap(); println!("Took this long: {:?}", b); // Join the handles in the vector for i in handles { i.join().unwrap(); } } Answer: List of improvements I would make:
{ "domain": "codereview.stackexchange", "id": 43269, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, sorting, rust, thread-safety", "url": null }
multithreading, sorting, rust, thread-safety I'm uncertain why you use Arc::clone(...), just use .clone() directly. Same for Vec::clone(). The initialization of the vector: you initialize it with an iterator, collect, and then iterate manually in a C-style for loop. Instead, just use the iterator you already have to iterate ;). This can be done with either .map(), or with the repeat().take() pattern. Name your variables more meaningful than tx and rx and vec. Don't name them by what their type is, but by what they represent. Like in the initialization, the join_handles vector could be an iterator instead. It doesn't make much of a difference, tbh, but leaves the vector to be non-mutable afterwards. I like it more with iterators, but this one is probably personal taste. Using a Arc<Mutex<bool>> to signal cancellation is kind of fine, but is VERY slow compared to the compiler-optimized Arc<AtomicBool>, which does the exact same thing. I think this is an important point to optimize, because that bool is the choke point of your otherwise embarrassingly parallel problem. I'm uncertain how much of a difference it makes, but I'd probably cache the thread_rng instead of querying it every iteration. The fact that the loops terminate when done becomes false is semantically confusing, I'd invert it The way you iterate through the vector to check if it's sorted is quite confusing. I think considering counter == data.len() the special case of the loop is confusing, and I'd make that the default case. The special case would then be that it's unsorted. Either way, the entire loop is written in a C/C++ style. In proper Rust style i'd rewrite it to be more functional, using iterators. The main reason is that direct array access via [] operator is discouraged as much as possible, as it is slow (rust does an out-of-range check every time) and error prone. To get the true performance potential of rust, you want to use iterators instead.
{ "domain": "codereview.stackexchange", "id": 43269, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, sorting, rust, thread-safety", "url": null }
multithreading, sorting, rust, thread-safety Usually, I'd simply use the .sorted() operation of the vector. But as this is an exercise, you probably want to implement it yourself, so here I demonstrate you how it would be implemented with iterators. Again, iterator has a .is_sorted() operation, which we will ignore. This is the point where I'd usually pull in itertools, as the .tuple_windows() function is exactly what you would need here, to check two consecutive numbers. But if you want to only use normal Rust iterator operations, I would go with creating something similar myself. You can iterate over the vector multiple times in parallel, with an offset of one. You can use this to query pairs of numbers, which you can then check for order. Then you can iterate until you find the first pair that isn't ordered correctly. Performance wise this is comparable or even faster than doing it without iterators, so no worries. Use usize for size-related numbers.
{ "domain": "codereview.stackexchange", "id": 43269, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, sorting, rust, thread-safety", "url": null }
multithreading, sorting, rust, thread-safety Many words, let's see code! Here's my attempt to improve your code: use rand::prelude::*; use rand::thread_rng; use rand_chacha::ChaCha8Rng; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::sync::mpsc; use std::sync::Arc; use std::thread; use std::time::Instant; const ELEMENT_COUNT: usize = 5; const THREAD_COUNT: usize = 5; fn main() { // Initialize a vector with <ELEMENT_COUNT> random numbers from 1-100 let mut rng = ChaCha8Rng::seed_from_u64(31); let data_to_sort: Vec<i32> = std::iter::repeat_with(|| rng.gen_range(1..100)) .take(ELEMENT_COUNT) .collect(); // Start a counter to track performance let clock = Instant::now(); let (set_duration, duration) = mpsc::channel(); let done = Arc::new(AtomicBool::new(false)); // Create a bunch of threads let handles = (0..THREAD_COUNT) .map(|_| { let set_duration = set_duration.clone(); let done = done.clone(); let mut data = data_to_sort.clone(); thread::spawn(move || { let mut rng = thread_rng(); while !done.load(Ordering::Acquire) { data.shuffle(&mut rng); let elements_left = data.iter(); let elements_right = data.iter().skip(1); let sorted = elements_left .zip(elements_right) .all(|(left, right)| left <= right); if sorted { set_duration.send(clock.elapsed()).unwrap(); // Set the done condition to true (effectively killing every other thread) done.store(true, Ordering::Release); break; } } }) }) .collect::<Vec<_>>(); let b = duration.recv().unwrap(); println!("Took this long: {:?}", b);
{ "domain": "codereview.stackexchange", "id": 43269, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, sorting, rust, thread-safety", "url": null }
multithreading, sorting, rust, thread-safety let b = duration.recv().unwrap(); println!("Took this long: {:?}", b); // Join the handles in the vector for i in handles { i.join().unwrap(); } }
{ "domain": "codereview.stackexchange", "id": 43269, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "multithreading, sorting, rust, thread-safety", "url": null }
c, stack Title: Stack implementation in C programming Language Question: I have tried to implement a Stack and associated functions in C, in order to understand the data structure better. Just wanted to know what do you think about my code overall. Furthermore, I am using 0 as a value to set "empty section of the stack", and I know this is ambiguous - any suggestion on how to improve that aspect or anything else in the code? /*Data Structure: Stack*/ #include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> struct stack{ //Data_Strucure: Stack of intgers int *stack; int size_of_stack; int elem_in_stack; }; struct stack creat_stack(unsigned int); int push(struct stack *, int); int pop(struct stack *); int empty(struct stack *); int peek(struct stack *); void print_the_stack(struct stack); int main(int argc, char *argv[]){ int elem, ret; struct stack new_stack = creat_stack(5); for(int i = 0, elem = 5; i < new_stack.size_of_stack; i++) if(push(&new_stack, elem--) == 1) fprintf(stderr, "Unable to allocate more elements into the stack."); print_the_stack(new_stack); ret = pop(&new_stack); printf("[POP] -> %d\n", ret); elem = 10; if(push(&new_stack, elem) == 1) fprintf(stderr, "Unable to allocate '%d' into the stack. No more space avaible.\n", elem); print_the_stack(new_stack); if((ret = peek(&new_stack)) == 1) fprintf(stderr, "Stack is empty"); printf("[PEEK] -> %d\n", ret); printf("[EMPTYING]...\n"); empty(&new_stack); print_the_stack(new_stack); } struct stack creat_stack(unsigned int size){ struct stack tmp; if((tmp.stack = malloc(sizeof(int) * size)) == NULL){ fprintf(stderr, "Unable to allocate memory for the Stack.\n"); exit(1); } tmp.size_of_stack = size; tmp.elem_in_stack = 0; for(int i = 0; i < tmp.size_of_stack; i++) tmp.stack[i] = 0; return tmp; }
{ "domain": "codereview.stackexchange", "id": 43270, "lm_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, stack", "url": null }
c, stack for(int i = 0; i < tmp.size_of_stack; i++) tmp.stack[i] = 0; return tmp; } int push(struct stack *stack, int nw_elem){ int pos = stack->size_of_stack - stack->elem_in_stack; if(stack->elem_in_stack == stack->size_of_stack) return 1; stack->stack[pos - 1] = nw_elem; stack->elem_in_stack++; } int pop(struct stack *stack){ int ret; if(stack->elem_in_stack > 0){ int pos = stack->size_of_stack - stack->elem_in_stack; ret = stack->stack[pos]; stack->elem_in_stack--; stack->stack[pos] = 0; return ret; } fprintf(stderr, "Stack is empty\n"); exit(1); } int empty(struct stack *stack){ for(int i = 0; i < stack->size_of_stack; i++) stack->stack[i] = 0; stack->size_of_stack = 0; stack->elem_in_stack = 0; } int peek(struct stack *stack){ int ret; if(stack->elem_in_stack > 0){ int pos = stack->size_of_stack - stack->elem_in_stack; return stack->stack[pos]; } else return 1; } void print_the_stack(struct stack stack){ printf("[CURRENT STACK STATE] -> { "); for(int i = 0; i < stack.size_of_stack; i++) printf("%d ", stack.stack[i]); printf("}\n"); } Plus, let me know if the code runs on your machine. On other implementation try, that was the major problem. Thanks in advance for any useful help Answer: Advice 1 time.h is not used. Remove it. Same for string.h. Advice 2 struct stack { //Data_Strucure: Stack of intgers int* stack; int size_of_stack; int elem_in_stack; }; Just declare (and rename the fields) as typedef struct stack { int* storage_array; size_t size; size_t capacity; } stack;
{ "domain": "codereview.stackexchange", "id": 43270, "lm_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, stack", "url": null }
c, stack That way, you don't have to write always struct stack* st; stack* st will do nicely. Since pop, push, etc., belong to the stack, I suggest you add the stack_ prefix to all the relevant stack operations: stack_pop, stack_push, etc. This is in order to avoid possible name clashes in projects where a programmer wants to use, say, priority queue functions that have similar names. Advice 3 I suggest you arrange your stack as a header file with all the function declarations, and an implementation file including the header file and providing the function definitions. Advice 4 You can easily extend your design to resize the storage array in order to allow (virtually) any number of int elements in your stack: on push, if the storage array is already filled, extend the storage array capacity by a factor \$q > 1\$. That way, the running time complexity of push will remain amortized \$\Theta(1)\$ regardless the fact that on full storage array you have to run the operation in \$\Theta(N)\$. Alternative implementation All in all, I had this in mind: cstack.h #ifndef COM_YOURCOMPANY_UTIL_STACK_H #define COM_YOURCOMPANY_UTIL_STACK_H typedef struct stack { int* storage_array; size_t size; size_t capacity; } stack; stack* stack_creat(); void stack_push(stack*, int); int stack_pop(stack*); int stack_empty(stack*); int stack_peek(stack*); void stack_print(stack*); #endif cstack.c #include "cstack.h" #include <stdlib.h> static const MINIMUM_STORAGE_ARRAY_CAPACITY = 4; stack* stack_creat() { stack* s = (stack*)malloc(sizeof(*s)); if ((s->storage_array = calloc(MINIMUM_STORAGE_ARRAY_CAPACITY, sizeof(int))) == NULL) { perror("Unable to allocate memory for the Stack.\n"); exit(EXIT_FAILURE); } s->size = 0; s->capacity = MINIMUM_STORAGE_ARRAY_CAPACITY; return s; }
{ "domain": "codereview.stackexchange", "id": 43270, "lm_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, stack", "url": null }
c, stack s->size = 0; s->capacity = MINIMUM_STORAGE_ARRAY_CAPACITY; return s; } static void stack_ensure_capacity_before_push(stack* s) { if (s->size == s->capacity) { s->storage_array = realloc(s->storage_array, sizeof(int) * (s->capacity *= 2)); } } static void stack_contract_after_pop(stack* s) { if (s->size * 4 <= s->capacity && s->capacity > 2 * MINIMUM_STORAGE_ARRAY_CAPACITY) { s->storage_array = realloc(s->storage_array, s->capacity /= 4); } } void stack_push(stack* s, int element) { stack_ensure_capacity_before_push(s); s->storage_array[s->size++] = element; } int stack_pop(stack* s) { int ret; if (s->size == 0) { perror("Popping from empty stack."); exit(EXIT_FAILURE); } ret = s->storage_array[--s->size]; stack_contract_after_pop(s); return ret; } int stack_empty(stack* s) { s->size = 0; stack_contract_after_pop(s); } int stack_peek(stack* s) { if (s->size == 0) { perror("Peeking from empty stack."); exit(EXIT_FAILURE); } return s->storage_array[s->size - 1]; } void stack_print(stack* s) { printf("[CURRENT STACK STATE] -> { "); for (int i = 0; i < s->size; i++) printf("%d ", s->storage_array[i]); printf("}\n"); } main.c #include "cstack.h" #include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { int elem, ret; stack* s = stack_creat(); for (int i = 0, elem = 5; i < 5; i++) stack_push(s, elem--); stack_print(s); ret = stack_pop(s); printf("[POP] -> %d\n", ret); elem = 10; stack_push(s, elem); stack_print(s); printf("[PEEK] -> %d\n", stack_peek(s)); printf("[EMPTYING]...\n"); stack_empty(s); stack_print(s); } Hope that helps.
{ "domain": "codereview.stackexchange", "id": 43270, "lm_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, stack", "url": null }
python, numpy Title: Extract all elements of array with the given list of coordinates Question: I have to extract all elements of array with the given list of coordinates and insert into 2*298808 as position given in while loop How can I compress the code even more? def arr_func(arr,selected_pixels_list): rows = 2 m = 0 n = 0 i =0 #Calculate the number of pixels selected length_of_the_list = len(selected_pixels_list) length_of_the_list = int(length_of_the_list/4)*4 cols = int(length_of_the_list/2) result_arr = np.zeros((rows,cols)) while(i<length_of_the_list): result_arr[m,n] = arr[selected_pixels_list[i]] result_arr[m,n+1] = arr[selected_pixels_list[i+1]] result_arr[m+1,n] = arr[selected_pixels_list[i+2]] result_arr[m+1,n+1] = arr[selected_pixels_list[i+3]] i = i+4 m = 0 n = n+2 coordinate_data_list return result_arr
{ "domain": "codereview.stackexchange", "id": 43271, "lm_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, numpy", "url": null }
python, numpy Answer: Your code is managing a lot of variables and implementing some moderately complex index logic. Sometimes that's necessary, but sometimes it indicates that you've walked down an overly complex pathway. In the rest of this discussion, I'll try to offer some intuition for building up a simpler approach. We want to rearrange data into a list of two lists. As I understand things, our goal is sketched in the partial code below. For discussion purposes, I've skipped the numpy part. Also note that I've simplified some of the variable names (your current names strike me as excessively verbose in some cases). Finally, I don't want to implement any index-based logic. If possible, I just want to iterate over pixels. Note the top-down problem-solving strategy: we write the top-level code we want to have even though we don't know exactly how to achieve some of the details yet. def arr_func(arr, pixels): result = [[], []] for p in pixels: # Get the value of arr[p] and stick it in the right spot # inside result. Specifically, we want to add 2 values to the # first inner list, then add 2 values to the second inner list, # toggling back and forth. ... return result How do we toggle back and forth? To achieve the unusual toggling we can use itertools.cycle, which creates an iterable representing an infinite cycle over some other iterable -- in our case, the iterable (0, 0, 1, 1), which is exactly how we need to toggle between the inner lists. from itertools import cycle def arr_func(arr, pixels): result = [[], []] indexes = cycle((0, 0, 1, 1)) for p in pixels: result[next(indexes)].append(arr[p]) return result Next steps. (1) Better names: give arr and arr_func substantive variable names, if possible. (2) There might be a sneaky way to rearrange the data entirely in numpy, so another reviewer might offer even better guidance.
{ "domain": "codereview.stackexchange", "id": 43271, "lm_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, numpy", "url": null }
python, python-3.x, regex, pandas Title: Regex pattern matching to generate pandas multi index
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas Question: Mostly just looking for a review of my regex and implementation of capture groups. its something I've been working to improve. The indexes have somewhat of a pattern to them of being.... (<level - not at surface>, <parameter>, <(unit) - not on every parameter>) indexs
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas indexs = ('Sfc Prs(mb)', 'Mean SLP (mb)', 'Altimeter (in. Hg)', 'Press Alt (ft)', 'Density Alt (ft)', '2 m agl Tmp (K)', '2 m agl Temp-D (K)', '2 m agl Dpt (K)', '2 m agl WBT (K)', 'Convect. Temp (K)', 'Heat Index (F)', 'Wind Chill (F)', 'FITS (F)', '2 m agl RH (%)', '10 m agl Dir', '10 m agl Spd (kt)', 'X-Wind Spd (kt)', 'NonCv Gust Dir', 'NonCv Gust Spd(kt)', '600m AGL Spd (kt)', '600m AGL Dir', 'LLWS Prob (%)', 'Panofsky Index', 'Max Turbc Blw 10K', '3hr Precip (in)', '3hr ConvPrp (in)', 'NonCv Precip Type', '12 Hour Rain (in)', '12 Snow Accum (in)', '24 Snow Accum (in)', 'Precip Water (in)', 'Fog Point. Temp(K)', 'Fog Threat', 'Fog Stability', 'X-Over Temp (K)', 'X-Over Fog (%)', 'Fog Probability(%)', 'DTA Visibility(sm)', 'Visibility (sm)', 'SFC LCL Temp (K)', 'SFC LCL Press (mb)', 'SFC LCL Height (m)', 'ML-CCL Temp (K)', 'ML-CCL Press (mb)', 'ML-CCL Height (m)', 'Cloud Base1(100ft)', 'Cloud Cover1(oct)', 'Cloud Base2(100ft)', 'Cloud Cover2(oct)', 'Cloud Base3(100ft)', 'Cloud Cover3(oct)', 'Cloud Base4(100ft)', 'Cloud Cover4(oct)', 'Cloud Base5(100ft)', 'Cloud Cover5(oct)', 'Lowest Cig(100ft)', 'Total Clouds(oct)', 'Max Icing Blw 10K', 'Sfc CAPE (J/kg)', 'Sfc CINH (J/kg)', 'Trop Height (m)', 'Trop Press (mb)', 'Trop Temp(K)', '1000-500 THKNS (m)', '1000-700 THKNS (m)', '1000-850 THKNS (m)', '850-700 THKNS (m)', '850-500 THKNS (m)', '0C Height (m)', 'Freezing Level (m)', 'Freezing Press(mb)', '-20C Height (m)', '-20C Pressure(mb)', 'Wet-Bulb Zero (m)', 'Prob FZRA (%)', 'Prob PL (%)', 'Prob MIX (%)', 'Prob SN (%)', 'Prob RA (%)', 'Prob RASN (%)', 'Prob Any Precip(%)', 'TSTM Flag (WRF)', 'MU Level (mb)', 'MU Temperature (K)', 'Parcel Temp (K)', 'MU Height (m)', 'ML CAPE (J/kg)', 'ML CINH (J/kg)', 'MU CAPE (J/kg)', 'MU CINH (J/kg)', 'DCAPE (J/kg)', 'MU-LCL Temp (K)', 'MU-LCL Press (mb)', 'MU-LCL Height (m)', 'MU-LCL P-Temp (K)', 'MU LFC (m)', 'MU LFC Prs (mb)', 'MU LFC Tmp(K)', 'MU EQ LEVEL (m)', 'MU EQ LVL Prs(mb)', 'MU EQ LVL Tmp(K)', 'Max Parcel Hgt (m)', 'Max
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas LFC Tmp(K)', 'MU EQ LEVEL (m)', 'MU EQ LVL Prs(mb)', 'MU EQ LVL Tmp(K)', 'Max Parcel Hgt (m)', 'Max Parcel Prs(mb)', 'Max Parcel Tmp (K)', 'Lightning Prob (%)', 'MU LI (K)', 'MU TTI (K)', 'MU KI (K)', 'SSI (K)', 'MU KO (K)', 'MU THI (K)', 'Lid Strength (K)', 'Cap Break (%)', 'TSTM Prob (%)', 'FM Hail Index (in)', 'RAM Hail Index(in)', 'VIL-D Hail (in)', 'Sig Hail Parameter', 'Max Hail Size (in)', 'Hail Size (in)', 'Tornado Prob (%)', 'Conv Gust Spd(kt)', 'T1 Gust Index (kt)', 'T2 Gust Index (kt)', 'WINDEX (kt)', 'WMSI-MDPI (kt)', 'Snyder Gusts (kt)', 'VIL-D Gusts (kt)', '0-1KM SRH (m2/s2)', '0-2KM SRH (m2/s2)', '0-3KM SRH (m2/s2)', 'EFF SRH (m2/s2)', '6KM SHEAR (m/s)', 'Sig Torn Parameter', '0-4KM VGP', '0-1KM EHI', 'BRN', 'Moist Cnv(g/kg/hr)', 'ThetaE Adv (K/hr)', 'UL Div (1/s)', 'SWEAT Index', 'Dry Microburst', '1000mb GPH (m)', '1000mb GPH DVal(m)', '1000mb Temp (K)', '1000mb Temp DVal(K)', '1000mb Dewpt (K)', '1000mb RH (%)', '1000mb Parcel Temp', '1000mb Theta-E (K)', '1000mb Dir', '1000mb Speed(kt)', '1000mb Clouds(%)', '1000mb FL-Vis (sm)', '1000mb Mixing Ratio', '1000mb CWMR (g/kg)', '1000mb Icing Type', '1000mb Turbulence', '1000mb VVS (-ub/s)', '975mb GPH (m)', '975mb GPH DVal(m)', '975mb Temp (K)', '975mb Temp DVal(K)', '975mb Dewpt (K)', '975mb RH (%)', '975mb Parcel Temp', '975mb Theta-E (K)', '975mb Dir', '975mb Speed(kt)', '975mb Clouds(%)', '975mb FL-Vis (sm)', '975mb Mixing Ratio', '975mb CWMR (g/kg)', '975mb Icing Type', '975mb Turbulence', '975mb VVS (-ub/s)', '950mb GPH (m)', '950mb GPH DVal(m)', '950mb Temp (K)', '950mb Temp DVal(K)', '950mb Dewpt (K)', '950mb RH (%)', '950mb Parcel Temp', '950mb Theta-E (K)', '950mb Dir', '950mb Speed(kt)', '950mb Clouds(%)', '950mb FL-Vis (sm)', '950mb Mixing Ratio', '950mb CWMR (g/kg)', '950mb Icing Type', '950mb Turbulence', '950mb VVS (-ub/s)', '925mb GPH (m)', '925mb GPH DVal(m)', '925mb Temp (K)', '925mb Temp DVal(K)', '925mb Dewpt (K)', '925mb RH (%)', '925mb Parcel Temp', '925mb Theta-E (K)', '925mb
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas Temp DVal(K)', '925mb Dewpt (K)', '925mb RH (%)', '925mb Parcel Temp', '925mb Theta-E (K)', '925mb Dir', '925mb Speed(kt)', '925mb Clouds(%)', '925mb FL-Vis (sm)', '925mb Mixing Ratio', '925mb CWMR (g/kg)', '925mb Icing Type', '925mb Turbulence', '925mb VVS (-ub/s)', '900mb GPH (m)', '900mb GPH DVal(m)', '900mb Temp (K)', '900mb Temp DVal(K)', '900mb Dewpt (K)', '900mb RH (%)', '900mb Parcel Temp', '900mb Theta-E (K)', '900mb Dir', '900mb Speed(kt)', '900mb Clouds(%)', '900mb FL-Vis (sm)', '900mb Mixing Ratio', '900mb CWMR (g/kg)', '900mb Icing Type', '900mb Turbulence', '900mb VVS (-ub/s)', '875mb GPH (m)', '875mb GPH DVal(m)', '875mb Temp (K)', '875mb Temp DVal(K)', '875mb Dewpt (K)', '875mb RH (%)', '875mb Parcel Temp', '875mb Theta-E (K)', '875mb Dir', '875mb Speed(kt)', '875mb Clouds(%)', '875mb FL-Vis (sm)', '875mb Mixing Ratio', '875mb CWMR (g/kg)', '875mb Icing Type', '875mb Turbulence', '875mb VVS (-ub/s)', '850mb GPH (m)', '850mb GPH DVal(m)', '850mb Temp (K)', '850mb Temp DVal(K)', '850mb Dewpt (K)', '850mb RH (%)', '850mb Parcel Temp', '850mb Theta-E (K)', '850mb Dir', '850mb Speed(kt)', '850mb Clouds(%)', '850mb FL-Vis (sm)', '850mb Mixing Ratio', '850mb CWMR (g/kg)', '850mb Icing Type', '850mb Turbulence', '850mb VVS (-ub/s)', '825mb GPH (m)', '825mb GPH DVal(m)', '825mb Temp (K)', '825mb Temp DVal(K)', '825mb Dewpt (K)', '825mb RH (%)', '825mb Parcel Temp', '825mb Theta-E (K)', '825mb Dir', '825mb Speed(kt)', '825mb Clouds(%)', '825mb FL-Vis (sm)', '825mb Mixing Ratio', '825mb CWMR (g/kg)', '825mb Icing Type', '825mb Turbulence', '825mb VVS (-ub/s)', '800mb GPH (m)', '800mb GPH DVal(m)', '800mb Temp (K)', '800mb Temp DVal(K)', '800mb Dewpt (K)', '800mb RH (%)', '800mb Parcel Temp', '800mb Theta-E (K)', '800mb Dir', '800mb Speed(kt)', '800mb Clouds(%)', '800mb FL-Vis (sm)', '800mb Mixing Ratio', '800mb CWMR (g/kg)', '800mb Icing Type', '800mb Turbulence', '800mb VVS (-ub/s)', '775mb GPH (m)', '775mb GPH DVal(m)', '775mb Temp (K)', '775mb Temp DVal(K)',
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas '800mb VVS (-ub/s)', '775mb GPH (m)', '775mb GPH DVal(m)', '775mb Temp (K)', '775mb Temp DVal(K)', '775mb Dewpt (K)', '775mb RH (%)', '775mb Parcel Temp', '775mb Theta-E (K)', '775mb Dir', '775mb Speed(kt)', '775mb Clouds(%)', '775mb FL-Vis (sm)', '775mb Mixing Ratio', '775mb CWMR (g/kg)', '775mb Icing Type', '775mb Turbulence', '775mb VVS (-ub/s)', '750mb GPH (m)', '750mb GPH DVal(m)', '750mb Temp (K)', '750mb Temp DVal(K)', '750mb Dewpt (K)', '750mb RH (%)', '750mb Parcel Temp', '750mb Theta-E (K)', '750mb Dir', '750mb Speed(kt)', '750mb Clouds(%)', '750mb FL-Vis (sm)', '750mb Mixing Ratio', '750mb CWMR (g/kg)', '750mb Icing Type', '750mb Turbulence', '750mb VVS (-ub/s)', '725mb GPH (m)', '725mb GPH DVal(m)', '725mb Temp (K)', '725mb Temp DVal(K)', '725mb Dewpt (K)', '725mb RH (%)', '725mb Parcel Temp', '725mb Theta-E (K)', '725mb Dir', '725mb Speed(kt)', '725mb Clouds(%)', '725mb FL-Vis (sm)', '725mb Mixing Ratio', '725mb CWMR (g/kg)', '725mb Icing Type', '725mb Turbulence', '725mb VVS (-ub/s)', '700mb GPH (m)', '700mb GPH DVal(m)', '700mb Temp (K)', '700mb Temp DVal(K)', '700mb Dewpt (K)', '700mb RH (%)', '700mb Parcel Temp', '700mb Theta-E (K)', '700mb Dir', '700mb Speed(kt)', '700mb Clouds(%)', '700mb FL-Vis (sm)', '700mb Mixing Ratio', '700mb CWMR (g/kg)', '700mb Icing Type', '700mb Turbulence', '700mb VVS (-ub/s)', '675mb GPH (m)', '675mb GPH DVal(m)', '675mb Temp (K)', '675mb Temp DVal(K)', '675mb Dewpt (K)', '675mb RH (%)', '675mb Parcel Temp', '675mb Theta-E (K)', '675mb Dir', '675mb Speed(kt)', '675mb Clouds(%)', '675mb FL-Vis (sm)', '675mb Mixing Ratio', '675mb CWMR (g/kg)', '675mb Icing Type', '675mb Turbulence', '675mb VVS (-ub/s)', '650mb GPH (m)', '650mb GPH DVal(m)', '650mb Temp (K)', '650mb Temp DVal(K)', '650mb Dewpt (K)', '650mb RH (%)', '650mb Parcel Temp', '650mb Theta-E (K)', '650mb Dir', '650mb Speed(kt)', '650mb Clouds(%)', '650mb FL-Vis (sm)', '650mb Mixing Ratio', '650mb CWMR (g/kg)', '650mb Icing Type', '650mb Turbulence', '650mb VVS
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas (sm)', '650mb Mixing Ratio', '650mb CWMR (g/kg)', '650mb Icing Type', '650mb Turbulence', '650mb VVS (-ub/s)', '625mb GPH (m)', '625mb GPH DVal(m)', '625mb Temp (K)', '625mb Temp DVal(K)', '625mb Dewpt (K)', '625mb RH (%)', '625mb Parcel Temp', '625mb Theta-E (K)', '625mb Dir', '625mb Speed(kt)', '625mb Clouds(%)', '625mb FL-Vis (sm)', '625mb Mixing Ratio', '625mb CWMR (g/kg)', '625mb Icing Type', '625mb Turbulence', '625mb VVS (-ub/s)', '600mb GPH (m)', '600mb GPH DVal(m)', '600mb Temp (K)', '600mb Temp DVal(K)', '600mb Dewpt (K)', '600mb RH (%)', '600mb Parcel Temp', '600mb Theta-E (K)', '600mb Dir', '600mb Speed(kt)', '600mb Clouds(%)', '600mb FL-Vis (sm)', '600mb Mixing Ratio', '600mb CWMR (g/kg)', '600mb Icing Type', '600mb Turbulence', '600mb VVS (-ub/s)', '575mb GPH (m)', '575mb GPH DVal(m)', '575mb Temp (K)', '575mb Temp DVal(K)', '575mb Dewpt (K)', '575mb RH (%)', '575mb Parcel Temp', '575mb Theta-E (K)', '575mb Dir', '575mb Speed(kt)', '575mb Clouds(%)', '575mb FL-Vis (sm)', '575mb Mixing Ratio', '575mb CWMR (g/kg)', '575mb Icing Type', '575mb Turbulence', '575mb VVS (-ub/s)', '550mb GPH (m)', '550mb GPH DVal(m)', '550mb Temp (K)', '550mb Temp DVal(K)', '550mb Dewpt (K)', '550mb RH (%)', '550mb Parcel Temp', '550mb Theta-E (K)', '550mb Dir', '550mb Speed(kt)', '550mb Clouds(%)', '550mb FL-Vis (sm)', '550mb Mixing Ratio', '550mb CWMR (g/kg)', '550mb Icing Type', '550mb Turbulence', '550mb VVS (-ub/s)', '525mb GPH (m)', '525mb GPH DVal(m)', '525mb Temp (K)', '525mb Temp DVal(K)', '525mb Dewpt (K)', '525mb RH (%)', '525mb Parcel Temp', '525mb Theta-E (K)', '525mb Dir', '525mb Speed(kt)', '525mb Clouds(%)', '525mb FL-Vis (sm)', '525mb Mixing Ratio', '525mb CWMR (g/kg)', '525mb Icing Type', '525mb Turbulence', '525mb VVS (-ub/s)', '500mb GPH (m)', '500mb GPH DVal(m)', '500mb Temp (K)', '500mb Temp DVal(K)', '500mb Dewpt (K)', '500mb RH (%)', '500mb Parcel Temp', '500mb Theta-E (K)', '500mb Dir', '500mb Speed(kt)', '500mb Clouds(%)', '500mb FL-Vis (sm)', '500mb
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas '500mb Theta-E (K)', '500mb Dir', '500mb Speed(kt)', '500mb Clouds(%)', '500mb FL-Vis (sm)', '500mb Mixing Ratio', '500mb CWMR (g/kg)', '500mb Icing Type', '500mb Turbulence', '500mb VVS (-ub/s)', '475mb GPH (m)', '475mb GPH DVal(m)', '475mb Temp (K)', '475mb Temp DVal(K)', '475mb Dewpt (K)', '475mb RH (%)', '475mb Parcel Temp', '475mb Theta-E (K)', '475mb Dir', '475mb Speed(kt)', '475mb Clouds(%)', '475mb FL-Vis (sm)', '475mb Mixing Ratio', '475mb CWMR (g/kg)', '475mb Icing Type', '475mb Turbulence', '475mb VVS (-ub/s)', '450mb GPH (m)', '450mb GPH DVal(m)', '450mb Temp (K)', '450mb Temp DVal(K)', '450mb Dewpt (K)', '450mb RH (%)', '450mb Parcel Temp', '450mb Theta-E (K)', '450mb Dir', '450mb Speed(kt)', '450mb Clouds(%)', '450mb FL-Vis (sm)', '450mb Mixing Ratio', '450mb CWMR (g/kg)', '450mb Icing Type', '450mb Turbulence', '450mb VVS (-ub/s)', '425mb GPH (m)', '425mb GPH DVal(m)', '425mb Temp (K)', '425mb Temp DVal(K)', '425mb Dewpt (K)', '425mb RH (%)', '425mb Parcel Temp', '425mb Theta-E (K)', '425mb Dir', '425mb Speed(kt)', '425mb Clouds(%)', '425mb FL-Vis (sm)', '425mb Mixing Ratio', '425mb CWMR (g/kg)', '425mb Icing Type', '425mb Turbulence', '425mb VVS (-ub/s)', '400mb GPH (m)', '400mb GPH DVal(m)', '400mb Temp (K)', '400mb Temp DVal(K)', '400mb Dewpt (K)', '400mb RH (%)', '400mb Parcel Temp', '400mb Theta-E (K)', '400mb Dir', '400mb Speed(kt)', '400mb Clouds(%)', '400mb FL-Vis (sm)', '400mb Mixing Ratio', '400mb CWMR (g/kg)', '400mb Icing Type', '400mb Turbulence', '400mb VVS (-ub/s)', '375mb GPH (m)', '375mb GPH DVal(m)', '375mb Temp (K)', '375mb Temp DVal(K)', '375mb Dewpt (K)', '375mb RH (%)', '375mb Parcel Temp', '375mb Theta-E (K)', '375mb Dir', '375mb Speed(kt)', '375mb Clouds(%)', '375mb FL-Vis (sm)', '375mb Mixing Ratio', '375mb CWMR (g/kg)', '375mb Icing Type', '375mb Turbulence', '375mb VVS (-ub/s)', '350mb GPH (m)', '350mb GPH DVal(m)', '350mb Temp (K)', '350mb Temp DVal(K)', '350mb Dewpt (K)', '350mb RH (%)', '350mb Parcel Temp', '350mb Theta-E
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas (K)', '350mb Temp DVal(K)', '350mb Dewpt (K)', '350mb RH (%)', '350mb Parcel Temp', '350mb Theta-E (K)', '350mb Dir', '350mb Speed(kt)', '350mb Clouds(%)', '350mb FL-Vis (sm)', '350mb Mixing Ratio', '350mb CWMR (g/kg)', '350mb Icing Type', '350mb Turbulence', '350mb VVS (-ub/s)', '325mb GPH (m)', '325mb GPH DVal(m)', '325mb Temp (K)', '325mb Temp DVal(K)', '325mb Dewpt (K)', '325mb RH (%)', '325mb Parcel Temp', '325mb Theta-E (K)', '325mb Dir', '325mb Speed(kt)', '325mb Clouds(%)', '325mb FL-Vis (sm)', '325mb Mixing Ratio', '325mb CWMR (g/kg)', '325mb Icing Type', '325mb Turbulence', '325mb VVS (-ub/s)', '300mb GPH (m)', '300mb GPH DVal(m)', '300mb Temp (K)', '300mb Temp DVal(K)', '300mb Dewpt (K)', '300mb RH (%)', '300mb Parcel Temp', '300mb Theta-E (K)', '300mb Dir', '300mb Speed(kt)', '300mb Clouds(%)', '300mb FL-Vis (sm)', '300mb Mixing Ratio', '300mb CWMR (g/kg)', '300mb Icing Type', '300mb Turbulence', '300mb VVS (-ub/s)', '275mb GPH (m)', '275mb GPH DVal(m)', '275mb Temp (K)', '275mb Temp DVal(K)', '275mb Dewpt (K)', '275mb RH (%)', '275mb Parcel Temp', '275mb Theta-E (K)', '275mb Dir', '275mb Speed(kt)', '275mb Clouds(%)', '275mb FL-Vis (sm)', '275mb Mixing Ratio', '275mb CWMR (g/kg)', '275mb Icing Type', '275mb Turbulence', '275mb VVS (-ub/s)', '250mb GPH (m)', '250mb GPH DVal(m)', '250mb Temp (K)', '250mb Temp DVal(K)', '250mb Dewpt (K)', '250mb RH (%)', '250mb Parcel Temp', '250mb Theta-E (K)', '250mb Dir', '250mb Speed(kt)', '250mb Clouds(%)', '250mb FL-Vis (sm)', '250mb Mixing Ratio', '250mb CWMR (g/kg)', '250mb Icing Type', '250mb Turbulence', '250mb VVS (-ub/s)', '225mb GPH (m)', '225mb GPH DVal(m)', '225mb Temp (K)', '225mb Temp DVal(K)', '225mb Dewpt (K)', '225mb RH (%)', '225mb Parcel Temp', '225mb Theta-E (K)', '225mb Dir', '225mb Speed(kt)', '225mb Clouds(%)', '225mb FL-Vis (sm)', '225mb Mixing Ratio', '225mb CWMR (g/kg)', '225mb Icing Type', '225mb Turbulence', '225mb VVS (-ub/s)', '200mb GPH (m)', '200mb GPH DVal(m)', '200mb Temp (K)', '200mb
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas Turbulence', '225mb VVS (-ub/s)', '200mb GPH (m)', '200mb GPH DVal(m)', '200mb Temp (K)', '200mb Temp DVal(K)', '200mb Dewpt (K)', '200mb RH (%)', '200mb Parcel Temp', '200mb Theta-E (K)', '200mb Dir', '200mb Speed(kt)', '200mb Clouds(%)', '200mb FL-Vis (sm)', '200mb Mixing Ratio', '200mb CWMR (g/kg)', '200mb Icing Type', '200mb Turbulence', '200mb VVS (-ub/s)', '175mb GPH (m)', '175mb GPH DVal(m)', '175mb Temp (K)', '175mb Temp DVal(K)', '175mb Dewpt (K)', '175mb RH (%)', '175mb Parcel Temp', '175mb Theta-E (K)', '175mb Dir', '175mb Speed(kt)', '175mb Clouds(%)', '175mb FL-Vis (sm)', '175mb Mixing Ratio', '175mb CWMR (g/kg)', '175mb Icing Type', '175mb Turbulence', '175mb VVS (-ub/s)', '150mb GPH (m)', '150mb GPH DVal(m)', '150mb Temp (K)', '150mb Temp DVal(K)', '150mb Dewpt (K)', '150mb RH (%)', '150mb Parcel Temp', '150mb Theta-E (K)', '150mb Dir', '150mb Speed(kt)', '150mb Clouds(%)', '150mb FL-Vis (sm)', '150mb Mixing Ratio', '150mb CWMR (g/kg)', '150mb Icing Type', '150mb Turbulence', '150mb VVS (-ub/s)', '125mb GPH (m)', '125mb GPH DVal(m)', '125mb Temp (K)', '125mb Temp DVal(K)', '125mb Dewpt (K)', '125mb RH (%)', '125mb Parcel Temp', '125mb Theta-E (K)', '125mb Dir', '125mb Speed(kt)', '125mb Clouds(%)', '125mb FL-Vis (sm)', '125mb Mixing Ratio', '125mb CWMR (g/kg)', '125mb Icing Type', '125mb Turbulence', '125mb VVS (-ub/s)', '100mb GPH (m)', '100mb GPH DVal(m)', '100mb Temp (K)', '100mb Temp DVal(K)', '100mb Dewpt (K)', '100mb RH (%)', '100mb Parcel Temp', '100mb Theta-E (K)', '100mb Dir', '100mb Speed(kt)', '100mb Clouds(%)', '100mb FL-Vis (sm)', '100mb Mixing Ratio', '100mb CWMR (g/kg)', '100mb Icing Type', '100mb Turbulence', '100mb VVS (-ub/s)', '75mb GPH (m)', '75mb GPH DVal(m)', '75mb Temp (K)', '75mb Temp DVal(K)', '75mb Dewpt (K)', '75mb RH (%)', '75mb Parcel Temp', '75mb Theta-E (K)', '75mb Dir', '75mb Speed(kt)', '75mb Clouds(%)', '75mb FL-Vis (sm)', '75mb Mixing Ratio', '75mb CWMR (g/kg)', '75mb Icing Type', '75mb Turbulence', '75mb VVS
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas (sm)', '75mb Mixing Ratio', '75mb CWMR (g/kg)', '75mb Icing Type', '75mb Turbulence', '75mb VVS (-ub/s)', '50mb GPH (m)', '50mb GPH DVal(m)', '50mb Temp (K)', '50mb Temp DVal(K)', '50mb Dewpt (K)', '50mb RH (%)', '50mb Parcel Temp', '50mb Theta-E (K)', '50mb Dir', '50mb Speed(kt)', '50mb Clouds(%)', '50mb FL-Vis (sm)', '50mb Mixing Ratio', '50mb CWMR (g/kg)', '50mb Icing Type', '50mb Turbulence', '50mb VVS (-ub/s)')
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas main.py import re from typing import Iterable, Union import pandas as pd indexs=... def make_index_tuples() -> Iterable[tuple[str, str, Union[str, None]]]: pattern = r""" (?:(\d{2,4}mb)\s+)? # capture group 1: match level if any ([A-Za-z0-9\s-]*) # capture group 2: match parameter between (?:\s\(|\((.*)\))? # capture group 3: matching anything between(UNIT) if any """ # sometimes there is a space between the parameter and unit sometimes not for index in indexs: level, param, unit = re.search(pattern, index, re.VERBOSE).groups() if level is None: level = "surface" param = param.strip().replace(" ", "_").lower() yield level, param, unit def start(): df_index = pd.MultiIndex.from_tuples( tuple(make_index_tuples()), names=("level", "parameter", "unit"), ) if __name__ == "__main__": start()
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas if __name__ == "__main__": start() results MultiIndex([('surface', 'sfc_prs', 'mb'), ('surface', 'mean_slp', 'mb'), ('surface', 'altimeter', 'in. Hg'), ('surface', 'press_alt', 'ft'), ('surface', 'density_alt', 'ft'), ('surface', '2_m_agl_tmp', 'K'), ('surface', '2_m_agl_temp-d', 'K'), ('surface', '2_m_agl_dpt', 'K'), ('surface', '2_m_agl_wbt', 'K'), ('surface', 'convect', nan), ... ( '50mb', 'theta-e', 'K'), ( '50mb', 'dir', nan), ( '50mb', 'speed', 'kt'), ( '50mb', 'clouds', '%'), ( '50mb', 'fl-vis', 'sm'), ( '50mb', 'mixing_ratio', nan), ( '50mb', 'cwmr', 'g/kg'), ( '50mb', 'icing_type', nan), ( '50mb', 'turbulence', nan), ( '50mb', 'vvs', '-ub/s')], names=['level', 'parameter', 'unit'], length=805) Answer: indexs should be spelled indices. Your implementation is non-vectorised and should make use of the Pandas str.extract function, which is perfectly suited to this task. I think your parameter section of the regex is a little too strict, and can basically match anything that isn't a paren. You should be using named capturing groups. You say: sometimes there is a space between the parameter and unit sometimes not So then why is there an unconditional \s at the beginning of your third group? level is a real number, perhaps a millibar differential quantity inferring the elevation. So don't write surface! Write 0. Only the first two columns should be made part of a multi-index. Suggested import re import pandas as pd
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python, python-3.x, regex, pandas INDEX_PAT = re.compile( r""" ^ # start (?: # non-capture: optional level wrapper (?P<level>\d+) # capture: level mb\s+ # strip millibar suffix )? (?P<param>[^()]*?) # capture: parameter, non-parens, lazy (?: # non-capture: optional unit wrapper \s* # greedy whitespace from previous field \( (?P<unit> # capture: unit [^()]+? # non-parens, lazy ) \) )? $ # end (?x) # verbose """ ) def parse_indices(strings: pd.Series) -> pd.DataFrame: df = strings.str.extract(INDEX_PAT) df.level = df.level.fillna(0).astype(int) return df if __name__ == "__main__": print(parse_indices(pd.DataFrame(indices)[0])) Output level param unit 0 0 Sfc Prs mb 1 0 Mean SLP mb 2 0 Altimeter in. Hg 3 0 Press Alt ft 4 0 Density Alt ft .. ... ... ... 800 50 Mixing Ratio NaN 801 50 CWMR g/kg 802 50 Icing Type NaN 803 50 Turbulence NaN 804 50 VVS -ub/s [805 rows x 3 columns]
{ "domain": "codereview.stackexchange", "id": 43272, "lm_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, regex, pandas", "url": null }
python Title: Check the order of results Question: Summary Append to list only if that value is the next value expected. """ Return codes can be wrong because errors happen. And the next return code can be reliant on this one. This module checks that a return code is expected next and that only then does it become the latest piece of a fulfilling order. """ __all__ = ['order_two_with_retry', 'wait_on_the_return_of_a_commandline'] import functools import operator import subprocess import sys import time import typing insert_object_at_the_end_of_the_list = list.append # optimization def if_the_list_is_empty(insertion: typing.Any, out: typing.List, expectation: typing.List) -> None: assert not out, 'the list is not empty' a = [insertion] if a == expectation[:1]: insert_object_at_the_end_of_the_list(out, insertion) def if_the_list_is_not_empty(insertion: typing.Any, out: typing.List, expectation: typing.List) -> None: a = out[::] insert_object_at_the_end_of_the_list(a, insertion) if a == expectation[:len(a)]: insert_object_at_the_end_of_the_list(out, insertion) else: out.clear() def lever(insertion: typing.Any, out: typing.List, expectation: typing.List) -> None: """Test equality (one).""" if not out: if_the_list_is_empty(insertion, out, expectation) else: if_the_list_is_not_empty(insertion, out, expectation) def order_two(insertionm: typing.Callable, insertionn: typing.Callable, out: typing.List, expectation: typing.List) -> None: lever(insertionm(), out, expectation) print(out) if not out: return lever(insertionn(), out, expectation) print(out) def order_two_with_retry(insertionm: typing.Callable, insertionn: typing.Callable, out: typing.List, expectation: typing.List) -> None: order_two(insertionm, insertionn, out, expectation) if not out: order_two(insertionm, insertionn, out, expectation)
{ "domain": "codereview.stackexchange", "id": 43273, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python if not out: order_two(insertionm, insertionn, out, expectation) # Test equality (all). test_insertions_against_expectation = operator.eq def main(): insertionm = functools.partial(wait_on_the_return_of_a_commandline, 'python -c "import random; import sys; sys.exit(random.randrange(0, 1 + 1))"') insertionn = insertionm out = [] expectation = [0, 0] order_two_with_retry(insertionm, insertionn, out, expectation) # This function can silence this module. # Reestablish noise with builtins.print def set_print(new_print): # noinspection PyShadowingBuiltins,PyGlobalUndefined global print # noinspection PyShadowingBuiltins print = new_print def filler(executingprocess): s = 0.4 while executingprocess.poll() is None: sys.stdout.write('\r. ') time.sleep(s) sys.stdout.write('\r.. ') time.sleep(s) sys.stdout.write('\r...') time.sleep(s) def wait_on_the_return_of_a_commandline(commandline): executingprocess = subprocess.Popen(commandline) filler(executingprocess) return executingprocess.returncode if __name__ == '__main__': main() Comments
{ "domain": "codereview.stackexchange", "id": 43273, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python if __name__ == '__main__': main() Comments Dunder all contains the two functions necessary to get the module running. In if_the_list... the new list is named a because a, b are the names of arguments to operators and I'm testing for equality (operator.eq(a, b)). The comment 'optimization' is there because that function does less steps then the next function for the same computation. out[::] is faster than list(out) on my computer; use of slices not to modify lists too soon and by accident (slices create new lists). If this returncode does not match the expected returncode, out is cleared because I want to try again, not ignore and keep going. order_two_with_retry retries once, and if I have an odd number, I should use lever for that. This is where the return code appears by calling a function or opening a subprocess. The alias to operator.eq: the name fits it into the module. Test for equality: out is a, expectation is b. main generates 0 or 1 from a subprocess randomly. It shows module usage. prints in order_two can be silenced by setting print to something like def print(*args, **kwargs): pass And finally, wait on subprocess exitcode with a console animation that repeats one dot, two, three. Question I'm looking for tips on commenting code as I'm not sure how to do it or what the reader needs. Answer: The comment 'optimization' is there because that function does less steps then the next function for the same computation.
{ "domain": "codereview.stackexchange", "id": 43273, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python I'm willing to bet that this has no impact at all, and even if it did it's premature optimisation. The same applies to out[::] is faster than list(out) on my computer. Think: you're calling a child process. That will overwhelmingly be the bottleneck, right? Meant in the nicest way possible, most of this code is insane and bad and needs to go away. Names like insert_object_at_the_end_of_the_list are gratuitously long and do not help. if_the_list_is_empty does not at all describe what the function actually does, which is to insert only if the expected prefix is seen. But this function should not exist. Don't assert in production code. lever is an equally unhelpful function name. Your use of subprocess assumes shell=True which is bad. Avoid this if possible. You only show a toy example so it's impossible to provide more advice on what you're actually doing. Delete set_print. It's unused, you don't show how it would be used, and I see no utility in it. poll() is not the correct Popen call to make here; instead call wait passing in your polling interval as a timeout. Importantly, this will bail early once the process is done, where your sleep will not. Do not sleep. Put your Popen instance in context management. Don't use random numbers in what should be a deterministic test. Many consoles won't output anything from a print() unless it terminates in a newline or has a flush(). An alternative to stdout.write is a print with its end='\r' followed by a flush. You should be putting the carriage return at the end and not the beginning of your string, to allow the next line of "real" output to overwrite it once the animation is done. Also, the animation will only be visible for the first three cycles unless you pad with spaces. Somewhat reading into what you "actually want", let's assume that you're trying to make a generic Popen poll-and-animate function, and a separate retry-on-failure function. The latter is easy as a parametric decorator: Suggested
{ "domain": "codereview.stackexchange", "id": 43273, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python Suggested from subprocess import Popen, TimeoutExpired, SubprocessError from sys import stdout from typing import Callable, Any
{ "domain": "codereview.stackexchange", "id": 43273, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python def wait_process(command: str, poll_interval: float = 0.4, expected: int = 0) -> None: with Popen(command) as process: while True: for dots in range(1, 4): try: process.wait(timeout=poll_interval) if process.returncode == expected: return raise SubprocessError( f'"{command}" completed with code {process.returncode}, ' f'expected {expected}' ) except TimeoutExpired: pass print(f'{"."*dots:3}', end='\r') stdout.flush() def retry_process(times: int) -> Callable: def decorator(inner: Callable) -> Callable: def wrapper(*args: Any, **kwargs: Any) -> Any: for attempt in range(times - 1): try: return inner(*args, **kwargs) except SubprocessError: pass return inner(*args, **kwargs) return wrapper return decorator @retry_process(times=2) def main() -> None: print('Starting first') command = 'python -c "from time import sleep; sleep(2); exit(0)"' wait_process(command=command, expected=0) print('First completed, starting second') wait_process(command=command, expected=1) print('Second completed') if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43273, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python if __name__ == '__main__': main() Output Starting first . .. ... . .. First completed, starting second . .. ... . .. Starting first . .. ... . .. First completed, starting second . .. ... . .. Traceback (most recent call last): File "C:\Users\gtoom\src\stackexchange\276074.py", line 47, in <module> main() File "C:\Users\gtoom\src\stackexchange\276074.py", line 32, in wrapper return inner(*args, **kwargs) File "C:\Users\gtoom\src\stackexchange\276074.py", line 42, in main wait_process(command=command, expected=1) File "C:\Users\gtoom\src\stackexchange\276074.py", line 13, in wait_process raise SubprocessError( subprocess.SubprocessError: "python -c "from time import sleep; sleep(2); exit(0)"" completed with code 0, expected 1
{ "domain": "codereview.stackexchange", "id": 43273, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python", "url": null }
python, web-scraping, database, sqlite, python-requests Title: Acupuncture database builder
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests Question: The following code builds a rudimentary acupuncture database by collecting data from the web. I would like to hear suggestions about improvements to the database structure, code organization, web-scraping techniques etc. (NOTE: Some tables created by the db script have not been fully populated. They are left here to inform the reviewer about my overall design strategy, and these would definitely be worked on, revised and expanded further after gathering feedback from the community.) The block of code commented out under the get_aliases function is dysfunctional, possibly because the owner of the Yibian website disallows direct calls to hrefs ending with .?ano= which lead to webpages containing detailed acupoint data. This results in errors when the target DOM tag cannot be found. The original intention of that block of code was to build a list of International Code IDs corresponding to each alias point so that these can be easily imported into the acuAliases table, which makes use of this ID as foreign key to link back to the main Acupoint table. The workaround for the current code under review is to utilize a block of code under the update_acu_alias_table function to half-manually update the null datasets by comparing alias labels (or "headings") and names in their original or transliterated form with the acupoint names in traditional Chinese (acuName_zh) to see if there is a match. The above strategy works 99.9% of the time, leaving just one special case, TE18, which has different characters and pronunciations for all its possible names and aliases. This, unfortunately, has to be updated manually with the code below the auto-compare-and-update code block. build_db.py import sqlite3 as sql import wikipedia as wp import pandas as pd from copy import deepcopy from typing import List, Set, Dict, Tuple, Type, BinaryIO from requests import Session, get import re from opencc import OpenCC from pypinyin import pinyin, Style from itertools import chain
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests import re from opencc import OpenCC from pypinyin import pinyin, Style from itertools import chain from lookup import get_id from bs4 import BeautifulSoup from urllib.parse import urljoin
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests SCRIPT = ''' CREATE TABLE IF NOT EXISTS Acupoint ( ID TEXT PRIMARY KEY, -- International Standard Code. prcID TEXT UNIQUE, -- PRC Standard Code. acuName_zh TEXT, acuName_zh_sim TEXT, acuName_en TEXT, acuName_tr TEXT, -- transliterated Chinese text meridianID TEXT, -- must create column before adding it as a foreign key. FOREIGN KEY (meridianID) REFERENCES Meridian (ID)); CREATE TABLE IF NOT EXISTS acuLoc ( -- Location of Acupoints. acuID TEXT PRIMARY KEY, acuLoc_desc TEXT, -- acuLoc_desc_en TEXT, acuLoc_pos TEXT, -- General position of acupoint: head, upper/lower limb etc. FOREIGN KEY (acuID) REFERENCES Acupoint (ID)); -- primary key is also a foreign key. CREATE TABLE IF NOT EXISTS acuFind ( -- How to find an Acupoint. acuID TEXT PRIMARY KEY, acuFind_desc TEXT, ref TEXT); CREATE TABLE IF NOT EXISTS acuEx ( -- Acupoints shared by the extraordinary meridians. ID TEXT PRIMARY KEY, -- in the form of TV1, BV2... etc. bypass TEXT, -- use primary key of Acupoint table as foreign key. meridianID TEXT, FOREIGN KEY (meridianID) REFERENCES Meridian (ID), FOREIGN KEY (bypass) REFERENCES Acupoint (ID)); CREATE TABLE IF NOT EXISTS acuAlias ( acuID TEXT, aliasName TEXT, aliasSrc TEXT, -- source of aliasName. PRIMARY KEY (acuID, aliasName)); CREATE TABLE IF NOT EXISTS Meridian ( ID TEXT PRIMARY KEY, meridianName_zh TEXT, meridianName_zh_sim TEXT, meridianName_tr TEXT, -- transliteration; Wikipedia provides values only for extraordinary meridians. meridianName_en TEXT, -- name of organ as meridian name. meridianExtra BOOLEAN DEFAULT "0" NOT NULL CHECK (meridianExtra IN (0, 1))); -- True for extraordinary meridian CREATE TABLE IF NOT EXISTS meridianRoute ( -- 循經路線. Routes taken by the extraordinary meridians are related to the AcuEx table. meridianID TEXT PRIMARY KEY,
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests meridianID TEXT PRIMARY KEY, route TEXT, -- route of meridian route_src TEXT, -- source of route description route_classic TEXT, -- route of meridian; quote 《黃帝內經·靈樞》. meridian_img TEXT, FOREIGN KEY (meridianID) REFERENCES Meridian (ID)); CREATE TABLE IF NOT EXISTS Images ( -- Images for archival and display purposes ID TEXT, category TEXT, -- Use names of existing tables to define the data category. eg. acuLoc to indicate location of a point. source TEXT, img BLOB, PRIMARY KEY (ID, category, source)); CREATE TABLE IF NOT EXISTS imgLink ( -- Link image to datapoint. ID INTEGER PRIMARY KEY AUTOINCREMENT, imgID TEXT, -- references Images.ID refID TEXT, -- references acuID, meridianID etc.; to be derived from imgID imgCAT TEXT, -- references Images.category imgSRC TEXT, -- references Images.source img_desc TEXT, -- description of image in context, if any. FOREIGN KEY (imgID) REFERENCES Images (ID), FOREIGN KEY (imgCAT) REFERENCES Images (category), FOREIGN KEY (imgSRC) REFERENCES Images (source), FOREIGN KEY (refID) REFERENCES acuLoc (acuID), FOREIGN KEY (refID) REFERENCES meridianRoute (meridianID)); '''
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests def created_tables() -> List[str]: r = re.compile("CREATE TABLE IF NOT EXISTS (\\w+)") tables = r.findall(SCRIPT) return tables def initialize_database(connect: Type[sql.Connection]): """Build the basic database structure from scratch. """ print("Building the Acupuncture database...") # Build database structure c = connect.cursor() # use Cursor object to perform SQL commands for table in created_tables(): # Drop tables if exist c.executescript(f''' DROP TABLE IF EXISTS {table}; ''') # Create tables # NOTE: Derived values (such as Yinyang attributes of meridians) will not be stored in the database. c.executescript(SCRIPT) # Furnish data def get_basic_data(connect: Type[sql.Connection]) -> None: """Scrape data from English wikipedia \ to populate the Acupoint and Meridian tables.""" print("Furnishing database with data from Wikipedia... ") html = wp.page("List_of_acupuncture_points").html() df = pd.read_html(html) # parses all tables into dataframes # Set meridian, extraordinary meridian and acupoint data meridian = df[0][['Code', 'Chinese Name', 'English']] meridian.columns = ['ID', 'meridianName_zh', 'meridianName_en'] extraordinary_meridian = df[1][['Code', 'Name', 'Transliteration', 'English']] extraordinary_meridian.columns = ['ID', 'meridianName_zh', 'meridianName_tr', 'meridianName_en'] acupoint = pd.concat(df[2:16])[['Point', 'Name', 'Transliteration', 'English']] # standard :16, all (include 奇穴):18 acupoint.columns = ['ID', 'acuName_zh', 'acuName_tr', 'acuName_en'] # ID = International Standard Code. # DATA CLEANING # Meridian data meridian = deepcopy(meridian) # make sure df is a copy, not a view to avoid SettingwithCopyWarning. meridian_list = list(meridian["meridianName_zh"]) meridian_list_abbrev = [re.search(".+[陰陽明](.+經)", item).group(1) for item in meridian_list]
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests extraordinary_meridian = deepcopy(extraordinary_meridian) as_list = extraordinary_meridian['meridianName_zh'].tolist() split_list = [item.split('; ') for item in as_list] sim_list = [sim for sim, zh in split_list] zh_list = [zh for sim, zh in split_list] extraordinary_meridian['meridianName_zh'] = zh_list extraordinary_meridian['meridianName_zh_sim'] = sim_list extraordinary_meridian['meridianExtra'] = 1 # Acupoint data acupoint = deepcopy(acupoint) # make sure df is a copy, not a view. name_list = list(acupoint['acuName_zh']) acu_list = [re.search("([\u4e00-\u9fff]+)([a-z\\d \\[;()\\]]+)?", item).group(1) for item in name_list] acupoint['acuName_zh'] = acu_list # remove aliases from Chinese name. as_list = list(acupoint['ID']) split_list = [item.split('-') for item in as_list] tag_list = [tag.upper() for tag, sn in split_list] sn_list = [sn for tag, sn in split_list] # serial-number of acupoint index tag_list = ["LR" if tag == "LIV" else tag for tag in tag_list] tag_list = ["GV" if tag == "DU" else tag for tag in tag_list] tag_list = ["CV" if tag == "REN" else tag for tag in tag_list] new_id_list = [tag + sn for tag, sn in zip(tag_list, sn_list)] meridian_id_list = tag_list acupoint["ID"] = new_id_list acupoint["meridianID"] = meridian_id_list acupoint["acuName_tr"] = [transliterate(item) for item in acupoint["acuName_zh"]] cc = OpenCC('t2s') acupoint["acuName_zh_sim"] = [cc.convert(item) for item in acu_list] meridian["meridianName_zh_sim"] = [cc.convert(item) for item in meridian_list] meridian["meridianName_tr"] = [transliterate(item) for item in meridian_list_abbrev] meridian["ID"] = ["LR" if tag == "LV" else tag for tag in meridian["ID"]] # aliases
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests # aliases c = connect.cursor() for i, item in enumerate(name_list): alias = re.search(".+([a-z0-9 \\[;\\(\\)\\]]+)([\u4e00-\u9fff]+)", item) if alias: c.executescript(f''' INSERT INTO acuAlias (acuID, aliasName, aliasSrc) VALUES ("{new_id_list[i]}", "{alias.group(2)}", "wiki"); ''') # NOTE: This wiki page uses a different code (against the PRC standard) for certain acupoints. # e.g. TE instead of SJ for 三焦經; GV instead of DU for 督脈 etc. # We'll be using the International Standard for this App. # The PRC Standard will be referenced under the Acupoint.prcID column. # PRC Standard CODE DISCREPANCIES # TE -> SJ (三焦) # LV -> LR (肝) # CV -> RN # GV -> DU # NOTE: China has switched to International code by 2012. # We keep track of that standard to access「A+醫學百科」data. prc_tag_list = ["SJ" if tag == "TE" else tag for tag in tag_list] # 三焦 prc_tag_list = ["RN" if tag == "CV" else tag for tag in prc_tag_list] # 任 prc_tag_list = ["DU" if tag == "GV" else tag for tag in prc_tag_list] # 督 prc_id_list = [tag + sn for tag, sn in zip(prc_tag_list, sn_list)] acupoint["prcID"] = prc_id_list # Write to database acupoint.to_sql('Acupoint', connect, if_exists='append', index=False) # save to sql database meridian.to_sql('Meridian', connect, if_exists='append', index=False) extraordinary_meridian.to_sql('Meridian', connect, if_exists='append', index=False) # Remove duplicated Simplified Chinese from alias table. c.executescript(''' DELETE FROM `acuAlias` WHERE EXISTS (SELECT `acuName_zh_sim` FROM `Acupoint` WHERE `acuName_zh_sim` = `aliasName`); ''') def get_extraordinary_route_data(connect: Type[sql.Connection]) -> (List[str], Dict[str, str]): """Scrape data from Chinese wikipedia \ to furnish extraordinary meridian route data to database."""
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests wp.set_lang("zh") html = wp.page("腧穴列表").html() df = pd.read_html(html) print("Getting Extraordinary Meridian data...") acu_ex = df[1] # dataframe of acupoints on the extraordinary meridians. acu_ex = deepcopy(acu_ex) acu_ex = acu_ex.iloc[2:, :] # slice off 任脈 and 督脈 acu_ex_list = acu_ex["穴位名稱及序號"].tolist() split_list = [item.split(': ') for item in acu_ex_list] route_list = [route for route, points in split_list] points_list = [points for route, points in split_list] meridian_list = list(acu_ex["國際代碼"]) acu_ex_dict = {} for i, lst in enumerate(points_list): points = lst.split(" ") split_list = [item.split(".") for item in points] bypass = [acuID for acuID, acuName in split_list] meridian = meridian_list[i] for j, bypass_point in enumerate(bypass): acu_ex_dict[f"{meridian}{j + 1}"] = bypass_point c = connect.cursor() for key in acu_ex_dict.keys(): c.executescript(f''' INSERT INTO acuEx (ID, bypass, meridianID) VALUES ("{key}", "{acu_ex_dict[key]}", "{''.join(i for i in key if not i.isdigit())}"); ''') for i, item in enumerate(route_list): c.executescript(f''' INSERT INTO meridianRoute (meridianID, route, route_src) VALUES ("{meridian_list[i]}", "{item}", "https://zh.wikipedia.org/wiki/腧穴列表#奇經八脈"); ''') def get_location_data(connect: Type[sql.Connection]) -> None: """Scrape data from A+醫學百科 \ to furnish acupoint location data in Chinese.""" print("Getting acupoint location data...") with get('http://cht.a-hospital.com/w/中华人民共和国国家标准·经穴部位') as resp: resp.raise_for_status() df = pd.read_html(resp.text) acu_loc = pd.concat(df[4:18]) acu_loc = deepcopy(acu_loc) acu_loc.columns = ["prcID", "acuName_zh", "acuName_tr", "acuLoc_desc"]
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests acu_loc.to_sql('acuLoc_temp', connect, if_exists='replace', index=False) c = connect.cursor() c.executescript(''' INSERT INTO `acuLoc`(`acuID`, `acuLoc_desc`) SELECT "ID", "acuLoc_desc" FROM `Acupoint` JOIN `acuLoc_temp` ON `Acupoint`.`prcID` = `acuLoc_temp`.`prcID`; DROP TABLE acuLoc_temp; ''') def transliterate(string): tr = "".join(list( chain.from_iterable( pinyin(string, style=Style.NORMAL)))).capitalize() return tr def get_aliases(): """Furnish alias names of acupoint from 醫砭 website.""" BASE_URL = 'http://yibian.hopto.org/acu' alias_list = [] heading_list = [] url_list = [] id_list = [] session = Session() for i in range(1, 15): with session.get (BASE_URL, params={ 'mn': 'jing', 'sn': i, } ) as resp: resp.raise_for_status() resp.encoding = resp.apparent_encoding soup = BeautifulSoup(resp.content, 'html.parser') alias_tags = soup.select(".content_small_label:-soup-contains('別名')") for tag in alias_tags: anchor = tag.find_previous_siblings('a')[0] heading = anchor.text href = anchor['href'] aliases = tag.find_next_sibling().text.split(",") print(f"Getting aliases for {heading}...") heading_list.append(heading) alias_list.append(aliases) url_list.append(urljoin(BASE_URL, href))
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests # print("Building id list...") # for url in url_list: # with session.get(url, # headers={"User-Agent": # "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:99.0) Gecko/20100101 Firefox/99.0}", # } # ) as resp: # resp.raise_for_status() # resp.encoding = resp.apparent_encoding # soup = BeautifulSoup(resp.content, 'html.parser') # print(url) # tag = soup.select_one('td.content_board table td b').nextSibling # id_str = "".join(filter(str.isalnum, tag)) # alias_id = re.sub("[^A-Z0-9]+", "", id_str) # id_list.append(alias_id) # print(alias_id) return id_list, heading_list, alias_list def alias_id_is_null(connect: Type[sql.Connection]): """Returns the names of acupoints where the ID is null. Meaning: Name given on website does not match existing data on our database.""" c = connect.cursor() c.execute(''' SELECT `aliasName` FROM `acuAlias` WHERE `acuID` ISNULL; ''') return [item[0] for item in c.fetchall()] def get_column(connect: Type[sql.Connection], column, table) -> List[str]: c = connect.cursor() c.execute(f''' SELECT {column} FROM {table}; ''') values = [value[0] for value in c.fetchall()] print(values) return values def update_acu_alias_table(connect: Type[sql.Connection]): id_list, heading_list, alias_list = get_aliases() hdg_idx_dict = {} # index that points to the corresponding heading for each alias list item for i, name in enumerate(heading_list): for item in alias_list[i]: hdg_idx_dict[item] = name
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests c = connect.cursor() for i, name in enumerate(heading_list): for item in alias_list[i]: c.execute(f''' INSERT INTO acuAlias (acuID, aliasName, aliasSrc) VALUES ((SELECT ID FROM Acupoint WHERE acuName_zh = "{name}"), "{item}", "醫砭") ''') # Update null values null_list = alias_id_is_null(connect) db_acuname = get_column(connect, "acuName_zh", "Acupoint") for i, item in enumerate(null_list): # null list item match db heading = hdg_idx_dict[item] null_id = get_id(item) if item in db_acuname: null_list.remove(item) c.executescript(f""" DELETE FROM acuAlias WHERE aliasName = "{item}"; INSERT INTO acuAlias (acuID, aliasName, aliasSrc) VALUES ("{null_id}", "{heading}", "醫砭"); """) null_list = alias_id_is_null(connect) for item in null_list: heading = hdg_idx_dict[item] # heading tr match db hdg_id = get_id(transliterate(heading)) # use transliterated heading to search if hdg_id: c.execute(f''' UPDATE acuAlias SET acuID = "{hdg_id}" WHERE aliasName = "{item}"; ''') try: c.execute(f''' INSERT INTO acuAlias (acuID, aliasName, aliasSrc) VALUES ("{hdg_id}", "{heading}", "醫砭"); ''') except sql.IntegrityError: print(f"Acupoint {heading} is already registered as an alias.") # Manual c.executescript(f''' UPDATE acuAlias SET acuID = "TE18", aliasSrc = "醫砭" WHERE aliasName = "資脈"; INSERT INTO acuAlias (acuID, aliasName, aliasSrc) VALUES ("TE18", "瘛脈", "醫砭"); ''')
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
python, web-scraping, database, sqlite, python-requests if __name__ == '__main__': with sql.connect("acu.db") as conn: # establish connection to database initialize_database(conn) get_basic_data(conn) get_extraordinary_route_data(conn) get_location_data(conn) update_acu_alias_table(conn) conn.commit() print("Done!") Answer: Your Set, Tuple and BinaryIO imports are unused so delete them. SCRIPT does not belong in this program. It should be moved to a separate .sql file. But further than that, the whole initialize_database routine should not be included in production code. The setup for a program and its runtime should be well-separated. Inference of created table names using your created_tables regex is not a good idea. If you want your setup script to be idempotent, include drop table if exists statements inline in your SQL verbatim; don't rely on parsing magic to do this. connect is not a Type[sql.Connection]; it's a Connection (i.e. an instance, not a type). It's important for the Mandarin strings in .+[陰陽明](.+經) to be moved to variables with English names for international maintainability. Some of your type hints are incomplete, for instance transliterate(string: str) -> str. A tool like mypy will let you know about this and other instances of gaps and mismatches.
{ "domain": "codereview.stackexchange", "id": 43274, "lm_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, web-scraping, database, sqlite, python-requests", "url": null }
functional-programming, typescript, angular-2+, rxjs Title: Convert from get response to array of type Question: I would like to know if this is the best/most efficient/industry standard way of converting from the http response to an array of typed values: Type class: export class University { public "state-province": string; public country: string; public name: string; constructor(state_province: string, country: string, name: string) { this["state-province"] = state_province; this.country = country; this.name = name; } } Here is the http request and conversion. The code in question is within the map(...) call: const resp = this.http .get<University[]>(`http://universities.hipolabs.com/search?country=United+Kingdom&name=camb`) .pipe(map(respData => { const uniArr: University[] = []; respData.forEach(element => { uniArr.push(new University(element['state-province'], element.country, element.name)); }); return uniArr; })) .subscribe(respData => { console.log('Content:', respData); }); In C# there are many easier ways to convert the response data of the get request into an array (or list) of typed instances. Am I doing this correctly here, in Angular/RxJS? Answer: Addressing Your Main Question I would like to know if this is the best/most efficient/industry standard way of converting from the http response to an array of typed values Just as an array has its forEach() method it also has a map() method. That method essentially pushes the return value of the callback function into an array and returns the array. Because of this the code within the map function callback can be simplified using that method instead of calling the forEach() method. Thus this inner block: .pipe(map(respData => { const uniArr: University[] = []; respData.forEach(element => { uniArr.push(new University(element['state-province'], element.country, element.name)); }); return uniArr; })
{ "domain": "codereview.stackexchange", "id": 43275, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "functional-programming, typescript, angular-2+, rxjs", "url": null }
functional-programming, typescript, angular-2+, rxjs can be simplified to: .pipe(map(respData => { return respData.map(element => { return new University(element['state-province'], element.country, element.name); }); }) Notice there is no need to declare the array- i.e. uniArr because the map method returns an array. And that can be simplified because there is only a single statement being returned .pipe(map(respData => { return respData.map( element => new University(element['state-province'], element.country, element.name) ); }) And the return before the call to the map method could also be removed though it might make for a long line that some would split .pipe(map(respData => respData.map(element => new University( element['state-province'], element.country, element.name )))) Using the map method approach there are no side-effects of the callback function and thus it is a pure function. This means it is simpler to test, and allows for fewer indentation levels. Review While there isn't much code to review here, the present code appears quite readable. Indentation is consistent and variables have acceptable names. It would be wise to check respData to ensure it is an array before calling a method like forEach() or map() on it, and if the code doesn't already catch exceptions from the call to this.http.get() then it would be wise to also handle those cases. For example, what happens if the network fails or the API is not available?
{ "domain": "codereview.stackexchange", "id": 43275, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "functional-programming, typescript, angular-2+, rxjs", "url": null }
java Title: TicketManager class in Java
{ "domain": "codereview.stackexchange", "id": 43276, "lm_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", "url": null }
java Question: I'm reading the famous Clean Code book of Robert C. Martin so I'm trying to refactor some of my latest code as exercise. I feel like the method getTicket breaks the SRP (Single Responsibility Principle) as it does too many things (get the ticket, check if it's still valid, get a new one...). On the other hand I don't see any room for improvements. What do you think? @Component public class TicketManager { private static final long TICKET_EXPIRATION_TIME_MIN = 5; private Map<String, TicketHolder> ticketWrapperMap; @PostConstruct private void init() { ticketWrapperMap = new HashMap<String, TicketManager.TicketHolder>(); } public String getTicket(String userId) { Preconditions.checkNotNull(userId); final Instant now = Instant.now(); TicketHolder ticketHolder = Optional.ofNullable(ticketWrapperMap.get(userId)).orElse(generateNewTicketHolder(userId, now)); if (isTicketValid(ticketHolder, now)) { return ticketHolder.getTicket(); } return generateNewTicketHolder(userId, now).getTicket(); } private TicketHolder generateNewTicketHolder(String userId, Instant now) { return ticketWrapperMap.put(userId, TicketHolder.of(now, generateNewTicket(userId))); } private boolean isTicketValid(TicketHolder ticketHolder, Instant now) { return ticketHolder != null && ticketHolder.getCreationTime().plus(Duration.ofMinutes(TICKET_EXPIRATION_TIME_MIN)).isAfter(now); } private String generateNewTicket(String userId) { return UUID.randomUUID().toString(); } @Getter @Setter @ToString static class TicketHolder { Instant creationTime; String ticket; private TicketHolder(Instant ldt, String ticket) { this.creationTime = ldt; this.ticket = ticket; }
{ "domain": "codereview.stackexchange", "id": 43276, "lm_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", "url": null }
java this.creationTime = ldt; this.ticket = ticket; } public static TicketHolder of(Instant ldt, String ticket) { Preconditions.checkNotNull(ldt); Preconditions.checkArgument(ticket != null && !ticket.isBlank()); return new TicketHolder(ldt, ticket); } } }
{ "domain": "codereview.stackexchange", "id": 43276, "lm_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", "url": null }
java Answer: "Get a valid ticket if one exists, otherwise generate a new one" is a useful convenience function, but it really does two things that, I believe, can usefully be done separately - "get a valid ticket if one exists" and "generate a new ticket". I would suggest creating those functions and making the current getTicket into a wrapper for those, perhaps looking something like getExistingTicket(userId).orElseGet(() -> generateNewTicket(userId)) I also think the logic of getTicket gets a bit muddied in places. You fetch a ticket from your list of known tickets, and if you don't find one you generate a new one. Now that you have a ticket, you check if it's valid. If it is, you return it, if not, you generate a new one and return that. My issue here is that that code, while it is working fine and free of bugs, it looks like it has a bug in it. See, since the code is written to explicitly check the validity of a newly generated ticket, that implies to a reader that a newly generated ticket might not be valid (yes, you and I both know it is, but I didn't know that at first, and neither will anyone else when reading the code for the first time). And then you go on to generate and return a new ticket without checking if it's valid. It'd be clearer to check for validity before generating a new one, like TicketHolder ticketHolder = ticketWrapperMap.get(userId); if (ticketHolder != null && isTicketValid(ticketHolder, now)) { return ticketHolder.getTicket(); } else { return generateNewTicketHolder(userId, now).getTicket(); } or, if you have strong opinions on the use of null return Optional .ofNullable(ticketWrapperMap.get(userId)) .filter(t -> isTicketValid(t, now)) .orElseGet(() -> generateNewTicketHolder(userId, now)) .getTicket();
{ "domain": "codereview.stackexchange", "id": 43276, "lm_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", "url": null }
java I also find it a bit weird to not expose the expiration time to callers. Might the caller need to know when a ticket will expire? It might be better to return the entire TicketHolder rather than just the String On a related note, I'm not sold on the name TicketHolder. A String with no associated TicketHolder isn't really a ticket at all - you have no idea if it's valid, so you can't use it, right? So, I'd actually argue that these TicketHolders aren't holders for tickets, but are, themselves, Tickets. Finally, while "manager" classes do have their uses, it's worth taking care to make sure it's clear what is the responsibility of the manager and the managee. Consider what exactly should be the responsibility of a TicketManager as opposed to Tickets themselves, and perhaps giving TickerManager a name that makes that clearer. Some things to consider might be: Might different managers have different criteria for when a ticket is considered valid? If not, validity is a property of a ticket rather than of a manager, meaning TicketManager::isTicketValid should probably be Ticket::isValid Do different managers have different ways to turn a user ID into a ticket string? If not, TicketManager::generateNewTicket could probably be part of Ticket instead, and you may even want to consider whether Ticket::new should take a user ID as its parameter instead of the ticket string
{ "domain": "codereview.stackexchange", "id": 43276, "lm_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", "url": null }
c#, file-system Title: Get files from disk filtering by size Question: does anyone knows how I can simplify this code? The objective is to get multiple files from the explorer and validate the number of files, the weight of each file and the total weight. public static async Task<IEnumerable<StorageFile>> GetMultipleFileFromDisk(Window rootWindow, int maxFiles, string fileTypes = null, ulong fileMaxSize = 0, ulong totalMaxSize = 0, PickerLocationId? pickerLocation = null, PickerViewMode viewMode = PickerViewMode.List) { var filePicker = new FileOpenPicker(); if (fileTypes != null) { var fileTypesArray = fileTypes.Split(";"); //IList<string> fileTypesList = fileTypes.Split(";"); // Get the current window's Handler by passing in the Window object var handler = WinRT.Interop.WindowNative.GetWindowHandle(rootWindow); // Associate the HWND with the file picker WinRT.Interop.InitializeWithWindow.Initialize(filePicker, handler); if (fileTypesArray.Count() >= 0) foreach (var fileType in fileTypesArray) filePicker.FileTypeFilter.Add(fileType); } filePicker.SuggestedStartLocation = pickerLocation ?? PickerLocationId.DocumentsLibrary; filePicker.ViewMode = viewMode; var files = await filePicker.PickMultipleFilesAsync(); if (files.Count > maxFiles) throw new Exception($"Só pode carregar {maxFiles} ficheiros."); IEnumerable<StorageFile> finalFiles;
{ "domain": "codereview.stackexchange", "id": 43277, "lm_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#, file-system", "url": null }
c#, file-system IEnumerable<StorageFile> finalFiles; if (fileMaxSize != 0) { var correctFiles = new List<StorageFile>(); foreach (var file in files) { var hasRightSize = await HasRightSize(file, fileMaxSize); if (hasRightSize) correctFiles.Add(file); else throw new Exception(file.Name + " excede o tamanho máximo."); } finalFiles = correctFiles; } else finalFiles = files; if (totalMaxSize <= 0) return finalFiles; if (!await HasRightSize(finalFiles, totalMaxSize)) finalFiles = null; return finalFiles; } Answer: Here are my refactoring ideas The if(fileTypes != null) block if (fileTypes != null) { var handler = WinRT.Interop.WindowNative.GetWindowHandle(rootWindow); WinRT.Interop.InitializeWithWindow.Initialize(filePicker, handler); foreach (var fileType in fileTypes.Split(";")) filePicker.FileTypeFilter.Add(fileType); } You don't need to put the result of Split into a variable, like fileTypesArray You can use it directly inside the foreach loop You don't need to guard your foreach loop with an empty collection check If it is empty then it will not execute the loop body If the Split could return null (but it couldn't) then it would make sense to guard it with a null check The if (fileMaxSize != 0) block IEnumerable<StorageFile> finalFiles = files; if (fileMaxSize != 0) { var correctFiles = new List<StorageFile>(); foreach (var file in files) { if (!await HasRightSize(file, fileMaxSize)) throw new Exception(file.Name + " excede o tamanho máximo."); correctFiles.Add(file); } finalFiles = correctFiles; }
{ "domain": "codereview.stackexchange", "id": 43277, "lm_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#, file-system", "url": null }
c#, file-system You can omit the outer else branch by initializing the finalFiles with the files You can omit the inner else branch by inverting the if condition since the throw statement breaks the execution So, it will not reach the Add command if it does not have the right size Based on your requirements it might make sense to use a more specific exception (either a built-in or a custom one). The final return statements if (totalMaxSize <= 0) return finalFiles; return await HasRightSize(finalFiles, totalMaxSize) ? finalFiles : null; Or return totalMaxSize <= 0 ? finalFiles : await HasRightSize(finalFiles, totalMaxSize) ? finalFiles : null; You can take advantage of the ternary conditional operator to make your statements more concise I depends on personal preference whether the latter option, with the nested conditional operator, is more legible than the former one
{ "domain": "codereview.stackexchange", "id": 43277, "lm_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#, file-system", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc Title: Tic-Tac-Toe vanilla JS Pseudo OOP Question: I'm working on building a simple game in vanilla JS (tic-tac-toe). Some weeks ago I created a functional MVP and asked some questions about it (Vanilla JS Tic-Tac-Toe). The code worked, but it was a single monolithic mess and the UI was ugly, so I decided to improve it. So, I refactored the code. I organized it into three files: main.js - contains the state and controls the game flow UIFunctions.js - UI related (painting cells, cleaning the screen, etc) gameCheckerFunctions - process the state and verifies if we have a winner gameStateFunctions - basically saves moves made and change the current player So, the questions are: How to implement a MVC pattern? Right now, the state and HTML elements are global variables, but I think this could be stored in state and UI classes Also, I'm having troubles with the concept of controller. Is main.js the code that will be the controller in an MVC pattern? There's a better algorithm to check for the winner? Is it a good looking code? How it could be improved? What looks ugly and could be done in a better way? I really would like to develop good practices from the beginning. Some features that I would like to implement are a CPU player, storing the score in localStorage, remember the player name, auth, two-player network gamming, etc. I'm in the correct way of doing things? Game can be played https://nabla-f.github.io/ The code: app.js // IMPORTS; import checker from './refactored/gameCheckerFunctions.js'; import game from './refactored/gameStateFunctions.js'; import ui from './refactored/UIFunctions.js'; // CONFIG const P1_CLASS = 'player1'; // Defined in styles.css const P2_CLASS = 'player2'; // Defined in styles.css // STATE let state = { activePlayer: P1_CLASS, boardArray: [[null, null, null], [null, null, null], [null, null, null]], boardDim: 3, moves: 0 }
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc let view = { button: null, cells: null, resultScreen: { screen: null, text: null, img: null } }; // WAIT FOR THE DOM window.addEventListener('DOMContentLoaded', (event) => { console.log('DOM fully loaded and parsed'); main(); }); // MAIN FUNCTION function main() { // GET ELEMENTS FROM DOM AND ADD EVENT LISTENERS view.button = document.querySelector("#resetBtn"); view.cells = document.querySelectorAll(".cell"); view.resultScreen.screen = document.querySelector("#done"); view.resultScreen.text = document.querySelector('.lead'); view.resultScreen.img = document.getElementById('winnerImg'); view.button.addEventListener('click', () => {ui.restartGameUI(view.cells, view.resultScreen)}); view.button.addEventListener('click', () => {game.restartGame(state, P1_CLASS); console.log(state)}); view.cells.forEach( cell => cell.addEventListener('click', turn) ); view.cells.forEach( cell => cell.classList.add('player1Turn') ); // GAME FLOW FUNCTION EXECUTED EACH TIME A PLAYER MAKES A MOVE function turn() { console.log(`Now playing: ${state.activePlayer}`) let cell = this; // currently clicked cell if (!cell.hasAttribute('data-disabled')) { game.storeMove(cell, state.boardArray, state.activePlayer); state.moves += 1 ui.paintCell(cell, state.activePlayer); if (checker.checkWinner(state.boardArray, state.boardDim, state.activePlayer)) { ui.paintWinner(view.resultScreen, state.activePlayer) } else if (checker.checkDraw(state.moves)) { ui.paintDraw(view.resultScreen); } else { state.activePlayer = game.changeTurn(state.activePlayer, P1_CLASS, P2_CLASS); ui.changeTurnHover(view.cells, state.activePlayer, P1_CLASS, P2_CLASS); } } }; }; UIFunctions.js // FUNCTIONS
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc UIFunctions.js // FUNCTIONS export default class UIFunctions { static paintCell(cell, playerClass) { console.log('cell clicked: ' + cell.id); cell.classList.add(playerClass); cell.setAttribute('data-disabled', 'true'); } static paintWinner(screen, playerClass) { screen.screen.classList.add(`${playerClass}winner`); screen.img.classList.add(`${playerClass}win-img`); } static paintDraw(screen) { screen.screen.classList.add(`drawgame`); screen.text.innerText = '...is a draw...'; } static changeTurnHover(cells, activePlayer, p1Class, p2Class) { cells.forEach( cell => cell.classList.remove(`${p1Class}Turn`) ); cells.forEach( cell => cell.classList.remove(`${p2Class}Turn`) ); cells.forEach( cell => { if (!cell.hasAttribute('data-disabled')) { cell.classList.add(`${activePlayer}Turn`); } }) } static restartGameUI(cells, screen) { cells.forEach( cell => cell.classList.remove('player1') ); cells.forEach( cell => cell.classList.remove('player2') ); cells.forEach( cell => cell.classList.remove('player2Turn') ); cells.forEach( cell => cell.classList.add('player1Turn') ); cells.forEach( cell => cell.removeAttribute('data-disabled') ); screen.screen.classList.remove('player1winner'); screen.screen.classList.remove('player2winner'); screen.screen.classList.remove('drawgame'); screen.img.classList.remove('player1win-img'); screen.img.classList.remove('player2win-img'); screen.text.innerText = 'Winner is '; } } gameCheckerFunctions.js export default class gameCheckerFunctions { static INDEXES = [0, 1, 2] static DIAG_INDEXES = [ [0, 1, 2], [2, 1, 0] ]; static getValueFromArray(array, row, column) { return array[row][column] }
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc static getValueFromArray(array, row, column) { return array[row][column] } static checkRows(boardArray, boardDim, playerClass) { for (let i=0; i < boardDim; i++) { let movesInLine = []; for (let column of this.INDEXES) { movesInLine.push(boardArray[i][column]); } if ( movesInLine.every( cell => cell == playerClass ) ) {return true;} } return false; } static checkColumns(boardArray, boardDim, playerClass) { for (let i=0; i < boardDim; i++) { let movesInLine = []; for (let row of this.INDEXES) { movesInLine.push(boardArray[row][i]); } if ( movesInLine.every( cell => cell == playerClass ) ) {return true;} } return false; } static checkDiags(boardArray, playerClass) { for (let diag of this.DIAG_INDEXES) { let movesInLine = []; for (let i=0; i <= 2; i++) { let move = boardArray[i][diag[i]]; movesInLine.push(move); } if ( movesInLine.every( cell => cell == playerClass ) ) {return true;} } return false; } static checkWinner(boardData, boardDim, playerClass) { if ( this.checkRows(boardData, boardDim, playerClass) || this.checkColumns(boardData, boardDim, playerClass) || this.checkDiags(boardData, playerClass) ) { console.log("This function works, there's a winner!"); return true } else { console.log('No winner this time'); return false } } static checkDraw(moves) { if (moves >= 9) { return true; } else { return false } } constructor() { throw new Error(" This class can't be instantiated"); } } gameStateFunctions.js // FUNCTIONS
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc gameStateFunctions.js // FUNCTIONS export default class gameStateFunctions { static changeTurn(activePlayer, p1Class, p2Class) { //turnFlag = !turnFlag; const newPlayer = (activePlayer == p1Class) ? p2Class : p1Class return newPlayer } static storeMove(cell, boardArray, activePlayer) { console.log(`current state in storeMove(): `) console.log(boardArray); let coordinates = cell.dataset.coord.split(':') const [x, y] = coordinates; if (boardArray[x][y] === null) { boardArray[x][y] = activePlayer; } } static restartGame(state, startingPlayerClass) { state.activePlayer = startingPlayerClass; state.moves = 0; state.boardArray = [[null, null, null], [null, null, null], [null, null, null]]; console.clear(); console.log('GAME RESTARTED'); } constructor() { throw new Error(" This class can't be instantiated"); } }
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc constructor() { throw new Error(" This class can't be instantiated"); } } index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script type="module" src="app.js"></script> <link rel="stylesheet" href="styles/normalize.css"> <link rel="stylesheet" href="styles/styles.css"> <title>Tic-Tac-Toe vanilla JS</title> </head> <body> <div id="board"> <div class="cells"> <div class="cell" id="cell-1" data-coord="0:0"></div> <div class="cell" id="cell-2" data-coord="0:1"></div> <div class="cell" id="cell-3" data-coord="0:2"></div> <div class="cell" id="cell-4" data-coord="1:0"></div> <div class="cell" id="cell-5" data-coord="1:1"></div> <div class="cell" id="cell-6" data-coord="1:2"></div> <div class="cell" id="cell-7" data-coord="2:0"></div> <div class="cell" id="cell-8" data-coord="2:1"></div> <div class="cell" id="cell-9" data-coord="2:2"></div> </div> <div id="done"> <div class="lead"> Winner is </div> <div id="winnerImg"></div> <button id="resetBtn" type="reset">Play Again</button> </div> </div> </body> </html> Answer: Answering Questions How to implement a MVC pattern? Right now, the state and HTML elements are global variables, but I think this could be stored in state and UI classes Also, I'm having troubles with the concept of controller. Is main.js the code that will be the controller in an MVC pattern?
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc First, I want to mention that I love to put all of my state into a single global object like that. I find it to be a very organized way to manage state, and helps developers to keep tabs on all of the potential state of the webpage. Some enterprise libraries, like Redux, actually revolve around the principle of storing the webpage's state into a single object like this. So, don't feel like there's anything wrong with doing that. And, if you want to do it with your view data as well, I don't have a problem with that. (This may not be a very OOP way of doing it, but not everything needs to be OOP) When it comes to designing webpages, what's important is to have a clear separation of UI and business logic. You're already doing this really well (so, kudos to you), but I will give you a couple more tips on how you can further improve this sort of separation further down. Model-view-controller is one way to achieve this sort of separation of UI and business logic, but it isn't the only way, and to be honest I don't find much value in trying to separate out the controller logic from the view logic, the two are already highly coupled, so such separation often does not provide much benefit. But, if you're trying to go for the model-view-controller pattern, what you'll want to do is move all of the definitions for your event listeners into their own controller file. Currently, you have them all defined within app.js. These event listeners can be pretty lightweight, where most of what they do is simply make calls to the model or view. The exact way in which the responsibilities of model, view, and controller should be separated is disputed, you'll find different people with different opinions, but as long as your event listeners are found in one region of your application, your view logic in another, and your business logic in another, and your business logic never touches view or controller logic, you should be golden. There's a better algorithm to check for the winner?
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc There's a better algorithm to check for the winner? There sure is. Try this one out. function checkWinner(boardData, playerClass) { const threeInARows = [ // horizontal [[0, 0], [0, 1], [0, 2]], [[1, 0], [1, 1], [1, 2]], [[2, 0], [2, 1], [2, 2]], // vertical [[0, 0], [1, 0], [2, 0]], [[0, 1], [1, 1], [2, 1]], [[0, 2], [1, 2], [2, 2]], // diagonal [[0, 0], [1, 1], [2, 2]], [[0, 2], [1, 1], [2, 0]] ]; return threeInARows.some( threeInARow => threeInARow.every(([x, y]) => boardData[y][x] === playerClass) ); } While yes, it's possible to derive general-purpose algorithms that check for a three-in-a-row row-wise, column-wise, and on each diagonal, it's not really necessary here. We're dealing with a very small tic-tac-toe board, and it's dead simple to just hard-code all of the different possible three-in-a-rows, and because this is a straightforward solution, it's going to be less likely to be buggy, all while being much simpler to read and understand. Is it a good looking code? How it could be improved? What looks ugly and could be done in a better way? I really would like to develop good practices from the beginning. See my suggestions that I present later on. Keep in mind that many of my suggestions are ones that tend to be the most noticeable for experienced developers, but also the least important. For example, I'll mention that you're inconsistent with your use of quotes. Will developers notice this? Some will, yes. Does this problem matter? Not much, inconsistency in quotes does not effect how easy it is to read or maintain the code. Other problems matter a little more, but many of them are just minor tips that don't matter much. Some features that I would like to implement are a CPU player, storing the score in localStorage, remember the player name, auth, two-player network gamming, etc. I'm in the correct way of doing things?
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc Most of these add-ons should be relatively straightforward. You may have to rework one thing or another to get it done properly, but that's ok for something like this. However, network gaming is a whole different story. Developing a game that can be played over the internet required a very different overall structure to your game. First, you're going to have to ask yourself if you're ok with users having the ability to cheat on this game. Will the users just be playing with friends, or will they be playing with strangers? How much is at stake if they end up playing someone who's cheating? As this is tic-tac-toe, perhaps you won't care so much about cheating, as the game is already a completely unfair game that puts a strong bias on the first player. The reason why I ask this is because this will influence how you architect and write the code. For example, say you design the system so that if you want to take your turn, you simply send a message like "{ type: "OCCUPY_SQUARE", x: 0, y: 1 }" to the server, and the server forwards this message to your opponent. If you care about preventing cheating, you'll additionally have to put checks in place to make sure someone doesn't modify their client's code to send three messages like this in a row, thus winning the game before the opponent has even taken a turn. In some cases, these checks will need to be done on the server. If you don't care about cheat protection (which you probably wouldn't for a game like this), then you can make the server into a simple message-forwarding system, and put the bulk of the logic into the client code, under the assumption that users will not tamper with it, and even if they do, it's not a big deal.
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc Next, you have to architect your program, so that any action that may eventually need to be sent over the wire is implemented as a JSON-serializable message. Here's the basic structure I like to use for this type of program (there's different ways of doing it, this is just what I've done in the past). First, I'll make my model export two things - the current state, and an executeAction() function. All state modifications must be done by sending an action (which is just a plain object) to executeAction(). executeAction() will then read this object's properties and decide how to mutate the state. // --- model.js --- // export const currentState = { ...initial state... }
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc export function executeAction(action) { if (action.type === 'OCCUPY_SQUARE') { const { x, y } = action; // ...logic related to occupying a square... // (Feel free to break out helper functions, so you don't bloat executeAction()) } else if (action.type === 'RESET') { const { someArg } = action; // ...logic related to this action... } else { throw new Error(`Unknown action type ${action.type}`); } }
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc At a later point, when you're ready to hook this game up to the internet, it becomes easy to JSON-serialize these actions and send them to your opponent. For example, if you click a square, the event handler will create an action like { type: 'OCCUPY_SQUARE', x: 1, y: 2 } then send that off to some send function. This function will pass the action along to your executeAction() function, causing your own state to be correctly modified, and it will send the action over the internet, to your opponent's client, where some code on their machine will receive the action and send it into their executeAction() function, causing them to end up in the exact same state as you are in. The next key to this puzzle would be to update the UI based on how the current state was updated. A simple way to do this, would be to simply make it so once you're done calling executeAction() with your desired action, you send the exact same action over to a function exported on the ui side, which we'll call executeUiAction(). The UI will take this action, along with the updated state, and figure out what actually needs to be changed in the UI to bring the UI up to date with what the state looks like. I usually use a slightly more complicated variation of this pattern that's capable of handling some other issues (the details depend on the project I'm working on), but what I presented should get you pretty far, and would probably accomplish everything you need for this tic-tac-toe game. But, feel free to tweak or even change it drastically as you go along, it's just a rough-draft idea of what you can do to handle online play. Structural changes const state = { ... boardDim: 3, ... };
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc boardDim doesn't belong in state, as it's never going to change, so it's not "state". If wanted, you could calculate the board size from boardArray instead, by just doing boardArray.length. You could even make a helper function to do this. (Also, boardDim is not the correct name for this. Technically, the dimensions of the board is 2, it's 2d. Perhaps "size" would be a better word?) Regarding separation of UI from business logic, make sure to keep anything related to the view out of the model. Theoretically, you should be able to rip out the UI and trivially replace it with a completely different one (like, a terminal-based UI), and not have to touch a line of your model's code. Not that this ever happens in real codebases, but this is the sort of separation we're striving to achieve. You seem to generally do good at this, but you do break this here and there, for example, you tend to pass around variables that are named playerClass or startingPlayerClass, alluding to CSS classes, but for all the model knows, CSS may not even be a thing in the environment its running in. I would instead do something along these lines in your model: export PLAYER = { player1: 'player1', player2: 'player2', }
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc This is an "enum" (not really, JavaScript doesn't have enums, but for all intents and purposes we can treat this sort of construct just like an enum). This "enum" will be located inside the model. Your model functions can be defined to expect a value from this enum. Your UI logic can then translate these enum values to CSS class names, or it can even choose to use the enum values as a CSS class name if it so wants. In a similar vein, storeMove() shouldn't accept an HTML element as a parameter, since it shouldn't even know that it's running in an environment where HTML is available. The parsing of the HTML element's data attribute should be done on the UI logic side. From what it looks like, your app.js is mostly UI logic, which is just fine. If this is what you're going for, then go ahead and move all business-logic related stuff out of there (I'm mostly referring to the state object), and move it into the modules that are dedicated to housing the business logic. And, again, if you want to split your UI logic in two, where all event listeners live separately from the rest of the view logic, that's fine too. Misc improvements Most of your modules are structured like this: export default class UIFunctions { static changeTurn(...) { ... } static storeMove(...) { ... } static restartGame(...) { ... } constructor() { throw new Error(" This class can't be instantiated"); } } If you don't intend for the class to ever be constructed, then you're using the wrong tool. A direct alternative would be to just use an object literal, like this: export default { changeTurn(...) { ... }, storeMove(...) { ... }, restartGame(...) { ... } }; But, for these scenarios, an even better solution would be to just export the functions directly from the module, like this: export function changeTurn(...) { ... } export function storeMove(...) { ... } export function restartGame(...) { ... }
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc Make sure to mark something as private if there's no reason to publicly expose it. For example, in gameCheckerFunctions, you can make functions like checkRows() private by placing a # character in front (see this page for more info). Alternatively, if you decide to follow the above recommendation and change this class into a bunch of exported functions, you can simply choose to not export functions like checkRows() to make them private to the module. Try to make your program have a single source of truth for all state/data. If a piece of state can be derived from another piece of state, then create a function to do this transformation and use that function, this is usually simpler than trying to keep two separate pieces of state in sync with each other. One example of extra state is the data-disabled attributes you place on the cell elements. The cells are aware of their coordinates, and you store in the state object who's in what cell, so you can already figure out via other means which cells should be disabled, you don't need this additional data-disabled attribute. Never use ==, always use === instead. Minor Details Take out the console.log()s. Generally, console.log() is used for debugging purposes, not for verbose logging of what your program is doing. In fact, flooding the logs with these sorts of logs can make debugging more difficult, because it's hard to see the logs you care about amidst the myriad of other logs being generated. (If you personally find this sort of logging useful, then by all means continue to do so on your personal projects, but I would refrain from doing it in shared codebases). Instead of having multiline if conditions, I like to break the condition out into a separate variable, for example, instead of this: if ( this.checkRows(boardData, boardDim, playerClass) || this.checkColumns(boardData, boardDim, playerClass) || this.checkDiags(boardData, playerClass) ) { ... }
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc I find it more readable to do this: const hasWon = ( this.checkRows(boardData, boardDim, playerClass) || this.checkColumns(boardData, boardDim, playerClass) || this.checkDiags(boardData, playerClass ); if (hasWon) { ... } You've got a couple of functions that are structured like this: static checkDraw(moves) { if (moves >= 9) { return true; } else { return false; } } Remember that operators such as >= return a boolean already, so this whole function can be rewritten as follows: static checkDraw(moves) { return moves >= 9; } You have this line of code: let cell = this; // currently clicked cell Instead of writing a comment explaining what this variable is, just change the name of the variable to be more self-explanatory. let currentlyClickedCell = this; The getValueFromArray() function is dead code. Stuff that really doesn't matter You're missing a number of semicolons. And, after function myFnName() {} a semicolon is not needed. Be consistent with your use of single/double quotes, and with let/const. You seem to use these all randomly. As an overwhelming common convention among JavaScript developers, class names start with an upper-case letter (instead of gameStateFunctions do GameStateFunctions). You've probably been told to always use {} after an if. This is good advice, however, it's unnecessary if you choose to place a single statement on the same line as the if. // Instead of this: if ( movesInLine.every( cell => cell === playerClass ) ) {return true;} // Just do this: if ( movesInLine.every( cell => cell === playerClass ) ) return true; Update: Answering comments How would I separate out controller logic? Here's an extremely simple, concrete example that shows how one might separate view, model, and controller logic from a very simple webpage. // MODEL // const model = { state: { counter: 0 }, moveCountBy(delta) { model.state.counter += delta; }, }; // CONTROLLER //
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
javascript, beginner, object-oriented, tic-tac-toe, mvc // CONTROLLER // const controller = { onIncrement() { model.moveCountBy(1); view.updateCounterDisplay(); }, onDecrement() { model.moveCountBy(-1); view.updateCounterDisplay(); }, }; // VIEW // let view; { const decrementEl = document.getElementById('decrement'); const incrementEl = document.getElementById('increment'); const counterDisplayEl = document.getElementById('counter-display'); decrementEl.addEventListener('click', controller.onDecrement); incrementEl.addEventListener('click', controller.onIncrement); view = { updateCounterDisplay() { counterDisplayEl.innerText = model.state.counter; }, init() { view.updateCounterDisplay(); } }; } // MAIN // view.init(); <button id="decrement">-</button> <span id="counter-display"></span> <button id="increment">+</button> Don't take this example as doctrine. It's just a rough-draft idea of how you could make the separation happen. There's different ways to do it, and if you feel like something else would be more organized, then do it.
{ "domain": "codereview.stackexchange", "id": 43278, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "javascript, beginner, object-oriented, tic-tac-toe, mvc", "url": null }
array, functional-programming, go, generics Title: Suggestions for improvement for generic array and map functions in Go 1.18 Question: Yesterday I build some generic functions for the new official Golang 1.18 release. What do you think about it and what could be added and improved? package main import ( "fmt" "log" "reflect" ) func ToString(this any) string { return fmt.Sprintf("%v", this) } type List[V any] []V func (this List[V]) Size() int { return len(this) } func (this *List[V]) Add(next V) *List[V] { *this = append(*this, next) return this } func (this List[V]) Get(v int) V { return this[v] } func (this *List[V]) Map(f func(V) V) *List[V] { var res List[V] for _, v := range *this { res.Add(f(v)) } return &res } func (this *List[V]) Filter(f func(V) bool) *List[V] { var res List[V] for _, v := range *this { if f(v) { res.Add(v) } } return &res } type Map[K comparable, V any] map[K]V func (this Map[K, V]) Size() int { return len(this) } func (this *Map[K, V]) Add(key K, value V) *Map[K, V] { (*this)[key] = value return this } func (this *Map[K, V]) Get(key K) V { return (*this)[key] } func (this Map[K, V]) Keys() *List[V] { res := make(List[V], 0, len(this)) for _, v := range this { res = append(res, v) } return &res } func (this Map[K, V]) Values() *List[V] { res := make(List[V], 0, len(this)) for _, v := range this { res = append(res, v) } return &res } func (this *Map[K, V]) ContainsKey(key K) bool { if _, ok := (*this)[key]; ok { return true } return false } func (this *Map[K, V]) ContainsValue(value V) bool { for _, v := range *this { if reflect.TypeOf(v) == reflect.TypeOf(value) && ToString(v) == ToString(value) { return true } } return false }
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics func (this *Map[K, V]) Map(f func(K, V) (K, V)) *Map[K, V] { res := make(Map[K, V], 0) for k, v := range *this { res.Add(f(k, v)) } return &res } func (this *Map[K, V]) Filter(f func(V) bool) *Map[K, V] { res := make(Map[K, V], 0) for k, v := range *this { if f(v) { res.Add(k, v) } } return &res } func main() { listTemp := make(List[int], 0) listTemp.Add(1) log.Println(listTemp) log.Println("string: " + ToString(listTemp.Get(0))) mapTemp := make(Map[string, string], 0) mapTemp.Add("al", "aluminum").Map(func(k string, v string) (string, string) { log.Println("first call: " + v) if v == "aluminum" { return k, "aluminium" } return k, v }).Values().Add("silver").Map(func(v string) string { log.Println("second call: " + v) return v }) mapTemp.Add("ag", "silver") mapTemp.Add("o", "oxygen") log.Println(mapTemp) log.Println("string: " + ToString(mapTemp)) log.Println(mapTemp.ContainsKey("al")) log.Println(mapTemp.ContainsKey("1")) log.Println(mapTemp.Values()) log.Println(mapTemp.Size()) log.Println(mapTemp.Values().Size()) log.Println(mapTemp.Get("al")) log.Println(mapTemp.Values().Get(2)) mapTemp2 := make(Map[string, int], 0) log.Println(mapTemp2.Add("al", 1).ContainsValue(1)) }
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics mapTemp2 := make(Map[string, int], 0) log.Println(mapTemp2.Add("al", 1).ContainsValue(1)) } You can also try it out on golang playground: https://go.dev/play/p/7OFh0KCmHSc I wanted to build functions which you can add behind each other like in Java or Dart, therefore I give often give back the value given into the function or for example on Map() I give back the changed value. Is this intuitive? I didn't find any functioning solutions out there yet, so please feel free to use my solution and improve it. Edit: After a bit of time I would also add these functions: func (l *List[V]) RemoveFirst() *List[V] { if l.Size() > 0 { res := (*l)[1:] return &res } return l } func (l *List[V]) RemoveLast() *List[V] { if l.Size() > 0 { res := (*l)[:len(*l)-1] return &res } return l } (...) func (m *Map[K, V]) RemoveKey(k K) *Map[K, V] { res := *m delete(res, k) return &res } Instead of this I now changed to a single character as a receiver (l for list and m for map). Do you think that it would make sense to also change the initial map and list or is it more intuitive to just give back the changed value? So if you call list.RemoveKey(key) alter the initial list AND give back the altered value or ONLY give back the altered value?
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics Answer: Right, I've had a closer look at the Map type you posted here (don't know why, but that one piqued my interest more than the list). There's quite a lot to unpack already, so I'm just going to focus on that part of your code to start things off with. After that, I've added a couple of notes specifically on the List type, but there's not much to say about your List specifically, so the bulk of this review focuses on the Map type (as a lot of the comments apply to List, too), and your use of generics specifically. Full disclosure: I'm not opposed to generics in general, but I've seen progress on projects crawl to a halt one too many times because of generic-overuse. Generics are a powerful tool, but shouldn't be used for the sake of using them. They should be used when called for. Golang generics has been talked of for years and years now, and I've always been of the opinion that I'd need to find myself in a situation where generics would actually boost productivity for me to want them. This has happened, but really, it hasn't happened anywhere near as often as you'd expect given how many people have claimed that "without generics, the language is useless". Take this as you will, but I'm just telling you that I may have some bias going in to this, but I've tried to ignore the "why" you wrote this, and instead focused on what you wrote. Let's start with some basic comments about the generic map, and how you're using it. type Map[K comparable, V any] map[K]V That's fine: you're essentially creating a type that can be instantiated to be any sort of map. Shocker, I know, that's what generics are supposed to do. What is important to note is that underneath it all, your type is just a map, that has the types for K and V set at compile-time. To all intents and purposes, then, its usage is no different to that of any other map. First of all, this is a bit of a pedantic nit-pick thing, but this: mapTemp := make(Map[string, string], 0)
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics can be written like you would do any other map (with some generic syntax): mapTemp := Map[string, string]{} This also allows you to create generic map literals: mapTemp := Map[int64, uint64]{ 1: 1, 2: 2, } That's nice, and I thought I'd mention it here because your code looks like you hadn't considered this. Another thing to consider is that, because this is just a map like any other, there's no reason why somebody wouldn't be able to write this: mapTemp["foo"] = "bar" // and delete(mapTemp, "foo") Completely side-stepping your methods. Putting it bluntly, that's what I would do, because I'm kind of struggling to see why I'd use those methods like this: func (m *Map[K, V]) RemoveKey(k K) *Map[K, V] { res := *m delete(res, k) return &res } Looking at this method, you may think that you're deleting a key from a copy (res := *m), and then returning a copy of the map. The thing is: both m and res end up pointing to the same underlying map. The use of res is redundant at best, and misleading at worst. Remember how go maps are implemented underneath: type hmap struct { Count int // number of data stored in map, used by Len (map) Flags uint8 // flags will identify the current map. For example, the 4th bit of hashwriting = 4 indicates that goroutine is writing to the map B uint8 // map has 2 ^ B buckets Hash 0 uint32 // seed of hash algorithm Buckets unsafe. Pointer // 2 ^ B arrays of buckets Oldbuckets unsafe. Pointer // during the expansion, there is a value in oldbuckets. Map is incremental expansion, not one-time completion. Expansion is mainly triggered by insertion and deletion ...... }
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics As you can see, the actual data is accessed/managed through unsafe.Pointer fields (i.e. pointers). Creating a copy is just going to copy the exact same pointers over, so delete(res, k) will delete from m, too. That brings me to the biggest gripe I have with all of your methods: Why use pointer receivers in the first place? func (m Map[K, V]) Add(k K, v V) { m[k] = v } works just as well. Sure, you don't have the chainable interface you have now, but let's be honest: do you care? In reality, you don't really see all that much code that does something like this: aMap["foo"] = 1 aMap["bar"] = 2 aMap["zar"] = 3 You more often see keys being copied over in a loop, in which case a chainable interface doesn't help, or you see maps being initialised with a set of K/V pairs. As I mentioned earlier, you can do this with your generic map types all the same, and without messy code like: tempMap.Add("foo", 1).Add("bar", 2).Add("zar", 3) Basically, if I were to implement a generic map type like this (with convenience methods like Filter and Keys - which we'll cover later), I'd just change the pointer receivers to be regular receivers, and I would preserve certain behaviours that you're currently missing (mainly the bool return when getting something from a map that allows you to differentiate between a nil value and a missing key): func (m Map[K, V]) Set(k K, v V) { m[k] = v } func (m Map[K, V]) Get(k K) (V, bool) { v, ok := m[k] return v, ok }
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics Other than that, your generic maps are fine, but they don't really offer any advantages over conventional maps. They're definitely not safe for concurrent access, for a start. I'd consider wrapping this map in a type that adds a mutex or something to at least provide that safety, and have a compelling reason to force people to use this interface. If not, the methods you've added like Filter are more of a nuisance than they offer a real advantage. As they stand, I can't use them in existing code: myMap := map[string]string{} myMap.Filter() // doesn't exist To use this Filter method, I have to go through my code and change myMap := pkg.Map[string, string]{}, then update all functions that I call with this map as an argument. It's a massive PITA to refactor things this way. Even if you bite this bullet, there will be a time where you have to pass a regular map to some 3rd party package, so you'll probably want to add some utility function like this: func (m Map[K, V]) Raw() map[K]V { ret := make(map[K]V, len(m)) for k, v := range m { ret[k] = v } return ret } But this comes at a cost: every time you call this, you'll allocate a copy of the map, for no reason other than, what IMO would be, your insistence on using a generic type, rather than relying on generic functions to achieve exactly the same thing... That would be my main argument to get rid of the methods/receiver functions. Instead, I would much rather rewrite the Filter function into something like this: func Filter[K comparable, V any](m map[K]V, f func(V) bool) map[K]V { ret := make(map[K]V, len(m)) for k, v := range m { if f(v) { ret[k] = v } } return ret }
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics Now I have a generic function that allows me to filter all existing maps through this single function. If you already have this generic map type in use, you can easily adapt this Filter function to work with both: func Filter[K comparable, V any, M ~map[K]V](m M, f func(V) bool) M { ret := make(M, len(m)) for k, v := range m { if f(v) { ret[k] = v } } return ret } There we go: filter generic maps, and existing ones in a single function. You can do the same thing with the other methods just as easily. You want a function to get the keys from any map? Easy: func Keys[K comparable, V any, M ~map[K]V](m M) []K { ret := make([]K, 0, len(m)) for k := range m { ret = append(ret, k) } return ret } Map Recap Just to summarise: The generic type itself is fine, but limits you to new code that uses this map type, or requires a rewrite of existing code. That's sub-optimal. If you adopt this type, which just will leave you having to copy the data into an actual map just to use some package that you can't convert. Having a generic way to Filter a map, or get the keys is a valid use-case for generics, but doesn't merit creating a new type. Generic functions can be written to work with any type that, at its core, is just a map. These functions are even more generic because they're not tied to a specific type. A type like this Map that aims to supersede an existing one should not take away any of the existing features (e.g v, ok := m[k] boolean flag). It should also have a reason for existing (ie add something of value). I can't really see a reason for this map to exist if it doesn't have some intrinsic feature that a regular map doesn't have (thread-safety for example).
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics I'm going to end the Map review here, and I'll revisit this once my fingers have recovered from typing this wall of text and review the List type. I suspect, however, that much of what I've said about the Map type will carry over to the List type, as it seems to be equivalent to []any, but instead of allowing s = append(s, 1, 2, 3, 4) (variadic append), you've restricted the interface to s.Add(1).Add(2).Add(3), which is so cumbersome, most people will just end up using append directly and again: side-step the methods you wrote. Well, I just couldn't help myself and briefly looked at the implementation of List. As I expected, it's basically just a slice, masked by some generic syntax. In doing so, you've limited the possibility to append multiple values in a single line (the append comment I made earlier), to gain very little... Sure, you can now have a variable of type List[int] or something, and call list.Filter() on it, but by slightly altering your Filter function, you can open the same Filter function open to all slices in existing code: func Filter[V any](s []V, func (v V) bool) []V { ret := make([]V, 0, len(s)) for _, v := range s { if f(v) { ret = append(ret, v) } } return ret } One thing that really stands out, though, is the Map function. I don't see why you'd create a copy of the original slice/list there. When I map a slice, I kind of expect that to alter the slice I'm mapping, so a generic MapSlice function for me would look something like this: func MapSlice[V any](s []V, f func(V) V) { for i, v := range s { s[i] = f(v) } } If I don't want to alter the original slice, I would just call it like this: MapSlice(append([]int{}, s...), func(i int) int { return i+1 })
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics When it comes to the remove first/last functions you want to add, I can only say: what's the use? The native slice/map types are arguably better to use, and if you want to remove the first or last element from a slice, you can do that in-line, or at worst have a function like func RMFirst[V any](s []V) []V { if len(s) == 0 { return s } return s[1:] } Deleting keys from maps, because delete(m, k) where k doesn't exist is defined as a no-op, doesn't merit a function - generic or otherwise. The main reason why I didn't review the List code along side the Map stuff was that I expected the List type to be more than a masked slice. When I talk about lists, I'm thinking back to the old C/C++ days and my mind goes to single/double linked lists and the like. None of the methods you have here, though, suggest that this is a list. You just have a slice, and nothing more. Like I said earlier: if you're going to introduce a new type, don't remove existing features (e.g. append), and add new ones: linking in the list, list iterators, and thread safety. Again, doing so would likely require you to create a struct, add a mutex, add a node type to link your list, and requires custom code to insert/delete values. and all that good stuff.
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics As a bit of an insomniac, I found myself writing a little bit of code last night and decided to implement some kind of thread-save generic map-based type. I decided to add a method to easily merge in an existing map, and extract a regular old map from the wrapper type. I also thought that, if thread safety is a concern (which is why you'd use a type like sync.Map), I figured it makes sense to have an iterator of sorts. The iterator itself would not be safe for concurrent use, but then the rationale is that you would spawn a number of routines and each one of them would receive their own iterator, so that's not a major issue. I wrote this in pretty much one go, and added some tests to make sure everything works as expected. The package itself looks something like this: import ( "errors" "sort" "sync" ) type SMap[K comparable, V any] struct { mu *sync.RWMutex m map[K]V } type SMapIter[K comparable, V any] struct { l sync.Locker i int keys []K k K v V m *SMap[K, V] } // NewSMap creates a new sync-safe map func NewSMap[K comparable, V any](init map[K]V) *SMap[K, V] { r := &SMap[K, V]{ mu: &sync.RWMutex{}, m: map[K]V{}, } // initialise r.Merge(init, true) // overwrite doesn't make a difference but we can skip pointless lookups return r } // Len returns underlying map length func (s *SMap[K, V]) Len() int { s.mu.RLock() defer s.mu.RUnlock() return len(s.m) } // Merge merges a given map into this type func (s *SMap[K, V]) Merge(m map[K]V, overwrite bool) { if len(m) == 0 { return } s.mu.Lock() for k, v := range m { if !overwrite { if _, ok := s.m[k]; ok { continue } } s.m[k] = v } s.mu.Unlock() } // Clone creates a copy func (s *SMap[K, V]) Clone() *SMap[K, V] { s.mu.RLock() r := NewSMap[K, V](s.m) // create new instance s.mu.RUnlock() return r }
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics // Get simply gets the value for a given key, returns false if the key doesn't exist func (s *SMap[K, V]) Get(k K) (V, bool) { s.mu.RLock() v, ok := s.m[k] s.mu.RUnlock() return v, ok } // Set sets a value for a given key (overwrites existing value) func (s *SMap[K, V]) Set(k K, v V) { s.mu.Lock() s.m[k] = v s.mu.Unlock() } // CAS is a simple Check And Set, returns false if the key was not set func (s *SMap[K, V]) CAS(k K, v V) bool { s.mu.Lock() defer s.mu.Unlock() if _, ok := s.m[k]; ok { return false } s.m[k] = v return true } // Raw returns a copy of the underlying map as a standard map[K]V func (s *SMap[K, V]) Raw() map[K]V { s.mu.RLock() ret := make(map[K]V, len(s.m)) for k, v := range s.m { ret[k] = v } s.mu.RUnlock() return ret } // Delete deletes one or more of the keys. Non-existing keys are a no-op as with a normal map func (s *SMap[K, V]) Delete(keys ...K) { s.mu.Lock() for _, k := range keys { delete(s.m, k) } s.mu.Unlock() } // Keys returns a slice of all keys func (s *SMap[K, V]) Keys() []K { s.mu.RLock() ks := make([]K, 0, len(s.m)) for k := range s.m { ks = append(ks, k) } s.mu.RUnlock() return ks } // Iter returns an iterator, iteration is non-deterministic like a normal map, unless // the optional sort function is provided, in which case the keys will be sorted using sort.SliceStable // After iterating over the values, Close must be called! func (s *SMap[K, V]) Iter(f func(a, b int) bool) *SMapIter[K, V] { iter := &SMapIter[K, V]{ l: s.mu.RLocker(), m: s, i: 0, } iter.l.Lock() // acquire lock already keys := s.Keys() if f != nil { sort.SliceStable(keys, func(i, j int) bool { return f(keys[i], keys[j]) }) } iter.keys = keys return iter }
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
array, functional-programming, go, generics // Next moves the iterator to the next element in the map, returns false if we already reached the end func (i *SMapIter[K, V]) Next() bool { if i.i >= len(i.keys) { return false } // set key/value i.k = i.keys[i.i] i.v = i.m.m[i.k] i.i++ // move index return true } // Key returns current key func (i *SMapIter[K, V]) Key() (K, error) { var k K if i.keys == nil { return k, errors.New("iterator closed") } return i.k, nil } // Val returns current value func (i *SMapIter[K, V]) Val() (V, error) { var v V if i.keys == nil { return v, errors.New("iterator closed") } return i.v, nil } // Close releases the iterator func (i *SMapIter[K, V]) Close() { var ( k K v V ) // clear all fields i.keys = nil i.k = k i.v = v i.i = 0 i.m = nil // release lock i.l.Unlock() } I've since created a repo on github in case anyone is interested.
{ "domain": "codereview.stackexchange", "id": 43279, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "array, functional-programming, go, generics", "url": null }
python, beginner, chess Title: Automate the Boring Stuff Chapter 5 Project - Chess Dictionary Validator Question: First post, very new to programming. This is my solution for the chapter 5 project of Automate the Boring Stuff and I wondered if I am making any mistakes and is there a way to make it more efficient using what the book has taught thus far. The project description: In this chapter, we used the dictionary value {'1h': 'bking', '6c': 'wqueen', '2g': 'bbishop', '5h': 'bqueen', '3e': 'wking'} to represent a chess board. Write a function named isValidChessBoard() that takes a dictionary argument and returns True or False depending on if the board is valid. A valid board will have exactly one black king and exactly one white king. Each player can only have at most 16 pieces, at most 8 pawns, and all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. The piece names begin with either a 'w' or 'b' to represent white or black, followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king'. This function should detect when a bug has resulted in an improper chess board. My code: MyBoard = {'a8': 'bR', 'b8': 'bN', 'c8': 'bB', 'd8': 'bK', 'e8': 'bQ', 'f8': 'bB', 'g8': 'bN', 'h8': 'bR', 'a7': 'bp', 'b7': 'bp', 'c7': 'bp', 'd7': 'bp', 'e7': 'bp', 'f7': 'bp', 'g7': 'bp', 'h7': 'bp', 'a6': '', 'b6': '', 'c6': '', 'd6': '', 'e6': '', 'f6': '', 'g6': '', 'h6': '', 'a5': '', 'b5': '', 'c5': '', 'd5': '', 'e5': '', 'f5': '', 'g5': '', 'h5': '', 'a4': '', 'b4': '', 'c4': '', 'd4': '', 'e4': '', 'f4': '', 'g4': '', 'h4': '', 'a3': '', 'b3': '', 'c3': '', 'd3': '', 'e3': '', 'f3': '', 'g3': '', 'h3': '', 'a2': 'wp', 'b2': 'wp', 'c2': 'wp', 'd2': 'wp', 'e2': 'wp', 'f2': 'wp', 'g2': 'wp', 'h2': 'wp', 'a1': 'wR', 'b1': 'wN', 'c1': 'wB', 'd1': 'wQ', 'e1': 'wK', 'f1': 'wB', 'g1': 'wN', 'h1': 'wR'}
{ "domain": "codereview.stackexchange", "id": 43280, "lm_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, beginner, chess", "url": null }
python, beginner, chess def isValidChessBoard(board): valid_count = True valid_position = True valid_board = True piece_count = {} black_pieces = 0 white_pieces = 0 board_pieces = list(board.values()) position = list(board.keys()) position_message = 'Correct position.' piececount_message = '' message = '' #Counting blacks and whites for i in board_pieces: if i == '': pass elif i[0] == 'b': black_pieces += 1 elif i[0] == 'w': white_pieces += 1 piececount_message = 'There are ' + str(white_pieces) + ' white pieces and ' + str(black_pieces) + ' black pieces.' #Checking valid position for p in position: position_str = int(p[1]) if position_str > 8 or position_str < 1: valid_position = False position_message = 'Invalid position.' #Counting the number of each piece and setting default for empty spaces for v in MyBoard.values(): piece_count.setdefault(v, 0) piece_count[v] += 1 print(piece_count) #Checking King numbers if piece_count.get('wK', 0) > 1 or piece_count.get('bK', 0) > 1\ or piece_count.get('wK', 0) < 1 or piece_count.get('bK', 0) < 1: valid_count = False message = 'King count error.' #Checking Queen numbers elif piece_count.get('wQ', 0) > 1 or piece_count.get('bQ', 0) > 1\ or piece_count.get('wQ', 0) < 1 or piece_count.get('bQ', 0) < 1: valid_count = False message = 'Queen count Error.' #Checking Bishop numbers elif piece_count.get('wB', 0) > 2 or piece_count.get('bB', 0) > 2\ or piece_count.get('wB', 0) < 2 or piece_count.get('bB', 0) < 2: valid_count = False message = 'Bishop count error.'
{ "domain": "codereview.stackexchange", "id": 43280, "lm_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, beginner, chess", "url": null }
python, beginner, chess #Checking Knight numbers elif piece_count.get('wN', 0) > 2 or piece_count.get('bN', 0) > 2\ or piece_count.get('wN', 0) < 2 or piece_count.get('bN', 0) < 2: valid_count = False message = 'Knight count error.' #Checking Rook numbers elif piece_count.get('wR', 0) > 2 or piece_count.get('bR', 0) > 2\ or piece_count.get('wR', 0) < 2 or piece_count.get('bR', 0) < 2: valid_count = False message = 'Rook count error.' #Checking Pawn numbers elif piece_count.get('wp', 0) > 8 or piece_count.get('bp', 0) > 8\ or piece_count.get('wp', 0) < 8 or piece_count.get('bp', 0) < 8: valid_count = False message = 'Pawn count error.' else: message = 'Correct number of pieces on the board.' valid_board = valid_count and valid_position print(piececount_message) print(position_message) print(message) print('Board Valid: ' + str(valid_board) + '.') isValidChessBoard(MyBoard) Answer: Your implementation has broken the spec. Pieces aren't supposed to have a single letter to identify them; they're supposed to have the full word. Your message and print code is non-ideal because: it complicates your implementation; it wasn't asked for in the spec; and it forces all callers to produce console output whether they wanted it or not. So it should go away. Your # Checking ... numbers code is repetitive and can be simplified by use of a lookup dictionary for expected counts of each piece. Another way that you've broken the spec - re-read this section: returns True or False depending on if the board is valid Your function does not return. Otherwise, consider: Add type hints Make a simple object-oriented interface for a Piece Suggested from typing import NamedTuple, Iterator, Literal
{ "domain": "codereview.stackexchange", "id": 43280, "lm_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, beginner, chess", "url": null }
python, beginner, chess Suggested from typing import NamedTuple, Iterator, Literal class Piece(NamedTuple): row: Literal['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] col: Literal['1', '2', '3', '4', '5', '6', '7', '8'] player: Literal['b', 'w'] piece: Literal['pawn', 'knight', 'bishop', 'rook', 'queen', 'king'] @classmethod def from_pair(cls, pos: str, piece: str) -> 'Piece': row, col = pos return cls(row=row, col=col, player=piece[0], piece=piece[1:]) @property def is_valid(self) -> bool: return ( # all pieces must be on a valid space from '1a' to '8h'; that is, a piece can’t be on space '9z'. self.row in {'a','b','c','d','e','f','g','h'} and self.col in {'1','2','3','4','5','6','7','8'} # The piece names begin with either a 'w' or 'b' to represent white or black and self.player in {'b','w'} # followed by 'pawn', 'knight', 'bishop', 'rook', 'queen', or 'king' and self.piece in {'pawn', 'knight', 'bishop', 'rook', 'queen', 'king'} ) def parse_pieces(board: dict[str, str]) -> Iterator[Piece]: for pos, player_piece in board.items(): if player_piece != '': yield Piece.from_pair(pos, player_piece) def is_valid_chess_board(board: dict[str, str]) -> bool: try: pieces = list(parse_pieces(board)) except IndexError: return False if not all(piece.is_valid for piece in pieces): return False counts = { 'pawn': 8, 'knight': 2, 'bishop': 2, 'rook': 2, 'queen': 1, 'king': 1, } for player in 'bw': for piece_name, piece_count in counts.items(): count = sum( piece.player == player and piece.piece == piece_name for piece in pieces ) if count != piece_count: return False return True
{ "domain": "codereview.stackexchange", "id": 43280, "lm_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, beginner, chess", "url": null }
python, beginner, chess return True def main() -> None: my_board = { 'a8': 'brook', 'b8': 'bknight', 'c8': 'bbishop', 'd8': 'bking', 'e8': 'bqueen', 'f8': 'bbishop', 'g8': 'bknight', 'h8': 'brook', 'a7': 'bpawn', 'b7': 'bpawn', 'c7': 'bpawn', 'd7': 'bpawn', 'e7': 'bpawn', 'f7': 'bpawn', 'g7': 'bpawn', 'h7': 'bpawn', 'a6': '', 'b6': '', 'c6': '', 'd6': '', 'e6': '', 'f6': '', 'g6': '', 'h6': '', 'a5': '', 'b5': '', 'c5': '', 'd5': '', 'e5': '', 'f5': '', 'g5': '', 'h5': '', 'a4': '', 'b4': '', 'c4': '', 'd4': '', 'e4': '', 'f4': '', 'g4': '', 'h4': '', 'a3': '', 'b3': '', 'c3': '', 'd3': '', 'e3': '', 'f3': '', 'g3': '', 'h3': '', 'a2': 'wpawn', 'b2': 'wpawn', 'c2': 'wpawn', 'd2': 'wpawn', 'e2': 'wpawn', 'f2': 'wpawn', 'g2': 'wpawn', 'h2': 'wpawn', 'a1': 'wrook', 'b1': 'wknight', 'c1': 'wbishop', 'd1': 'wqueen', 'e1': 'wking', 'f1': 'wbishop', 'g1': 'wknight', 'h1': 'wrook', } print(is_valid_chess_board(my_board)) if __name__ == '__main__': main()
{ "domain": "codereview.stackexchange", "id": 43280, "lm_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, beginner, chess", "url": null }
c++, file-system, c++20, dynamic-loading Title: Lengthening the time it takes to access files using function hooking Question: https://github.com/speedrun-program/load_extender This is something I made and posted here about a year ago, but I decided to remake it. To compile this on Windows, you need to install EasyHook. load_extender_injector.cpp (only used on Windows because LD_PRELOAD and DYLD_INSERT_LIBRARIES can be used on Linux and Mac OS) #include <tchar.h> #include <cstdio> // easyhook.h installed with NuGet // https://easyhook.github.io/documentation.html #include <easyhook.h> #include <Windows.h> void getExitInput(char ch) { for (; ch != '\n'; ch = std::getchar()); printf("Press Enter to exit\n"); ch = std::getchar(); } int _tmain(int argc, _TCHAR* argv[]) { WCHAR* dllToInject32 = nullptr; WCHAR* dllToInject64 = nullptr; _TCHAR* lpApplicationName = argv[0]; DWORD lpBinaryType = 0; if (GetBinaryType(lpApplicationName, &lpBinaryType) == 0 || (lpBinaryType != 0 && lpBinaryType != 6)) { std::printf("ERROR: This exe wasn't identified as 32-bit or as 64-bit\n"); getExitInput('\n'); return 0; } else if (lpBinaryType == 0) { dllToInject32 = (WCHAR*)L"load_extender_32.dll"; } else { dllToInject64 = (WCHAR*)L"load_extender_64.dll"; } std::printf("Enter the process Id: "); long long int PIDLongLong = 0; char ch = std::getchar(); for (; ch != '\n'; ch = std::getchar()) { if (ch >= '0' && ch <= '9') { ch = ch - '0'; // this prevents a warning message PIDLongLong *= 10; PIDLongLong += ch; } if (PIDLongLong > 4294967295) { std::printf("PID too large\n"); getExitInput(ch); return 0; } }
{ "domain": "codereview.stackexchange", "id": 43281, "lm_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++, file-system, c++20, dynamic-loading", "url": null }
c++, file-system, c++20, dynamic-loading NTSTATUS nt = RhInjectLibrary( (DWORD)PIDLongLong, // The process to inject into 0, // ThreadId to wake up upon injection EASYHOOK_INJECT_DEFAULT, dllToInject32, // 32-bit dllToInject64, // 64-bit nullptr, // data to send to injected DLL entry point 0 // size of data to send ); if (nt != 0) { std::printf("RhInjectLibrary failed with error code = %d\n", nt); PWCHAR err = RtlGetLastErrorString(); std::printf("%ls\n", err); getExitInput(ch); return 0; } std::printf("Library injected successfully.\n"); getExitInput(ch); return 0; } load_extender.cpp #include <cstdio> #include <climits> #include <mutex> #include <thread> #include <chrono> #include <vector> #include <string> #include <string_view> #include <unordered_map> #ifdef _WIN32 // easyhook.h installed with NuGet // https://easyhook.github.io/documentation.html #include <easyhook.h> #include <Windows.h> using wcharOrChar = wchar_t; // file paths are UTF-16LE on Windows using strType = std::wstring; using svType = std::wstring_view; #else #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <dlfcn.h> using wcharOrChar = char; using strType = std::string; using svType = std::string_view; #endif // using multiple cpp files made exe bigger, so definitions are in this header #include "shared_stuff.h" static myMapType m; static std::mutex mutexForMap = setupMap(m);
{ "domain": "codereview.stackexchange", "id": 43281, "lm_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++, file-system, c++20, dynamic-loading", "url": null }
c++, file-system, c++20, dynamic-loading static myMapType m; static std::mutex mutexForMap = setupMap(m); #ifdef _WIN32 static NTSTATUS WINAPI NtCreateFileHook( PHANDLE FileHandle, ACCESS_MASK DesiredAccess, POBJECT_ATTRIBUTES ObjectAttributes, PIO_STATUS_BLOCK IoStatusBlock, PLARGE_INTEGER AllocationSize, ULONG FileAttributes, ULONG ShareAccess, ULONG CreateDisposition, ULONG CreateOptions, PVOID EaBuffer, ULONG EaLength) { const wchar_t* path = (const wchar_t*)(ObjectAttributes->ObjectName->Buffer); int pathEndIndex = (ObjectAttributes->ObjectName->Length) / sizeof(wchar_t); int filenameIndex = pathEndIndex; for (; filenameIndex >= 0 && path[filenameIndex] != '\\'; filenameIndex--); filenameIndex++; // moving past '\\' character or to 0 if no '\\' was found auto it = m.find(svType(path + filenameIndex, (size_t)pathEndIndex - filenameIndex)); if (it != m.end()) { delayFile(m, it->second, mutexForMap); } return NtCreateFile( FileHandle, DesiredAccess, ObjectAttributes, IoStatusBlock, AllocationSize, FileAttributes, ShareAccess, CreateDisposition, CreateOptions, EaBuffer, EaLength ); } extern "C" void __declspec(dllexport) __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO * inRemoteInfo); void __stdcall NativeInjectionEntryPoint(REMOTE_ENTRY_INFO* inRemoteInfo) { HOOK_TRACE_INFO hHook1 = { nullptr }; HMODULE moduleHandle = GetModuleHandle(TEXT("ntdll")); if (moduleHandle) { LhInstallHook( GetProcAddress(moduleHandle, "NtCreateFile"), NtCreateFileHook, nullptr, &hHook1 ); }
{ "domain": "codereview.stackexchange", "id": 43281, "lm_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++, file-system, c++20, dynamic-loading", "url": null }