text
stringlengths
1
2.12k
source
dict
python, beginner, graphics, turtle-graphics, raytracing d = b**2 - 4 * a * c if d < 0: point_of_contact = [] return False else: if d == 0: solution_1 = (-b - math.sqrt(d)) / (2 * a) point_of_contact = [ camera[0] + solution_1 * (pixel[0] - camera[0]), camera[1] + solution_1 * (pixel[1] - camera[1]), camera[2] + solution_1 * (pixel[2] - camera[2]), ] return True else: solution_1 = (-b - math.sqrt(d)) / (2 * a) solution_2 = (-b + math.sqrt(d)) / (2 * a) point_of_contact1 = [ camera[0] + solution_1 * (pixel[0] - camera[0]), camera[1] + solution_1 * (pixel[1] - camera[1]), camera[2] + solution_1 * (pixel[2] - camera[2]), ] point_of_contact2 = [ camera[0] + solution_2 * (pixel[0] - camera[0]), camera[1] + solution_2 * (pixel[1] - camera[1]), camera[2] + solution_2 * (pixel[2] - camera[2]), ] distance1 = math.sqrt( (point_of_contact1[0] - camera[0]) ** 2 + (point_of_contact1[1] - camera[1]) ** 2 + (point_of_contact1[2] - camera[2]) ** 2 ) distance2 = math.sqrt( (point_of_contact2[0] - camera[0]) ** 2 + (point_of_contact2[1] - camera[1]) ** 2 + (point_of_contact2[2] - camera[2]) ** 2 ) if distance1 < distance2: point_of_contact = point_of_contact1 else: point_of_contact = point_of_contact2 return True def color(pixel, diffrence_in_angle, spector): turtle.penup() turtle.pencolor(1 - diffrence_in_angle, 0 + spector, 0 + spector) turtle.goto(pixel[0], pixel[1]) turtle.dot() turtle.pendown() turtle.penup()
{ "domain": "codereview.stackexchange", "id": 45557, "lm_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, graphics, turtle-graphics, raytracing", "url": null }
python, beginner, graphics, turtle-graphics, raytracing def getColor(sphere, point_of_contact): global diffrence_in_angle global spector global spector_1 spector = 0 spector_1 = 0 normal_vector = [ point_of_contact[0] - sphere[0], point_of_contact[1] - sphere[1], point_of_contact[2] - sphere[2], ] light_vector = [ light[0] - point_of_contact[0], light[1] - point_of_contact[1], light[2] - point_of_contact[2], ] step_1 = ( (normal_vector[0] * light_vector[0]) + (normal_vector[1] * light_vector[1]) + (normal_vector[2] * light_vector[2]) ) step_2 = math.sqrt( normal_vector[0] ** 2 + normal_vector[1] ** 2 + normal_vector[2] ** 2 ) step_3 = math.sqrt( light_vector[0] ** 2 + light_vector[1] ** 2 + light_vector[2] ** 2 ) step_4 = (step_1) / (step_2 * step_3) diffrence_in_angle = (math.acos(step_4)) / 3.14 spector = 1 - diffrence_in_angle**0.09333 def checkFloor(camera, pixel, floorLevel): global floor_contact if pixel[1] == 0: return False else: t = -1 * (camera[1] + floorLevel) / (pixel[1] - camera[1]) floor_contact = [ camera[0] + (t * (pixel[0] - camera[0])), camera[1] + (t * (pixel[1] - camera[1])), camera[2] + (t * (pixel[2] - camera[2])), ] return True def colorFloor( pixel, ): turtle.penup() turtle.pencolor(0.4, 0.4, 0.4) turtle.goto(pixel[0], pixel[1]) turtle.dot() turtle.pendown() turtle.penup() for x in range(-200, 200, 1): for y in range(-200, 200, 1): pixel[0] = x pixel[1] = y if checkIntersections_sphere(camera, pixel, sphere, radius): getColor(sphere, point_of_contact) color(pixel, diffrence_in_angle, spector) else: if checkFloor(camera, pixel, floorLevel): if checkIntersections_sphere(floor_contact, light, sphere, radius):
{ "domain": "codereview.stackexchange", "id": 45557, "lm_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, graphics, turtle-graphics, raytracing", "url": null }
python, beginner, graphics, turtle-graphics, raytracing if checkIntersections_sphere(floor_contact, light, sphere, radius): colorFloor(pixel) sphere = [200, 0, 101] camera = [200, 0, -100] for x in range(50, 475, 1): for y in range(-200, 200, 1): pixel[0] = x pixel[1] = y if checkIntersections_sphere(camera, pixel, sphere, radius): getColor(sphere, point_of_contact) color(pixel, diffrence_in_angle, spector) else: if checkFloor(camera, pixel, floorLevel): if checkIntersections_sphere(floor_contact, light, sphere, radius): colorFloor(pixel) sphere = [-200, 0, 101] camera = [-200, 0, -100] for x in range(-800, 75, 1): for y in range(-200, 200, 1): pixel[0] = x pixel[1] = y if checkIntersections_sphere(camera, pixel, sphere, radius): getColor(sphere, point_of_contact) color(pixel, diffrence_in_angle, spector) else: if checkFloor(camera, pixel, floorLevel): if checkIntersections_sphere(floor_contact, light, sphere, radius): colorFloor(pixel) window.mainloop() Answer: Overview You've done an excellent job: Overall code layout is good You did a good job partitioning code into functions You leveraged code written by others with the imports Used meaningful names for functions and variables Here are some adjustments for you to consider, mainly for coding style. Documentation Add comments at the top of the file to state the purpose of the code. For example: ''' Draw 3 spheres. Note: please be patient as it takes about 40 seconds to draw the high-resolution graphics. '''
{ "domain": "codereview.stackexchange", "id": 45557, "lm_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, graphics, turtle-graphics, raytracing", "url": null }
python, beginner, graphics, turtle-graphics, raytracing Layout I recommend moving the functions to the top, after the import statements. Having them in the middle of the code interrupts the natural flow of the code (from a human readability standpoint). You sometimes have blank lines where there is no need for them and other places where they would be useful. Consider this code: for x in range(-200, 200, 1): for y in range(-200, 200, 1): pixel[0] = x pixel[1] = y if checkIntersections_sphere(camera, pixel, sphere, radius): getColor(sphere, point_of_contact) color(pixel, diffrence_in_angle, spector) else: if checkFloor(camera, pixel, floorLevel): if checkIntersections_sphere(floor_contact, light, sphere, radius): colorFloor(pixel) sphere = [200, 0, 101] camera = [200, 0, -100] In these nested for loops, I don't think you need any blank lines, but you should have one after the loops: for x in range(-200, 200, 1): for y in range(-200, 200, 1): pixel[0] = x pixel[1] = y if checkIntersections_sphere(camera, pixel, sphere, radius): getColor(sphere, point_of_contact) color(pixel, diffrence_in_angle, spector) else: if checkFloor(camera, pixel, floorLevel): if checkIntersections_sphere(floor_contact, light, sphere, radius): colorFloor(pixel) sphere = [200, 0, 101] camera = [200, 0, -100] DRY Since most of the code in those nested loops is repeated 3 times (once for each sphere), consider creating another function for that. Another place where you repeat code is: normal_vector = [ point_of_contact[0] - sphere[0], point_of_contact[1] - sphere[1], point_of_contact[2] - sphere[2], ] You can use zip in a list comprehension: normal_vector = [p - s for p, s in zip(point_of_contact, sphere)]
{ "domain": "codereview.stackexchange", "id": 45557, "lm_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, graphics, turtle-graphics, raytracing", "url": null }
python, beginner, graphics, turtle-graphics, raytracing Naming According to the PEP 8 style guide, function and variable names should be lowercase, with words separated by underscores as necessary to improve readability. For example, function colorFloor would be color_floor The checkIntersections_sphere function returns a boolean value. It is customary to name such functions with the is_ prefix. For example, something like is_point_of_contact might be appropriate, depending on what the function does. Similarly, checkFloor could be is_floor. The name of color function could convey a little more meaning. If the function adds a color, it could be named add_color. Simplicity In the following line: turtle.pencolor(1 - diffrence_in_angle, 0 + spector, 0 + spector) if it is not required to add 0, then the code would be simpler without it: turtle.pencolor(1 - diffrence_in_angle, spector, spector) Similarly: b = (-1 * 2) * ( could be: b = -2 * ( Lint check pylint identified a few issues. It recommends adding docstrings to the functions to summarize what they do. It also recommends minimizing the usage of global variables. Performance To address your concern about the code taking longer than you would like, I recommend you focus on the nested for loops and the functions that perform a lot of calculations. The for loops use a step size of 1. Increasing the step size speeds things up, but you lose resolution.
{ "domain": "codereview.stackexchange", "id": 45557, "lm_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, graphics, turtle-graphics, raytracing", "url": null }
c#, array, .net, generics, lambda Title: Find Method Implementation for Multidimensional Array in C# Question: I found that Array.Find(T[], Predicate) Method is only support one dimensional array. I am trying to generalize it to multi-dimensional array in this post. The experimental implementation The experimental implementation is as below. Find Method Implementation public class Infrastructures { public static T? Find<T>(T[,] array, Predicate<T> match) { if (array is null) { throw new ArgumentNullException(nameof(array)); } if (match is null) { throw new ArgumentNullException(nameof(match)); } for (long row = 0; row < array.GetLongLength(0); row++) { for (long column = 0; column < array.GetLongLength(1); column++) { if (match(array[row, column])) { return array[row, column]; } } } return default; } public static T? Find<T>(T[,,] array, Predicate<T> match) { if (array is null) { throw new ArgumentNullException(nameof(array)); } if (match is null) { throw new ArgumentNullException(nameof(match)); } for (long dim1 = 0; dim1 < array.GetLongLength(0); dim1++) { for (long dim2 = 0; dim2 < array.GetLongLength(1); dim2++) { for (long dim3 = 0; dim3 < array.GetLongLength(2); dim3++) { if (match(array[dim1, dim2, dim3])) { return array[dim1, dim2, dim3]; } } } } return default; } public static T? Find<T>(T[,,,] array, Predicate<T> match) { if (array is null) { throw new ArgumentNullException(nameof(array)); }
{ "domain": "codereview.stackexchange", "id": 45558, "lm_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#, array, .net, generics, lambda", "url": null }
c#, array, .net, generics, lambda if (match is null) { throw new ArgumentNullException(nameof(match)); } for (long dim1 = 0; dim1 < array.GetLongLength(0); dim1++) { for (long dim2 = 0; dim2 < array.GetLongLength(1); dim2++) { for (long dim3 = 0; dim3 < array.GetLongLength(2); dim3++) { for(long dim4 = 0; dim4 < array.GetLongLength(3); dim4++) { if (match(array[dim1, dim2, dim3, dim4])) { return array[dim1, dim2, dim3, dim4]; } } } } } return default; } public static T? Find<T>(T[,,,,] array, Predicate<T> match) { if (array is null) { throw new ArgumentNullException(nameof(array)); } if (match is null) { throw new ArgumentNullException(nameof(match)); } for (long dim1 = 0; dim1 < array.GetLongLength(0); dim1++) { for (long dim2 = 0; dim2 < array.GetLongLength(1); dim2++) { for (long dim3 = 0; dim3 < array.GetLongLength(2); dim3++) { for (long dim4 = 0; dim4 < array.GetLongLength(3); dim4++) { for(long dim5 = 0; dim5 < array.GetLongLength(4); dim5++) { if (match(array[dim1, dim2, dim3, dim4, dim5])) { return array[dim1, dim2, dim3, dim4, dim5]; } } } } } } return default; }
{ "domain": "codereview.stackexchange", "id": 45558, "lm_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#, array, .net, generics, lambda", "url": null }
c#, array, .net, generics, lambda public static T? Find<T>(T[,,,,,] array, Predicate<T> match) { if (array is null) { throw new ArgumentNullException(nameof(array)); } if (match is null) { throw new ArgumentNullException(nameof(match)); } for (long dim1 = 0; dim1 < array.GetLongLength(0); dim1++) { for (long dim2 = 0; dim2 < array.GetLongLength(1); dim2++) { for (long dim3 = 0; dim3 < array.GetLongLength(2); dim3++) { for (long dim4 = 0; dim4 < array.GetLongLength(3); dim4++) { for (long dim5 = 0; dim5 < array.GetLongLength(4); dim5++) { for(long dim6 = 0; dim6 < array.GetLongLength(5); dim6++) { if (match(array[dim1, dim2, dim3, dim4, dim5, dim6])) { return array[dim1, dim2, dim3, dim4, dim5, dim6]; } } } } } } } return default; } } Test cases The test cases listed here include two dimensional case, three dimensional case and four dimensional case. Console.WriteLine("Two dimensional find method test:"); Point[,] Points2D = { { new Point(100, 200), new Point(300, 400) }, { new Point(100, 400), new Point(200, 400) } }; var first2D = Infrastructures.Find(Points2D, x => x.X == 100); // Display the first structure found. Console.WriteLine("Found: X = {0}, Y = {1}", first2D.X, first2D.Y);
{ "domain": "codereview.stackexchange", "id": 45558, "lm_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#, array, .net, generics, lambda", "url": null }
c#, array, .net, generics, lambda Console.WriteLine("Three dimensional find method test:"); Point[,,] Points3D = { { { new Point(100, 200), new Point(300, 400) }, { new Point(100, 400), new Point(200, 400) } }, { { new Point(100, 200), new Point(300, 400) }, { new Point(100, 400), new Point(200, 400) } } }; var first3D = Infrastructures.Find(Points3D, x => x.X == 100); Console.WriteLine("Three dimensional find method test:"); // Display the first structure found. Console.WriteLine("Found: X = {0}, Y = {1}", first3D.X, first3D.Y); Console.WriteLine("Four dimensional find method test:"); Point[,,,] Points4D = { { { { new Point(100, 200), new Point(300, 400) }, { new Point(100, 400), new Point(200, 400) } }, { { new Point(100, 200), new Point(300, 400) }, { new Point(100, 400), new Point(200, 400) } } }, { { { new Point(100, 200), new Point(300, 400) }, { new Point(100, 400), new Point(200, 400) } }, { { new Point(100, 200), new Point(300, 400) }, { new Point(100, 400), new Point(200, 400) } } }}; var first4D = Infrastructures.Find(Points4D, x => x.X == 100); // Display the first structure found. Console.WriteLine("Found: X = {0}, Y = {1}", first4D.X, first4D.Y); The output of the test code above: Two dimensional find method test: Found: X = 100, Y = 200 Three dimensional find method test: Three dimensional find method test: Found: X = 100, Y = 200 Four dimensional find method test: Found: X = 100, Y = 200 I am seeking a more generalized way to perform find operation in multidimensional array. All suggestions are welcome.
{ "domain": "codereview.stackexchange", "id": 45558, "lm_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#, array, .net, generics, lambda", "url": null }
c#, array, .net, generics, lambda Answer: You can simply cast the array and use LINQ. The approach is simple enough to be used directly, but if you prefer to implement the Find methods, I suggest making them Extension Methods, so that the point notation can be used. To do so, the containing class must be static and the array parameter must be prepended with this. public static class Infrastructures { public static T? Find<T>(this T[,] array, Func<T, bool> match) => array.Cast<T>().FirstOrDefault(match); public static T? Find<T>(this T[,,] array, Func<T, bool> match) => array.Cast<T>().FirstOrDefault(match); public static T? Find<T>(this T[,,,] array, Func<T, bool> match) => array.Cast<T>().FirstOrDefault(match); public static T? Find<T>(this T[,,,,] array, Func<T, bool> match) => array.Cast<T>().FirstOrDefault(match); public static T? Find<T>(this T[,,,,,] array, Func<T, bool> match) => array.Cast<T>().FirstOrDefault(match); } Note that multidimensional arrays implement IEnumerable but not IEnumerable<T>. The Enumerable.Cast<T>() extension method converts IEnumerable to IEnumerable<T>. We could also add a more generic method dealing any number of array dimensions by using an Array array parameter; however, this is not type safe and we would have to specify the type parameter (e.g., array.Find<int>(...)) when calling Find.: public static T? Find<T>(this Array array, Func<T, bool> match) => array.Cast<T>().FirstOrDefault(match); This test... int[,] t2 = { { 1, 2 }, { 3, 4 } }; int[,,] t3 = { { { 1, 2 }, { 3, 4 } }, { { 5, 6 }, { 7, 8 } } }; int result1 = t2.Find(x => x == 3); int result2 = t3.Find(x => x == 5); Console.WriteLine(result1); Console.WriteLine(result2); Console.ReadKey(); Prints 3 and 5. Note also that a multidimensional array can be enumerated directly with a simple foreach-statement: foreach (int i in t3) { Console.WriteLine(i); }
{ "domain": "codereview.stackexchange", "id": 45558, "lm_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#, array, .net, generics, lambda", "url": null }
assembly Title: Simple GAS assembly program to print out all of the command line arguments provided to it Question: Although I've used assembly quite a bit for some simply things, I feel like I've never properly learnt how to write it idiomatically, by which I mean: which variables to use where, how best to structure loops and conditionals, how best/when to preserve registers over procedure calls, etc... I wrote a small program which interfaces with the C standard library runtime, and will simply print the the amount of command line arguments followed by a list of all those arguments, for example: $ ./sver Hello, this is a test! The (6) arguments: ./sver Hello, this is a test! And here's the code itself: .global main .type main, @function main: mov %rsi, %r12 mov %rdi, %rsi lea message(%rip), %rdi xor %rax, %rax pushq %rsi call printf popq %rsi loop: cmp $0, %rsi # If we've printed everything, then finish jz end mov 0(%r12), %rdi # Dereference r12 to get the current arg pushq %rsi call puts # Print one argument popq %rsi add $8, %r12 # Advance r12 to point at the next arg dec %rsi jmp loop end: mov $0, %eax ret .section .data message: .string "The (%u) arguments:\n" # Explicitly say that I don't want an executable stack, otherwise GCC complains .section .note.GNU-stack,"",@progbits I'm compiling this with GCC. Some aspects specifically that I'm unsure about:
{ "domain": "codereview.stackexchange", "id": 45559, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "assembly", "url": null }
assembly I'm compiling this with GCC. Some aspects specifically that I'm unsure about: I'm using R12 to store a copy of RSI (which is just argv from C). I use it later when iterating to print all the arguments. However I feel like something about this is weird - is there a more idiomatic way of doing this? Before/after calls to printf and puts I need to preserve the value of RSI, since I use it as the argument counter. To do this I push/pop it from the stack, but perhaps it would be better to store it in some callee-saved register instead? But it still specifically has to be in RSI for printf to work, at least... I tried writing a functionally equivalent program in C to look at its compiled assembly, but it's pretty incomprehensible, with lots of seemingly unnecessary jumping around etc. I think my main problem is that I often don't know which register I should use to store a given value, or whether I should even put it on the stack. Thanks! Answer: mov $0, %eax xor %rax, %rax The efficient way to zero a 64-bit register is to xor the register to itself, and because any writing to a 32-bit register will automatically zero the upper dword, it is best to xor the 32-bit version of the register to itself: xor %eax, %eax. Using xor %rax, %rax requires a REX prefix byte while xor %eax, %eax does not. Shorter code is generally better. The mov $0, %eax instruction has an even longer encoding and you should only use it in cases where you don't want flags modified. cmp $0, %rsi jz end The efficient way to find out if a 64-bit register is 0, is to test the register to itself. Here you would write test %rsi, %rsi followed by jz end. Following a cmp (like you were doing), it would have been more idiomatic to write je end. Both jz and je have the same encoding but je better conveys the meaning of two items being 'equal' to each other. pushq %rsi call printf popq %rsi ... pushq %rsi call puts popq %rsi
{ "domain": "codereview.stackexchange", "id": 45559, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "assembly", "url": null }
assembly pushq %rsi call printf popq %rsi ... pushq %rsi call puts popq %rsi Before/after calls to printf and puts I need to preserve the value of RSI, since I use it as the argument counter. To do this I push/pop it from the stack, but perhaps it would be better to store it in some callee-saved register instead? But it still specifically has to be in RSI for printf to work, at least... The %rsi register is a so-called call-clobbered register, see this Stack Overflow answer. So these printf and puts functions are allowed to use %rsi for their own purposes and leave it changed. That's why you had to preserve the register yourself. You can easily escape from this simply by choosing a call-preserved register instead. I would suggest you pick %rbx for your loop control variable. loop: cmp $0, %rsi # If we've printed everything, then finish jz end ... dec %rsi jmp loop end: An efficient loop tries to minimize the number of control transferring instructions (here jz and jmp), and prefers to put the loop condition's logic at the bottom of the loop. Remember that the dec instruction already defines a number of flags, including the ZF (zero flag), therefore you could replace the unconditional jmp loop by the conditional jnz loop. Of course, you would then also move the initial test-for-zero to outside of the loop. All of the above in one code snippet: main: mov %rdi, %rbx # argc mov %rsi, %r12 # argv lea message(%rip), %rdi mov %rbx, %rsi xor %eax, %eax call printf test %rbx, %rbx jz end next: mov 0(%r12), %rdi # Dereference r12 to get the current arg call puts add $8, %r12 # Advance r12 to point at the next arg dec %rbx jnz next end: xor %eax, %eax ret
{ "domain": "codereview.stackexchange", "id": 45559, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "assembly", "url": null }
assembly xor %eax, %eax ret Isn't argc always at least one? The initial test-for-zero seems not necessary then. And also, argc will be a small number, so we can write the shorter mov %edi, %ebx, mov %ebx, %esi, and dec %ebx instructions instead: main: mov %edi, %ebx # argc mov %rsi, %r12 # argv lea message(%rip), %rdi mov %ebx, %esi xor %eax, %eax call printf next: mov 0(%r12), %rdi # Dereference r12 to get the current arg call puts add $8, %r12 # Advance r12 to point at the next arg dec %ebx jnz next xor %eax, %eax ret
{ "domain": "codereview.stackexchange", "id": 45559, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "assembly", "url": null }
beginner, rust Title: Beginner Rust Todo app Question: I am trying to use the practices that I have learnt from the rust book. Any advice is welcome. Please feel free to be as nitpicky as possible. use std::fmt; use std::io::{self, Write}; struct Item { name: String, done: bool, } impl fmt::Display for Item { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} [{}]", self.name, if self.done { 'X' } else { ' ' }) } } fn main() { let mut todos: Vec<Item> = Vec::new(); loop { let mut input = String::new(); print!("> "); io::stdout().flush().unwrap(); io::stdin() .read_line(&mut input) .expect("Failed to read line"); let tokens: Vec<&str> = input.trim().split_whitespace().collect(); match tokens[..] { ["add", item_name] => { let item_name = String::from(item_name); println!("Added item: {item_name}"); let item = Item { name: item_name, done: false, }; todos.push(item); } ["remove", item_name] => { let item_name = String::from(item_name); if let Some(index) = todos.iter().position(|x| (*x).name == item_name) { todos.remove(index); } println!("Removed item: {item_name}"); } ["toggle", item_name] => { let item_name = String::from(item_name); if let Some(index) = todos.iter().position(|x| (*x).name == item_name) { todos[index].done = !todos[index].done } } ["show"] => { for item in todos.iter() { println!(" {item}"); } }
{ "domain": "codereview.stackexchange", "id": 45560, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust", "url": null }
beginner, rust ["exit"] => { println!("Exited applciation"); break; } _ => println!("invalid input"), } } } Answer: Use cargo clippy to find common mistakes: Redundant trim In input.trim().split_whitespace() you can remove the trim(), since split_whitespace already ignores leading and trailing whitespace. Unnecessary deref In this closure: |x| (*x).name == item_name), you can remove the * since the compiler will dereference it automatically. Explicit iter() It's more idiomatic to write &todos instead of todos.iter(). Unnnecessary String creation This line is repeated throughout your match arms: let item_name = String::from(item_name);. However, in most arms, you can elide it, since you can compare directly against the &str item_name. Simpler Vec initialization In the line let mut todos: Vec<Item> = Vec::new();, you can remove the explicit type and call the vec! macro for more concise code: let mut todos = vec![]; Typo applciation should be application. Inaccurate output When removing an element, you always print a sucess message. It would make more sense to only print it inside the if so it only is shown after really removing an element. Additionally, a sucessful toggle should also get a sucess message for consistency. eprintln! for errors Errors should be printed to stderr via eprintln! and not via println!. Final code use std::fmt; use std::io::{self, Write}; struct Item { name: String, done: bool, } impl fmt::Display for Item { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} [{}]", self.name, if self.done { 'X' } else { ' ' }) } } fn main() { let mut todos = vec![]; loop { let mut input = String::new(); print!("> "); io::stdout().flush().unwrap(); io::stdin() .read_line(&mut input) .expect("Failed to read line"); let tokens: Vec<&str> = input.split_whitespace().collect();
{ "domain": "codereview.stackexchange", "id": 45560, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust", "url": null }
beginner, rust match tokens[..] { ["add", item_name] => { let item = Item { name: String::from(item_name), done: false, }; todos.push(item); println!("Added item: {item_name}"); } ["remove", item_name] => { if let Some(index) = todos.iter().position(|x| x.name == item_name) { todos.remove(index); println!("Removed item: {item_name}"); } } ["toggle", item_name] => { if let Some(index) = todos.iter().position(|x| x.name == item_name) { todos[index].done = !todos[index].done; println!("Toggled item: {item_name}"); } } ["show"] => { for item in &todos { println!(" {item}"); } } ["exit"] => { println!("Exited application"); break; } _ => eprintln!("invalid input"), } } } Further ideas Consider adding a help command for easier usage. Consider adding support for saving the todos to and loading them from a file to preserve state over multiple runs.
{ "domain": "codereview.stackexchange", "id": 45560, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "beginner, rust", "url": null }
java, security, spring, jpa, jwt Title: Any possible issues with my approach to Access Management where I'm associating the list of Departments with the User class? Question: I have a spring boot project with JWT being used for Spring Security. I want to implement Access Management in my project and I'm using this approach. In my project, whenever a user is created, a list of Departments is assigned to to the user. The user should be able to view and edit data that is related to the departments that have been assigned to them. I have implemented this using the below code, where the class Department is the Master data. A list of "assigned" Departments is associated with each User. public class User implements UserDetails { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.UUID) private UUID id; private String username; private String password; @JsonManagedReference @OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.EAGER) private List<AssignedDepartment> assignedDepartmentList = new ArrayList<>(); public void setAssignedDepartment(List<AssignedDepartment> assignedDepartmentList1) { for(AssignedDepartment assignedDepartment : assignedDepartmentList1) { assignedDepartment.setUser(this); this.assignedDepartmentList.add(assignedDepartment); } } } public class AssignedDepartment { @Id @GeneratedValue(strategy= GenerationType.IDENTITY) private Integer id; @JsonBackReference @ManyToOne @JoinColumn(name = "username", referencedColumnName = "username", nullable = false) private User user; @ManyToOne @JoinColumn(name = "department_code", referencedColumnName = "departmentCode") private Department department; } public class Department implements Serializable { private static final long serialVersionUID = 1L; @Id private String departmentCode; private String departmentName; }
{ "domain": "codereview.stackexchange", "id": 45561, "lm_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, security, spring, jpa, jwt", "url": null }
java, security, spring, jpa, jwt @Id private String departmentCode; private String departmentName; } Considering the above implementation and approach and the below code, where I'm getting the list of assigned Departments from the JWT token (passed as a Bearer token) that is passed in the API request, is my implementation correct and safe? The below function is called every time any API is getting hit. I have tested the code and it works fine. The list of departments is always being fetched correctly based on the JWT token that I sent in the API request. I just want to confirm if there are any issues that might arise from this approach. private List<String> getListOfDepartmentsAssignedToCurrentUser() throws Exception { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if(authentication == null || !authentication.isAuthenticated()) { throw new Exception("Unable to get departments for current user with authentication details: " + authentication); } try { List<AssignedDepartment> userAssignedDepartments = ((User) authentication.getPrincipal()).getUserAssignedDepartments(); return userAssignedDepartments.stream() .map(m -> m.getDepartment().getDepartmentCode()) .collect(Collectors.toList()); } catch (Exception e) { throw new Exception("Error while streaming departments for current user with Exception: " + e.toString()); } }
{ "domain": "codereview.stackexchange", "id": 45561, "lm_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, security, spring, jpa, jwt", "url": null }
java, security, spring, jpa, jwt Answer: Storing that information in a token is a tradeoff from looking it up based on some other piece of information like a user ID. It saves you from having to look departments up for each API request at the cost of relying on a token's integrity and lifetime. If a user's department list changes, that will only be reflected when a new token is issued and an old token will continue to be acceptable for as long as you have configured its lifetime. This may or may not be a security issue for you. Short lifetimes with refresh tokens are possible but validation relies on system clocks and token management packages usually have default jitter settings on the order of minutes, so you can have expiration validation issues when you get down to lifetimes of seconds or minutes. Revoking tokens is possible, but requires more infrastructure and a check each time a token is used. Otherwise you want to make sure you choose an appropriate token signing algorithm consummate with your security needs.
{ "domain": "codereview.stackexchange", "id": 45561, "lm_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, security, spring, jpa, jwt", "url": null }
react.js, form, jsx Title: Basic login form in React.js Question: I have made a very basic login/registration form in React.js. The inputted data is send to a Java Spring Boot Rest-API to create an user or to authenticate using JWT. But in this question I want to focus on the React.js code. import React, { Component } from 'react' import axios from "axios" import Cookies from "js-cookie" import "../styles/Home.sass" class Home extends Component { constructor() { super() this.state = { message: {}, inputs: {}, } this.handleChange = this.handleChange.bind(this) this.Form = this.Form.bind(this) } handleChange = (event) => { let inputs = this.state.inputs inputs[event.target.name] = event.target.value this.setState({inputs}) } render() { return ( <div id="container"> <div id="text"> <div> <h1>Welcome to Finonline</h1> <span id="slogan">Administrate your personal expenses online.</span> <p> This is a demo-project for my job-application showcasing my skills in full-stack webdevelopment, Java, Spring Boot and React.js. </p> </div> </div> <div id="form-container"> <this.Form /> </div> </div> ) } Form() { const handleSubmit = (event, action) => { event.preventDefault() switch (action) { case "register": this.register(this.state.inputs) break default: this.login(this.state.inputs) } }
{ "domain": "codereview.stackexchange", "id": 45562, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "react.js, form, jsx", "url": null }
react.js, form, jsx return ( <form onSubmit={(event) => handleSubmit(event, 'login')} > <span className="title">Login</span> <div className="input-wrapper"> <img src="/assets/images/profile.png" alt="" /> <input type="text" name="name" placeholder="Username" minLength="3" required="" onChange={this.handleChange} /> </div> <div className="input-wrapper"> <img src="/assets/images/password.png" alt="" /> <input type="password" name="pass" placeholder="Password" minLength="5" required="" onChange={this.handleChange} /> </div> <div id="form-buttons"> <input type="submit" name="login" value="Login" onClick={(event) => handleSubmit(event, 'login')} /> <input type="submit" name="register" value="Or register" id="registerbtn" onClick={(event) => handleSubmit(event, 'register')} /> </div> <span id="message" className={this.state.message["type"]}> { this.state.message["text"] } </span> </form> ) } async register(data) { let message = this.state.message try { const response = await axios.post(`http://127.0.0.1:8080/users`, data , { insecureHTTPParser: true, headers: { "Content-Type": "application/json", } })
{ "domain": "codereview.stackexchange", "id": 45562, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "react.js, form, jsx", "url": null }
react.js, form, jsx if (response.status == 201) { message["type"] = "ok" message["text"] = "Successfully registered." this.setState({ message }) } else { message["type"] = "error" message["text"] = "Error: " + response.data this.setState({ message }) } } catch (err) { message["type"] = "error" message["text"] = "Error: This user already exists." this.setState({ message }) } } async login(data) { let message = this.state.message try { const response = await axios.post(`http://127.0.0.1:8080/auth`, data , { insecureHTTPParser: true, headers: { "Content-Type": "application/json", } }) if (response.status == 200) { message["type"] = "ok" message["text"] = "Login successful." this.setState({ message }) } else { message["type"] = "error" message["text"] = "Error: Login failed." this.setState({ message }) } } catch (err) { message["type"] = "error" message["text"] = "Error: Login failed." this.setState({ message }) } } } export default Home I have made a class extending Component. I have two states: message which holds the response message from the API and the type (ok/error), and inputs which holds the entered input from the user. Is this clean React.js code? Should the functions login and register be present in this class? Is it okay to have a separate function for the form?
{ "domain": "codereview.stackexchange", "id": 45562, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "react.js, form, jsx", "url": null }
react.js, form, jsx Answer: You can improve you cleanliness by removing some of your redundant patterns and building up robustness. You have a lot of message["type"] = "ok" message["text"] = "Login successful." I'd probably pull that into a function. "type" may benefit from an enumeration with string values. Your register and login both have very similar structures that can probably be abstracted. I'd consider using response.ok https://developer.mozilla.org/en-US/docs/Web/API/Response/ok over a manual check of magic status code values. Otherwise, I might pull those 200, 201, etc into their own variables for readability. handleSubmit has a one case switch. There's a number of ways you can do this, but I might consider an object with the functions since they have the same signature. This could naturally lead into a factory pattern later, e.g. sketching something (didn't check if it runs): const actions = { "register": this.register, "login" : this.login } const actionToCall = actions[action]; if(actionToCall) { actionToCall(this.state.inputs) } else { throw new Error("Bad action") } You could also just use an if/else, or if you're really wanting to use a switch, explicitly have register and login cases and the default throw an error. Having login and register are fine, but you could pull out some classes that have a common interface like "ActionHandler" and use a true factory pattern to build them. For just two that might be overkill. Form as it's own function is good and I would go further to pull it out to its own component. It's already operating at that leve, but you've got Form tightly coupled with the Home state. I'd have Form communicate to Home by passing state as a prop and a callback function which sets the state (this could just be passing in the setState function`)
{ "domain": "codereview.stackexchange", "id": 45562, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "react.js, form, jsx", "url": null }
python, beginner, turtle-graphics Title: Drawing a mathematical envelope with turtle graphics Question: I started coding a week ago. I played a bit with the turtle module and I am looking for ways to improve my code. Please feel free to share improvements. Here is the shape it creates: #I created a mathematical envelope by connecting points laying on straight lines forming with the x-axis angles of 60, 90, 120, 180... deegrees import turtle as t import math t.speed(0) t.bgcolor("black") t.pencolor("deepskyblue") def star1(start, end, step, x_direction1, y_direction1, x_direction2): #goes from the x-axis to a 60° straight line (slope = +- 3/sqrt(3)) for i in range(start, end, step): t.penup() t.goto(x_direction2 * (255 - 5.1 * i), 0) t.pendown() t.goto(x_direction1*255/100*(i+1), y_direction1* 3/math.sqrt(3)*255/100 * (i+1)) def star2 (start, end, step, x_direction1, y_direction1, x_direction2, y_direction2): #from 60° straight line to the simmetric in respect to the y-axis for i in range (start, end, step): t.penup() t.goto(x_direction1*(127.5-255/100*i),y_direction1*3/math.sqrt(3)*(127.5-255/100*i)) t.pendown() t.goto(x_direction2*255/100* (i+1), y_direction2 * 3/math.sqrt(3)*255/100*(i+1)) def refine (x_direction, y_direction): #closing the inner spaces t.goto(x_direction * 127.5, y_direction * 3/math.sqrt(3) * 127.5) def whole_star(): #star with spaces. The start, end and step indexes aren't all the same just for a smoother drawing animation star1(0, 50, 1, 1, 1, 1) star2(0, 50, 1, 1, 1, -1, 1) star1(49, -1, -1, -1, 1, -1) star1(0, 50, 1, -1, -1, -1) star2(0, 50, 1, -1, -1, 1, -1) star1(49, -1, -1, 1, -1, 1) def final_star(): #refined star whole_star() t.penup() t.goto(255, 0) t.pendown() t.goto(-255, 0) t.penup() refine(-1, 1) t.pendown() refine(1, -1) t.penup() refine(1, 1) t.pendown() refine(-1, -1)
{ "domain": "codereview.stackexchange", "id": 45563, "lm_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, turtle-graphics", "url": null }
python, beginner, turtle-graphics final_star() t.hideturtle() t.done() Answer: It's good that you got this working (especially since you only started a week ago). It's also unsurprising that you're using turtle, which is geared toward beginner graphics. As you've already seen, it takes some time for the drawing to render. A more scalable approach is to use Numpy and Matplotlib, which offers several advantages: It's much faster (especially if you write the curve construction to be vectorised) It does polar coordinate systems for you, so that your own curve definitions are much simpler It can draw axes, etc. It's more suitable for "mathematical objects" (however you interpret that) An implementation could look like: import numpy as np from matplotlib import pyplot as plt from matplotlib.collections import LineCollection def star(points: int, resolution: int) -> np.ndarray: # four-dimensional array: points, resolution, line start/end, angle/radius coords = np.empty((points, resolution, 2, 2)) # all angles in radians circle = 2*np.pi theta = circle / points # point angle increment # indexer to convert vectors to (n, 1) d2 = (slice(None), np.newaxis) # start ray angles, including 0, excluding full rotation coords[..., 0, 0] = np.arange( 0, circle - 0.5*theta, theta, )[d2] # end ray angles, excluding 0, including full rotation coords[..., 1, 0] = np.arange( # end ray angles theta, circle + 0.5*theta, theta, )[d2] # start line radii, starting at the ray centre, excluding the circumference coords[..., 0, 1] = np.arange( 0, 1, 1/resolution, ) # end line radii, starting at the ray circumference, excluding the centre coords[..., 1, 1] = np.arange( 1, 0, -1/resolution, ) # all coords, line start/end, angle/radius return coords.reshape((-1, 2, 2))
{ "domain": "codereview.stackexchange", "id": 45563, "lm_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, turtle-graphics", "url": null }
python, beginner, turtle-graphics # all coords, line start/end, angle/radius return coords.reshape((-1, 2, 2)) def plot(coords: np.ndarray) -> plt.Figure: plt.style.use('dark_background') sky_blue = '#00a0da' lines = LineCollection(coords, colors=sky_blue, alpha=0.2) fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.add_collection(lines) return fig def demo() -> None: coords = star(points=6, resolution=50) plot(coords) plt.show() if __name__ == '__main__': demo() It's also effectively "instant" to generate a much larger diagram, shown here with 16 points and a quite-excessive resolution of 300 line segments per point: To get fancier, you can auto-estimate an appropriate line alpha, and auto-assign tick frequency: import numpy as np from matplotlib import pyplot as plt from matplotlib.collections import LineCollection from matplotlib.ticker import FixedLocator # ... def plot(coords: np.ndarray, points: int, resolution: int) -> plt.Figure: plt.style.use('dark_background') # More resolution means we need more transparent lines alpha_estimate = min(1., 10/resolution) sky_blue = '#00a0da' lines = LineCollection(coords, colors=sky_blue, alpha=alpha_estimate) fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.add_collection(lines) # Align the theta axis ticks to evenly spaced points circle = 2*np.pi theta = circle / points locator = FixedLocator( locs=np.arange(0, circle - 0.5*theta, theta), nbins=12, # limit tick count ) ax.xaxis.set_major_locator(locator) return fig def demo() -> None: points = 6 resolution = 100 coords = star(points=points, resolution=resolution) plot(coords, points=points, resolution=resolution) plt.show() I was wondering if you could also animate it like in turtle.
{ "domain": "codereview.stackexchange", "id": 45563, "lm_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, turtle-graphics", "url": null }
python, beginner, turtle-graphics I was wondering if you could also animate it like in turtle. Yes; matplotlib has animation support: import numpy as np from matplotlib import pyplot as plt from matplotlib.animation import FuncAnimation from matplotlib.collections import LineCollection from matplotlib.ticker import FixedLocator def star(points: int, resolution: int) -> np.ndarray: # four-dimensional array: points, resolution, line start/end, angle/radius coords = np.empty((points, resolution, 2, 2)) # all angles in radians circle = 2*np.pi theta = circle / points # point angle increment # indexer to convert vectors to (n, 1) d2 = (slice(None), np.newaxis) # start ray angles, including 0, excluding full rotation coords[..., 0, 0] = np.arange( 0, circle - 0.5*theta, theta, )[d2] # end ray angles, excluding 0, including full rotation coords[..., 1, 0] = np.arange( theta, circle + 0.5*theta, theta, )[d2] # start line radii, starting at the ray centre, excluding the circumference coords[..., 0, 1] = np.arange(0, 1, 1/resolution) # end line radii, starting at the ray circumference, excluding the centre coords[..., 1, 1] = np.arange(1, 0, -1/resolution) return coords def make_artists(points: int, resolution: int) -> tuple[ plt.Figure, plt.PolarAxes, LineCollection, ]: plt.style.use('dark_background') # More resolution means we need more transparent lines alpha_estimate = min(1., 20/resolution) sky_blue = '#0ae' lines = LineCollection([], colors=sky_blue, alpha=alpha_estimate) fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.add_collection(lines) # Align the theta axis ticks to evenly spaced points circle = 2*np.pi theta = circle / points locator = FixedLocator( locs=np.arange(0, circle - 0.5*theta, theta), nbins=12, # limit tick count ) ax.xaxis.set_major_locator(locator) return fig, ax, lines
{ "domain": "codereview.stackexchange", "id": 45563, "lm_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, turtle-graphics", "url": null }
python, beginner, turtle-graphics return fig, ax, lines def make_plot(coords: np.ndarray, lines: LineCollection) -> None: lines.set_segments(coords.reshape((-1, 2, 2))) def animate( frame: int, coords: np.ndarray, lines: LineCollection, ) -> tuple[plt.Artist, ...]: subarray = coords[:, :frame, ...] lines.set_segments(subarray.reshape((-1, 2, 2))) return lines, def make_animation( fig: plt.Figure, coords: np.ndarray, lines: LineCollection, resolution: int, duration: float = 5, ) -> FuncAnimation: n_frames = resolution frame_ms = 1e3 * duration / n_frames return FuncAnimation( fig=fig, func=animate, fargs=(coords, lines), frames=n_frames, interval=frame_ms, repeat=False, ) def demo() -> None: points = 6 resolution = 100 coords = star(points=points, resolution=resolution) fig, ax, lines = make_artists(points=points, resolution=resolution) # make_plot(coords=coords, lines=lines) anim = make_animation( fig=fig, coords=coords, lines=lines, resolution=resolution, ) plt.show() if __name__ == '__main__': demo() It works, though I can't be bothered to make a screen recording.
{ "domain": "codereview.stackexchange", "id": 45563, "lm_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, turtle-graphics", "url": null }
python, object-oriented Title: Calculate Earth-based planetary positions given a date, time, and timezone Question: I have a project where the user supplies a date, time, and timezone, and my code will calculate a bunch of coordinates on the Earth. There are four sets of coordinates setA, setB, setC, setD. Coordinates setA and setB make up a great circle around the Earth. Likewise for coordinates setC and setD. The user is interested in plotting these coordinates in a 2D mapping system like Google Maps. CoordinatesCalculator.py import datetime as dt import numpy as np from . import utils from . import config from . import astronomy class CoordinatesCalculator: def __init__(self) -> None: self.results = None def calculate(self, timestamp: dt.datetime, longitude: float, latitude: float) -> dict[str, dict[str, np.array]]: self.results = {} for name, data in config.CELESTIAL_INTERESTS.items(): # Calculate coordinates a, b = sets_A_and_B() c = setC() d = setD() self.results[name] = { "setA": a, "setB": b, "setC": c, "setD": d } return self.results def set_C(self, target: utils.CelestialTarget, time: dt.datetime) -> float: return astronomy.subpoint_meridian(target, time) def set_D(self, c: float) -> float: return (c % 360) - 180 # degrees def sets_A_and_B(self, target: utils.CelestialTarget, time: dt.datetime): return astronomy.terminator_great_circle(target, time, samples = config.SAMPLES) def print_sets_C_and_D(self) -> None: ... def export_csv(self, targets: list[str], latitude_first = False) -> None: ... def plot2D(self, targets: list[str]) -> None: ... How this is used by the user import datetime as dt import pytz from .CoordinatesCalculator import CoordinatesCalculator
{ "domain": "codereview.stackexchange", "id": 45564, "lm_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, object-oriented", "url": null }
python, object-oriented import pytz from .CoordinatesCalculator import CoordinatesCalculator if __name__ == "__main__": timestamp_string = "2021-06-20 06:00:00" tz = "Europe/London" latitude = -113 longitude = 46 # Build an aware datetime object naive_observer_time = dt.datetime.strptime(timestamp_string, "%Y-%m-%d %H:%M:%S") aware_observer_time = pytz.timezone(tz).localize(naive_observer_time) # Calculate the results calculator = CoordinatesCalculator() results = calculator.calculate(aware_observer_time, longitude, latitude) # Print, plot, and export the results calculator.print_sets_C_and_D() calculator.plot2D(["Sun", "Moon", "Mars"]) calculator.export_csv(["Sun", "Moon", "Mars"]) Return dictionary results = { "Sun": { "setA": np.array([]), "setB": np.array([]), "setC": np.array([]), "setD": np.array([]) }, "Moon": { "setA": np.array([]), "setB": np.array([]), "setC": np.array([]), "setD": np.array([]) }, "Mars": { "setA": np.array([]), "setB": np.array([]), "setC": np.array([]), "setD": np.array([]) } } My Questions The CoordinatesCalculator class doesn't really have a state, should this just become a function? Should my return dictionary also have parameters that the user inputted? I kind of want some object that contains everything about the calculation (e.g. the time, date, time zone, and the resulting coordinates). The issue with the following is it makes it weird to iterate over if the user wants to just iterate over the coordinates data. results = { "Date": "2021-06-20", "Time": "06:00:00", "Timezone": "Europe/London", "Sun": { "setA": np.array([]), "setB": np.array([]), "setC": np.array([]), "setD": np.array([]) }, "Moon": { "setA": np.array([]), "setB": np.array([]), "setC": np.array([]), "setD": np.array([]) } }
{ "domain": "codereview.stackexchange", "id": 45564, "lm_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, object-oriented", "url": null }
python, object-oriented The CoordinatesCalculator is handling functions that belong to the results, such as export_csv and plot2D. Should I make the results its own class Results that then has the export_csv and plot2D? This would satisfy the itch for an object that contains everything about the calculation. Something like: class Results: def __init__(self, date, time, timezone, setA, setB, setC, setD): self.date = date self.time = time self.timezone = timezone self.setA = setA self.setB = setB self.setC = setC self.setD = setD def print_sets_C_and_D(self): pass def export_csv(self): pass def plot2D(self): pass def to_json(self): pass If I wanted to turn this into an API, does it suffice to just have a Results.to_json() function? Maybe the JSON results would have the structure, so that the user can iterate over the results in a clean way: { "date": date, "time": time, "timezone": timezone, "results": { "Sun": { "setA": [], "setB": [], "setC": [], "setD": [] }, "Moon": { "setA": [], "setB": [], "setC": [], "setD": [] } } } Answer: Should CoordinatesCalculator just become a function? Yes. It wants to be a module offering some functions that will calculate, plot, export to CSV and so on. Use an _ underscore prefix for any private helper functions that a user would have no need of calling directly. That way we offer a relatively simple Public API for each new user to learn about. Should my return dictionary also have parameters that the user inputted? Yes. The issue ... is it makes it weird to iterate over if the user wants to just iterate over the coordinates data. I respectfully disagree. We see this all the time in e.g. RESTful JSON APIs. for name, coords in result['Sun']: assert name.startswith('set') ...
{ "domain": "codereview.stackexchange", "id": 45564, "lm_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, object-oriented", "url": null }
python, object-oriented Or to examine more coordinates: celestial_bodies = ["Sun", "Moon", "Mars"] for body in celestial_bodies: for name, coords in result[body]: assert name.startswith("set") ... Alternatively, define a helper function that dynamically discovers the relevant set of celestial bodies by probing the result, and iterate over names returned by the helper. You could also define variant API endpoints, variant function names, accept a set of desired celestial bodies, and so on. But that sounds like putting the wrong amount of complexity in the API, given that the items are small to transport across TCP and are not time consuming to produce. We're probably better off to just let the client pick out its favorite values. It can readily define a helper that extracts its favorite subset, and then a different client can similarly define a helper for its slightly different needs. Such an approach will tend to reduce version churn in the server's API, as the third or fourth client explores additional regions of the powerset of celestial bodies. An aspect of the API which is very weird is to see date + time broken up. Offer it as a single ISO-8601 timestamp. Also, consider normalizing the user's input to UTC, so your timestamps all end with "Z". Do hang onto the original timezone name as a separate field. I imagine that your astronomy module uses TAI (or TT) on the inside, rather than UTC. Consider including both in the result dict, or at least include the number of seconds they differ by for the given timestamp. Should I make the results its own class Result that then has the export_csv and plot2D? Yes, a Result class would be lovely. Consider making it a dataclass. If I wanted to turn this into a [web] API, does it suffice to just have a Results.to_json() function?
{ "domain": "codereview.stackexchange", "id": 45564, "lm_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, object-oriented", "url": null }
python, object-oriented Yup, pretty much. You may find .asdict() convenient. Or use a @dataclass_json decorator. It is a fact of life that Things Change. This includes software, and the APIs defined by software. It is possible that your webclient caller is already aware of which version of your API they're accessing, for example because the URI started "https://api.example.com/v2/calculate". Alternatively you might wish to insert a SemVer k: v pair like "version": "2.0.1" so the client will know what keys to expect, and what semantics are imposed on the values. It is customary to bump the version after implementing a bugfix or offering new features. You solicit a (lat, long) coordinate. Sometimes users supply 53 bits of FP significand, with most of the low order bits being meaningless. Consider deliberately rounding to ~ 6 decimal places, as one-meter resolution on Earth's surface likely suffices for your purposes.
{ "domain": "codereview.stackexchange", "id": 45564, "lm_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, object-oriented", "url": null }
java, algorithm, sorting, radix-sort Title: Efficient least-significant digit (LSD) radix sort for int keys in Java Question: (This post has a continuation post.) This one is my attempt at LSD radix sort: Code com.github.coderodde.util.LSDRadixsort.java: package com.github.coderodde.util; import java.util.Arrays;
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort /** * This class provides the method for sorting {@code int} arrays using * least-significant digit (LSD) radix sort. */ public final class LSDRadixsort { /** * The number of counters in the counter array. */ private static final int NUMBER_OF_COUNTERS = 256; /** * Sorts the entire {@code int} array into ascending order. * * @param array the array to sort. */ public static void sort(int[] array) { sort(array, 0, array.length); } /** * Sorts the range {@code array[fromIndex ... toIndex - 1]} into ascending * order. * * @param array the array holding the range. * @param fromIndex the starting, inclusive index of the sorting range. * @param toIndex the ending, exclusive index of the sorting range. */ public static void sort(int[] array, int fromIndex, int toIndex) { checkRangeIndices(array.length, fromIndex, toIndex); int rangeLength = toIndex - fromIndex; if (rangeLength < 2) { // Trivially sorted: return; } // buffer and counterMap are allocated only once for the sake of // performance: int[] buffer = new int[rangeLength]; int[] counterMap = new int[NUMBER_OF_COUNTERS]; // Spawn sorting: sortImpl(array, buffer, counterMap, fromIndex, toIndex); } private static void sortImpl(int[] array, int[] buffer, int[] counterMap, int fromIndex, int toIndex) { // Sort first by least-significant bytes, then by second // least-significant, and finally by third least-signficant byte:
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort // least-significant, and finally by third least-signficant byte: for (int byteIndex = 0; byteIndex != 3; byteIndex++) { countingSortImpl(array, buffer, counterMap, byteIndex, fromIndex, toIndex); } // Deal with the signed data: countingSortImplSigned(array, buffer, counterMap, fromIndex, toIndex); } /** * Performs the counting sort on {@code array[fromIndex ... toIndex - 1]}. * * @param array the array to sort. * @param buffer the buffer array. * @param counterMap the counter array. We reuse this in order not to * allocate it everytime we call this method. * @param byteIndex the index of the byte that serves as the sorting key. * @param fromIndex the starting, inclusive index of the sorting range. * @param toIndex the ending, exclusive index of the sorting range. */ private static void countingSortImpl(int[] array, int[] buffer, int[] counterMap, int byteIndex, int fromIndex, int toIndex) { Arrays.fill(counterMap, 0); // Count the elements: for (int i = fromIndex; i != toIndex; i++) { counterMap[extractCounterIndex(array[i], byteIndex)]++; }
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort // Make the counter map accummulative: for (int i = 1; i != NUMBER_OF_COUNTERS; i++) { counterMap[i] += counterMap[i - 1]; } // Build the buffer array (which will end up sorted): for (int i = toIndex - 1; i >= fromIndex; i--) { int index = extractCounterIndex(array[i], byteIndex); buffer[counterMap[index]-- - 1] = array[i]; } // Just copy the buffer to the array: System.arraycopy(buffer, 0, array, fromIndex, buffer.length); } /** * Sorts the {@code array[fromIndex ... toIndex - 1]} by most significant * bytes that contain the sign bits. * * @param array the array to sort. * @param buffer the buffer array. * @param counterMap the counter map. We pass this array in order not to * create it in this method. * @param fromIndex the starting, inclusive index of the sorting range. * @param toIndex the ending, exclusive index of the sorting range. */ private static void countingSortImplSigned(int[] array, int[] buffer, int[] counterMap, int fromIndex, int toIndex) { Arrays.fill(counterMap, 0); // Count the elements: for (int i = fromIndex; i != toIndex; i++) { counterMap[extractCounterIndexSigned(array[i])]++; }
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort // Make the counter map accummulative: for (int i = 1; i != NUMBER_OF_COUNTERS; i++) { counterMap[i] += counterMap[i - 1]; } // Build the output array: for (int i = toIndex - 1; i >= fromIndex; i--) { int index = extractCounterIndexSigned(array[i]); buffer[counterMap[index]-- - 1] = array[i]; } // Just copy the buffer to the array: System.arraycopy(buffer, 0, array, fromIndex, buffer.length); } /** * Extracts the counter array index from the integer datum. * * @param datum the integer key. * @param byteIndex the index of the byte of the key to consider. * @return the index into counter array. */ private static int extractCounterIndex(int datum, int byteIndex) { // Shift so that the target byte is the leftmost byte and set to zero // all the remaining bits: return (datum >>> (byteIndex * 8)) & 0xff; } /** * Extracts the counter array index from the integer datum. Considers only * the most significant byte that contains the sign bit. The sign bit is * flipped in order to put the datum in correct location in the counter * array. * * @param datum the integer key. * @return the index into counter array. */ private static int extractCounterIndexSigned(int datum) { // We use xor ^ operator in order to flip the bit index 7 (8th bit from // the least significant end): return (datum >>> 24) ^ 0b1000_0000; } /** * Checks that the specified sorting range is reasonable. * * @param arrayLength the total length of the target array. * @param fromIndex the starting, inclusive index of the sorting range.
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort * @param fromIndex the starting, inclusive index of the sorting range. * @param toIndex the ending, exclusive index of the sorting range. */ private static void checkRangeIndices(int arrayLength, int fromIndex, int toIndex) { if (fromIndex < 0) { throw new IllegalArgumentException( String.format( "fromIndex(%d) is negative. Must be at least 0.", fromIndex)); } if (toIndex > arrayLength) { throw new IllegalArgumentException( String.format( "toIndex(%d) is too large. Must be at most %d.", toIndex, arrayLength)); } if (fromIndex > toIndex) { throw new IllegalArgumentException( String.format( "toIndex(%d) > fromIndex(%d).", toIndex, fromIndex)); } } }
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort com.github.coderodde.util.demo.LSDRadixsortDemo.java: package com.github.coderodde.util.demo; import com.github.coderodde.util.LSDRadixsort; import java.util.Arrays; import java.util.Random;
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort public class LSDRadixsortDemo { private static final int LENGTH = 100_000_000; private static final int PREFIX_SUFFIX_EXCLUSION_RANGE_LENGTH = 50; public static void main(String[] args) { long seed = System.currentTimeMillis(); Random random = new Random(seed); System.out.printf("Seed = %d.\n", seed); long startTime = System.currentTimeMillis(); int[] array1 = createRandomIntegerArray(LENGTH, random); int[] array2 = array1.clone(); long endTime = System.currentTimeMillis(); int fromIndex = random.nextInt(PREFIX_SUFFIX_EXCLUSION_RANGE_LENGTH + 1); int toIndex = LENGTH - random.nextInt( PREFIX_SUFFIX_EXCLUSION_RANGE_LENGTH + 1); System.out.printf("Built demo arrays in %d milliseconds.\n", endTime - startTime); startTime = System.currentTimeMillis(); LSDRadixsort.sort(array1, fromIndex, toIndex); endTime = System.currentTimeMillis(); long durationRadixsort = endTime - startTime; System.out.printf("LSDRadixsort took %d milliseconds.\n", durationRadixsort); startTime = System.currentTimeMillis(); Arrays.sort(array2, fromIndex, toIndex); endTime = System.currentTimeMillis(); long durationArraysSort = endTime - startTime; System.out.printf("Arrays.sort took %d milliseconds.\n", durationArraysSort); System.out.printf("Arrays agree: %b.\n", Arrays.equals(array1, array2)); float ratio = (float) durationRadixsort / (float) durationArraysSort; System.out.println( String.format( "Time ratio: %.3f.\n", ratio)
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort String.format( "Time ratio: %.3f.\n", ratio) .replace(',', '.')); } private static int[] createRandomIntegerArray(int length, Random random) { int[] array = new int[length]; for (int i = 0; i < length; i++) { array[i] = random.nextInt(); } return array; } }
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort Typical output Seed = 1710160736231. Built demo arrays in 1437 milliseconds. LSDRadixsort took 2885 milliseconds. Arrays.sort took 16079 milliseconds. Arrays agree: true. Time ratio: 0.179. Critique request So how am I doing here? Anything to improve? Naming? Javadoc? Answer: In general the code uses the right spacing and variable naming. * This class provides the method for sorting {@code int} arrays using * least-significant digit (LSD) radix sort. No it doesn't, unless you call a byte a digit; this should be mentioned at least to future developers that need to look at the code (this might be less important to users as the functionality should remain the same even if digits are used). I'd also indicate that this is a helper or utility class, to save users from looking for constructors or factory methods. Possibly it would also be a good idea to indicate the order of operations required for a sort. That's the only reason to prefer it over other options it seems to me. LSDRadixsort It depends, but nowadays I see often that the acronyms are also in CamelCase: LsdRadixSort. LSDRadixsort is fine of course but I see the point of the proponents of using smaller caps for anything but the first letter. private static final int NUMBER_OF_COUNTERS = 256; To me this was just the size of a buffer, but it it seems it is the number of values within a byte. In that case you could use BYTE_VALUES or something similar. Or assign it Byte.MAX_VALUE - Byte.MIN_VALUE + 1 to indicate the bytes. checkRangeIndices(array.length, fromIndex, toIndex); The disadvantage of such a check method is that the exception appears to be coming from another method than the one requiring the parameters. This may obscure the error somewhat. There are ways to alter the stack trace, but they are rather ugly so I won't go into them. // Trivially sorted:
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
java, algorithm, sorting, radix-sort // Trivially sorted: // Sort first by least-significant bytes, then by second // least-significant, and finally by third least-signficant byte: To me the use of capitalization and the colon is somewhat annoying and unnecessary. int[] counterMap = new int[NUMBER_OF_COUNTERS]; A map is generally not an array, here I would have expected a comment about how the map is being used. // Spawn sorting: Generally we associate spawning with the spawning of a process or a thread. I would not use any comment just to indicate a call. for (int byteIndex = 0; byteIndex != 3; byteIndex++) { Generally byteIndex < 3 is used, and I would keep to that if simply to avoid confusion. I'm seeing this at multiple places in the code. extractCounterIndex This is a badly named method. It is the byte / digit value that is being extracted. That it is stored in the also badly named "map" in inconsequential for the method itself. buffer[counterMap[index]-- - 1] = array[i]; All those comments, and this hard to read piece of code that performs the magic is not explained. There is a lot of code which is duplicated just to get around the issue of a signed byte. It should be possible to refactor that and get rid of the spurious code (mapping from [-128, -127] to [0, 255] and back again when required). As it is, if there was a bug or other fix then it might end up in one method and not in the other. Maybe it would be an interesting idea to also be able to treat integers as unsigned.
{ "domain": "codereview.stackexchange", "id": 45565, "lm_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, algorithm, sorting, radix-sort", "url": null }
c++, error-handling, c++17, portability Title: TCP socket base class and Winsock implementation Question: I'm coding a chat application from scratch in modern C++. I'm currently building an interface for interacting with sockets. I want it to be cross platform. Am I approaching platform independence correctly? Also is my error handling acceptable? Please tell me what is wrong and what should I improve or change. Socket.h #include <string_view> #include <cstdint> #include <optional> #include <memory> bool InitNetworking(); class TcpSocket { public: TcpSocket() = default; virtual ~TcpSocket() = default; TcpSocket(const TcpSocket &) = delete; TcpSocket(TcpSocket &&) = delete; void operator=(const TcpSocket &) = delete; void operator=(TcpSocket &&) = delete; virtual void *GetHandle() = 0; virtual bool Connect(std::string_view ip_address, std::uint16_t port) = 0; virtual std::shared_ptr<TcpSocket> Accept(std::string_view ip_address, std::uint16_t port) = 0; virtual int Send(TcpSocket &sock, std::string_view message) = 0; virtual std::string Receive() = 0; static std::unique_ptr<TcpSocket> Create(std::string_view name, void *socket_handle = nullptr); private: }; Socket.cpp #include "Socket.h" #include "Win32TcpSocket.h" #ifdef _WIN32 static WSADATA wsa; bool InitNetworking() { if (!WSAStartup(MAKEWORD(2, 2), &wsa)) return true; return false; } std::unique_ptr<TcpSocket> TcpSocket::Create(std::string_view name, void *socket_handle) { auto ptr = Win32TcpSocket::Create(name, (SOCKET)socket_handle); return ptr; } #endif Win32TcpSocket.h #include <string_view> #include <cstdint> #include <memory> #include "Socket.h" #include <WinSock2.h> #include <WS2tcpip.h> class Win32TcpSocket : public TcpSocket { public: Win32TcpSocket() = default; virtual ~Win32TcpSocket();
{ "domain": "codereview.stackexchange", "id": 45566, "lm_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++, error-handling, c++17, portability", "url": null }
c++, error-handling, c++17, portability virtual void *GetHandle() override; virtual bool Connect(std::string_view ip_address, std::uint16_t port) override; virtual std::shared_ptr<TcpSocket> Accept(std::string_view ip_address, std::uint16_t port) override; virtual int Send(TcpSocket &sock, std::string_view message) override; virtual std::string Receive() override; static std::unique_ptr<Win32TcpSocket> Create(std::string_view name, SOCKET socket_handle = 0); private: SOCKET m_socket = INVALID_SOCKET; std::string_view m_name = ""; }; Win32TcpSocket.cpp #include <iostream> #include <exception> #include <stdexcept> std::unique_ptr<Win32TcpSocket> Win32TcpSocket::Create(std::string_view name, SOCKET socket_handle) { auto ptr = std::make_unique<Win32TcpSocket>(); if (!socket_handle) { ptr->m_socket = socket(AF_INET, SOCK_STREAM, 0); if (ptr->m_socket == INVALID_SOCKET) throw std::runtime_error("Invalid socket!"); } else { ptr->m_socket = socket_handle; } ptr->m_name = name; return ptr; } void *Win32TcpSocket::GetHandle() { return (void*)m_socket; } Win32TcpSocket::~Win32TcpSocket() { if(m_socket != INVALID_SOCKET) closesocket(m_socket); m_socket = INVALID_SOCKET; } bool Win32TcpSocket::Connect(std::string_view ip_address, std::uint16_t port) { sockaddr_in hint = {}; hint.sin_family = AF_INET; hint.sin_port = htons(port); inet_pton(AF_INET, ip_address.data(), &hint.sin_addr); int connect_result = connect(m_socket, (sockaddr *)&hint, sizeof(hint)); if (connect_result == SOCKET_ERROR) { return false; } return true; } std::shared_ptr<TcpSocket> Win32TcpSocket::Accept(std::string_view ip_address, std::uint16_t port) { sockaddr_in server_address{}; server_address.sin_family = AF_INET; inet_pton(AF_INET, ip_address.data(), &server_address.sin_addr); server_address.sin_port = htons(port);
{ "domain": "codereview.stackexchange", "id": 45566, "lm_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++, error-handling, c++17, portability", "url": null }
c++, error-handling, c++17, portability int err = bind(m_socket, (struct sockaddr *)&server_address, sizeof(server_address)); if (err == SOCKET_ERROR) { return nullptr; } err = WSAGetLastError(); if (listen(m_socket, SOMAXCONN) == SOCKET_ERROR) { return nullptr; } sockaddr_in client_address = {}; int sz = sizeof(client_address); SOCKET client = accept(m_socket, (struct sockaddr *)&client_address, &sz); if (client == INVALID_SOCKET) { return nullptr; } sockaddr_in hints{}; int hint_size = sizeof(hints); err = getpeername(client, (sockaddr *)&hints, &hint_size); if (err == INVALID_SOCKET) { return nullptr; } char buff[256]{}; inet_ntop(AF_INET, &(hints.sin_addr), buff, 256); auto ptr = Win32TcpSocket::Create(buff, client); return ptr; } int Win32TcpSocket::Send(TcpSocket &sock, std::string_view message) { SOCKET sockfd = (SOCKET)sock.GetHandle(); if (sockfd != INVALID_SOCKET) { return send(sockfd, message.data(), (int)message.length(), 0); } return 0; } std::string Win32TcpSocket::Receive() { char buff[256]{}; int bytes = recv(m_socket, buff, 256, 0); return buff; }
{ "domain": "codereview.stackexchange", "id": 45566, "lm_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++, error-handling, c++17, portability", "url": null }
c++, error-handling, c++17, portability Answer: Firstly, there is no right or wrong about different approaches. The difference is rather how smooth it will be working with this, how easy it is to get it to work and how hard it is to break it. Now, looking at your code, it could be improved, but it is clear to read and understand. No problem there, so let's look at the architecture... Socket Baseclass Is Overloaded The socket baseclass does two things: Input/Output and accepting new connections. These two things are fundamentally different and they are typically used in totally different parts of the program as well. Mixing them into the baseclass will give you headaches. Access To The Handle You define the type of the handle in the baseclass already (void*, the least specific type of all) and force each implementation to provide a getter. There are two things wrong with this: Not every implementation uses void*. So, in order to use the handle, you need to cast it to some other type first. This is always error-prone. You don't document what can or should be done with this handle. Am I now responsible for calling close() on the handle? Under MS Windows, it also needs to be closesocket(), I believe, which doesn't make it any easier to use.
{ "domain": "codereview.stackexchange", "id": 45566, "lm_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++, error-handling, c++17, portability", "url": null }
c++, error-handling, c++17, portability In summary, don't put this into the baseclass. Instead, only provide this handle in the derived class and use the correct type. Further, distinguish between just lending a copy (no ownership) and transfer of ownership. You can support both, which is what you already do in the constructor taking a socket handle. Using Polymorphism You have one base class (actually, just an interface) and one derived class for each OS. Why would you do that at all, when you always only have one of them "active"? Under MS Windows, you only use the Win32TcpSocket, under Solaris, you would perhaps only use the SolarisTcpSocket, so it's always the same anyway. Use one class declaration (header) and different implementations (.cpp files) instead, that would be much clearer. Also, you could get rid of any virtual, which reduces the footprint a tiny bit. Documentation Generally, concerning your use of polymorphism here, the base class is clearly an interface, which is good. However, there is no documentation what each function does, what is required of the parameters and what guarantees the methods offer. I could guess and would probably be close, but not spot on. For example, the Send() method, which @reinderien already mentioned, is very counter-intuitive. This also affects correct use of this class. Lastly and most importantly, writing things down forces you to think about it and possibly find weird or counterintuitive stuff yourself. OS-Specific Split On A Higher Level Your socket class is still very low level. Also, if you want to extend this, you may find yourself looking at e.g. select() (common), WaitForMultipleObjects() (Windows), epoll (Linux) or other OS-specific things that are similar but have very different low-level APIs. Also, consider e.g. a blocking and a non-blocking call to accept().
{ "domain": "codereview.stackexchange", "id": 45566, "lm_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++, error-handling, c++17, portability", "url": null }
c++, error-handling, c++17, portability For that reason, I'd make a split on a higher level. For example, I'd create one class that manages establishing connections and only that. Internally, it could well use a thread that uses a blocking accept() or perhaps some OS-specific API. It would actively emit the new connections using a callback function. Then, I would use a different class for something that only does IO. Again, this could be using buffers and a thread internally for ease of use. Neither of the two would expose raw handles. Miscellaneous Stuff
{ "domain": "codereview.stackexchange", "id": 45566, "lm_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++, error-handling, c++17, portability", "url": null }
c++, error-handling, c++17, portability Why is the MS Windows-specific code in socket.cpp? It should be in the OS-specific file. The TcpSocket base class shouldn't need to know about the Win32TcpSocket derived class. If you return true or false, don't use an if clause to switch between them. Instead, just return the condition you would use in the if clause anyway. Example return connect_result != SOCKET_ERROR;. The name "win32 API" is obsolete, it's called "Windows API" today, so I'd drop that from the name of the class. Don't use a shared_ptr if you actually transfer full ownership. Also, make your type moveable, then you wouldn't need to clarify that anyway. Since you then can't return nullptr, you'll have to signal errors with exceptions. There, you can also provide context like e.g. the failed call and what the errno/GetLastError()/WSAGetLastError() value was. IPv6 support? DNS names support? Just a suggestion. I assume you know or at least suspect that you're reinventing the wheel, which is fine for learning. However, one skill to learn is also to evaluate and integrate other libraries. I would suggest ZeroMQ and Boost, both have goodies for TCP networking.
{ "domain": "codereview.stackexchange", "id": 45566, "lm_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++, error-handling, c++17, portability", "url": null }
performance, random, image, matrix, perl Title: Perl gradient noise generator Question: I'm working on 2-D top-down graphics engine, and need a way to simulate clouds. My idea was that I could create a layer comprised of a matrix of rectangles whose alpha value would be picked from a corresponding cell in a separate matrix. Below is the Perl code I've written to generate a matrix comprised of values between 0 and 1. ########################### # Author: Geoffrey Hudson # Date: 2/6/2018 # Purpose: Generate a matrix of values between 0 and 1 inclusive that can be used as alpha values for cloud like patterns # Generate a 10x10 matrix until I get one that isn't empty do{ @matrix = &makeMatrix(10); }while(!&sumMatrix(\@matrix)); # "Cloud-ify" my matrix with 5 passes &cloudMatrix(\@matrix, 5); # Print my matrix to STDOUT print &printMatrix(\@matrix); ########################### # Generates a matrix with the dimensions size X size. # Each cell has an 2% chance of being 1, which are used as the seed values for future growth. sub makeMatrix{ @m = (); $size = shift; $size--; for(0..$size){ my @arr = (); for(0..$size){ $n = rand() < .02 ? 1 : 0; push(@arr, $n); } splice @m, 1, 0, \@arr; } return @m; } ########################### # Returns the X and Y values of a cell adjacent to the input. # $notX and $notY are given when finding a cell adjacent to the previously adjacent cell, and we do not want the starting point. # E.G. # start = [0][4] # adjacent = [1][4] # adjacent2 = getadjacent(@m, 1,4,0,4) = [1][3] # Params: # @m: the matrix # $x: the X coord to start with # $y: the Y coord to start with # $notX: if given, an X value that cannot be used, elsewise set to -1 # $notY: if given, an Y value that cannot be used, elsewise set to -1 sub getAdjacent{ @m = @{ $_[0] }; $x = $_[1]; $y = $_[2]; $notX = $_[3] ? $_[3] : -1; $notY = $_[4] ? $_[4] : -1; $outX; $outY;
{ "domain": "codereview.stackexchange", "id": 45567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, random, image, matrix, perl", "url": null }
performance, random, image, matrix, perl $outX; $outY; $attempts; do{ # A catch to prevent endless looping. Left over from testing various while conditions. Left in just in case. $attempts++; if($attempts > 1000){ die "$outX: $x | $notX\n$outY: $y | $notY"; } do{ $outX = (int(rand(3))-1) + $x; }while($outX < 0 || $outX >= scalar @m); do{ $outY = (int(rand(3))-1) + $y; }while($outY < 0 || $outY >= scalar @{ $m[$x] }); }while(($outX == $x && $outX == $notX) && ($outY == $y && $outY == $notY)); return ($outX, $outY); } ########################### # Finds the higher of two numbers. # Params: # $n1: any given number # $n2: any other given number sub getMinMax{ $n1 = shift; $n2 = shift; if($n1 <= $n2){ return ($n1, $n2); } else{ return($n2, $n1); } } ########################### # Given a matrix, iterate over it $rounds times. # Simple Steps: # 1. Iterate through the rows # 2. In each row, check each cell # 3. If a cell != 0, find an adjacent cell # 4. Find a cell that is adjacent to the previously found adjacent cell, that is not the parent cell # 5. Set the value of the first adjacent cell to a value between the parent cell, and the second adjacent cell # such that the value is greater than 0, and less than 1 # Params: # @m: a matrix # $rounds: the number of times to go over the matrix sub cloudMatrix{ @m = @{ $_[0] }; $rounds = $_[1]-1;
{ "domain": "codereview.stackexchange", "id": 45567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, random, image, matrix, perl", "url": null }
performance, random, image, matrix, perl for(0..$rounds){ for($i=0;$i<scalar @m;$i++){ for($j=0;$j<scalar @{ $m[$i] }; $j++){ if($m[$i][$j] != 0){ ($k, $l) = &getAdjacent(\@m, $i, $j); if($m[$k][$l] != 0) { next; } ($m, $n) = &getAdjacent(\@m, $k, $l, $i, $j); ($min, $max) = &getMinMax($m[$m][$n], $m[$i][$j]); if($min == $max){ $newVal = $min; }else{ $attempts = 0; do{ $newVal = sprintf('%.1f', rand($max)+($min+.004)); $attempts++; }while($newVal > 1); } $m[$k][$l] = $newVal; } } } } } ########################### # Returns the sum of the matrix. # Used to ensure I'm not getting empty arrays. sub sumMatrix{ return eval join "+", map { join "+", @{ $_ }} @{ $_[0] }; } ########################### # prints the array in such a way that I can easily split it for javascript array later. # Params: # @m: the matrix to print sub printMatrix{ @m = @{ $_[0] }; foreach $row (@m){ @r = @{ $row }; foreach $cell (@r){ $cell = sprintf('%.1f', $cell); $s .= "$cell,"; } $s =~ s/,$/\n/; } return $s; }
{ "domain": "codereview.stackexchange", "id": 45567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, random, image, matrix, perl", "url": null }
performance, random, image, matrix, perl To see example outputs, here is a Try it online! My Question Is this program efficient? Without code golfing it, is there anything I could do to increase efficiency? Am I missing something that could be a problem when scaled differently? Say, a matrix sized 2000, or 1,000,000 passes. What I'm Not Looking For I know, I should use strict and warnings. In the immediate sense, I don't care about that. As I'm the only person using this, and this is only a prototype to be rewritten in a different language later on, it is intentional that I have no checks on input types. Answer: Overview The code layout is good, and you used meaningful names for functions and variables. It's great that you added comments for each sub, along with the function's inputs. CPAN The code does not leverage anything from CPAN. For general matrix operations, there is likely some optimized code available on CPAN. Even if you do not install and use any module from there, you could still perform some research and get ideas from the source code there. Strict and Warnings I realize that you intentionally omit these from your code. However, since the goal of this site is to promote good coding practices, and all answers on the site are meant for everyone who reads this question, it is important to mention. This is for the benefit of readers who may be inexperienced with Perl. The first item on every Perl code review is to make sure the code has: use strict; use warnings; These pragmas help find bugs in your code. Simpler Here is a slightly simpler version of your printMatrix function. There is no reason to copy the @m array; you can just directly dereference $row: sub printMatrix { for $row (@{ $_[0] }) { for $cell (@{ $row }) { $s .= sprintf '%.1f,', $cell; } $s =~ s/,$/\n/; } return $s; }
{ "domain": "codereview.stackexchange", "id": 45567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, random, image, matrix, perl", "url": null }
performance, random, image, matrix, perl Instead of copying the first element of @_ as an array, you can just dereference that as well (although, arguably at the expense of readability). Also, it is simpler to add the comma in the sprintf call. Perlish It is considered more "Perlish" to use map instead of the for/push combination for simple code: sub makeMatrix { my $size = shift; $size--; my @m; for (0 .. $size) { my @arr = map { (rand() < .02) ? 1 : 0 } 0 .. $size; splice @m, 1, 0, \@arr; } return @m; } Linting perlcritic identifies several style issues. Run it yourself to see the full report. For example, don't call functions with a leading ampersand. Change: @matrix = &makeMatrix(10); to: @matrix = makeMatrix(10); Unused code In the getAdjacent function, warnings correctly identified these lines as unused code: $outX; $outY; $attempts; They can be removed to simplify the code. Naming It is confusing to see $m twice in this expression: $m[$m][$n] Consider renaming the inner $m as something else, like $x: $m[$x][$n]
{ "domain": "codereview.stackexchange", "id": 45567, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "performance, random, image, matrix, perl", "url": null }
python, python-3.x, converting Title: GUID to hex-string and back Question: I'm new to Python and I'm trying to convert between Microsoft GUIDs and plain hex strings: def hex_to_guid(hex): h = binascii.unhexlify(hex) return '-'.join(map(bytes.decode, map( binascii.hexlify, (h[0:4][::-1], h[4:6][::-1], h[6:8][::-1], h[8:10], h[10:])))) def guid_to_hex(guid): g = binascii.unhexlify(guid.translate(str.maketrans('', '', '-'))) return ''.join(map(bytes.decode, map( binascii.hexlify, (g[3::-1], g[5:3:-1], g[7:5:-1], g[8:])))) I suspect this may not be very readable. Am I being too clever? Answer: This could definitely be easier to follow. Here are some suggestions: Add some comments and docstrings. The single English sentence in your questions is a big help to understanding the purpose of these functions, and where I might find more information, but it’s not attached to the code. Something as simple as: def hex_to_guid(hex): """Convert a hex string to a Microsoft GUID""" ... would be a big improvement. If you ever look back over this code, it’ll be easier if you have this reference alongside the function. Label the parts of the GUID. In hex_to_guid, you’re packing too much into that final line, and it’s not obvious what any of the components mean. Working from Microsoft’s specification, I think I was able to work out what all the slices were, and then I put them in named variables: # The Microsoft GUID format has four named fields. Split the # bytes into the four fields. Since the fields are big-endian, # we need to reverse the stream returned by unhexlify(). # https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx data1 = reversed(h[0:4]) data2 = reversed(h[4:6]) data3 = reversed(h[6:8]) data4a = h[8:10] data4b = h[10:] return '-'.join(map(bytes.decode, map( binascii.hexlify, (data1, data2, data3, data4a, data4b))))
{ "domain": "codereview.stackexchange", "id": 45568, "lm_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, converting", "url": null }
python, python-3.x, converting Now it’s much easier to check whether the implementation matches the spec. (I’m not confident I’ve got this right, but it’s much easier to check when the parts are named and referenced than before.) Prefer list comprehensions to map(). They’re much more Pythonic, and generally much easier to read. You should also split your code into intermediate steps – it makes it easier to disentangle and debug the individual parts. Something like this seems more natural to me: components = [data1, data2, data3, data4a, data4b] hex_bytes = [binascii.hexlify(d) for d in components] decoded = [bytes.decode(b) for b in hex_bytes] return '-'.join(decoded) There’s a single logical operation per line of code. You don’t have to unpack complicated map() expressions to read it. (My variable names are terrible; you can probably think of something better.) Don’t do too much on a single line. You should never do too much on a single line of code. Readability is much improved by splitting operations over multiple lines, and assigning your intermediate results to variables with meaningful names. The first line of guid_to_hex could easily be split across two or three lines (possibly with interspersed comments to explain what’s going on). Here’s how I might do it: # Remove all dashes from the guid string # @@AWLC: I don't know why you went via translate() and maketrans() # for something that it seems like replace() would handle. guid = guid.replace('-', '') g = binascii.unhexlify(guid) You can then name and unpack the components as before. For what it’s worth, this is what I was left with when I finished writing this answer. It’s substantially longer (although a lot of it is whitespace and prose), but I also claim that a new reader will find my version substantially easier to read, understand and debug: def hex_to_guid(hex): """Convert a hex string to a Microsoft GUID""" h = binascii.unhexlify(hex)
{ "domain": "codereview.stackexchange", "id": 45568, "lm_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, converting", "url": null }
python, python-3.x, converting # The Microsoft GUID format has four named fields. Split the # bytes into the four fields. Since the fields are big-endian, # we need to reverse the stream returned by unhexlify(). # https://msdn.microsoft.com/en-us/library/aa373931(VS.85).aspx data1 = reversed(h[0:4]) data2 = reversed(h[4:6]) data3 = reversed(h[6:8]) data4a = h[8:10] data4b = h[10:] components = [data1, data2, data3, data4a, data4b] hex_bytes = [binascii.hexlify(d) for d in components] decoded = [bytes.decode(b) for b in hex_bytes] return '-'.join(decoded) def guid_to_hex(guid): """Convert a Microsoft GUID to a hex string""" guid = guid.replace('-', '') g = binascii.unhexlify(guid) # As in hex_to_guid, we split the GUID into four named fields. data1 = reversed(g[0:3]) data2 = reversed(g[3:5]) data3 = reversed(g[5:7]) data4 = g[8:] components = [data1, data2, data3, data4] hex_bytes = [binascii.hexlify(d) for d in components] decoded = [bytes.decode(b) for b in hex_bytes] return '-'.join(decoded) This is still by no means perfect: there’s still a lot of code repetition in these two functions. Brevity and cleanliness are good, but they’re on a sliding scale with readability: you should find a balance, not an extreme.
{ "domain": "codereview.stackexchange", "id": 45568, "lm_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, converting", "url": null }
python, object-oriented, datetime, api Title: Return a set of geodetic coordinates for a particular moment in time Question: Use case The user is interested in supplying a timestamp of a particular moment in time. This python application will perform two astronomy calculations for a set list of planetary bodies: Calculate the longitude of the body's subpoint Calculate the boundary on the earth that separates the visible portion from the not visible portion, for an observer standing on the planet. Called the terminator The user is interested in plotting these coordinates. The longitude of the body's subpoint is a float, and the user can choose to turn this into a line on a 2D map by transforming this into a (latitude, longitude) pair. The terminator is a set of geodetic coordinates (latitude, longitude), broken into two halves: halfA and halfB. This is relevant to the user. All of these coordinates make up lines when plotted. How this is used by the user import datetime as dt import pytz from astrolib import calculatelines if __name__ == "__main__": # Define the input parameteres timestamp_string = "2023-03-20 06:00:00" timestamp_format = "%Y-%m-%d %H:%M:%S" utc = "UTC" # Build an aware datetime object naive_observer_time = dt.datetime.strptime(timestamp_string, timestamp_format) aware_observer_time = pytz.timezone(utc).localize(naive_observer_time) # Calculate the results linescollection = calculatelines(aware_observer_time) # Get the data for the sun sun = linescollection.lines["Sun"] # Get the subpoint longitude for mars mars_subpoint_longitude = linescollection.lines["Mars"].subpoint_lng
{ "domain": "codereview.stackexchange", "id": 45569, "lm_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, object-oriented, datetime, api", "url": null }
python, object-oriented, datetime, api # Print the data for the entire set of results print(f"Moment in time: {linescollection.datetime}") for target, lines in linescollection.lines.items(): print(f"Target: {target}") print(f"halfA: {lines.halfA}") print(f"halfB: {lines.halfB}") print(f"Subpoint longitude: {lines.subpoint_lng}") print(f"Anti subpoint longitude: {lines.anti_subpoint_lng}") # $ python main.py # Moment in time: 2023-03-20T06-00-00Z # # Target: Sun # halfA: [ ... ] # halfB: [ ... ] # Subpoint longitude: 91.898710654239 # Anti subpoint longitude: -88.101289345761 # # Target: Mercury # halfA: [ ... ] # halfB: [ ... ] # Subpoint longitude: 94.88150140154595 # Anti subpoint longitude: -85.11849859845405 # # Target: Venus # halfA: [ ... ] # halfB: [ ... ] # Subpoint longitude: 124.11636516090724 # Anti subpoint longitude: -55.883634839092764 The linescollection return object from dataclasses import dataclass import numpy as np @dataclass class Lines: target: str halfA: np.array halfB: np.array subpoint_lng: float anti_subpoint_lng: float @dataclass class LinesCollection: datetime: str lines: dict[str, Lines] The calculatelines API import datetime as dt from astrolib import utils from astrolib import config from astrolib import astronomy from astrolib.responses import ACGLines, ACGLinesCollection def calculatelines(timestamp: dt.datetime) -> LinesCollection: utils.raise_exception_if_naive_time(timestamp) results = {} for target in config.CELESTIAL_INTERESTS.keys(): subpoint_longitude = _calculate_subpoint_longitude(target, timestamp) anti_subpoint_longitude = _calculate_anti_subpoint_longitude(subpoint_longitude) halfA, halfB = _calculate_terminator_coordintes(target, timestamp, anti_subpoint_longitude) results[target] = ACGLines(target, halfA, halfB, subpoint_longitude, anti_subpoint_longitude) response = ACGLinesCollection(timestamp.strftime(config.ISO8061), results) return response
{ "domain": "codereview.stackexchange", "id": 45569, "lm_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, object-oriented, datetime, api", "url": null }
python, object-oriented, datetime, api response = ACGLinesCollection(timestamp.strftime(config.ISO8061), results) return response def _calculate_subpoint_longitude(target: str, time: dt.datetime) -> float: return astronomy.subpoint_meridian(target, time) def _calculate_anti_subpoint_longitude(subpoint_longitude: float) -> float: return (subpoint_longitude % 360) - 180 # degrees def _calculate_terminator_coordintes(target: str, time: dt.datetime, anti_subpoint_longitude: float): terminator_coordinates = astronomy.terminator_great_circle(target, time, samples = config.SAMPLES) halfA_mask, halfB_mask = _get_masks(terminator_coordinates, anti_subpoint_longitude) halfA_coordinates = terminator_coordinates[halfA_mask] halfB_coordinates = terminator_coordinates[halfB_mask] return (halfA_coordinates, halfB_coordinates) My Questions and Context: The motivation for LinesCollection is the following: I want the response from calculatelines() to have both the input parameters and the results I want the results to be easily iterable In the future if/when this is turned into a web API, perhaps the user can supply a list of bodies they are interested in. If they only supply one body, then they should still get the datetime in the response, but I don't want the response type of calculatelines to change from LinesCollection to Lines. The response should still have the same format in my opinion, and only the length of linescollection.lines should change Is there anyway to improve my API design? Something that feels awkward is linescollection.lines. It feels like this can be improved with the following code. Namely, calculatelines returns a Calculation object with the attribute results. calculation = calculatelines(aware_observer_time) sun = calculation.results["Sun"] mars_subpoint_longitude = calculation.results["Mars"].subpoint_lng
{ "domain": "codereview.stackexchange", "id": 45569, "lm_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, object-oriented, datetime, api", "url": null }
python, object-oriented, datetime, api Should Lines also have a datetime attribute? That way, given any Lines object for a particular body, the user has the complete info they need: the body name, the time, and the body's data. This feels cumbersome though. As long as the user has a LinesCollection they have the full set of data, but LinesCollection becomes a misnomer when the user only requests data for a singular body. Should calculate lines take a python datetime object or a string in ISO 8601 format and then the code will generate a python datetime object? Should I allow timezone inputs or should I push timezone responsibility onto the user and only allow inputs in UTC time? Answer: How this is used by the user if __name__ == "__main__": I am always pleased to see habitual use of a __main__ guard. But here, it does very little. Better to def main(): and make the guard do a one-line call to main. We use such a guard so that other modules can safely import this one. For example, you might have a main() function calling some utility() function, and then a separate unit test module also wants to import and call into utility(). The guard lets that import complete successfully, without a print() or other side effects. The absence of any def or class statements renders the current guard mostly moot. redundant comments # Build an aware datetime object This is a helpful comment, and I thank you for it. Most of the other comments could be safely elided, as they say nothing beyond what the code has already said with eloquence and precision. When describing a computation, we use code to explain the how and comments to explain the why. Consider writing a very short make_zone_aware() helper, which would let you elide that "aware" comment. Indeed, in a codebase that quite thoroughly banishes naïve times, the notion of an "aware" distinction simply would not arise. timestamp class LinesCollection: datetime: str
{ "domain": "codereview.stackexchange", "id": 45569, "lm_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, object-oriented, datetime, api", "url": null }
python, object-oriented, datetime, api I prefer an identifier of timestamp. As written, this suggests a dt.datetime object, which clearly a string is not. We're not keeping track of the end user's favorite timezone, and that is fine, this codebase has a strong emphasis on "all UTC all the time!" which its users will soon come to know and love. That's a perfectly sensible way of representing instants in time. If you do choose to keep this as a str rather than make it an aware dt.datetime, I would lobby for tacking on a final "Z". Either than or a final "+00:00". Then even if a maintenance engineer didn't read the docs that stress using UTC, we still can't accidentally misinterpret the meaning of the given timestamp. (And I don't care whether a "T" or a SPACE separates YMD from HMS.) lint halfA: np.array halfB: np.array Pep-8 asks for names like half_a, whatever. It would be nicer to spell it "lines_collection". Also, I'm sorry that numpy type annotation is not yet easy to do. I hear it's improving and will be better in a future release. What you have there is helpful already. nit, typo: def _calculate_terminator_coordintes paranoia utils.raise_exception_if_naive_time(timestamp) Wow, I love it, keep it up! I have also seen CI/CD linting do an effective job of banishing naïveté from a large codebase. meridian type This is pretty interesting: def _calculate_anti_subpoint_longitude(subpoint_longitude: float) -> float: return (subpoint_longitude % 360) - 180 # degrees So the constraint is: -180 <= meridian < 180 Consider defining a custom return type for that, rather than float. The idea would be to make it very hard to accidentally manipulate a "300 degrees longitude" figure. Astropy offers support for units. type stability If they only supply one body, then they should still get the datetime in the response, but I don't want the response type of calculatelines to change Yes, I wholeheartedly agree. That's a good design principle. naming
{ "domain": "codereview.stackexchange", "id": 45569, "lm_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, object-oriented, datetime, api", "url": null }
python, object-oriented, datetime, api Yes, I wholeheartedly agree. That's a good design principle. naming ... improve my API design? Something that feels awkward is linescollection.lines. I find that "collection", while not bad, is on the awkward side. Often we can find a suitable term, a collective noun, in the Business Domain. Here, given that we have celestial objects of interest, I propose that body_lines might fit -- it offers a Lines result per body. (I do wish we didn't have a plural Lines, but it seems accurate and I don't see a better name.) calculatelines returns a Calculation object with the attribute results. I can't say I'm keen on that. It puts a strong emphasis on the whole business of calculating figures. I prefer to believe that the results are a true description of some aspect of the solar system, and worry about naming that. Should Lines also have a datetime attribute? No, I see no motivation for that. If some common usage or API winds up divorcing a Lines from its collection, we could revisit the issue, using new information. As written, the datastructure makes it very clear that all results are for matching timestamps. LinesCollection becomes a misnomer when the user only requests data for a singular body. I respectfully disagree. A container, or a collection, can have zero, one, or more items in it. It may be an "empty" or a "small" collection, and that is perfectly fine. Should calculate lines take a python datetime object or a string My primary focus is the meaning of parameters should be unambiguous and clear. I'm partial to accepting an aware dt.datetime if that's convenient. If it's a str, then ending with Z or +00:00 suffices to make it clear. Should I allow timezone inputs or should I push timezone responsibility onto the user and only allow inputs in UTC time?
{ "domain": "codereview.stackexchange", "id": 45569, "lm_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, object-oriented, datetime, api", "url": null }
python, object-oriented, datetime, api I have not yet seen any indication that end-user A needs their original timezone preserved, nor that communicating A's result object to end-user B would somehow be improved if B could readily tell what that timezone was. So "no", make it each user's responsibility. We have an "astrolib subpoint library" which, given an instant in time, makes some lovely calculations. We could also have a "time utils library" with a few trivial helpers for going to/from UTC. And then we invite end users to compose the two libraries.
{ "domain": "codereview.stackexchange", "id": 45569, "lm_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, object-oriented, datetime, api", "url": null }
python, beginner, object-oriented, tkinter Title: python tkinter Monty Hall GUI visualization Question: I created a visualization to Monty Hall with python. this is my first program with python tkinter. I'm new to python (and OOP in python). I used three pictures for the doors. Adding them here. download the doors gifs - https://ufile.io/2h7fb Or, download separately: door1.gif - https://ibb.co/jSNntw door2.gif - https://ibb.co/bTCntw door3.gif - https://ibb.co/bs0U6G Would love to get some review. I'm sure my object oriented skills are not good at the moment. from tkinter import Tk, Canvas, Button, PhotoImage import random DOOR_1 = 1 DOOR_2 = 2 DOOR_3 = 3 DOORS = (DOOR_1, DOOR_2, DOOR_3) class MontyHall(Tk): def __init__(self): Tk.__init__(self) self.total_counter = 0 self.winning_switchers = 0 self.winning_non_switchers = 0 self.geometry("600x600") self.title("Monty Hall") self.rowconfigure(2, weight=1) self.canvas = Canvas(self, width=600, height=500) self.text = self.canvas.create_text(300, 120) self.answer = self.canvas.create_text(300, 140) self.text_switching = self.canvas.create_text(300, 30) self.text_not_switching = self.canvas.create_text(300, 60) self.door1_pic = PhotoImage(file='door1.gif') self.door2_pic = PhotoImage(file='door2.gif') self.door3_pic = PhotoImage(file='door3.gif') self.door1_show = self.canvas.create_image(100, 350, image=self.door1_pic) self.door2_show = self.canvas.create_image(300, 350, image=self.door2_pic) self.door3_show = self.canvas.create_image(500, 350, image=self.door3_pic) self.canvas.grid(row=2, sticky='s') self.canvas.tag_bind(self.door1_show, "<Button-1>", self.door1) self.canvas.tag_bind(self.door2_show, "<Button-1>", self.door2) self.canvas.tag_bind(self.door3_show, "<Button-1>", self.door3)
{ "domain": "codereview.stackexchange", "id": 45570, "lm_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, object-oriented, tkinter", "url": null }
python, beginner, object-oriented, tkinter def door1(self, *args): self.canvas.itemconfig(self.text, text="you chose door number 1") self.choose_door(DOOR_1) def door2(self, *args): self.canvas.itemconfig(self.text, text="you chose door number 2") self.choose_door(DOOR_2) def door3(self, *args): self.canvas.itemconfig(self.text, text="you chose door number 3") self.choose_door(DOOR_3) def choose_door(self, door_chosen): self.block_doors(4) self.canvas.itemconfig(self.answer, text="") correct_door = random.choice(DOORS) if correct_door != door_chosen: close = random.choice(list(set(DOORS) - {correct_door, door_chosen})) else: close = random.choice(list(set(DOORS) - {door_chosen})) self.block_doors(close) self.options(door_chosen, correct_door, close) def block_doors(self, block_door_number): if block_door_number == 4: self.canvas.tag_unbind(self.door1_show, "<Button-1>") self.canvas.tag_unbind(self.door2_show, "<Button-1>") self.canvas.tag_unbind(self.door3_show, "<Button-1>") if block_door_number == 3: self.canvas.delete(self.door3_show) elif block_door_number == 2: self.canvas.delete(self.door2_show) elif block_door_number == 1: self.canvas.delete(self.door1_show)
{ "domain": "codereview.stackexchange", "id": 45570, "lm_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, object-oriented, tkinter", "url": null }
python, beginner, object-oriented, tkinter def unhide_door(self, open_door): if open_door == 1: self.canvas.tag_bind(self.door2_show, "<Button-1>", self.door2) self.canvas.tag_bind(self.door3_show, "<Button-1>", self.door3) self.door1_show = self.canvas.create_image(100, 350, image=self.door1_pic) self.canvas.tag_bind(self.door1_show, "<Button-1>", self.door1) if open_door == 2: self.canvas.tag_bind(self.door1_show, "<Button-1>", self.door1) self.canvas.tag_bind(self.door3_show, "<Button-1>", self.door3) self.door2_show = self.canvas.create_image(300, 350, image=self.door2_pic) self.canvas.tag_bind(self.door2_show, "<Button-1>", self.door2) if open_door == 3: self.canvas.tag_bind(self.door1_show, "<Button-1>", self.door1) self.canvas.tag_bind(self.door2_show, "<Button-1>", self.door2) self.door3_show = self.canvas.create_image(500, 350, image=self.door3_pic) self.canvas.tag_bind(self.door3_show, "<Button-1>", self.door3) def options(self, door_number, correct_door, closed_door): self.total_counter += 1 def show_results(): self.canvas.itemconfig(self.text_switching, text='Switching won {0:5} times out of {1} ({2:.2f}% of the time)' .format(self.winning_switchers, self.total_counter, (self.winning_switchers / self.total_counter * 100))) self.canvas.itemconfig(self.text_not_switching, text='Not switching won {0:5} times out of {1} ({2:.2f}% of the time)'. format(self.winning_non_switchers, self.total_counter, (self.winning_non_switchers / self.total_counter * 100)))
{ "domain": "codereview.stackexchange", "id": 45570, "lm_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, object-oriented, tkinter", "url": null }
python, beginner, object-oriented, tkinter def change(*args): button1.grid_forget() button2.grid_forget() chosen_door = next(iter(set(DOORS) - {door_number, closed_door})) if chosen_door == correct_door: self.canvas.itemconfig(self.answer, text="you were right") self.winning_switchers += 1 else: self.canvas.itemconfig(self.answer, text="you were wrong") self.unhide_door(closed_door) def keep(*args): button1.grid_forget() button2.grid_forget() if door_number == correct_door: self.canvas.itemconfig(self.answer, text="you were right") self.winning_non_switchers += 1 else: self.canvas.itemconfig(self.answer, text="you were wrong") self.unhide_door(closed_door) button1 = Button(self, text='Click to change door') button1.bind("<Button-1>", change) button1.grid(row=0, sticky='w') button2 = Button(self, text='Click to keep door') button2.bind("<Button-1>", keep) button2.grid(row=1, sticky='w') show_results() if __name__ == "__main__": application = MontyHall() application.mainloop() Answer: Overview You've done an excellent job: Overall code layout is good You did a good job partitioning code into functions You leveraged code written by others with the imports Used meaningful names for classes, functions and variables Here are some adjustments for you to consider, mainly for coding style. Documentation Add comments at the top of the file to state the purpose of the code. For example: ''' Monty Hall problem. Here's how it works... add summary here ''' Instructions When I run the code, all I see is three doors. I don't know what I am expected to do. You should display some simple instructions in the GUI to prompt the user for expected actions, such as: Click on one of the doors to blah, blah, blah...
{ "domain": "codereview.stackexchange", "id": 45570, "lm_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, object-oriented, tkinter", "url": null }
python, beginner, object-oriented, tkinter Efficiency In the unhide_door function, it is wasteful to check the value of the open_door variable in three separate if statements. They can be combined into a single if/elif: if open_door == 1: // ... elif open_door == 2: // ... elif open_door == 3: You partially did this in function block_doors. However, you should merge the two if statements into one if/elif. Simpler Consider removing these constants; it might be simpler just to use the numbers themselves: DOOR_1 = 1 DOOR_2 = 2 DOOR_3 = 3 DRY There are a lot of instances where the the code is repeated 3 times, once for each door. Although I don't have a specific recommendation in mind, it would be worth spending some time looking for an opportunity to combine common code.
{ "domain": "codereview.stackexchange", "id": 45570, "lm_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, object-oriented, tkinter", "url": null }
algorithm, c, calculator Title: Shunting yard calculator in C Question: I'm new to C, and made this program that parses a string expression into a linked list post-fix expression, and then evaluates it, without parsing the string beforehand. Wondering if there is anything to improve/fix (I feel like my implementation is kinda big...) main.c #include "util.h" #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> Node *parse_to_postfix(char *expr); long double evaluate_postfix(Node *expr, int *err); int main(void) { char expr[200] = {0}; while (1) { fgets(expr, 200, stdin); if (strncmp(expr, "quit", 4) == 0) { break; } Node *parsed = parse_to_postfix(expr); if (parsed != NULL) { int err; long double result = evaluate_postfix(parsed, &err); if (err == 0) { printf("= %Lf\n", result); } } memset(expr, 0, strlen(expr)); } return 0; } Node *parse_to_postfix(char *expr) { Stack *output = stack_create(NULL); Stack *op_stack = stack_create(NULL); Node *bottom = NULL; int first_node_created = 0, previous_node_is_op = 1; char *num_buf = calloc(strlen(expr) + 1, sizeof(char)); if (num_buf == NULL) { perror("error:"); abort(); } for (char c = *expr; c != 0; c = *++expr) { if (isspace(c)) { continue; } int c_is_op = is_operator(c); int converted_num = 0; // convert num_buf to long double and push to output if ((c_is_op || c == '(' || c == ')') && strlen(num_buf) > 0) { stack_push(output, node_create(strtold(num_buf, NULL), TYPE_NUMBER)); memset(num_buf, 0, strlen(num_buf)); converted_num = 1; }
{ "domain": "codereview.stackexchange", "id": 45571, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, calculator", "url": null }
algorithm, c, calculator if (c_is_op) { // convert - into -1 * if (c == '-' && ((op_stack->top != NULL && (previous_node_is_op || (op_stack->top->value_type == TYPE_PAREN && !converted_num))) || output->top == NULL)) { c = '*'; stack_push(output, node_create(-1, TYPE_NUMBER)); // simulate having -1 * take precedence over right associative operators if (node_check_valuetype(op_stack->top, TYPE_OPERATOR) && !is_left_assoc(op_stack->top->operator)) { stack_push(op_stack, node_create(c, TYPE_OPERATOR)); // push * to op_stack goto exit_ifs; } } while (node_check_valuetype(op_stack->top, TYPE_OPERATOR) && ((is_left_assoc(c) && get_precedence(c) <= get_precedence(op_stack->top->operator)) || (!is_left_assoc(c) && get_precedence(c) < get_precedence(op_stack->top->operator)))) { stack_push(output, stack_pop(op_stack)); // pop from stack to output } stack_push(op_stack, node_create(c, TYPE_OPERATOR)); // push c to op_stack } else if (c == '(') { stack_push(op_stack, node_create(c, TYPE_PAREN)); } else if (c == ')') { while (!node_check_valuetype(op_stack->top, TYPE_PAREN) && op_stack->top->paren != '(') { stack_push(output, stack_pop(op_stack)); // pop from stack to output } free(stack_pop(op_stack)); // free left parenthesis } else { num_buf[strlen(num_buf)] = c; } exit_ifs: // set reference to first node added to output if (!first_node_created && output->top != NULL) { bottom = output->top; first_node_created = 1; } previous_node_is_op = c_is_op; }
{ "domain": "codereview.stackexchange", "id": 45571, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, calculator", "url": null }
algorithm, c, calculator previous_node_is_op = c_is_op; } // convert any left over digits in num_buf if (strlen(num_buf) > 0) { stack_push(output, node_create(strtold(num_buf, NULL), TYPE_NUMBER)); } // pop remaining operators in op_stack to output while (op_stack->top != NULL) { stack_push(output, stack_pop(op_stack)); } if (!first_node_created && output->top != NULL) { bottom = output->top; } stack_free(op_stack); free(output); free(num_buf); // debugging purposes // Node *head = bottom; // while (head != NULL) { // node_print(head, 0); // head = head->previous; // } // printf("\n"); return bottom; } long double evaluate_postfix(Node *expr, int *err) { Stack *stack = stack_create(NULL); Node *previous = expr->previous; *err = 0; while (expr != NULL) { previous = expr->previous; if (node_check_valuetype(expr, TYPE_NUMBER)) { stack_push(stack, node_remove(expr)); } else if (node_check_valuetype(expr, TYPE_OPERATOR)) { if (stack->top == NULL || stack->top->next == NULL) { printf("error: syntax error\n"); *err = 1; break; } Node *a = stack_pop(stack), *b = stack_pop(stack); long double result;
{ "domain": "codereview.stackexchange", "id": 45571, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, calculator", "url": null }
algorithm, c, calculator Node *a = stack_pop(stack), *b = stack_pop(stack); long double result; switch (expr->operator) { case '+': result = b->number + a->number; break; case '-': result = b->number - a->number; break; case '/': result = b->number / a->number; break; case '*': result = b->number * a->number; break; case '^': result = pow(b->number, a->number); break; } free(a); free(b); free(node_remove(expr)); // free operator from expression stack_push(stack, node_create(result, TYPE_NUMBER)); } expr = previous; } long double whole_result = (node_check_valuetype(stack->top, TYPE_NUMBER)) ? stack->top->number : 0; stack_free(stack); node_free(expr); return whole_result; } util.c #include "util.h" #include <stdio.h> #include <stdlib.h> void node_print(Node *target, int newline) { if (target == NULL) { printf("cannot print NULL node\n"); return; } char nl = (newline) ? '\n' : ' '; switch (target->value_type) { case TYPE_NUMBER: printf("%Lf%c", target->number, nl); break; case TYPE_OPERATOR: printf("%c%c", target->operator, nl); break; case TYPE_PAREN: printf("%c%c", target->paren, nl); break; default: printf("node has no declared value type\n"); } } Node *node_create(long double value, enum NodeType type) { Node *new = malloc(sizeof(*new)); if (new == NULL) { perror("error:"); abort(); } new->next = NULL; new->previous = NULL;
{ "domain": "codereview.stackexchange", "id": 45571, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, calculator", "url": null }
algorithm, c, calculator new->next = NULL; new->previous = NULL; switch (type) { case TYPE_NUMBER: new->number = value; break; case TYPE_OPERATOR: new->operator=(char) value; break; case TYPE_PAREN: new->paren = (char)value; break; default: printf("error: no matching NodeType\n"); return NULL; } new->value_type = type; return new; } Node *node_insert(Node *target, Node *previous, Node *next) { if (previous != NULL) { previous->next = target; } if (next != NULL) { next->previous = target; } target->previous = previous; target->next = next; return target; } Node *node_remove(Node *target) { if (target == NULL) { printf("error: cannot remove NULL node\n"); return NULL; } Node *previous = target->previous, *next = target->next; if (previous != NULL) { previous->next = next; } if (next != NULL) { next->previous = previous; } target->next = NULL; target->previous = NULL; return target; } void node_free(Node *target) { if (target != NULL) { Node *prev_target = target->previous; while (target != NULL) { Node *next = target->next; free(target); target = next; } target = prev_target; while (target != NULL) { Node *previous = target->previous; free(target); target = previous; } } } Stack *stack_create(Node *head) { Stack *new = malloc(sizeof(*new)); if (new == NULL) { perror("error:"); abort(); } new->top = head; return new; } void stack_free(Stack *target) { if (target != NULL) { node_free(target->top); } free(target); }
{ "domain": "codereview.stackexchange", "id": 45571, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, calculator", "url": null }
algorithm, c, calculator Node *stack_push(Stack *target, Node *node) { if (target != NULL) { if (node == NULL) { printf("error: cannot push NULL node to stack\n"); return NULL; } Node *prev_top = target->top; target->top = node; node_insert(node, NULL, prev_top); return node; } else { printf("error: cannot push on undeclared Stack\n"); return NULL; } } Node *stack_pop(Stack *target) { if (target != NULL) { Node *top = target->top; if (top == NULL) { printf("error: cannot pop NULL node from stack\n"); return NULL; } Node *new_top = top->next; Node *popped = node_remove(top); target->top = new_top; return popped; } else { printf("error: cannot pop on undeclared Stack\n"); return NULL; } } int is_operator(char target) { switch (target) { case '+': break; case '-': break; case '/': break; case '*': break; case '^': break; default: return 0; } return 1; } int get_precedence(char operator) { switch (operator) { case '+': return 1; case '-': return 1; case '/': return 2; case '*': return 2; case '^': return 3; default: printf("error: cannot get precendence of unknown operator '%c'\n", operator); return 0; } } int is_left_assoc(char operator) { switch (operator) { case '+': return 1; case '-': return 1; case '/': return 1; case '*': return 1; case '^': return 0; default: printf("error: cannot get associativity of unknown operator '%c'\n", operator); return 0; } }
{ "domain": "codereview.stackexchange", "id": 45571, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, calculator", "url": null }
algorithm, c, calculator int node_check_valuetype(Node *target, enum NodeType type) { return (target == NULL || target->value_type != type) ? 0 : 1; } util.h #ifndef INCLUDE_UTIL_H #define INCLUDE_UTIL_H enum NodeType { TYPE_OPERATOR, TYPE_NUMBER, TYPE_PAREN}; typedef struct Node { struct Node *next; struct Node *previous; union { char operator; char paren; long double number; }; enum NodeType value_type; } Node; typedef struct Stack { Node *top; } Stack; // print value of node void node_print(Node *target, int newline); // allocate node Node *node_create(long double value, enum NodeType type); // insert node between two nodes Node *node_insert(Node *target, Node *previous, Node *next); // update surrounding nodes and return popped node Node *node_remove(Node *target); // free all nodes that are connected to target void node_free(Node *target); // free all nodes and stack void stack_free(Stack *target); // allocate new stack Stack *stack_create(Node *head); // push node to stack Node *stack_push(Stack *target, Node *node); // pop node from stack Node *stack_pop(Stack *target); // if char is an operator * / + - ^ int is_operator(char target); // get precendence value of operator int get_precedence(char operator); // return 1 if operator is left associative int is_left_assoc(char operator); // check if node matches type, return 0 when NULL int node_check_valuetype(Node *target, enum NodeType type); #endif I compiled them using these gcc flags: gcc 13.2.1: -Wall -Wextra -Wpedantic -std=c17 -g -lm Answer: Expanding on the idea of an array for the stack, the Node type wouldn't need to hold pointers and you wouldn't have to allocate a Node on the heap. This would eliminate much of the memory management, such as this bit: free(a); free(b); free(node_remove(expr));
{ "domain": "codereview.stackexchange", "id": 45571, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, calculator", "url": null }
algorithm, c, calculator I would rather have something like Error evaluate_postfix(Node *expr, long double *result) rather than returning the error via pointer. Although, I'd much prefer parse_to_postfix to check for syntax errors instead. evaluate_postfix shouldn't consume *expr. You wouldn't expect a function with that kind of a name to have side-effects. main() owns expr so it should be responsible for freeing it. parse_to_postfix is too complex. Much of the complexity comes from handling the unary minus. I think you could better handle it by treating it as a part of the following number. If the previous token is anything but a number or ), then - is unary and you could put it into num_buf. I would also separate the parsing of numbers into its own function. Instead of pushing digits to num_buf, you'd call parse_number(&expr) when you encounter a digit (or a unary minus or some other number character), which would consume all following digits (and other bits of a number) from the input and return the number's value. In fact, strtold would do this for you. What happens if parentheses don't match in the input? Particularly if there's no ( before ), it seems your code would produce a very non-informative error message: error: cannot push NULL node to stack.
{ "domain": "codereview.stackexchange", "id": 45571, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "algorithm, c, calculator", "url": null }
python, windows, powershell Title: Powershell script that directly executes python script Question: Wrote this script after having some problems with clients on Win10 and consequent necessity to ship ultra-bloated .exe file of Python project over the Web to them. This is my first try to write Powershell scripts (mostly used Linux & Shell scripts before), thus I guess code is not optimal and/or bloated and/or missing some critical steps. How can I improve it? The script is intended for users who have limited understanding of the operating system and Python and might not be inclined to learn more. The goal is for the script to be user-friendly: the user simply double-clicks it, and it performs its function seamlessly. param ( [switch]$ScanSystem = $true, [string]$ScanDrives = "C:,D:", [switch]$AllowCancel = $false, [switch]$Help, [switch]$InstallPython = $true, [switch]$SetupEnvironment = $true, [switch]$RecreateEnvironment = $false, [switch]$RemoveEnvironment = $false, [switch]$InstallDependencies = $true, [string]$PythonVersion = "3.11.7", [switch]$UpdatePip = $true, [double]$RequiredSpaceInGB = 1.0, [string]$ScriptName = "main.py" ) # Check for the /help parameter and display script information if ($Help) { Write-Host "USAGE:" -ForegroundColor Yellow Write-Host "`t.\scriptName.ps1 [PARAMETERS]`n" Write-Host "PARAMETER DESCRIPTION:" -ForegroundColor Yellow Write-Host "`t-ScanSystem`n`t`tChecks for Python presence in the entire system. Default is $true." Write-Host "`t`tExample: -ScanSystem:$false to disable system scan.`n" Write-Host "`t-ScanDrives`n`t`tSpecifies which drives to scan. Default is 'C:,D:'." Write-Host "`t`tExample: -ScanDrives 'E:,F:' to scan drives E: and F:.`n" Write-Host "`t-AllowCancel`n`t`tAllows to cancel execution. Default is $false." Write-Host "`t`tExample: -AllowCancel:$true to allow installation cancellation.`n"
{ "domain": "codereview.stackexchange", "id": 45572, "lm_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, windows, powershell", "url": null }
python, windows, powershell Write-Host "`t-InstallPython`n`t`tInstalls Python if not found. Default is $true." Write-Host "`t`tExample: -InstallPython:$false to not install Python.`n" Write-Host "`t-SetupEnvironment`n`t`tCreates and activates a virtual environment. Default is $true." Write-Host "`t`tExample: -SetupEnvironment:$false to not create an environment.`n" Write-Host "`t-InstallDependencies`n`t`tInstalls libraries from requirements.txt. Default is $true." Write-Host "`t`tExample: -InstallDependencies:$false to not install dependencies.`n" Write-Host "`t-PythonVersion`n`t`tSpecifies the Python version to install. Default is '3.11.7'." Write-Host "`t`tExample: -PythonVersion '3.9.1' to install Python 3.9.1.`n" Write-Host "`t-UpdatePip`n`t`tUpdates pip to the latest version. Default is $true." Write-Host "`t`tExample: -UpdatePip:$false to not update pip.`n" Write-Host "`t-RequiredSpaceInGB`n`t`tRequired amount of free disk space in GB. Default is 1.0." Write-Host "`t`tExample: -RequiredSpaceInGB 2.5 for installation if at least 2.5 GB is available.`n" Write-Host "`t-RecreateEnvironment`n`t`tRecreates the virtual environment if it already exists. Default is $false." Write-Host "`t`tExample: -RecreateEnvironment:$true to recreate the environment.`n" Write-Host "`t-RemoveEnvironment`n`t`tRemoves the virtual environment if it exists. Default is $false." Write-Host "`t`tExample: -RemoveEnvironment:$true to remove the environment.`n" Write-Host "`t-ScriptName`n`t`tSpecifies the Python script to execute. Default is 'main.py'." Write-Host "`t`tExample: -ScriptName 'script.py' to execute 'script.py'.`n"
{ "domain": "codereview.stackexchange", "id": 45572, "lm_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, windows, powershell", "url": null }
python, windows, powershell Write-Host "EXAMPLES:" -ForegroundColor Yellow Write-Host "`t.\start.ps1 -ScanSystem:$false -InstallPython:$true -PythonVersion '3.8.10' -UpdatePip:$true -ScriptName 'other_script.py'" -ForegroundColor Green Write-Host "`t.\start.ps1 -AllowCancel:$true -SetupEnvironment:$false -ScriptName 'run_me.py'`n" -ForegroundColor Green Pause Exit } # Setting the character encoding to UTF-8 $OutputEncoding = [System.Text.Encoding]::UTF8 chcp 65001 # To run in Windows PS ISE: execute the command below in the shell # Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
{ "domain": "codereview.stackexchange", "id": 45572, "lm_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, windows, powershell", "url": null }
python, windows, powershell Write-Host "###########################################" -ForegroundColor Yellow Write-Host "# #" -ForegroundColor Yellow Write-Host "# Automatic Python Installation #" -ForegroundColor Yellow Write-Host "# #" -ForegroundColor Yellow Write-Host "###########################################" -ForegroundColor Yellow Write-Host "# #" -ForegroundColor Yellow Write-Host "# 1. Downloading and Installing Python #" -ForegroundColor Yellow Write-Host "# 2. Creating a Virtual Environment #" -ForegroundColor Yellow Write-Host "# 3. Installing Necessary Libraries #" -ForegroundColor Yellow Write-Host "# #" -ForegroundColor Yellow Write-Host "###########################################" -ForegroundColor Yellow Write-Host "`nSeveral gigabytes of free space may be required to continue the installation.`n" -ForegroundColor Red Write-Host "Current script run parameters:" -ForegroundColor Yellow Write-Host "---------------------------------" -ForegroundColor Yellow Write-Host "Scan System: $ScanSystem" -ForegroundColor Yellow Write-Host "Scan Drives: $ScanDrives" -ForegroundColor Yellow Write-Host "Allow Cancel: $AllowCancel" -ForegroundColor Yellow Write-Host "Install Python: $InstallPython" -ForegroundColor Yellow Write-Host "Setup Environment: $SetupEnvironment" -ForegroundColor Yellow Write-Host "Install Dependencies: $InstallDependencies" -ForegroundColor Yellow Write-Host "Python Version: $PythonVersion" -ForegroundColor Yellow Write-Host "Update Pip: $UpdatePip" -ForegroundColor Yellow Write-Host "Required Space: $RequiredSpaceInGB GB" -ForegroundColor Yellow Write-Host "Recreate Environment: $RecreateEnvironment" -ForegroundColor Yellow Write-Host "Remove Environment: $RemoveEnvironment" -ForegroundColor Yellow Write-Host "---------------------------------" -ForegroundColor Yellow
{ "domain": "codereview.stackexchange", "id": 45572, "lm_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, windows, powershell", "url": null }
python, windows, powershell if ($AllowCancel) { Write-Host "Press any key to continue or X to cancel the installation." -ForegroundColor Yellow $userInput = Read-Host "Select action" if ($userInput -ieq "X") { Write-Host "Installation canceled by the user. You may close the window." -ForegroundColor Red Pause exit } } Write-Host "Checking for an internet connection.." try { $response = Invoke-WebRequest -Uri "http://www.python.org" -UseBasicParsing -TimeoutSec 5 Write-Host "Internet connection is available." -ForegroundColor Green } catch { Write-Host "No internet connection. Check your connection." -ForegroundColor Red Pause exit } $scanChoice = $ScanSystem $scanDrives = $ScanDrives.Split(",").Trim() if ($scanChoice) { Write-Host "You have chosen to scan the system for python.exe." -ForegroundColor Yellow $pythonPaths = Get-ChildItem -Path $scanDrives -Recurse -ErrorAction SilentlyContinue | Where-Object { $_.Name -match 'python[0-9.-]*\.exe$' } | Select-Object -ExpandProperty DirectoryName } else { Write-Host "Scanning the system path for python.exe." -ForegroundColor Yellow $pathDirs = $env:PATH -split ';' $pythonPaths = $pathDirs | Where-Object { Test-Path "$_\python.exe" } | ForEach-Object { $_ } } if ($InstallPython -and $pythonPaths.Count -eq 0) { Write-Host "Python not found in standard locations. Attempting to install Python..." -ForegroundColor Red # Checking available disk space $drive = Get-PSDrive -Name (Get-Location).Drive.Name if ($drive.Free -lt $RequiredSpaceInGB * 1GB) { Write-Host "Not enough disk space to continue the installation. At least $RequiredSpaceInGB GB is required." -ForegroundColor Red Pause exit }
{ "domain": "codereview.stackexchange", "id": 45572, "lm_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, windows, powershell", "url": null }
python, windows, powershell # Maybe use winget? But it requires previous installation.. $pythonInstaller = "python-$PythonVersion.exe" $pythonUrl = "https://www.python.org/ftp/python/$PythonVersion/$pythonInstaller" Invoke-WebRequest -Uri $pythonUrl -OutFile $pythonInstaller Write-Host "Download completed." -ForegroundColor Green Write-Host "Installing Python..." Start-Process $pythonInstaller -ArgumentList '/quiet InstallAllUsers=1 PrependPath=1' -Wait -NoNewWindow Write-Host "Python version $PythonVersion successfully installed." -ForegroundColor Green } elseif ($pythonPaths.Count -eq 1) { $pythonPath = $pythonPaths[0] Write-Host "Found Python at: $pythonPath" } else { Write-Host "Multiple Python installations found:" $i = 1 foreach ($path in $pythonPaths) { Write-Host "$i`: $path" $i++ } $selectedPythonIndex = Read-Host "Enter the number of the desired Python installation" if ($selectedPythonIndex -and $selectedPythonIndex -match '^\d+$' -and $selectedPythonIndex -le $pythonPaths.Count) { $pythonPath = $pythonPaths[$selectedPythonIndex - 1] Write-Host "You have selected Python at: $pythonPath" -ForegroundColor Green } else { Write-Host "Invalid input. Please enter a number corresponding to one of the listed paths." -ForegroundColor Red Pause exit } } # Path where Python is expected to be after installation $pythonExecutable = Join-Path -Path $pythonPath -ChildPath "python.exe" # Checking for presence try { $pythonVersionOutput = & "$pythonPath\python.exe" --version if ($pythonVersionOutput -like "Python $PythonVersion*") { Write-Host "Python version $PythonVersion successfully installed." -ForegroundColor Green } else { throw "Python version does not match the expected: $PythonVersion" } } catch { Write-Host "Error checking Python installation: $_" -ForegroundColor Red Pause exit }
{ "domain": "codereview.stackexchange", "id": 45572, "lm_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, windows, powershell", "url": null }
python, windows, powershell # Virtual environment management $venvPath = ".\venv" if ($RemoveEnvironment -and (Test-Path $venvPath)) { Write-Host "Removing existing virtual environment at $venvPath..." -ForegroundColor Yellow Remove-Item -Path $venvPath -Recurse -Force Write-Host "Virtual environment removed." -ForegroundColor Green } if ($SetupEnvironment -or $RecreateEnvironment) { if (Test-Path $venvPath) { if ($RecreateEnvironment) { Write-Host "Recreating virtual environment at $venvPath..." -ForegroundColor Yellow Remove-Item -Path $venvPath -Recurse -Force Write-Host "Old virtual environment removed." -ForegroundColor Green Write-Host "Creating virtual environment at $venvPath..." -ForegroundColor Yellow & "$pythonPath\python.exe" -m venv $venvPath Write-Host "Virtual environment created." -ForegroundColor Green } else { Write-Host "Virtual environment already exists at $venvPath. Using existing one." -ForegroundColor Yellow } } } if (Test-Path $venvPath) { # Activating the virtual environment $activateScript = Join-Path -Path $venvPath -ChildPath "Scripts\Activate.ps1" if (Test-Path $activateScript) { Write-Host "Activating virtual environment..." -ForegroundColor Yellow . $activateScript } else { Write-Host "Activation script not found: $activateScript" -ForegroundColor Red } } # Updating pip if ($SetupEnvironment) { & "$pythonPath\python.exe" -m pip install --upgrade pip } # Installing dependencies if ($InstallDependencies) { Write-Host "Installing necessary libraries..." & "$pythonPath\python.exe" -m pip install -r requirements.txt }
{ "domain": "codereview.stackexchange", "id": 45572, "lm_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, windows, powershell", "url": null }
python, windows, powershell # Running the specified script Write-Host "Launching script $ScriptName..." & "$pythonExecutable" $ScriptName if ($LASTEXITCODE -ne 0) { Write-Host "Error executing script $ScriptName" -ForegroundColor Red } else { Write-Host "Installation and script execution for $ScriptName completed." -ForegroundColor Green } Pause Answer: The two things that jumped out at me are the wall of calls to Write-Host that can be cleaned up using Here-Strings, and how you are implementing the -Help switch. Here-Strings in PowerShell are just multi-line string literals. They begin with @" and end with "@. The opening block of text when running the script is a prime candidate for this: Write-Host = @" ########################################### # # # Automatic Python Installation # # # ########################################### # # # 1. Downloading and Installing Python # # 2. Creating a Virtual Environment # # 3. Installing Necessary Libraries # # # ########################################### @" -ForegroundColor Yellow Write-Host "Several gigabytes of free space may be required to continue the installation." -ForegroundColor Red Write-Host @" Current script run parameters: --------------------------------- Scan System: $ScanSystem Scan Drives: $ScanDrives Allow Cancel: $AllowCancel Install Python: $InstallPython Setup Environment: $SetupEnvironment Install Dependencies: $InstallDependencies Python Version: $PythonVersion Update Pip: $UpdatePip Required Space: $RequiredSpaceInGB GB Recreate Environment: $RecreateEnvironment Remove Environment: $RemoveEnvironment --------------------------------- @" -ForegroundColor Yellow
{ "domain": "codereview.stackexchange", "id": 45572, "lm_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, windows, powershell", "url": null }
python, windows, powershell The -Help parameter is an interesting problem in PowerShell. The get-help commandlet is the idiomatic way to implement help text, in conjunction with writing comment-based help topics. From experience, I've found that nobody (except me) remembers this command exists, or they habitually pass -Help to the script, because every other command line utility supports some variation of this. You can still implement your own -Help param while also utilizing the get-help commandlet: if ($Help) { get-help $PSCommandPath -Full exit } The remainder of the script looks as straight forward as any other installation wrapper script. The only improvement I would suggest is to define local functions in lieu of a myriad Write-Host "..." -ForgroundColor XXXX calls, but this would only serve to clean things up. function WriteError([string] $message) { Write-Host $message -ForegroundColor Red } function WriteWarning([string] $message) { Write-Host $message -ForegroundColor Yellow } function WriteSuccess([string] $message) { Write-Host $message -ForegroundColor Green } This simplifies things like Write-Host "Not enough disk space to continue the installation. At least $RequiredSpaceInGB GB is required." -ForegroundColor Red to: WriteError "Not enough disk space to continue the installation. At least $RequiredSpaceInGB GB is required." Not a dramatic difference, but at least you can tell at the beginning of the line of code that you are writing an error, as opposed to reading to the end to see -ForegroundColor Red. I suppose you could put the forground color first, but then you need to pass the message with a parameter name: Write-Host -ForegroundColor Red -Object "Not enough disk space..." Defining local functions allows you to give them meaningful names, which also makes the code easier to understand.
{ "domain": "codereview.stackexchange", "id": 45572, "lm_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, windows, powershell", "url": null }
c++, multithreading, c++20 Title: Generic multithreading solution for improving the performance of slow tasks Question: I'm currently in the process of replacing an archaic multithreading solution using some of the newer C++ standard library features now that our software has been updated to use C++20. Previously, most of our multithreading was implemented using thread managers that controlled the flow of the threads and allocated tasks to them. Typically this was done to chop up a very slow function into smaller "bites" of work that could be spread across available threads in order to improve performance. I wanted to create a templated solution that removes the overhead of creating a unique thread manager class and that also reduces complexity for future multithreading implementations. Here is the new solution I've come up with: Threads.h #include <chrono> #include <future> #include <vector> using namespace std::chrono_literals; template <class TPayload> void DoTasksAsync( std::function<void(const TPayload&)> asyncTask, const std::vector<TPayload>& jobs, std::function<bool()> shouldContinue) { int numWorkerThreads = std::thread::hardware_concurrency() - 1; size_t jobsLeft = jobs.size(); std::vector<std::future<void>> futures; do { // create a time point 1 microsecond from now std::chrono::system_clock::time_point aLittleLater = std::chrono::system_clock::now() + 1us; // remove all futures that have finished in space of 1 microsecond std::erase_if(futures, [aLittleLater](std::future<void>& thr) { return thr.wait_until(aLittleLater) == std::future_status::ready; });
{ "domain": "codereview.stackexchange", "id": 45573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, c++20", "url": null }
c++, multithreading, c++20 // if there is space in the futures vector, begin another task in another thread // with the next payload while (futures.size() < numWorkerThreads && jobsLeft > 0) { TPayload payload = std::move(jobs[--jobsLeft]); futures.push_back( std::async( std::launch::async, [&asyncTask, payload = std::move(payload)] { asyncTask(payload); }) ); } } while (futures.size() > 0 && shouldContinue()); // ensure all threads have finished // -- important when shouldContinue() breaks the loop while threads are still executing for (std::future<void>& thr : futures) { if (thr.valid()) { thr.wait(); } else { throw std::future_error(std::future_errc::no_state); } } } Here is an example of how it might be used: Sorter.cpp #include "Threads.h" #include <algorithm> #include <iostream> #include <vector> enum SortingAlgorithm { Bubble, IntroSort }; template<class T> class Sorter { public: void Sort(std::vector<T>& vector, SortingAlgorithm algorithm) { switch (algorithm) { case Bubble: DoBubble(vector); break; case IntroSort: DoIntroSort(vector); break; } } private: void DoBubble(std::vector<T>& vector) { size_t size = vector.size(); for (int i = 0; i < size - 1; i++) { for (int j = 1; j < size - 1; j++) { if (vector[j] < vector[j - 1]) { T temp = vector[j]; vector[j] = vector[j - 1]; vector[j - 1] = temp; } } } }
{ "domain": "codereview.stackexchange", "id": 45573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, c++20", "url": null }
c++, multithreading, c++20 void DoIntroSort(std::vector<T>& vector) { std::sort(vector.begin(), vector.end()); } }; struct SortVectorPayload { Sorter<int>* Sorter; SortingAlgorithm Algorithm; std::vector<int>* Vector; }; static void SortVectorAsync(const SortVectorPayload& payload) { payload.Sorter->Sort(*payload.Vector, payload.Algorithm); } int main() { Sorter<int>* sorter = new Sorter<int>(); std::vector<SortVectorPayload> payloads; // fill the list of payloads with some random stuff to do std::vector<std::vector<int>*> lists; for (int i = 0; i < 100; i++) { lists.push_back(new std::vector<int>(1000)); std::generate(lists.back()->begin(), lists.back()->end(), []() { return std::rand(); }); payloads.push_back(SortVectorPayload{ sorter, Bubble, lists.back() }); } for (int i = 0; i < 100; i++) { lists.push_back(new std::vector<int>(1000)); std::generate(lists.back()->begin(), lists.back()->end(), []() { return std::rand(); }); payloads.push_back(SortVectorPayload{ sorter, IntroSort, lists.back() }); } // sort the lists on available threads DoTasksAsync(std::function(SortVectorAsync), payloads, []() { return true; }); for (std::vector<int>* list : lists) { delete list; } delete sorter; } So, here are my major concerns I'd like to get some help with: I'm using two std::move() calls inside DoTasksAsync to put the payloads in the right location. Is there anything inherently wrong with using both of these calls when perhaps one would suffice, or am I using too few and copying more data than I need to?
{ "domain": "codereview.stackexchange", "id": 45573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, c++20", "url": null }
c++, multithreading, c++20 The only way I could come up with for checking the status of all the futures that are currently running was to create a timepoint 1 microsecond in the future and calling wait_until() on each future. Is there a cleaner way of doing this that would also allow the main thread to continue checking the shouldContinue() function each iteration? I never call get() on any of my futures. Will these leave futures floating around that are still waiting for something to get their result even after they've left the scope of the function? I don't deal with return types at all and just use the payload to have each thread modify some shared data (with appropriate locks and such). What changes could I make to this function to enable return values from each thread's task? And finally, is what I'm doing here even a good idea at all or am I completely barking up the wrong tree?
{ "domain": "codereview.stackexchange", "id": 45573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, c++20", "url": null }
c++, multithreading, c++20 Answer: Use worker threads that pick jobs themselves There are a few issues with your code. First, you call std::async() once for every job. With most implementations of the standard library, it means it creates a new std::thread for every job. While you limit the amount of concurrent threads, creating and destroying a std::thread still has some cost. So it would be better to just create numWorkerThread std::threads, and have each thread pick multiple jobs from jobs themselves, until all jobs are finished. Another issue is that in your implementation, you have a busy-loop waiting for futures to become ready. Sure, it waits up to a microsecond, but that's usually not enough for a CPU core to go into low-power idle mode, so effectively you are still burning power continuously just waiting for another core to finish a task. It's much better to use std::condition_variable to signal that something has finished. Or you could even avoid explicitly waiting entirely. Consider this implementation: template <class TPayload> void DoTasksAsync( std::function<void(const TPayload&)> asyncTask, const std::vector<TPayload>& jobs, std::function<bool()> shouldContinue) { const std::size_t numWorkerThreads = std::min(jobs.size(), std::thread::hardware_concurrency()); std::atomic_size_t next_job = 0; std::vector<std::jthread> threads; threads.reserve(numWorkerThreads); for (std::size_t i = 0; i != numWorkerThreads; ++i) { threads.emplace([&](){ std::size_t job; while (shouldContinue() && (job = next_job++) < jobs.size()) { std::invoke(asyncTask, jobs[job]); } }); } }
{ "domain": "codereview.stackexchange", "id": 45573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, c++20", "url": null }
c++, multithreading, c++20 Moving from a const container You pass jobs by const reference, but later you try to std::move() items from jobs. Because jobs is const, it cannot actually do a real move, and will instead just perform a copy instead. You could pass jobs as a non-const reference, but even better is to not std::move() at all (as shown above), as no copy has to be made if asyncTask itself takes the payload parameter by const reference. Handling the return value of asyncTask This is definitely possible, you just need to ensure DoTasksAsync is also templated on the return value of asyncTask somehow, and you have to decide on some way to store the return values. You could for example use a std::vector for that: template <class TResult, class TPayload> auto DoTasksAsync( std::function<TResult(const TPayload&)> asyncTask, …) { … std::vector<TResult> results(numWorkerThreads); … results[job] = std::invoke(asyncTask, jobs[job]); … return results; } However, note that we now have to explicitly pass the type of the return value as a template parameter when calling DoTasksAsync(). Unfortunately, it cannot deduce this. The solution to this is not to use std::function for passing asyncTask, but rather use a template parameter for the function type, and then deducing the return type from that: template <class TPayload, class TAsyncTask> auto DoTasksAsync( TAsyncTask asyncTask, …) { using TResult = std::invoke_result_t<TAsyncTask, decltype(jobs.first())>; … std::vector<TResult> results(numWorkerThreads); … }
{ "domain": "codereview.stackexchange", "id": 45573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, c++20", "url": null }
c++, multithreading, c++20 Make it more generic Your function requires that the payloads are stored in a std::vector. However, what if you had them in a std::list instead? Or a std::deque, or any other type of container? The only thing you care about is that you can iterate over the range of payloads. So consider writing the function like so: template <class TJobs, class TAsyncTask> auto DoTasksAsync( TAsyncTask asyncTask, TJobs&& jobs, …) { … }
{ "domain": "codereview.stackexchange", "id": 45573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, c++20", "url": null }
c++, multithreading, c++20 You might also consider that the caller wants the result in something different than a std::vector. You could instead have it provide an output iterator to store the results in. This brings me to: You are effectively implementing a parallel std::transform() You are applying asyncTask to all elements of jobs. That's basically a parallel std::transform(). Consider looking at the interface of std::transform() and std::ranges::transform(). Even better, std::transform() can actually run things in parallel, if you it pass an execution policy as the first parameter. So maybe you don't need DoTasksAsync() at all? Consider using a dynamic thread-safe queue for jobs You have to pass a vector of a fixed size to DoAsyncTasks(). However, if you look at your example code, then you are building up payloads, but only once that is fully built can you start processing the payloads. But ideally you could already have a thread start working on the first list right after you added that. The usual solution to that is to use a thread-safe queue. The worker threads will pick items from that queue to process, and the main thread can push new jobs to that queue whenever it wants to. You can find many examples here on Code Review. Avoid manual memory management In your example code, you do a lot of manual memory management. This often leads to bugs, as indeed happens in your code: you forgot to delete sorter, so you have a memory leak. Either avoid using pointers altogether, use smart pointers and/or use better containers. For example, there is no need to allocate sorter on the heap: CSorter sorter(); And to get a stable array of lists: std::deque<std::vector<int>> lists; This works since std::deque will never move its elements around in memory.
{ "domain": "codereview.stackexchange", "id": 45573, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, multithreading, c++20", "url": null }
python Title: Referral Network & Rewards Question: I want to be able to distribute a total reward among network, where the distribution diminishes according to the depth of the network but the total sum of distributed rewards equals the initial total reward. I have attempted to model this with: \$S = a * (1 - r^n) / (1 - r)\$ The below Python snippet presents this series. def distribute_total_reward(total_reward: float, decay_rate: float, max_levels: int = 10) -> list: # Solve for the first term (a) a = total_reward * (1 - decay_rate) / (1 - decay_rate ** max_levels) rewards = [a * (decay_rate ** i) for i in range(max_levels)] return rewards if __name__ == "__main__": # Total reward to be distributed tw = 3500 # 50% Decay rate for the distribution dr = 0.5 # Number of levels in the network ml = 8 reward_distribution = distribute_total_reward(tw, dr, ml) for level, reward in enumerate(reward_distribution, start=1): print(f"Level {level} referrer receives: £${reward:.2f}") print(f"Total Distributed: ${sum(reward_distribution):.2f}")
{ "domain": "codereview.stackexchange", "id": 45574, "lm_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 print(f"Total Distributed: ${sum(reward_distribution):.2f}") Note: I have arbitrarily set tw, dr, ml. One of the things I have struggled with is building out the solution to support circular referrals. I think this sort of breaks a referral system designed with hierarchy because anyone can referrer anyone else. I want to accommodate the flexibility of reverse referrals (i.e., downstream referring upstream and vice versa). I have tried implementing a fixed reward for reverse referrals, separate from the main referral rewards. However, I feel like this is too simplistic as it assumes a fixed number of reverse referrals. Realistically, we need to dynamically identify these reverse referral scenarios and allocate accordingly. Here is the code: def distribute( total_reward: int, decay_rate: float, max_levels: int = 10, reverse_referral_reward: int = 5 ) -> tuple: """ Distributes the total reward among the referral network and handles reverse referrals. """ num_reverse_referrals = 2 adjusted_total_reward = total_reward - (num_reverse_referrals * reverse_referral_reward) a = adjusted_total_reward * (1 - decay_rate) / (1 - decay_rate ** max_levels) rewards = [a * (decay_rate ** i) for i in range(max_levels)] reverse_rewards = [reverse_referral_reward for _ in range(num_reverse_referrals)] return rewards, reverse_rewards if __name__ == "__main__": total_reward = 3500 # Total reward to be distributed decay_rate = 0.5 # Decay rate for the distribution max_levels = 8 # Number of levels in the referral network reverse_referral_reward = 5 # Reward for reverse referrals primary_rewards, reverse_rewards = distribute( total_reward, decay_rate, max_levels, reverse_referral_reward ) for level, reward in enumerate(primary_rewards, start=1): print(f"Level {level} primary referrer receives: ${reward:.2f}")
{ "domain": "codereview.stackexchange", "id": 45574, "lm_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 for i, reward in enumerate(reverse_rewards, start=1): print(f"Reverse referral {i} receives: ${reward:.2f}") print(f"Total Distributed Reward: ${sum(primary_rewards) + sum(reverse_rewards):.2f}")
{ "domain": "codereview.stackexchange", "id": 45574, "lm_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 }