body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I have made a simple Kotlin application called Rock-Paper-Scissor-Lizard-Spock. The application takes in user input and check if belongs to given set of array. If it belongs then it compares user input and random value from array to generate result. Else it prints error and asks for user input again. My code is working fine. Is it possible to simplify my code?</p> <pre><code> fun getUserChoice(userChoice: Array&lt;String&gt;): String { var isValidChoice = false var userValue = &quot;&quot; while (!isValidChoice) { // Ask the user for their choice println(&quot;Please enter one of the following:&quot;) for ((index, item) in userChoice.withIndex()) { println(&quot;${index + 1} . $item&quot;) } val userInput = readLine().toString() println(&quot;You have chosen $userInput&quot;) // validate the user input if (userInput in userChoice ) { isValidChoice = true userValue = userInput } else (println(ERROR_MESSAGE)) // If the choice is invalid inform the user if (!isValidChoice) { ERROR_MESSAGE } } return userValue } fun getGameChoice(randomChoice: String) = randomChoice fun printResult(gamePrint: String, userPrint: String) { println(&quot;I have chosen $gamePrint&quot;) if (gamePrint == userPrint) { println(&quot;It is a draw&quot;) } else if (gamePrint == &quot;Rock&quot; &amp;&amp; userPrint == &quot;Paper&quot;) { println(&quot;$userPrint covers $gamePrint. $userPrint wins!!&quot;) } else if (gamePrint == &quot;Lizard&quot; &amp;&amp; userPrint == &quot;Paper&quot;) { println(&quot;$gamePrint eats $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Scissor&quot; &amp;&amp; userPrint == &quot;Paper&quot;) { println(&quot;$gamePrint cuts $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Spock&quot; &amp;&amp; userPrint == &quot;Paper&quot;) { println(&quot;$userPrint disproves $gamePrint. $userPrint wins!!&quot;) } else if (gamePrint == &quot;Rock&quot; &amp;&amp; userPrint == &quot;Scissor&quot;) { println(&quot;$userPrint crushes $gamePrint. $userPrint wins!!&quot;) } else if (gamePrint == &quot;Rock&quot; &amp;&amp; userPrint == &quot;Lizard&quot;) { println(&quot;$userPrint crushes $gamePrint. $userPrint wins!!&quot;) } else if (gamePrint == &quot;Rock&quot; &amp;&amp; userPrint == &quot;Spock&quot;) { println(&quot;$gamePrint vaporizes $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Paper&quot; &amp;&amp; userPrint == &quot;Scissor&quot;) { println(&quot;$gamePrint cuts $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Spock&quot; &amp;&amp; userPrint == &quot;Scissor&quot;) { println(&quot;$gamePrint smashes $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Lizard&quot; &amp;&amp; userPrint == &quot;Scissor&quot;) { println(&quot;$userPrint cuts $gamePrint. $userPrint wins!!&quot;) } else if (gamePrint == &quot;Paper&quot; &amp;&amp; userPrint == &quot;Lizard&quot;) { println(&quot;$userPrint eats $gamePrint. $userPrint wins!!&quot;) } else if (gamePrint == &quot;Spock&quot; &amp;&amp; userPrint == &quot;Lizard&quot;) { println(&quot;$userPrint poisons $gamePrint. $userPrint wins!!&quot;) } else if (gamePrint == &quot;Paper&quot; &amp;&amp; userPrint == &quot;Spock&quot;) { println(&quot;$gamePrint disproves $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Scissor&quot; &amp;&amp; userPrint == &quot;Lizard&quot;) { println(&quot;$gamePrint decapitates $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Scissor&quot; &amp;&amp; userPrint == &quot;Spock&quot;) { println(&quot;$userPrint smashes $gamePrint. $userPrint wins!!&quot;) } else if (gamePrint == &quot;Lizard&quot; &amp;&amp; userPrint == &quot;Spock&quot;) { println(&quot;$gamePrint poisons $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Spock&quot; &amp;&amp; userPrint == &quot;Rock&quot;) { println(&quot;$gamePrint vaporizes $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Paper&quot; &amp;&amp; userPrint == &quot;Rock&quot;) { println(&quot;$gamePrint covers $userPrint. $gamePrint wins!!&quot;) } else if (gamePrint == &quot;Lizard&quot; &amp;&amp; userPrint == &quot;Rock&quot;) { println(&quot;$userPrint crushes $gamePrint. $userPrint wins!!&quot;) } else if (gamePrint == &quot;Scissor&quot; &amp;&amp; userPrint == &quot;Rock&quot;) { println(&quot;$userPrint crushes $gamePrint. $userPrint wins!!&quot;) } else (ERROR_MESSAGE) } const val ERROR_MESSAGE = &quot;You must enter a valid choice&quot; fun main() { val choices = arrayOf(&quot;Rock&quot;, &quot;Paper&quot;, &quot;Scissor&quot;, &quot;Lizard&quot;, &quot;Spock&quot;) val gameChoice = getGameChoice(choices.random()) val userChoice = getUserChoice(choices) printResult(gameChoice, userChoice) } <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<p>Whenever you see repetitious code like your very long if/else statement, you can probably make it a lot simpler. In this case, you can create a collection to concisely store what beats what as a list of relationships. This is a lot more maintainable if you are debugging later or find that you need to modify something. Unfortunately, since the wheel of relationships is complicated, I can't think of a way to get the compiler to ensure we don't accidentally leave out a relationship.</p>\n<p>I would start with defining an enum for the possible choices, and a list of all the possible comparisons. An enum is a natural choice when you have a finite, pre-defined set of choices. Now the compiler will catch if we make any typos typing the choice names anywhere, which is a risk when you are using them as String literals.</p>\n<pre><code>enum class Choice {\n Rock, Paper, Scissors, Lizard, Spock;\n companion object {\n val relationships = listOf(\n Relationship(Rock, Lizard, &quot;crushes&quot;),\n Relationship(Rock, Scissors, &quot;crushes&quot;),\n Relationship(Paper, Spock, &quot;disproves&quot;),\n Relationship(Paper, Rock, &quot;covers&quot;),\n Relationship(Scissors, Paper, &quot;cuts&quot;),\n Relationship(Scissors, Lizard, &quot;decapitates&quot;),\n Relationship(Spock, Rock, &quot;vaporizes&quot;),\n Relationship(Spock, Scissors, &quot;smashes&quot;),\n Relationship(Lizard, Paper, &quot;eats&quot;),\n Relationship(Lizard, Spock, &quot;poisons&quot;)\n )\n }\n}\ndata class Relationship(val winner: Choice, val loser: Choice, val means: String)\n</code></pre>\n<p>Now the <code>getUserChoice</code> function doesn't need a list passed to it. We just need to check against the enum values. You can eliminate the complexity of <code>isValidInput</code> and <code>userValue</code> by using <code>while (true)</code> and returning directly:</p>\n<pre><code>fun getUserChoice(): Choice {\n while (true) {\n println(&quot;Please enter one of the following:&quot;)\n for ((index, item) in Choice.values().withIndex()) {\n println(&quot;${index + 1} . $item&quot;)\n }\n val userInput = readLine().toString()\n println(&quot;You have chosen $userInput&quot;)\n try {\n return Choice.valueOf(userInput)\n } catch (e: IllegalArgumentException) {\n println(ERROR_MESSAGE)\n }\n }\n}\n</code></pre>\n<p>Now that we have a list of relationships, <code>printResult</code> becomes very simple. We find a relationship that matches our two inputs. If none is found, indicated by null, we can presume it's a tie.</p>\n<pre><code>fun printResult(gameChoice: Choice, userChoice: Choice) {\n println(&quot;I have chosen $gameChoice&quot;)\n val relationship = Choice.relationships.firstOrNull {\n (it.winner == gameChoice &amp;&amp; it.loser == userChoice) ||\n (it.loser == gameChoice &amp;&amp; it.winner == userChoice)\n }\n when (relationship) {\n null -&gt; println(&quot;It is a draw&quot;)\n else -&gt; with (relationship) { println(&quot;$winner $means $loser. $winner wins!!&quot;) }\n }\n}\n</code></pre>\n<p>Finally, your <code>getGameChoice</code> function doesn't make sense because it just returns its argument. You should move the randomization inside the function so it makes sense:</p>\n<pre><code>fun getGameChoice() = Choice.values().random()\n</code></pre>\n<p>The main function becomes:</p>\n<pre><code>fun main() {\n val gameChoice = getGameChoice()\n val userChoice = getUserChoice()\n printResult(gameChoice, userChoice)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:17:32.827", "Id": "508766", "Score": "0", "body": "*I can't think of a way to get the compiler to ensure we don't accidentally leave out a relationship.* - One option would be to use nested `switch` statements, but I think this option might be even better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:23:12.067", "Id": "508769", "Score": "0", "body": "Exactly, unless you would encode the win/lose inside the statements in some other way, and have the else statement simply switch the two around, but then you would have a potential stackoverflow so... Not worth it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:24:22.610", "Id": "508770", "Score": "0", "body": "Upon more thought, I still can't see how it could be done. Every choice has precisely two inferior choices that must be defined. I don't see a way to enforce matching two other choices to every choice or to ensure that there are no accidental redundancies." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-09T17:26:07.793", "Id": "511403", "Score": "1", "body": "You might want change the sequence of the arguments to Relationship. Compare `Relationship(Rock, Lizard, \"crushes\")` vs `Relationship(Rock, \"crushes\", Lizard)`. And maybe `Relationship` also to something else, I just haven't figured a better name yet. Plus, the relationships should be in a map. `firstOrNull` is a linear search over in-memory data. It doesn't matter in this case, it's just generally not a nice appraoch, maps are better at this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-09T18:27:35.770", "Id": "511411", "Score": "0", "body": "@ChristianHujer Yes, those would be good improvements." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:14:27.943", "Id": "257584", "ParentId": "257557", "Score": "4" } }, { "body": "<p>In these two scenarios:</p>\n<p>1.</p>\n<pre><code>} else (ERROR_MESSAGE)\n</code></pre>\n<ol start=\"2\">\n<li></li>\n</ol>\n\n<pre><code>if (!isValidChoice) {\n ERROR_MESSAGE\n}\n</code></pre>\n<p>No error message is actually printed. Simply writing the code <code>ERROR_MESSAGE</code> does not print it.</p>\n<p>These should be:</p>\n<p>1.</p>\n<pre><code>} else println(ERROR_MESSAGE)\n</code></pre>\n<ol start=\"2\">\n<li></li>\n</ol>\n\n<pre><code>if (!isValidChoice) {\n println(ERROR_MESSAGE)\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:20:20.220", "Id": "257585", "ParentId": "257557", "Score": "2" } } ]
{ "AcceptedAnswerId": "257584", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T06:37:40.103", "Id": "257557", "Score": "4", "Tags": [ "kotlin" ], "Title": "Rock-Paper-Scissor-Lizard-Spock in Kotlin" }
257557
<p>Is there any better way to re-write my code :</p> <pre><code>class ContactView(viewsets.ViewSet): @action(methods=['get'], detail=False) def filter(self, request, pk=None): search = request.query_params.get('search') print(search) queryset = Contact.objects.all().filter( Q(first_name__icontains=search) | Q(city__icontains=search) | Q(country__icontains=search) | Q(last_name__icontains=search) | Q(email__icontains=search) | Q(company__icontains=search) ) serializer = ContactSerializer(queryset, many=True) return Response(serializer.data) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T09:00:33.940", "Id": "508721", "Score": "0", "body": "Welcome to CodeReview. Could you please elaborate on *better*? From what aspect?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T08:51:46.443", "Id": "257559", "Score": "0", "Tags": [ "python", "django" ], "Title": "Contacts viewset" }
257559
<h1><a href="https://github.com/camurban/pterasoftware" rel="noreferrer">Ptera Software</a></h1> <p><em>A Flapping Wing Aerodynamics Simulator Written in Python</em></p> <p><a href="https://i.stack.imgur.com/1KzjB.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/1KzjB.gif" alt="output" /></a> <a href="https://i.stack.imgur.com/Nv6LI.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Nv6LI.jpg" alt="logo" /></a></p> <h2>Motivation</h2> <p>About a year ago, I became fascinated by how animals fly. As an aerospace engineering student, it surprised me that natural flight was barely covered in my courses. I soon realized that the reason why flapping wing aerodynamics isn't taught to undergraduate engineers is that it's insanely complicated.</p> <p>This only made me more interested. I had some experience with UAV design, so I wanted to find a tool that would help me create a flapping wing micro-air vehicle (MAV), such as the <a href="https://www.youtube.com/watch?v=CEhu-FePBC0&amp;ab_channel=MAVLabTUDelft" rel="noreferrer">TU Delft's DelFly</a>. Unfortunately, there were no open-source, easy to use, and fast programs for doing so. Therefore, in a moment of temporary insanity, I decided to write my own!</p> <h2>Initial Goals</h2> <p>My initial goal for <a href="https://github.com/camUrban/PteraSoftware" rel="noreferrer">Ptera Software</a> was to create a tool that other researchers and I can use to design the aerodynamics of ornithopters. This is goal zero. I also wanted my software to be:</p> <ol> <li>Easy to use</li> <li>Easy to read</li> <li>Easy to maintain</li> <li>Validated</li> <li>Attractive to contributors in the open-source community</li> <li>Fast enough to analyze at least 1000 configurations in 24 hours Based on these requirements, I decided that the solver would be a Python implementation of the Unsteady Vortex-Lattice Method (UVLM). I also decided to host the repository on GitHub, and distribute it via PyPI.</li> </ol> <h2>Current State</h2> <p>Like many ignorant non-CS engineers before me, I was confident that creating, debugging, testing, and maintaining a massive project would be as easy as writing a 100-line MATLAB script. Months of coding and therapy later, I had released my 'stable' 1.0.0 package.</p> <p>I've copied the source code of my unsteady solver below. I did this to abide by the rule that we keep things as native to this site as possible. If you can, I recommend going to the vectorization branch on GitHub and navigate to unsteady_ring_vortex_lattice_method.py. If the vectorization branch is no longer active, go to the latest release's master branch.</p> <h3>Unsteady Sover</h3> <pre><code>class UnsteadyRingVortexLatticeMethodSolver: &quot;&quot;&quot;This is an aerodynamics solver that uses an unsteady ring vortex lattice method.&quot;&quot;&quot; def __init__(self, unsteady_problem): &quot;&quot;&quot;This is the initialization method.&quot;&quot;&quot; # Initialize this solution's attributes. self.num_steps = unsteady_problem.num_steps self.delta_time = unsteady_problem.delta_time self.steady_problems = unsteady_problem.steady_problems self.first_results_step = unsteady_problem.first_results_step # Initialize attributes to hold aerodynamic data that pertains to this problem. self.current_step = None self.current_airplane = None self.current_operating_point = None self.current_freestream_velocity_geometry_axes = None self.current_wing_wing_influences = None self.vectorized_current_wing_wing_influences = None self.current_freestream_wing_influences = None self.vectorized_current_freestream_wing_influences = None self.current_wake_wing_influences = None self.vectorized_current_wake_wing_influences = None self.current_vortex_strengths = None self.vectorized_current_vortex_strengths = None self.streamline_points = None # Initialize attributes to hold geometric data that pertains to this problem. self.panels = None self.panel_normal_directions = None self.panel_areas = None self.panel_centers = None self.panel_collocation_points = None self.panel_back_right_vortex_vertices = None self.panel_front_right_vortex_vertices = None self.panel_front_left_vortex_vertices = None self.panel_back_left_vortex_vertices = None self.panel_right_vortex_centers = None self.panel_right_vortex_vectors = None self.panel_front_vortex_centers = None self.panel_front_vortex_vectors = None self.panel_left_vortex_centers = None self.panel_left_vortex_vectors = None self.panel_back_vortex_centers = None self.panel_back_vortex_vectors = None self.seed_points = None # Initialize variables to hold aerodynamic data that pertains details about # this panel's location on its wing. self.panel_is_trailing_edge = None self.panel_is_leading_edge = None self.panel_is_left_edge = None self.panel_is_right_edge = None # Initialize variables to hold aerodynamic data that pertains to this # problem's last time step. self.last_panel_collocation_points = None self.last_panel_vortex_strengths = None self.last_panel_back_right_vortex_vertices = None self.last_panel_front_right_vortex_vertices = None self.last_panel_front_left_vortex_vertices = None self.last_panel_back_left_vortex_vertices = None self.last_panel_right_vortex_centers = None self.last_panel_front_vortex_centers = None self.last_panel_left_vortex_centers = None self.last_panel_back_vortex_centers = None # Initialize variables to hold aerodynamic data that pertains to this # problem's wake. self.wake_ring_vortex_strengths = None self.wake_ring_vortex_front_right_vertices = None self.wake_ring_vortex_front_left_vertices = None self.wake_ring_vortex_back_left_vertices = None self.wake_ring_vortex_back_right_vertices = None def run( self, verbose=True, prescribed_wake=True, calculate_streamlines=True, ): &quot;&quot;&quot;This method runs the solver on the unsteady problem.&quot;&quot;&quot; # Initialize all the airplanes' panels' vortices. if verbose: print(&quot;Initializing all airplanes' panel vortices.&quot;) self.initialize_panel_vortices() # Iterate through the time steps. for step in range(self.num_steps): # Save attributes to hold the current step, airplane, and operating point. self.current_step = step self.current_airplane = self.steady_problems[self.current_step].airplane self.current_operating_point = self.steady_problems[ self.current_step ].operating_point self.current_freestream_velocity_geometry_axes = ( self.current_operating_point.calculate_freestream_velocity_geometry_axes() ) if verbose: print( &quot;\nBeginning time step &quot; + str(self.current_step) + &quot; out of &quot; + str(self.num_steps - 1) + &quot;.&quot; ) # Initialize attributes to hold aerodynamic data that pertains to this # problem. self.current_wing_wing_influences = np.zeros( (self.current_airplane.num_panels, self.current_airplane.num_panels) ) self.vectorized_current_wing_wing_influences = np.zeros( (self.current_airplane.num_panels, self.current_airplane.num_panels) ) self.current_freestream_velocity_geometry_axes = ( self.current_operating_point.calculate_freestream_velocity_geometry_axes() ) self.current_freestream_wing_influences = np.zeros( self.current_airplane.num_panels ) self.vectorized_current_freestream_wing_influences = np.zeros( self.current_airplane.num_panels ) self.current_wake_wing_influences = np.zeros( self.current_airplane.num_panels ) self.vectorized_current_wake_wing_influences = np.zeros( self.current_airplane.num_panels ) self.current_vortex_strengths = np.ones(self.current_airplane.num_panels) self.vectorized_current_vortex_strengths = np.ones( self.current_airplane.num_panels ) # Initialize attributes to hold geometric data that pertains to this # problem. self.panels = np.empty(self.current_airplane.num_panels, dtype=object) self.panel_normal_directions = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_areas = np.zeros(self.current_airplane.num_panels) self.panel_centers = np.zeros((self.current_airplane.num_panels, 3)) self.panel_collocation_points = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_back_right_vortex_vertices = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_front_right_vortex_vertices = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_front_left_vortex_vertices = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_back_left_vortex_vertices = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_right_vortex_centers = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_right_vortex_vectors = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_front_vortex_centers = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_front_vortex_vectors = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_left_vortex_centers = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_left_vortex_vectors = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_back_vortex_centers = np.zeros( (self.current_airplane.num_panels, 3) ) self.panel_back_vortex_vectors = np.zeros( (self.current_airplane.num_panels, 3) ) self.seed_points = np.empty((0, 3)) # Initialize variables to hold details about this panel's location on its # wing. self.panel_is_trailing_edge = np.zeros( self.current_airplane.num_panels, dtype=bool ) self.panel_is_leading_edge = np.zeros( self.current_airplane.num_panels, dtype=bool ) self.panel_is_left_edge = np.zeros( self.current_airplane.num_panels, dtype=bool ) self.panel_is_right_edge = np.zeros( self.current_airplane.num_panels, dtype=bool ) # Initialize variables to hold details about the last airplane's panels. self.last_panel_collocation_points = np.zeros( (self.current_airplane.num_panels, 3) ) self.last_panel_vortex_strengths = np.zeros( self.current_airplane.num_panels ) self.last_panel_back_right_vortex_vertices = np.zeros( (self.current_airplane.num_panels, 3) ) self.last_panel_front_right_vortex_vertices = np.zeros( (self.current_airplane.num_panels, 3) ) self.last_panel_front_left_vortex_vertices = np.zeros( (self.current_airplane.num_panels, 3) ) self.last_panel_back_left_vortex_vertices = np.zeros( (self.current_airplane.num_panels, 3) ) self.last_panel_right_vortex_centers = np.zeros( (self.current_airplane.num_panels, 3) ) self.last_panel_front_vortex_centers = np.zeros( (self.current_airplane.num_panels, 3) ) self.last_panel_left_vortex_centers = np.zeros( (self.current_airplane.num_panels, 3) ) self.last_panel_back_vortex_centers = np.zeros( (self.current_airplane.num_panels, 3) ) self.wake_ring_vortex_strengths = np.empty(0) self.wake_ring_vortex_front_right_vertices = np.empty((0, 3)) self.wake_ring_vortex_front_left_vertices = np.empty((0, 3)) self.wake_ring_vortex_back_left_vertices = np.empty((0, 3)) self.wake_ring_vortex_back_right_vertices = np.empty((0, 3)) # Collapse this problem's geometry matrices into 1D ndarrays of attributes. if verbose: print(&quot;Collapsing geometry.&quot;) self.collapse_geometry() # Find the matrix of wing-wing influence coefficients associated with # this current_airplane's geometry. if verbose: print(&quot;Calculating the wing-wing influences.&quot;) self.calculate_wing_wing_influences() # Find the vector of freestream-wing influence coefficients associated # with this problem. if verbose: print(&quot;Calculating the freestream-wing influences.&quot;) self.calculate_freestream_wing_influences() # Find the vector of wake-wing influence coefficients associated with # this problem. if verbose: print(&quot;Calculating the wake-wing influences.&quot;) self.calculate_wake_wing_influences() # Solve for each panel's vortex strength. if verbose: print(&quot;Calculating vortex strengths.&quot;) self.calculate_vortex_strengths() # Solve for the near field forces and moments on each panel. if self.current_step &gt;= self.first_results_step: if verbose: print(&quot;Calculating near field forces.&quot;) self.calculate_near_field_forces_and_moments() # Solve for the near field forces and moments on each panel. if verbose: print(&quot;Shedding wake vortices.&quot;) self.populate_next_airplanes_wake(prescribed_wake=prescribed_wake) # Solve for the location of the streamlines if requested. if calculate_streamlines: if verbose: print(&quot;\nCalculating streamlines.&quot;) self.calculate_streamlines() def initialize_panel_vortices(self): &quot;&quot;&quot;This method calculates the locations every problem's airplane's bound vortex vertices, and then initializes its panels' bound vortices. Every panel has a ring vortex, which is a quadrangle whose front vortex leg is at the panel's quarter chord. The left and right vortex legs run along the panel's left and right legs. If the panel is not along the trailing edge, they extend backwards and meet the back vortex leg at a length of one quarter of the rear panel's chord back from the rear panel's front leg. Otherwise, they extend back backwards and meet the back vortex leg at a length of one quarter of the current panel's chord back from the current panel's back leg. &quot;&quot;&quot; # Iterate through all the steady problem objects. for steady_problem in self.steady_problems: this_freestream_velocity_geometry_axes = ( steady_problem.operating_point.calculate_freestream_velocity_geometry_axes() ) # Iterate through this problem's airplane's wings. for wing in steady_problem.airplane.wings: # Iterate through the wing's chordwise and spanwise positions. for chordwise_position in range(wing.num_chordwise_panels): for spanwise_position in range(wing.num_spanwise_panels): panel = wing.panels[chordwise_position, spanwise_position] front_left_vortex_vertex = panel.front_left_vortex_vertex front_right_vortex_vertex = panel.front_right_vortex_vertex # Define the back left and right vortex vertices based on # whether the panel is along the trailing edge or not. if not panel.is_trailing_edge: next_chordwise_panel = wing.panels[ chordwise_position + 1, spanwise_position ] back_left_vortex_vertex = ( next_chordwise_panel.front_left_vortex_vertex ) back_right_vortex_vertex = ( next_chordwise_panel.front_right_vortex_vertex ) else: # As these vertices are directly behind the trailing # edge, they are spaced back from their # panel's vertex by one quarter the distance traveled # during a time step. This is to more # accurately predict drag. back_left_vortex_vertex = ( front_left_vortex_vertex + (panel.back_left_vertex - panel.front_left_vertex) + this_freestream_velocity_geometry_axes * self.delta_time * 0.25 ) back_right_vortex_vertex = ( front_right_vortex_vertex + (panel.back_right_vertex - panel.front_right_vertex) + this_freestream_velocity_geometry_axes * self.delta_time * 0.25 ) # Initialize the panel's ring vortex. panel.ring_vortex = ps.aerodynamics.RingVortex( front_right_vertex=front_right_vortex_vertex, front_left_vertex=front_left_vortex_vertex, back_left_vertex=back_left_vortex_vertex, back_right_vertex=back_right_vortex_vertex, strength=None, ) def collapse_geometry(self): &quot;&quot;&quot;This method converts attributes of the problem's geometry into 1D ndarrays. This facilitates vectorization, which speeds up the solver.&quot;&quot;&quot; global_panel_position = 0 # Iterate through the current airplane's wings. for wing in self.current_airplane.wings: # Convert this wing's 2D ndarray of panels into a 1D ndarray. panels = np.ravel(wing.panels) wake_ring_vortices = np.ravel(wing.wake_ring_vortices) # Iterate through the 1D ndarray of this wing's panels. for panel in panels: # Update the solver's list of attributes with this panel's attributes. self.panels[global_panel_position] = panel self.panel_normal_directions[ global_panel_position, : ] = panel.normal_direction self.panel_areas[global_panel_position] = panel.area self.panel_centers[global_panel_position] = panel.center self.panel_collocation_points[ global_panel_position, : ] = panel.collocation_point self.panel_back_right_vortex_vertices[ global_panel_position, : ] = panel.ring_vortex.right_leg.origin self.panel_front_right_vortex_vertices[ global_panel_position, : ] = panel.ring_vortex.right_leg.termination self.panel_front_left_vortex_vertices[ global_panel_position, : ] = panel.ring_vortex.left_leg.origin self.panel_back_left_vortex_vertices[ global_panel_position, : ] = panel.ring_vortex.left_leg.termination self.panel_right_vortex_centers[ global_panel_position, : ] = panel.ring_vortex.right_leg.center self.panel_right_vortex_vectors[ global_panel_position, : ] = panel.ring_vortex.right_leg.vector self.panel_front_vortex_centers[ global_panel_position, : ] = panel.ring_vortex.front_leg.center self.panel_front_vortex_vectors[ global_panel_position, : ] = panel.ring_vortex.front_leg.vector self.panel_left_vortex_centers[ global_panel_position, : ] = panel.ring_vortex.left_leg.center self.panel_left_vortex_vectors[ global_panel_position, : ] = panel.ring_vortex.left_leg.vector self.panel_back_vortex_centers[ global_panel_position, : ] = panel.ring_vortex.back_leg.center self.panel_back_vortex_vectors[ global_panel_position, : ] = panel.ring_vortex.back_leg.vector self.panel_is_trailing_edge[ global_panel_position ] = panel.is_trailing_edge self.panel_is_leading_edge[ global_panel_position ] = panel.is_leading_edge self.panel_is_right_edge[global_panel_position] = panel.is_right_edge self.panel_is_left_edge[global_panel_position] = panel.is_left_edge # Check if this panel is on the trailing edge. if panel.is_trailing_edge: # If it is, calculate it's streamline seed point and add it to # the solver's ndarray of seed points. self.seed_points = np.vstack( ( self.seed_points, panel.back_left_vertex + 0.5 * (panel.back_right_vertex - panel.back_left_vertex), ) ) # Increment the global panel position. global_panel_position += 1 for wake_ring_vortex in wake_ring_vortices: self.wake_ring_vortex_strengths = np.hstack( (self.wake_ring_vortex_strengths, wake_ring_vortex.strength) ) self.wake_ring_vortex_front_right_vertices = np.vstack( ( self.wake_ring_vortex_front_right_vertices, wake_ring_vortex.front_right_vertex, ) ) self.wake_ring_vortex_front_left_vertices = np.vstack( ( self.wake_ring_vortex_front_left_vertices, wake_ring_vortex.front_left_vertex, ) ) self.wake_ring_vortex_back_left_vertices = np.vstack( ( self.wake_ring_vortex_back_left_vertices, wake_ring_vortex.back_left_vertex, ) ) self.wake_ring_vortex_back_right_vertices = np.vstack( ( self.wake_ring_vortex_back_right_vertices, wake_ring_vortex.back_right_vertex, ) ) # Initialize a variable to hold the global position of the panel as we # iterate through them. global_panel_position = 0 if self.current_step &gt; 0: last_airplane = self.steady_problems[self.current_step - 1].airplane # Iterate through the current airplane's wings. for wing in last_airplane.wings: # Convert this wing's 2D ndarray of panels into a 1D ndarray. panels = np.ravel(wing.panels) # Iterate through the 1D ndarray of this wing's panels. for panel in panels: # Update the solver's list of attributes with this panel's # attributes. self.last_panel_collocation_points[ global_panel_position, : ] = panel.collocation_point self.last_panel_vortex_strengths[ global_panel_position ] = panel.ring_vortex.strength self.last_panel_back_right_vortex_vertices[ global_panel_position, : ] = panel.ring_vortex.right_leg.origin self.last_panel_front_right_vortex_vertices[ global_panel_position, : ] = panel.ring_vortex.right_leg.termination self.last_panel_front_left_vortex_vertices[ global_panel_position, : ] = panel.ring_vortex.left_leg.origin self.last_panel_back_left_vortex_vertices[ global_panel_position, : ] = panel.ring_vortex.left_leg.termination self.last_panel_right_vortex_centers[ global_panel_position, : ] = panel.ring_vortex.right_leg.center self.last_panel_front_vortex_centers[ global_panel_position, : ] = panel.ring_vortex.front_leg.center self.last_panel_left_vortex_centers[ global_panel_position, : ] = panel.ring_vortex.left_leg.center self.last_panel_back_vortex_centers[ global_panel_position, : ] = panel.ring_vortex.back_leg.center # Increment the global panel position. global_panel_position += 1 def calculate_wing_wing_influences(self): &quot;&quot;&quot;This method finds the matrix of wing-wing influence coefficients associated with this airplane's geometry.&quot;&quot;&quot; # Find the matrix of normalized velocities induced at every panel's # collocation point by every panel's ring # vortex. The answer is normalized because the solver's vortex strength list # was initialized to all ones. This # will be updated once the correct vortex strength's are calculated. total_influences = ps.aerodynamics.calculate_velocity_induced_by_ring_vortices( points=self.panel_collocation_points, back_right_vortex_vertices=self.panel_back_right_vortex_vertices, front_right_vortex_vertices=self.panel_front_right_vortex_vertices, front_left_vortex_vertices=self.panel_front_left_vortex_vertices, back_left_vortex_vertices=self.panel_back_left_vortex_vertices, strengths=self.current_vortex_strengths, collapse=False, ) # Take the batch dot product of the normalized velocities with each panel's # normal direction. This is now the # problem's matrix of wing-wing influence coefficients. self.current_wing_wing_influences = np.einsum( &quot;...k,...k-&gt;...&quot;, total_influences, np.expand_dims(self.panel_normal_directions, axis=1), ) def calculate_freestream_wing_influences(self): &quot;&quot;&quot;This method finds the vector of freestream-wing influence coefficients associated with this problem.&quot;&quot;&quot; # Find the normal components of the freestream velocity on every panel by # taking a batch dot product. freestream_influences = np.einsum( &quot;ij,j-&gt;i&quot;, self.panel_normal_directions, self.current_freestream_velocity_geometry_axes, ) # Get the current flapping velocities at every collocation point. current_flapping_velocities_at_collocation_points = ( self.calculate_current_flapping_velocities_at_collocation_points() ) # Find the normal components of every panel's flapping velocities at their # collocation points by taking a batch # dot product. flapping_influences = np.einsum( &quot;ij,ij-&gt;i&quot;, self.panel_normal_directions, current_flapping_velocities_at_collocation_points, ) # Calculate the total current freestream-wing influences by summing the # freestream influences and the # flapping influences. self.current_freestream_wing_influences = ( freestream_influences + flapping_influences ) def calculate_wake_wing_influences(self): &quot;&quot;&quot;This method finds the vector of the wake-wing influences associated with the problem at this time step.&quot;&quot;&quot; # Check if this time step is not the first time step. if self.current_step &gt; 0: # Get the wake induced velocities. This is a (M x 3) ndarray with the x, # y, and z components of the velocity # induced by the entire wake at each of the M panels. wake_induced_velocities = ps.aerodynamics.calculate_velocity_induced_by_ring_vortices( points=self.panel_collocation_points, back_right_vortex_vertices=self.wake_ring_vortex_back_right_vertices, front_right_vortex_vertices=self.wake_ring_vortex_front_right_vertices, front_left_vortex_vertices=self.wake_ring_vortex_front_left_vertices, back_left_vortex_vertices=self.wake_ring_vortex_back_left_vertices, strengths=self.wake_ring_vortex_strengths, collapse=True, ) # Set the current wake-wing influences to the normal component of the # wake induced velocities at each panel. self.current_wake_wing_influences = np.einsum( &quot;ij,ij-&gt;i&quot;, wake_induced_velocities, self.panel_normal_directions ) else: # If this is the first time step, set the current wake-wing influences to # zero everywhere, as there is no # wake yet. self.current_wake_wing_influences = np.zeros( self.current_airplane.num_panels ) def calculate_vortex_strengths(self): &quot;&quot;&quot;This method solves for each panel's vortex strength.&quot;&quot;&quot; # Solve for the strength of each panel's vortex. self.current_vortex_strengths = np.linalg.solve( self.current_wing_wing_influences, -self.current_wake_wing_influences - self.current_freestream_wing_influences, ) # Iterate through the panels and update their vortex strengths. for panel_num in range(self.panels.size): # Get the panel at this location. panel = self.panels[panel_num] # Update this panel's ring vortex strength. panel.ring_vortex.update_strength(self.current_vortex_strengths[panel_num]) def calculate_solution_velocity(self, points): &quot;&quot;&quot;This function takes in a group of points. At every point, it finds the induced velocity due to every vortex and the freestream velocity. :param points: 2D ndarray of floats This variable is an ndarray of shape (N x 3), where N is the number of points. Each row contains the x, y, and z float coordinates of that point's position in meters. :return solution_velocities: 2D ndarray of floats The output is the summed effects from every vortex, and from the freestream on a given point. The result will be of shape (N x 3), where each row identifies the velocity at a point. The results units are meters per second. &quot;&quot;&quot; # Find the vector of velocities induced at every point by every panel's ring # vortex. The effect of every ring # vortex on each point will be summed. ring_vortex_velocities = ( ps.aerodynamics.calculate_velocity_induced_by_ring_vortices( points=points, back_right_vortex_vertices=self.panel_back_right_vortex_vertices, front_right_vortex_vertices=self.panel_front_right_vortex_vertices, front_left_vortex_vertices=self.panel_front_left_vortex_vertices, back_left_vortex_vertices=self.panel_back_left_vortex_vertices, strengths=self.current_vortex_strengths, collapse=True, ) ) # Find the vector of velocities induced at every point by every wake ring # vortex. The effect of every wake ring # vortex on each point will be summed. wake_ring_vortex_velocities = ( ps.aerodynamics.calculate_velocity_induced_by_ring_vortices( points=points, back_right_vortex_vertices=self.wake_ring_vortex_back_right_vertices, front_right_vortex_vertices=self.wake_ring_vortex_front_right_vertices, front_left_vortex_vertices=self.wake_ring_vortex_front_left_vertices, back_left_vortex_vertices=self.wake_ring_vortex_back_left_vertices, strengths=self.wake_ring_vortex_strengths, collapse=True, ) ) # Find the total influence of the vortices, which is the sum of the influence # due to the bound ring vortices and # the wake ring vortices. total_vortex_velocities = ring_vortex_velocities + wake_ring_vortex_velocities # Calculate and return the solution velocities, which is the sum of the # velocities induced by the vortices and # freestream at every point. solution_velocities = ( total_vortex_velocities + self.current_freestream_velocity_geometry_axes ) return solution_velocities def calculate_near_field_forces_and_moments(self): &quot;&quot;&quot;This method finds the the forces and moments calculated from the near field. Citation: This method uses logic described on pages 9-11 of &quot;Modeling of aerodynamic forces in flapping flight with the Unsteady Vortex Lattice Method&quot; by Thomas Lambert. Note: The forces and moments calculated are in geometry axes. The moment is about the airplane's reference point, which should be at the center of gravity. The units are Newtons and Newton-meters. :return: None &quot;&quot;&quot; # Initialize a variable to hold the global panel position as the panel's are # iterate through. global_panel_position = 0 # Initialize three lists of variables, which will hold the effective strength # of the line vortices comprising # each panel's ring vortex. effective_right_vortex_line_strengths = np.zeros( self.current_airplane.num_panels ) effective_front_vortex_line_strengths = np.zeros( self.current_airplane.num_panels ) effective_left_vortex_line_strengths = np.zeros( self.current_airplane.num_panels ) # Iterate through the current_airplane's wings. for wing in self.current_airplane.wings: # Convert this wing's 2D ndarray of panels into a 1D ndarray. panels = np.ravel(wing.panels) # Iterate through this wing's 1D ndarray panels. for panel in panels: # Check if this panel is on its wing's right edge. if panel.is_right_edge: # Change the effective right vortex line strength from zero to # this panel's ring vortex's strength. effective_right_vortex_line_strengths[ global_panel_position ] = self.current_vortex_strengths[global_panel_position] else: # Get the panel directly to the right of this panel. panel_to_right = wing.panels[ panel.local_chordwise_position, panel.local_spanwise_position + 1, ] # Change the effective right vortex line strength from zero to # the difference between this panel's # ring vortex's strength, and the ring vortex strength of the # panel to the right of it. effective_right_vortex_line_strengths[global_panel_position] = ( self.current_vortex_strengths[global_panel_position] - panel_to_right.ring_vortex.strength ) # Check if this panel is on its wing's leading edge. if panel.is_leading_edge: # Change the effective front vortex line strength from zero to # this panel's ring vortex's strength. effective_front_vortex_line_strengths[ global_panel_position ] = self.current_vortex_strengths[global_panel_position] else: # Get the panel directly in front of this panel. panel_to_front = wing.panels[ panel.local_chordwise_position - 1, panel.local_spanwise_position, ] # Change the effective front vortex line strength from zero to # the difference between this panel's # ring vortex's strength, and the ring vortex strength of the # panel in front of it. effective_front_vortex_line_strengths[global_panel_position] = ( self.current_vortex_strengths[global_panel_position] - panel_to_front.ring_vortex.strength ) # Check if this panel is on its wing's left edge. if panel.is_left_edge: # Change the effective left vortex line strength from zero to # this panel's ring vortex's strength. effective_left_vortex_line_strengths[ global_panel_position ] = self.current_vortex_strengths[global_panel_position] else: # Get the panel directly to the left of this panel. panel_to_left = wing.panels[ panel.local_chordwise_position, panel.local_spanwise_position - 1, ] # Change the effective left vortex line strength from zero to the # difference between this panel's # ring vortex's strength, and the ring vortex strength of the # panel to the left of it. effective_left_vortex_line_strengths[global_panel_position] = ( self.current_vortex_strengths[global_panel_position] - panel_to_left.ring_vortex.strength ) # Increment the global panel position. global_panel_position += 1 # Calculate the solution velocities at the centers of the panel's front leg, # left leg, and right leg. velocities_at_ring_vortex_front_leg_centers = ( self.calculate_solution_velocity(points=self.panel_front_vortex_centers) + self.calculate_current_flapping_velocities_at_front_leg_centers() ) velocities_at_ring_vortex_left_leg_centers = ( self.calculate_solution_velocity(points=self.panel_left_vortex_centers) + self.calculate_current_flapping_velocities_at_left_leg_centers() ) velocities_at_ring_vortex_right_leg_centers = ( self.calculate_solution_velocity(points=self.panel_right_vortex_centers) + self.calculate_current_flapping_velocities_at_right_leg_centers() ) # Using the effective line vortex strengths, and the Kutta-Joukowski theorem # to find the near field force in # geometry axes on the front leg, left leg, and right leg. Also calculate the # unsteady component of the # force on each panel, which is derived from the unsteady Bernoulli equation. near_field_forces_on_ring_vortex_right_legs_geometry_axes = ( self.current_operating_point.density * np.expand_dims(effective_right_vortex_line_strengths, axis=1) * nb_explicit_cross( velocities_at_ring_vortex_right_leg_centers, self.panel_right_vortex_vectors, ) ) near_field_forces_on_ring_vortex_front_legs_geometry_axes = ( self.current_operating_point.density * np.expand_dims(effective_front_vortex_line_strengths, axis=1) * nb_explicit_cross( velocities_at_ring_vortex_front_leg_centers, self.panel_front_vortex_vectors, ) ) near_field_forces_on_ring_vortex_left_legs_geometry_axes = ( self.current_operating_point.density * np.expand_dims(effective_left_vortex_line_strengths, axis=1) * nb_explicit_cross( velocities_at_ring_vortex_left_leg_centers, self.panel_left_vortex_vectors, ) ) unsteady_near_field_forces_geometry_axes = ( self.current_operating_point.density * np.expand_dims( (self.current_vortex_strengths - self.last_panel_vortex_strengths), axis=1, ) * np.expand_dims(self.panel_areas, axis=1) * self.panel_normal_directions ) # Sum the forces on the legs, and the unsteady force, to calculate the total # near field force, in geometry # axes, on each panel. near_field_forces_geometry_axes = ( near_field_forces_on_ring_vortex_front_legs_geometry_axes + near_field_forces_on_ring_vortex_left_legs_geometry_axes + near_field_forces_on_ring_vortex_right_legs_geometry_axes + unsteady_near_field_forces_geometry_axes ) # Find the near field moment in geometry axes on the front leg, left leg, # and right leg. Also find the # moment on each panel due to the unsteady force. near_field_moments_on_ring_vortex_front_legs_geometry_axes = nb_explicit_cross( self.panel_front_vortex_centers - self.current_airplane.xyz_ref, near_field_forces_on_ring_vortex_front_legs_geometry_axes, ) near_field_moments_on_ring_vortex_left_legs_geometry_axes = nb_explicit_cross( self.panel_left_vortex_centers - self.current_airplane.xyz_ref, near_field_forces_on_ring_vortex_left_legs_geometry_axes, ) near_field_moments_on_ring_vortex_right_legs_geometry_axes = nb_explicit_cross( self.panel_right_vortex_centers - self.current_airplane.xyz_ref, near_field_forces_on_ring_vortex_right_legs_geometry_axes, ) unsteady_near_field_moments_geometry_axes = nb_explicit_cross( self.panel_collocation_points - self.current_airplane.xyz_ref, unsteady_near_field_forces_geometry_axes, ) # Sum the moments on the legs, and the unsteady moment, to calculate the # total near field moment, in # geometry axes, on each panel. near_field_moments_geometry_axes = ( near_field_moments_on_ring_vortex_front_legs_geometry_axes + near_field_moments_on_ring_vortex_left_legs_geometry_axes + near_field_moments_on_ring_vortex_right_legs_geometry_axes + unsteady_near_field_moments_geometry_axes ) # Initialize a variable to hold the global panel position. global_panel_position = 0 # Iterate through this solver's panels. for panel in self.panels: # Update the force and moment on this panel. panel.near_field_force_geometry_axes = near_field_forces_geometry_axes[ global_panel_position, : ] panel.near_field_moment_geometry_axes = near_field_moments_geometry_axes[ global_panel_position, : ] # Update the pressure on this panel. panel.update_pressure() # Increment the global panel position. global_panel_position += 1 # Sum up the near field forces and moments on every panel to find the # total force and moment on the geometry. total_near_field_force_geometry_axes = np.sum( near_field_forces_geometry_axes, axis=0 ) total_near_field_moment_geometry_axes = np.sum( near_field_moments_geometry_axes, axis=0 ) # Find the total near field force in wind axes from the rotation matrix and # the total near field force in # geometry axes. self.current_airplane.total_near_field_force_wind_axes = ( np.transpose( self.current_operating_point.calculate_rotation_matrix_wind_axes_to_geometry_axes() ) @ total_near_field_force_geometry_axes ) # Find the total near field moment in wind axes from the rotation matrix and # the total near field moment in # geometry axes. self.current_airplane.total_near_field_moment_wind_axes = ( np.transpose( self.current_operating_point.calculate_rotation_matrix_wind_axes_to_geometry_axes() ) @ total_near_field_moment_geometry_axes ) # Calculate the current_airplane's induced drag coefficient induced_drag_coefficient = ( -self.current_airplane.total_near_field_force_wind_axes[0] / self.current_operating_point.calculate_dynamic_pressure() / self.current_airplane.s_ref ) # Calculate the current_airplane's side force coefficient. side_force_coefficient = ( self.current_airplane.total_near_field_force_wind_axes[1] / self.current_operating_point.calculate_dynamic_pressure() / self.current_airplane.s_ref ) # Calculate the current_airplane's lift coefficient. lift_coefficient = ( -self.current_airplane.total_near_field_force_wind_axes[2] / self.current_operating_point.calculate_dynamic_pressure() / self.current_airplane.s_ref ) # Calculate the current_airplane's rolling moment coefficient. rolling_moment_coefficient = ( self.current_airplane.total_near_field_moment_wind_axes[0] / self.current_operating_point.calculate_dynamic_pressure() / self.current_airplane.s_ref / self.current_airplane.b_ref ) # Calculate the current_airplane's pitching moment coefficient. pitching_moment_coefficient = ( self.current_airplane.total_near_field_moment_wind_axes[1] / self.current_operating_point.calculate_dynamic_pressure() / self.current_airplane.s_ref / self.current_airplane.c_ref ) # Calculate the current_airplane's yawing moment coefficient. yawing_moment_coefficient = ( self.current_airplane.total_near_field_moment_wind_axes[2] / self.current_operating_point.calculate_dynamic_pressure() / self.current_airplane.s_ref / self.current_airplane.b_ref ) self.current_airplane.total_near_field_force_coefficients_wind_axes = np.array( [induced_drag_coefficient, side_force_coefficient, lift_coefficient] ) self.current_airplane.total_near_field_moment_coefficients_wind_axes = np.array( [ rolling_moment_coefficient, pitching_moment_coefficient, yawing_moment_coefficient, ] ) def calculate_streamlines(self, num_steps=10, delta_time=0.1): &quot;&quot;&quot;Calculates the location of the streamlines coming off the back of the wings.&quot;&quot;&quot; # Initialize a ndarray to hold this problem's matrix of streamline points. self.streamline_points = np.expand_dims(self.seed_points, axis=0) # Iterate through the streamline steps. for step in range(num_steps): # Get the last row of streamline points. last_row_streamline_points = self.streamline_points[-1, :, :] # Add the freestream velocity to the induced velocity to get the total # velocity at each of the last row of # streamline points. total_velocities = self.calculate_solution_velocity( points=last_row_streamline_points ) # Interpolate the positions on a new row of streamline points. new_row_streamline_points = ( last_row_streamline_points + total_velocities * delta_time ) # Stack the new row of streamline points to the bottom of the matrix of # streamline points. self.streamline_points = np.vstack( ( self.streamline_points, np.expand_dims(new_row_streamline_points, axis=0), ) ) def populate_next_airplanes_wake(self, prescribed_wake=True): &quot;&quot;&quot;This method updates the next time step's airplane's wake. :param prescribed_wake: Bool, optional This parameter determines if the solver uses a prescribed wake model. If false it will use a free-wake, which may be more accurate but will make the solver significantly slower. The default is True. :return: None &quot;&quot;&quot; # Populate the locations of the next airplane's wake's vortex vertices: self.populate_next_airplanes_wake_vortex_vertices( prescribed_wake=prescribed_wake ) # Populate the locations of the next airplane's wake vortices. self.populate_next_airplanes_wake_vortices() def populate_next_airplanes_wake_vortex_vertices(self, prescribed_wake=True): &quot;&quot;&quot;This method populates the locations of the next airplane's wake vortex vertices. :param prescribed_wake: Bool, optional This parameter determines if the solver uses a prescribed wake model. If false it will use a free-wake, which may be more accurate but will make the solver significantly slower. The default is True. :return: None &quot;&quot;&quot; # Check if this is not the last step. if self.current_step &lt; self.num_steps - 1: # Get the next airplane object and the current airplane's number of wings. next_airplane = self.steady_problems[self.current_step + 1].airplane num_wings = len(self.current_airplane.wings) # Iterate through the wing positions. for wing_num in range(num_wings): # Get the wing objects at this position from the current and the next # airplane. this_wing = self.current_airplane.wings[wing_num] next_wing = next_airplane.wings[wing_num] # Check if this is the first step. if self.current_step == 0: # Get the current wing's number of chordwise and spanwise panels. num_spanwise_panels = this_wing.num_spanwise_panels num_chordwise_panels = this_wing.num_chordwise_panels # Set the chordwise position to be at the trailing edge. chordwise_position = num_chordwise_panels - 1 # Initialize a matrix to hold the vertices of the new row of wake # ring vortices. first_row_of_wake_ring_vortex_vertices = np.zeros( (1, num_spanwise_panels + 1, 3) ) # Iterate through the spanwise panel positions. for spanwise_position in range(num_spanwise_panels): # Get the next wing's panel object at this location. next_panel = next_wing.panels[ chordwise_position, spanwise_position ] # The position of the next front left wake ring vortex vertex # is the next panel's ring vortex's # back left vertex. next_front_left_vertex = next_panel.ring_vortex.back_left_vertex # Add this to the new row of wake ring vortex vertices. first_row_of_wake_ring_vortex_vertices[ 0, spanwise_position ] = next_front_left_vertex # Check if this panel is on the right edge of the wing. if spanwise_position == (num_spanwise_panels - 1): # The position of the next front right wake ring vortex # vertex is the next panel's ring # vortex's back right vertex. next_front_right_vertex = ( next_panel.ring_vortex.back_right_vertex ) # Add this to the new row of wake ring vortex vertices. first_row_of_wake_ring_vortex_vertices[ 0, spanwise_position + 1 ] = next_front_right_vertex # Set the next wing's matrix of wake ring vortex vertices to a # copy of the row of new wake ring # vortex vertices. This is correct because this is the first time # step. next_wing.wake_ring_vortex_vertices = np.copy( first_row_of_wake_ring_vortex_vertices ) # Initialize variables to hold the number of spanwise vertices. num_spanwise_vertices = num_spanwise_panels + 1 # Initialize a new matrix to hold the second row of wake ring # vortex vertices. second_row_of_wake_ring_vortex_vertices = np.zeros( (1, num_spanwise_panels + 1, 3) ) # Iterate through the spanwise vertex positions. for spanwise_vertex_position in range(num_spanwise_vertices): # Get the corresponding vertex from the first row. wake_ring_vortex_vertex = next_wing.wake_ring_vortex_vertices[ 0, spanwise_vertex_position ] if prescribed_wake: # If the wake is prescribed, set the velocity at this # vertex to the freestream velocity. velocity_at_first_row_wake_ring_vortex_vertex = ( self.current_freestream_velocity_geometry_axes ) else: # If the wake is not prescribed, set the velocity at this # vertex to the solution velocity at # this point. velocity_at_first_row_wake_ring_vortex_vertex = ( self.calculate_solution_velocity( np.expand_dims(wake_ring_vortex_vertex, axis=0) ) ) # Update the second row with the interpolated position of the # first vertex. second_row_of_wake_ring_vortex_vertices[ 0, spanwise_vertex_position ] = ( wake_ring_vortex_vertex + velocity_at_first_row_wake_ring_vortex_vertex * self.delta_time ) # Update the wing's wake ring vortex vertex matrix by vertically # stacking the second row below it. next_wing.wake_ring_vortex_vertices = np.vstack( ( next_wing.wake_ring_vortex_vertices, second_row_of_wake_ring_vortex_vertices, ) ) # If this isn't the first step, then do this. else: # Set the next wing's wake ring vortex vertex matrix to a copy of # this wing's wake ring vortex # vertex matrix. next_wing.wake_ring_vortex_vertices = np.copy( this_wing.wake_ring_vortex_vertices ) # Get the number of chordwise and spanwise vertices. num_chordwise_vertices = next_wing.wake_ring_vortex_vertices.shape[ 0 ] num_spanwise_vertices = next_wing.wake_ring_vortex_vertices.shape[1] # Iterate through the chordwise and spanwise vertex positions. for chordwise_vertex_position in range(num_chordwise_vertices): for spanwise_vertex_position in range(num_spanwise_vertices): # Get the wake ring vortex vertex at this position. wake_ring_vortex_vertex = ( next_wing.wake_ring_vortex_vertices[ chordwise_vertex_position, spanwise_vertex_position ] ) if prescribed_wake: # If the wake is prescribed, set the velocity at this # vertex to the freestream velocity. velocity_at_first_row_wake_vortex_vertex = ( self.current_freestream_velocity_geometry_axes ) else: # If the wake is not prescribed, set the velocity at # this vertex to the solution # velocity at this point. velocity_at_first_row_wake_vortex_vertex = np.squeeze( self.calculate_solution_velocity( np.expand_dims(wake_ring_vortex_vertex, axis=0) ) ) # Update the vertex at this point with its interpolated # position. next_wing.wake_ring_vortex_vertices[ chordwise_vertex_position, spanwise_vertex_position ] += ( velocity_at_first_row_wake_vortex_vertex * self.delta_time ) # Set the chordwise position to the trailing edge. chordwise_position = this_wing.num_chordwise_panels - 1 # Initialize a new matrix to hold the new first row of wake ring # vortex vertices. first_row_of_wake_ring_vortex_vertices = np.empty( (1, this_wing.num_spanwise_panels + 1, 3) ) # Iterate spanwise through the trailing edge panels. for spanwise_position in range(this_wing.num_spanwise_panels): # Get the panel object at this location on the next # airplane's wing object. next_panel = next_wing.panels[ chordwise_position, spanwise_position ] # Add the panel object's back left ring vortex vertex to the # matrix of new wake ring vortex # vertices. first_row_of_wake_ring_vortex_vertices[ 0, spanwise_position ] = next_panel.ring_vortex.back_left_vertex if spanwise_position == (this_wing.num_spanwise_panels - 1): # If the panel object is at the right edge of the wing, # add its back right ring vortex # vertex to the matrix of new wake ring vortex vertices. first_row_of_wake_ring_vortex_vertices[ 0, spanwise_position + 1 ] = next_panel.ring_vortex.back_right_vertex # Stack the new first row of wake ring vortex vertices above the # wing's matrix of wake ring vortex # vertices. next_wing.wake_ring_vortex_vertices = np.vstack( ( first_row_of_wake_ring_vortex_vertices, next_wing.wake_ring_vortex_vertices, ) ) def populate_next_airplanes_wake_vortices(self): &quot;&quot;&quot;This method populates the locations of the next airplane's wake vortices.&quot;&quot;&quot; # Check if the current step is not the last step. if self.current_step &lt; self.num_steps - 1: # Get the next airplane object. next_airplane = self.steady_problems[self.current_step + 1].airplane # Iterate through the copy of the current airplane's wing positions. # for wing_num in range(len(current_airplane_copy.wings)): for wing_num in range(len(self.current_airplane.wings)): this_wing = self.current_airplane.wings[wing_num] next_wing = next_airplane.wings[wing_num] # Get the next wing's matrix of wake ring vortex vertices. next_wing_wake_ring_vortex_vertices = ( next_wing.wake_ring_vortex_vertices ) # Get the wake ring vortices from the this wing copy object. this_wing_wake_ring_vortices_copy = pickle.loads( pickle.dumps( self.current_airplane.wings[wing_num].wake_ring_vortices ) ) # Find the number of chordwise and spanwise vertices in the next # wing's matrix of wake ring vortex # vertices. num_chordwise_vertices = next_wing_wake_ring_vortex_vertices.shape[0] num_spanwise_vertices = next_wing_wake_ring_vortex_vertices.shape[1] # Initialize a new matrix to hold the new row of wake ring vortices. new_row_of_wake_ring_vortices = np.empty( (1, num_spanwise_vertices - 1), dtype=object ) # Stack the new matrix on top of the copy of this wing's matrix and # assign it to the next wing. next_wing.wake_ring_vortices = np.vstack( (new_row_of_wake_ring_vortices, this_wing_wake_ring_vortices_copy) ) # Iterate through the vertex positions. for chordwise_vertex_position in range(num_chordwise_vertices): for spanwise_vertex_position in range(num_spanwise_vertices): # Set booleans to determine if this vertex is on the right # and/or trailing edge of the wake. has_right_vertex = ( spanwise_vertex_position + 1 ) &lt; num_spanwise_vertices has_back_vertex = ( chordwise_vertex_position + 1 ) &lt; num_chordwise_vertices if has_right_vertex and has_back_vertex: # If this position is not on the right or trailing edge # of the wake, get the four vertices # that will be associated with the corresponding ring # vortex at this position. front_left_vertex = next_wing_wake_ring_vortex_vertices[ chordwise_vertex_position, spanwise_vertex_position ] front_right_vertex = next_wing_wake_ring_vortex_vertices[ chordwise_vertex_position, spanwise_vertex_position + 1 ] back_left_vertex = next_wing_wake_ring_vortex_vertices[ chordwise_vertex_position + 1, spanwise_vertex_position ] back_right_vertex = next_wing_wake_ring_vortex_vertices[ chordwise_vertex_position + 1, spanwise_vertex_position + 1, ] if chordwise_vertex_position &gt; 0: # If this is isn't the front of the wake, update the # position of the ring vortex at this # location. next_wing.wake_ring_vortices[ chordwise_vertex_position, spanwise_vertex_position ].update_position( front_left_vertex=front_left_vertex, front_right_vertex=front_right_vertex, back_left_vertex=back_left_vertex, back_right_vertex=back_right_vertex, ) if chordwise_vertex_position == 0: # If this is the front of the wake, get the vortex # strength from the wing panel's ring # vortex direction in front of it. this_strength_copy = this_wing.panels[ this_wing.num_chordwise_panels - 1, spanwise_vertex_position, ].ring_vortex.strength # Then, make a new ring vortex at this location, # with the panel's ring vortex's # strength, and add it to the matrix of ring vortices. next_wing.wake_ring_vortices[ chordwise_vertex_position, spanwise_vertex_position ] = ps.aerodynamics.RingVortex( front_left_vertex=front_left_vertex, front_right_vertex=front_right_vertex, back_left_vertex=back_left_vertex, back_right_vertex=back_right_vertex, strength=this_strength_copy, ) def calculate_current_flapping_velocities_at_collocation_points(self): &quot;&quot;&quot;This method gets the velocity due to flapping at all of the current airplane's collocation points.&quot;&quot;&quot; # Check if the current step is the first step. if self.current_step &lt; 1: # Set the flapping velocities to be zero for all points. Then, return the # flapping velocities. flapping_velocities = np.zeros((self.current_airplane.num_panels, 3)) return flapping_velocities # Get the current airplane's collocation points, and the last airplane's # collocation points. these_collocations = self.panel_collocation_points last_collocations = self.last_panel_collocation_points # Calculate and return the flapping velocities. flapping_velocities = (these_collocations - last_collocations) / self.delta_time return flapping_velocities def calculate_current_flapping_velocities_at_right_leg_centers(self): &quot;&quot;&quot;This method gets the velocity due to flapping at the centers of the current airplane's bound ring vortices' right legs.&quot;&quot;&quot; # Check if the current step is the first step. if self.current_step &lt; 1: # Set the flapping velocities to be zero for all points. Then, return the # flapping velocities. flapping_velocities = np.zeros((self.current_airplane.num_panels, 3)) return flapping_velocities # Get the current airplane's bound vortices' right legs' centers, and the # last airplane's bound vortices' right # legs' centers. these_right_leg_centers = self.panel_right_vortex_centers last_right_leg_centers = self.last_panel_right_vortex_centers # Calculate and return the flapping velocities. flapping_velocities = ( these_right_leg_centers - last_right_leg_centers ) / self.delta_time return flapping_velocities def calculate_current_flapping_velocities_at_front_leg_centers(self): &quot;&quot;&quot;This method gets the velocity due to flapping at the centers of the current airplane's bound ring vortices' front legs.&quot;&quot;&quot; # Check if the current step is the first step. if self.current_step &lt; 1: # Set the flapping velocities to be zero for all points. Then, return the # flapping velocities. flapping_velocities = np.zeros((self.current_airplane.num_panels, 3)) return flapping_velocities # Get the current airplane's bound vortices' front legs' centers, and the # last airplane's bound vortices' front # legs' centers. these_front_leg_centers = self.panel_front_vortex_centers last_front_leg_centers = self.last_panel_front_vortex_centers # Calculate and return the flapping velocities. flapping_velocities = ( these_front_leg_centers - last_front_leg_centers ) / self.delta_time return flapping_velocities def calculate_current_flapping_velocities_at_left_leg_centers(self): &quot;&quot;&quot;This method gets the velocity due to flapping at the centers of the current airplane's bound ring vortices' left legs.&quot;&quot;&quot; # Check if the current step is the first step. if self.current_step &lt; 1: # Set the flapping velocities to be zero for all points. Then, return the # flapping velocities. flapping_velocities = np.zeros((self.current_airplane.num_panels, 3)) return flapping_velocities # Get the current airplane's bound vortices' left legs' centers, and the last # airplane's bound vortices' left # legs' centers. these_left_leg_centers = self.panel_left_vortex_centers last_left_leg_centers = self.last_panel_left_vortex_centers # Calculate and return the flapping velocities. flapping_velocities = ( these_left_leg_centers - last_left_leg_centers ) / self.delta_time return flapping_velocities </code></pre> <h3>Goals 0-4</h3> <p>I think that my tool satisfies design goals zero through four. It can analyze the forces and moments on user defined geometry that's flapping with user defined motion. Setting and running up a simulation can be done with a script such as:</p> <pre><code>import pterasoftware as ps example_airplane = ps.geometry.Airplane( wings=[ ps.geometry.Wing( symmetric=True, wing_cross_sections=[ ps.geometry.WingCrossSection( airfoil=ps.geometry.Airfoil(name=&quot;naca2412&quot;,), ), ps.geometry.WingCrossSection( y_le=5.0, airfoil=ps.geometry.Airfoil(name=&quot;naca2412&quot;,), ), ], ), ], ) example_operating_point = ps.operating_point.OperatingPoint() example_problem = ps.problems.SteadyProblem( airplane=example_airplane, operating_point=example_operating_point, ) example_solver = ps.steady_horseshoe_vortex_lattice_method.SteadyHorseshoeVortexLatticeMethodSolver( steady_problem=example_problem ) example_solver.run() ps.output.draw( solver=example_solver, show_delta_pressures=True, show_streamlines=True, ) </code></pre> <p>The source code is heavily commented, uses the Black python formatter, gets an A code quality grade via CodeFactor, has 94% testing coverage, and implements some basic CI techniques. Additionally, I just finished a validation study that compared the solver's output to experimental data:</p> <p><a href="https://i.stack.imgur.com/PgvEP.png" rel="noreferrer"><img src="https://i.stack.imgur.com/PgvEP.png" alt="validation" /></a></p> <p>Those curves might not be identical, but they are pretty close for a mid-fidelity unsteady fluids solver! A full Navier-Stokes simulation using software like Ansys would be more accurate, but unsteady high-fidelity solvers are the stuff of HPC clusters running one simulation for hours or even days.</p> <p>While I feel okay with goals zero through four, I've learned that my intuition about these things is most often wrong. So, please feel free to rip apart my project on any of these topics!</p> <h3>Goal 5</h3> <p>This is my first ever open-source project, so maybe my expectations are unrealistic. However, I was hoping for more community engagement and use. I've posted about my repository on Reddit, FaceBook, and LinkedIn, and only two people have opened issues on GitHub. Does that sound reasonable given how niche the idea is? Is there anything I can do to increase engagement?</p> <h3>Goal 6</h3> <p>The latest version can run a typical simulation in around 156 seconds. This means that in 24 hours, I could do about 553 runs. The latest, non-packaged version (the vectorization branch on GitHub) leans heavily on NumPy and Numba to increase speed. Until recently, a single function in aerodynamics.py, <code>calculate_velocity_induced_by_line_vortices</code> was responsible for around 60% of my run time. Thanks to StackOverflow user Jérôme Richard, who answered my optimization question <a href="https://stackoverflow.com/questions/66750661/can-i-speed-up-this-aerodynamics-calculation-with-numba-vectorization-or-multi">here</a>, this is no longer the case.</p> <p>However, my code is still two times too slow. How can I optimize the system as a whole? For example, to increase ease-of-use, I went with a object-oriented approach and store many large instances of custom objects. My class hierarchy can be found in geometry, aerodynamics, and movement.py (not included due to character limit). However, now my code is heavily memory bound, which isn't helping performance</p> <p>Should I simply focus on parallelizing my calls to the computationally intensive functions? How close to the theoretical speed limit of this simulation using Python and a workstation laptop?</p> <h2>Future Work</h2> <p>Other features I have planned are:</p> <ul> <li>Developing a workflow for using Ptera Software to perform system identification for a flapping wing control system</li> <li>Modifying the algorithm to analyze hovering flapping wings (right now, the assumptions of the model aren't valid for situations where the vehicle isn't moving forward at some velocity)</li> <li>Creating either a CLI or GUI</li> <li>Implementing aeroelastic (flexible wing) effects</li> <li>Tightening the speed requirement even further (i.e., could the solver run in under 10 seconds?)</li> </ul> <p>How important do you think each of these features would be to users?</p> <h2>Closing</h2> <p>You can't talk about ornithopters without mentioning Dune...so I hope this project pleases you, and the house Atreides.</p>
[]
[ { "body": "<p>I concur with your conclusions with your goals, especially 1-3.</p>\n<p>I think it's fantastic.</p>\n<p>For goal 5 it's hard to say. I've the feeling it <em>is</em> quite a niche project\nin a way. For example I haven't got a clue of how many people are\ngenerally working in that area, let alone looking around for a new\nproject like this. It might make sense to push more into academia\nthough, perhaps there's some way to get a paper out of this, or a talk\nwith a more inclined audience?</p>\n<hr />\n<p>I can't say too much on the actual performance, though I'd really\nsuggest using a good profiler to figure out where the bottlenecks are.\nIn any case, maybe someone else will give you some more helpful\nsuggestions on this topic.</p>\n<hr />\n<p>Now for the code itself, I've got no complaints. It's clean, very well\ndocumented, naming is fantastic, you've made it <em>extremely</em> easy to get\nit all set up (assuming you know anything about Python environments - I\nsuppose you could even have section that spells out the invocations for\npeople who do not (e.g. I had to <code>pip install wheel</code> manually when\ntrying to install the dependencies (I'm not 100% sure that's a common\nproblem, just wanted to let you know) and I also knew how to set up a\nvirtual environment to not clutter things)).</p>\n<p>Long term you might benefit from adding type information via the\n<code>typing</code> module, if at all possible with <code>numpy</code> and the other\nlibraries.</p>\n<p>The declarative approach to defining the wings is excellent, even if I\ndon't understand the topic at all, the examples and test cases are such\na good show case for everything.</p>\n<hr />\n<p>A couple of tiny things I've noticed now:</p>\n<pre><code> if spanwise_position == 0:\n panel.is_left_edge = True\n else:\n panel.is_left_edge = False\n</code></pre>\n<p>That can always be simplified to\n<code>panel.is_left_edge = spanwise_position == 0</code>. Same goes for other\ninstances of this pattern of course.</p>\n<p>Also consider providing a bit more information in the exceptions, say,\nthe value that was wrong, if any, or the expected value that didn't\nmatch. Helps enormously during debugging!</p>\n<p><code>animate</code> needs at least a filename parameter for what's now\n<code>animation.gif</code>, potentially you might want users to specify a\n<code>file</code>-like object too, but that's just icing on the top.</p>\n<p>In general a lot of the methods are pretty long. If at all possible I'd\nsuggest finding some opportunities to compress duplicate code segments\nand to move inner parts of loops out into their own helper method to\nmake things a little bit easier to understand. That would also give you\nanother opportunity to give those helper methods a good name.</p>\n<p>Maybe move some repeated strings into constants (well, global variables,\nbut treating them as constants), possibly also make them configurable in\nthe long term.</p>\n<p>There's also a number of single-use definitions of variables, a lot\nimmediately before a <code>return</code>. I'd inline those since I don't see that\nthe naming gives the reader any hints, the value should already be\ndescribed enough as the return value of the method itself.</p>\n<p>There's some methods that get invoked over and over. If it's avoidable,\nthat is, if the return value doesn't change, simply precompute it and\nput it into a reusable variable instead\n(e.g. <code>calculate_near_field_forces_and_moments</code> has a lot of that with\nthe <code>calculate_dynamic_pressure</code> calls.</p>\n<p>You sometimes have this <code>if verbose: print(...)</code> pattern - that can be\nsimplified by using a &quot;proper&quot; logger and providing a configurable log\nlevel, like <code>logger.trace(...)</code> would only show up if the log level was\nraised high enough to see all the details.</p>\n<p>I'm noticing some conversions going on for convenience\n(e.g. <code>np.ravel</code>). For performance it might be necessary to compromise\na bit and solve this differently without expensive allocations and\ncopying. This is not substantiated by a profiler so far, but it seems\nadvisable regardless.</p>\n<p>Also memory-related, in <code>geometry.py</code>, the <code>x/y/z_ref</code> variables are\nredundant if the <code>xyz_ref</code> vector already exists? I'm not 100% sure\nabout whether any difference is intentional or not (c.f. <code>float(...)</code>),\nbut this sounds like an excellent case for using accessors or regular\nmethods to get the individual components of that vector.</p>\n<p>The pattern <code>if x is None: x = []</code> is easier to write as <code>x = x or []</code>,\nas long as there's no difference expected wrt. other non-falsy values\n(e.g. <code>bool(&quot;&quot;)</code>). IMO that's usually not the case and the functional\nway to write it is shorter.</p>\n<p>In <code>geometry.py</code>, line 134 the <code>enumerate</code> is unnecessary. I'd also say\nthis would look better as a functional definition via <code>sum</code> and <code>map</code>,\nbut that's probably not super important.</p>\n<p>In <code>populate_coordinates</code>, there's a <code>return</code> in the very nested <code>if</code>\nblock. Definitely make that block a separate method, it's very hard to\nsee where things are due to the deep nesting and the quite hidden\n<code>return</code> statement. The <code>return</code> in the later <code>try</code> block is also odd\nand can be removed. I'd also put the parsing of the file into its own\nmethod in order to be able to test it separately from other things.</p>\n<p>Apropos test cases, there's a lot of <code>del</code> calls in those, are they\nactually helping with memory consumption, or are they more for\ndocumentation?</p>\n<p>Oh, I'd lowercase <code>REQUIREMENTS.txt</code>, that's the\n<a href=\"https://pip.pypa.io/en/stable/user_guide/#requirements-files\" rel=\"nofollow noreferrer\">usual naming convention</a>\nfor it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T03:30:51.657", "Id": "512910", "Score": "1", "body": "Thank you for the feedback! I am finally getting around to implementing some of your suggestions. Could you explain the `x=x or []` syntax please? I've never seen that before, and couldn't find anything via Google." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-24T10:02:16.053", "Id": "512929", "Score": "1", "body": "Right, I'm not sure what you'd need to search for, it's basically coming from the observation that `or` short-circuits and returns its arguments depending on whether they are \"truthy\", so `bool(...)` returns `True` for them. That together with the fact that the empty list `[]` is \"falsy\", you basically get the equivalent of `if not x: x = []` in a very compact form. And of course you can similarly observe this with `and` as well." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T00:40:52.263", "Id": "257702", "ParentId": "257560", "Score": "1" } } ]
{ "AcceptedAnswerId": "257702", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T08:51:50.427", "Id": "257560", "Score": "11", "Tags": [ "python", "performance", "numpy", "simulation", "numba" ], "Title": "From Hummingbirds to Ornithopters: Simulating the Aerodynamics of Flapping Wings" }
257560
<p>I have programmed a function to split strings, and it gives the expected output. I am looking forward to write better code and I was told here is a good place to start.</p> <p>Here's my program:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; char **split(char *str) { int str_length = 0; int i = 0; int separator_count = 0; while (str[i] != '\0') { if (str[i] == ' ') { separator_count++; } i++; } char **word_array; word_array = malloc((separator_count + 2) * sizeof(char *)); int word_len = 0; int separator_index = 0; int b = 0; //to iterate over &quot;str&quot; for (int a = 0; a &lt; (separator_count + 2); a++) { word_len = 0; while (str_length &lt; strlen(str) + 1) { str_length++; if (str[b] == ' ' || str[b] == '\0') { separator_index = b; word_array[a] = malloc(word_len * sizeof(char)); int word_depth = 0; for (int c = (separator_index - word_len); c &lt; separator_index; c++) { chrctr = str[c]; word_array[a][word_depth] = str[c]; word_depth++; } word_array[a][word_len] = '\0'; //terminate found and stored word with null charachter word_len = 0; //reset word length counter to 0 b++; //skip to next charachter break; // break to go to next index of word_array } word_len++; b++; } } word_array[separator_count + 2] = NULL; return word_array; } int main() { char s[] = &quot;A complete toolkit for building search into your product.&quot;; //test string char **ss = split(s); for (int i = 0; i &lt; sizeof(ss); i++) { //here is the problem, and doing sizeof(ss)/sizeof(ss[0])=1 !! for (int j = 0; j &lt; strlen (ss[i]); j++) { printf(&quot;%c&quot;, ss[i][j]); } printf (&quot;\n&quot;); } } </code></pre> <p>Please comment with any advice or remarks on how to make this better.</p>
[]
[ { "body": "<p>First, I'll address your issue within the main function. Where you've marked your issue, <code>sizeof(ss)</code> isn't returning the number of elements, it's returning the size of the ss variable which is a pointer. It's the same as <code>sizeof(char *)</code> (which is typically 8 on most platforms). It's a little confusing, but know that <code>char s[]</code> and <code>char *s</code> <a href=\"https://stackoverflow.com/questions/10186765/what-is-the-difference-between-char-array-and-char-pointer-in-c\">aren't the same</a>. What you need is a way to retrieve the number of splits within the returned result. There are a number of ways you can do this, one of which would be to redefine the function signature to include the output and then return an integral type denoting the number of splits:</p>\n<pre><code>int split(const char *input, char **output);\n</code></pre>\n<p>However, there is also a way to do this without even knowing how many splits there are. You actually sort of have it implemented, but you don't use it. Similar to how the end of c-strings are detected, you can nullify the final byte of the array to indicate the end of the list (which I see you've already done at the end of the split function - there <em>is</em> an issue that you have with improperly indexing the final element, but I'll address that after). So, instead of your loop terminating at the condition <code>i == num_splits</code>, you can simply terminate when a null pointer is detected:</p>\n<pre><code>int main() {\n char s[] = &quot;A complete toolkit for building search into your product.&quot;; //test string\n char **ss = split(s);\n for (int i = 0; ss[i]; i++) {\n for (int j = 0; j &lt; strlen (ss[i]); j++) {\n printf(&quot;%c&quot;, ss[i][j]);\n }\n printf (&quot;\\n&quot;);\n }\n}\n</code></pre>\n<p>Making this amendment should fix your issue without having to change anything with the split function.</p>\n<p>On the indexing issue you have (in several locations), you're off by one. Remembering that arrays are 0-indexed, the final element of an array is indexed by it's size minus 1. So, the lines\n<code>word_array[a][word_len] = '\\0';</code>, and\n<code>word_array[separator_count + 2] = NULL;</code>\nare indexing past the allocated memory. The first line is actually fine, you just need to fix it in the allocation: <code>word_array[a] = malloc((word_len + 1) * sizeof(char));</code> The second line should be changed to <code>word_array[separator_count + 1] = NULL;</code>.</p>\n<p>It's also very possible that I've missed some additional errors, but if I find them then I'll edit this answer or hopefully you or another user will notice and address them.</p>\n<p>As far as your split function code, there are some things that would improve it a bit. I won't give you an exhaustive list, especially since some suggestions might be more on the subjective side, but here a some that I think you may find helpful:</p>\n<ol>\n<li>This one I believe is simply something you overlooked, but the <code>chrchr</code> variable is never declared (used in the line <code>chrctr = str[c];</code>). I assume it's meant to be discarded anyways since you just use <code>str[c]</code> directly in the next line.</li>\n<li>Using <code>strlen</code> in your while loop generally isn't good practice since the compiler may spit out code that calls it more than necessary. In fact, you can get rid of it entirely since you can retrieve the string length from your first loop where you count the number of separators (you already have the string length within the <code>i</code> variable).</li>\n<li>You can avoid printing each character at a time and, because you've nullified the final byte at the end of each word, print each word using <code>print(&quot;%s\\n&quot;, ss[i]);</code>.</li>\n<li>There's still more you can do to improve this, but I don't want to overload you with too much information. But I will end with a final note that you should consider a different structure than dynamically allocated arrays within a dynamically allocated array. All this dynamic allocation has to be cleaned up when it's done being used, and managing this memory just adds more complexity and possible complications (not to mention, it's very error prone).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T20:02:54.633", "Id": "257590", "ParentId": "257569", "Score": "1" } }, { "body": "<p><strong>Design: Code should explain cases</strong></p>\n<ol>\n<li>Double space: <code>&quot;abc xyz&quot;</code> --&gt; Is that to be 2 or 3 tokens?</li>\n<li>Leading space: <code>&quot; abc xyz&quot;</code> --&gt; Is that to be 2 or 3 tokens?</li>\n<li>Trailing space: <code>&quot;abc xyz &quot;</code> --&gt; Is that to be 2 or 3 tokens?</li>\n</ol>\n<p><strong>Design : Generalization</strong></p>\n<p><code>split()</code> only considers <code>' '</code>. Maybe all white-spaces, <code>'\\t'</code>, <code>'\\n'</code>, ...?</p>\n<p>Or pass into the function a list of separators: <code>split(char *str, const char *separators)</code></p>\n<p><strong>Design: <code>const</code></strong></p>\n<p>As data referenced by <code>str</code> does not change, consider <code>char **split(const char *str)</code> for greater applicability and self documentation.</p>\n<p><strong>Bug: Insufficient memory</strong></p>\n<pre><code>// word_array[a] = malloc(word_len * sizeof(char));\nword_array[a] = malloc((word_len + 1u) * sizeof(char));\n...\nword_array[a][word_len] = '\\0';\n</code></pre>\n<p><strong>Bug: Writing outside allocation</strong></p>\n<pre><code>word_array = malloc((separator_count + 2) * sizeof(char *)); \n...\nword_array[separator_count + 2] = NULL; //OOPS!\n\n// I suspect OP wanted \nword_array[separator_count + 1] = NULL;\n</code></pre>\n<p><strong>Allocate to the size of the reference object, not the type</strong></p>\n<pre><code>// word_array = malloc((separator_count + 2) * sizeof(char *)); \nword_array = malloc(sizeof *word_array * (separator_count + 2u)); \n\n\n// word_array[a] = malloc(word_len * sizeof(char));\nword_array[a] = malloc(sizeof (word_array[a][0] * word_len);\n</code></pre>\n<p>It is easier to code right, review and maintain.</p>\n<p>Leading with the widest types in the multiplication prevents overflow - though that is not so important in this case.</p>\n<p><strong>Robust code checks allocation success</strong></p>\n<pre><code>ptr = malloc(sizeof *ptr * n);\nif (ptr == NULL &amp;&amp; n &gt; 0) {\n HandleOutOfMemory(); // Some user code\n}\n</code></pre>\n<p><strong>Clean-up allocations</strong></p>\n<p><code>main()</code> called <code>split(s)</code> which allocates, but failed to call a matching <code>free()</code>. Not much concern with <code>main()</code> as code ends anyways, but good practice.</p>\n<p><strong>Minor: <code>int word_len</code> insufficient for large strings</strong></p>\n<pre><code>// int word_len \nsize_t word_len \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T20:52:33.763", "Id": "257593", "ParentId": "257569", "Score": "8" } }, { "body": "<p>The description, the name of <code>split()</code> and the actual code are a bit contradicting. What you are doing is an array of pointers to chars (the words).</p>\n<p>Since the amount of words is not known, one either has to count them in a first loop (as you did), or then start with a certain size and <code>reallocate()</code> when the words keep coming. I just use a fixed size.</p>\n<p>I found <code>strtok()</code> which opens another possibility: just replace any delimiter by a <code>\\0</code> and call it a string / return pointer to start. That means the string itself gets modified. No <code>malloc()</code> needed for the strings, only to save the pointers (whose number I have limited to 1000).</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\n#define MAX 1000\nchar *words[MAX];\nchar *delim = &quot; &quot;;\n\nvoid split(char *str) {\n\n int i;\n char *token = strtok(str, delim);\n printf(&quot;%s %p\\n&quot;, token, token);\n\n while ((token = strtok(NULL, delim)) != NULL &amp;&amp; i &lt; MAX) {\n printf(&quot;%s %p\\n&quot;, token, token);\n words[i++] = token;\n }\n}\n\nint main(void) {\n char s[] = &quot;A complete toolkit for building search into your product.&quot;;\n split(s);\n\n printf(&quot;Fifth word is '%s' \\n&quot;, words[5]);\n return 0;\n}\n</code></pre>\n<p>Output:</p>\n<pre><code>A 0x7ffd0ce68220\ncomplete 0x7ffd0ce68222\ntoolkit 0x7ffd0ce6822b\nfor 0x7ffd0ce68233\nbuilding 0x7ffd0ce68237\nsearch 0x7ffd0ce68240\ninto 0x7ffd0ce68247\nyour 0x7ffd0ce6824c\nproduct. 0x7ffd0ce68251\nFifth word is 'into'\n</code></pre>\n<p>Your output is not correct (last line missing), and it is unclear what the goal of the program is.</p>\n<p>My output is also incorrect...forgot to save the first token and to take index zero into account: 'into' is the 7th word.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T01:21:02.553", "Id": "508906", "Score": "0", "body": "An alternative to `strtok()` is paired use of `strspn(), strcspn()`. Advantage: `char *str` can now be `const char *str` and code does not mess up the caller's, maybe in the middle of, use of `strok()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T01:25:48.483", "Id": "508907", "Score": "0", "body": "Bug: Try `printf(\"word is '%s' \\n\", words[0]);` after calling `split(s);`. I get \"word is '(null)'\", not the hoped for \"word is 'A'\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T08:24:26.587", "Id": "508931", "Score": "0", "body": "See existing last line in my answer: 5. vs. 7. word. \"forgot to save first token\". (before the loop). \"Mess up caller\": but then you could memcpy() first; more elegant than a separate malloc() for each word. A mere \"Dynamic memory allocation\" only in the title is not enough information." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T13:44:08.673", "Id": "257617", "ParentId": "257569", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T12:17:51.140", "Id": "257569", "Score": "4", "Tags": [ "algorithm", "c", "strings", "functional-programming" ], "Title": "Split function using C and dynamic memory allocation" }
257569
<p>So I am trying to create a small C# application which generates a deck of cards, and ask to the user if they want to shuffle the deck, and then display 1 card at a time to the user. Would this be effective use of classes 4 rules of oop? Thanks</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assignment2OOP { class Program { static void Main(string[] args) { // Call method to start the program DrawCards(); Console.ReadKey(); } // Short program which deals one card from deck at a time and also shuffles the deck private static void DrawCards() { Deck newDeck = new Deck(); Console.WriteLine(&quot;Would you like to shuffle your deck of cards? (type yes)&quot;); string option = Console.ReadLine(); if(option == &quot;yes&quot; || option == &quot;Yes&quot;) { newDeck.Shuffle(); Console.Clear(); } while(true) { Console.WriteLine(&quot;Would you like to draw a card?&quot; + &quot;\n&gt; Type 'yes' for yes\n&gt; Type 'anything else' for no&quot;); string answer = Console.ReadLine(); if (answer == &quot;yes&quot; || answer == &quot;Yes&quot; || answer == &quot;y&quot;) { Console.Clear(); Console.WriteLine($&quot;&gt; {newDeck.Deal()}\n&quot;); } else { Console.WriteLine(&quot;No more cards will be drawn..&quot;); break; } } } } } </code></pre> <pre><code>namespace Assignment2OOP { class Card { // Fields public List&lt;string&gt; Suit { get; private set; } public List&lt;string&gt; Value { get; private set; } // Constructor public Card() { Suit = new List&lt;string&gt; { &quot;Spades&quot;, &quot;Clubs&quot;, &quot;Hearts&quot;, &quot;Diamonds&quot; }; Value = new List&lt;string&gt; { &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;, &quot;10&quot;, &quot;Ace&quot;, &quot;Queen&quot;, &quot;Jack&quot;, &quot;King&quot;}; } // Makes a set of unqiue cards public List&lt;string&gt; GetSetOfCards() { List&lt;string&gt; cardsSet = new List&lt;string&gt;(); foreach (var suit in Suit) foreach (var value in Value) cardsSet.Add(value + &quot; of &quot; + suit); return cardsSet; } } } </code></pre> <pre><code>namespace Assignment2OOP { class Deck { // Fields public List&lt;string&gt; cards { get; private set; } // Constructor public Deck() { cards = new List&lt;string&gt;(); FillDeck(); } // Fill up the deck when a new object is instansiated private void FillDeck() { Card setOfCards = new Card(); foreach(string card in setOfCards.GetSetOfCards()) cards.Add(card); } public void Shuffle() { // Use Guid to shuffle the list //cards = cards.OrderBy(x =&gt; Guid.NewGuid()).ToList(); // Or use more common way to shuffle Random rnd = new Random(); int count = cards.Count; while(count &gt; 1) { count--; int rng = rnd.Next(count); var value = cards[rng]; cards[rng] = cards[count]; cards[count] = value; } } // Keep an index of the top card of the deck private int topCardIndex = 51; public string Deal() { // Mark sure the deck isnt empty if(topCardIndex &gt; 0) { // Get card at top and return it and decrease topCardIndex string topCard = cards[topCardIndex]; topCardIndex--; return topCard; } else { return &quot;No more cards left in the deck!&quot;; } } // Method which shows user all cards in current deck public void DisplayDeck() { foreach(var card in cards) Console.WriteLine(card); } } } <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T14:59:29.790", "Id": "508735", "Score": "0", "body": "At the first glance I would say the abstractions and encapsulation are nailed. On the other hand it does support only one type of card set (French-suited cards). In case of OOP it might make sense to use inheritance and polymorphism to support different type of cards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:06:37.113", "Id": "508739", "Score": "0", "body": "@PeterCsala thanks for the feedback,yeh thats a good idea i will look to implement that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:07:51.227", "Id": "508741", "Score": "0", "body": "I disagree with @PeterCsala that you nailed it. `Card` is not really a card but a list of cards, which suggests it should be in `Deck`. And `DisplayDeck` is a UI feature, so it should not be in `Deck`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:09:38.797", "Id": "508742", "Score": "0", "body": "@RickDavin How would go about making the Cards class so that you can have a list of cards in the Deck class,as i struggled on that part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:11:03.457", "Id": "508745", "Score": "0", "body": "@RickDavin Where would i put the DisplayDeck in a static method in main?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T18:08:12.280", "Id": "508881", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [What should I do when someone answers my question?](https://codereview.stackexchange.com/help/someone-answers) as well as [_what you may and may not do after receiving answers_](http://codereview.meta.stackexchange.com/a/1765)." } ]
[ { "body": "<p>Sorry for quick review. Work is pressing but rather than a conversation in comments, this will have to suffice.</p>\n<p>There are lots of examples of C# and card games here at CR. Maybe you could search for them and review since many of those answers are quite good.</p>\n<p>The better answers use <code>enum</code> for <code>Suit</code> and <code>Rank</code>. A <code>Card</code> class or struct is therefore a simple pairing of a <code>Suit</code> and <code>Rank</code>. Granted later one must assign a value to a card based on rules of a particular game, e.g. is an Ace a value of 1 or 13 in Poker, or is it a 1 or 11 in BlackJack.</p>\n<p>A <code>Deck</code> is a collection of cards. I am not thrilled with names like <code>GetSetofCards</code> or <code>FillDeck</code>. I am partial to <code>CreateStandardDeck</code>.</p>\n<p>For the <code>Shuffle</code> method, the Fisher-Yates shuffle is the most highly recommended. Typically it is wise to include a comment that you are using it just so any reviewer giving it a fast glance will see it.</p>\n<p>One of the messiest non-OOP things I see in your code is mixing UI related things in with the logic. <code>Deal</code> is returning a string. To me, a deal should deal a hand, or else a set of hands to different players. Maybe <code>GetNextCard</code> is a more appropriate name, or perhaps <code>GetTopCard</code>. But that method should return a <code>Card</code>, not a string. The UI is what displays a card, so move that logic back to what controls the console display.</p>\n<p>Likewise <code>DisplayDeck</code> should be moved out of the <code>Deck</code> class and back to your UI class. Except you really don't have a separate UI-related class other than the 2 methods in <code>Program</code>. You may consider having a UI only class and move <code>DrawCards</code> into it, as well as these other UI methods I have touched upon.</p>\n<p>I see a bit of repetition when asking for console input and checking an answer. You may want to streamline this into a single method where you pass in a question and the acceptable answer. If some answers are case sensitive, then you would also want to pass in a flag to ignore case so that &quot;yes&quot;, &quot;YES&quot;, and &quot;Yes&quot; are all the same good answer.</p>\n<p>But again, my best advice is to search on [C#] and Card here on Code Review. There is a wealth of information in some of those answers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T18:47:18.060", "Id": "508774", "Score": "0", "body": "Thanks for the overall help, but some of the stuff you said was actually asked by the task - https://ibb.co/3hsTXVD Here is link the task image. And we also havent been taught to use enums at all,so iam trying to find a way to create the cards without enums,cause surely there must be away." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T20:47:42.187", "Id": "508780", "Score": "0", "body": "@Mj_ Do not take refuge in what being limited by what the task stated. This will limit your progress as a developer. Plus, you fall short of some of the directives about the task, e.g. that the `Card` needs to be a card and not a list of cards." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T18:06:18.847", "Id": "508880", "Score": "0", "body": "I updated the code would you say this is slighty better way?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:26:49.803", "Id": "257576", "ParentId": "257575", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T14:39:41.597", "Id": "257575", "Score": "3", "Tags": [ "object-oriented" ], "Title": "game in oop mini game" }
257575
<p>I have a C code, that takes edges of weighted graph and some point a<br> It returns minimal distances from point a to others and previous point in way, which have minimal length (best way).</p> <p>For example, if best way is a → b → c:</p> <ul> <li>previous point for a is null/-1/-2 ...</li> <li>previous point for b is a</li> <li>previous point for c is b</li> </ul> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdint.h&gt; int edges_start[3000]; int edges_end[3000]; float edges_len[3000]; int g_links_id[1000][100]; float g_links_weight[1000][100]; int cache_id[1000]; float cache_distance[1000]; int cache_prev[1000]; int cache_links_id[1000][100]; float cache_links_weight[1000][100]; int queue_id[1000]; float queue_distance[1000]; int queue_prev[1000]; int queue_links_id[1000][100]; float queue_links_weight[1000][100]; int queue_links_id_len[1000]; // MUSL memset implementation: // https://github.com/esmil/musl/blob/master/src/string/memset.c #include &lt;stdint.h&gt; #include &lt;string.h&gt; void* __attribute__((weak)) memset(void* dest, int c, size_t n) { unsigned char* s = dest; size_t k; if(!n) { return dest; } s[0] = s[n - 1] = (unsigned char)c; if(n &lt;= 2) { return dest; } s[1] = s[n - 2] = (unsigned char)c; s[2] = s[n - 3] = (unsigned char)c; if(n &lt;= 6) { return dest; } s[3] = s[n - 4] = (unsigned char)c; if(n &lt;= 8) { return dest; } k = -(uintptr_t)s &amp; 3; s += k; n -= k; n &amp;= (unsigned long)-4; n /= 4; // Cast to void first to prevent alignment warning uint32_t* ws = (uint32_t*)(void*)s; uint32_t wc = c &amp; 0xFF; wc |= ((wc &lt;&lt; 8) | (wc &lt;&lt; 16) | (wc &lt;&lt; 24)); /* Pure C fallback with no aliasing violations. */ for(; n; n--, ws++) { *ws = wc; } return dest; } #include &lt;string.h&gt; typedef int word; #define wsize sizeof(word) #define wmask (wsize - 1) void* memcpy(void* dst0, const void* src0, size_t length) { char* dst = dst0; const char* src = src0; size_t t; if(length == 0 || dst == src) { /* nothing to do */ goto done; } #define TLOOP(s) if (t) TLOOP1(s) #define TLOOP1(s) do { s; } while (--t) if((uintptr_t)dst &lt; (uintptr_t)src) { t = (uintptr_t)src; /* only need low bits */ if((t | (uintptr_t)dst) &amp; wmask) { if((t ^ (uintptr_t)dst) &amp; wmask || length &lt; wsize) { t = length; } else { t = wsize - (t &amp; wmask); } length -= t; TLOOP1(*dst++ = *src++); } t = length / wsize; // Silence warning for alignment change by casting to void* TLOOP(*(word*)(void*)dst = *(const word*)(const void*)src; src += wsize; dst += wsize); t = length &amp; wmask; TLOOP(*dst++ = *src++); } else { src += length; dst += length; t = (uintptr_t)src; if((t | (uintptr_t)dst) &amp; wmask) { if((t ^ (uintptr_t)dst) &amp; wmask || length &lt;= wsize) { t = length; } else { t &amp;= wmask; } length -= t; TLOOP1(*--dst = *--src); } t = length / wsize; // Silence warning for alignment change by casting to void* TLOOP(src -= wsize; dst -= wsize; *(word*)(void*)dst = *(const word*)(const void*)src); t = length &amp; wmask; TLOOP(*--dst = *--src); } done: return (dst0); } void init_cpp(int L) { for (int i=0; i &lt; L; i++) { queue_links_id_len[i] = 0; cache_id[i] = -2; queue_id[i] = -2; cache_distance[i] = 100000; queue_distance[i] = 100000; cache_prev[i] = -2; queue_prev[i] = -2; for (int j=0; j &lt; 100; j++) { queue_links_id[i][j] = -2; queue_links_weight[i][j] = 100000; cache_links_id[i][j] = -2; cache_links_weight[i][j] = 100000; } } } void init_edges_cpp() { for (int i=0; i &lt; 3000; i++) { edges_start[i] = -2; edges_end[i] = -2; edges_len[i] = -2.0; } for (int i=0; i &lt; 1000; i++) { for (int j=0; j &lt; 100; j++) { g_links_id[i][j] = -2; g_links_weight[i][j] = -2.0; } } } void add_edge_cpp(int index, int start, int end, float len) { edges_start[index] = start; edges_end[index] = end; edges_len[index] = len; } void fill_graph_cpp() { for (int i=0; i &lt; 3000; i++) { int s = edges_start[i]; int e = edges_end[i]; float len = edges_len[i]; if (s == -2) { break; } int links_len = 0; for (int j=0; j &lt; 100; j++) { if (g_links_id[s][j] == -2) { links_len = j; break; } } g_links_id[s][links_len] = e; g_links_weight[s][links_len] = len; for (int j=0; j &lt; 100; j++) { if (g_links_id[e][j] == -2) { links_len = j; break; } } g_links_id[e][links_len] = s; g_links_weight[e][links_len] = len; } } void get_dists_cpp(int a, int L) { int i = L; while (--i &gt;= 0) { for (int j = 0; j &lt; 100; j++) { //console.log() if (g_links_id[i][j] == -2) { break; } cache_links_id[i][j] = g_links_id[i][j]; cache_links_weight[i][j] = g_links_weight[i][j]; } cache_id[i] = i; } queue_id[0] = cache_id[a]; cache_distance[a] = 0; queue_distance[0] = cache_distance[a]; queue_prev[0] = queue_prev[a]; for (int j=0; j &lt; 100; j++) { if (cache_links_id[a][j] == -2) { queue_links_id_len[0] = j; break; } queue_links_id[0][j] = cache_links_id[a][j]; queue_links_weight[0][j] = cache_links_weight[a][j]; } i=0; int queue_len = 1; while (i &lt; queue_len) { int node_id = queue_id[i]; float node_distance = queue_distance[i]; int node_prev = queue_prev[i]; /* int j=0; for (int k=0; k &lt; 100; k++) { if (queue_links_id[i][k] == -2) { j=k; break; } } */ int j = queue_links_id_len[i]; while (--j &gt;= 0) { int link_id = queue_links_id[i][j]; float link_weight = queue_links_weight[i][j]; int c_id = cache_id[link_id]; float c_distance = cache_distance[link_id]; int c_prev = cache_prev[link_id]; float d = node_distance + link_weight; if (d &lt;= c_distance) { cache_prev[link_id] = node_id; cache_distance[link_id] = d; queue_id[queue_len] = cache_id[link_id]; queue_distance[queue_len] = cache_distance[link_id]; for (int k=0; k &lt; 100; k++) { if (cache_links_id[link_id][k] == -2) { queue_links_id_len[queue_len] = k; break; } queue_links_id[queue_len][k] = cache_links_id[link_id][k]; queue_links_weight[queue_len][k] = cache_links_weight[link_id][k]; } queue_prev[queue_len] = cache_prev[link_id]; queue_len++; } } i++; } } int get_edges_start(int index) { return edges_start[index]; } float get_cache_distance(int index) { return cache_distance[index]; } int get_cache_prev(int index) { return cache_prev[index]; } int main() { init_edges_cpp(); init_cpp(5); add_edge_cpp(0, 0, 2, 1); add_edge_cpp(1, 0, 1, 1); add_edge_cpp(2, 1, 2, 1); add_edge_cpp(3, 2, 3, 1); add_edge_cpp(4, 2, 4, 1); add_edge_cpp(5, 3, 4, 1); fill_graph_cpp(); get_dists_cpp(0, 5); for (int i=0; i &lt; 5; i++) { printf(&quot;vert: %d &quot;, i); printf(&quot;dist: %f &quot;, get_cache_distance(i)); printf(&quot;prev: %d\n&quot;, get_cache_prev(i)); } return 0; } </code></pre> <p>You can <a href="https://onlinegdb.com/HJPW5YD4d" rel="nofollow noreferrer">run this code online</a>.</p> <p>I put in the code implementations of <code>memcpy</code> and <code>memset</code> because I need to compile this code to wasm with <a href="https://wasdk.github.io/WasmFiddle/" rel="nofollow noreferrer">this service</a>. So I need these implementations.</p> <p>Also I did not use advanced structures because it makes impossible (or very very hard) to compile code to webassembly.</p> <p>I think that the code can be made faster. How can I make it faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T00:24:49.330", "Id": "508796", "Score": "0", "body": "Can you mention the algorithm you implemented? I think Dijkstra's algorithm should be enough for most cases and much easy to implement. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T00:28:51.487", "Id": "508797", "Score": "1", "body": "In fact, it is the BFS, but modified for weighed graphs. But we can say, that it's a Dijkstra with queue, where vertices can be in the queue not once. This works faster, than original Dijkstra." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T15:43:20.163", "Id": "257578", "Score": "0", "Tags": [ "performance", "algorithm", "c" ], "Title": "Shortest path algorithm for weighted graphs, targeting web-assembly" }
257578
<p>I'm writing C++ Windows code that will start a process, then read its stdout and stderr, separately, into buffers.</p> <p>If I try to just read the streams one at a time it may hang if the child process is trying to write to the other stream. So I learned I need to create named pipes, and then make calls to ReadFile with an OVERLAPPED struct and wait on them.</p> <p>The fully working solution is available <a href="https://github.com/erezwanderman/Read_StdOut_StdErr_WIN32" rel="nofollow noreferrer">at GitHub</a>. However, I'm asking for a review mostly on the file ReadMultiplePipes.cpp listed below.</p> <p>I only need to support 2 pipes (stdout &amp; stderr), but I made a more general function that receives a vector of handles to pipes and returns a vector of chars of the same length. It reads them until they are all pending (or closed), and then waits on all the pending ones and goes back to reading again.</p> <p>Here are my areas of concern:</p> <ul> <li>Is the code correctly doing Overlapped I/O, that is, it won't hang if the subprocess is writing output, it won't lose bytes etc.</li> <li>Is the error handling and resource management correct, i.e. no leaks.</li> <li>Is there a shorter way to do it, I didn't think reading two streams would need so much code.</li> </ul> <h3>ReadMultiplePipes.cpp</h3> <pre class="lang-c++ prettyprint-override"><code>#include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;list&gt; #include &lt;sstream&gt; #include &lt;vector&gt; #include &lt;tchar.h&gt; #include &lt;Windows.h&gt; #include &quot;Shared.h&quot; struct ReadPipeInfo { ReadPipeInfo(HANDLE handle) : readHandle(handle) { ZeroMemory(&amp;overlapped, sizeof(OVERLAPPED)); if (!(overlapped.hEvent = CreateEvent(nullptr, false, true, nullptr))) throw std::runtime_error(&quot;Call CreateEvent failed.&quot;); } ~ReadPipeInfo() { CloseHandle(overlapped.hEvent); } HANDLE readHandle = nullptr; std::vector&lt;char&gt; outputBuffer; OVERLAPPED overlapped = {}; UCHAR buf[1024 * 4] = {}; // 0 - open // 997 - ERROR_IO_PENDING - Overlapped I/O operation is in progress. // 107 - ERROR_BROKEN_PIPE - The pipe has been ended. DWORD state = 0; }; static DWORD ReadAndInsertOverlappedResult(ReadPipeInfo&amp; readPipe); std::vector&lt;std::vector&lt;char&gt;&gt; ReadFromMultiplePipes(const std::list&lt;HANDLE&gt;&amp; handles) { std::vector&lt;std::shared_ptr&lt;ReadPipeInfo&gt;&gt; readPipes; std::transform(handles.begin(), handles.end(), std::back_inserter(readPipes), [](HANDLE x) { return std::make_shared&lt;ReadPipeInfo&gt;(x); }); while (std::any_of(readPipes.begin(), readPipes.end(), [](auto&amp; i) { return i-&gt;state != ERROR_BROKEN_PIPE; }) ) { // Read until all pipes are pending or broken std::vector&lt;std::shared_ptr&lt;ReadPipeInfo&gt;&gt;::iterator it; while ((it = std::find_if(readPipes.begin(), readPipes.end(), [](auto&amp; i) { return i-&gt;state == 0; })) != readPipes.end()) { auto&amp; currOpenPipe = **it; BOOL rfResult = ::ReadFile(currOpenPipe.readHandle, currOpenPipe.buf, sizeof(currOpenPipe.buf), nullptr, &amp;currOpenPipe.overlapped); if (rfResult) CHECK_WIN32_ERROR(ReadAndInsertOverlappedResult(currOpenPipe)); else { DWORD lastError = ::GetLastError(); if (lastError != ERROR_IO_PENDING &amp;&amp; lastError != ERROR_BROKEN_PIPE) // 997 109 throw std::runtime_error(&quot;ReadFile failed&quot;); else { currOpenPipe.state = lastError; ::SetLastError(0); } } } // Wait for pending IO std::vector&lt;std::shared_ptr&lt;ReadPipeInfo&gt;&gt; pendingReadPipes; std::copy_if(readPipes.begin(), readPipes.end(), std::back_inserter(pendingReadPipes), [](auto&amp; x) { return x-&gt;state == ERROR_IO_PENDING; }); if (pendingReadPipes.size() &gt; 0) { std::vector&lt;HANDLE&gt; eventsToWait; std::transform(pendingReadPipes.begin(), pendingReadPipes.end(), std::back_inserter(eventsToWait), [](auto&amp; x) { return x-&gt;overlapped.hEvent; }); DWORD waitResult = ::WaitForMultipleObjects((DWORD)eventsToWait.size(), eventsToWait.data(), FALSE, INFINITE); if (waitResult &gt;= WAIT_OBJECT_0 &amp;&amp; waitResult &lt; WAIT_OBJECT_0 + pendingReadPipes.size()) { auto&amp; currPendingPipe = *pendingReadPipes[waitResult]; CHECK_WIN32_ERROR(ReadAndInsertOverlappedResult(currPendingPipe)); } else throw std::runtime_error(&quot;WaitForMultipleObjects failed&quot;); } } std::vector&lt;std::vector&lt;char&gt;&gt; ret; std::transform(readPipes.begin(), readPipes.end(), std::back_inserter(ret), [](auto&amp; x) { return x-&gt;outputBuffer; }); return ret; } static DWORD ReadAndInsertOverlappedResult(ReadPipeInfo&amp; readPipe) { DWORD lpNumberOfBytesTransferred = 0; BOOL gor = ::GetOverlappedResult(readPipe.readHandle, &amp;readPipe.overlapped, &amp;lpNumberOfBytesTransferred, false); if (gor) { readPipe.state = 0; readPipe.outputBuffer.insert(readPipe.outputBuffer.end(), readPipe.buf, readPipe.buf + lpNumberOfBytesTransferred); return TRUE; } else { if (::GetLastError() != ERROR_BROKEN_PIPE) // 109 return FALSE; readPipe.state = ERROR_BROKEN_PIPE; ::SetLastError(0); return TRUE; } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T17:44:45.763", "Id": "257581", "Score": "2", "Tags": [ "c++", "stream", "winapi", "child-process" ], "Title": "Reading stdout and stderr of a sub process using Win32, Overlapped I/O" }
257581
<p>I have implemented a radix sort algorithm in Python 3. It first finds the maximum number of digits in the list, then changes them to strings and adds 0's. For example, [7, 23, 107, 1, 53] to ['007', '023', '107', '001', '053']. I then make a new matrix, [[] * 10]. I append the numbers with last digit of 0 in lst[0], numbers with last digit of 1 in lst[1], etc. I then flatten the matrix into a list, and recurse with the lst, and with the position one less than the one before (in this case, the second to last digit). Can I get advice on how to improve it? Here is my code:</p> <pre><code>def radix_sort(lst): '''list -&gt; list''' #finds maximum number of digits in list num_of_digits = max([len(str(x)) for x in lst]) #Adds 0s to the front of the number if necessary and changes it to a string for x in range(len(lst)): lst[x] = '0' * (num_of_digits - len(str(lst[x]))) + str(lst[x]) #helper function to sort based on the position def helper(lst, pos): '''list, int -&gt; list''' #places numbers with 0 in the position in the ans[0], 1 in the position in ans[1], etc. ans = [[] for _ in range(10)] #adding numbers to the position in ans for x in lst: ans[int(x[pos])].append(x) #flattened list, reusing lst to save memory lst = [] for x in ans: for y in x: lst.append(y) #we have sorted the whole list if pos == 0: return lst #recurse again with smaller position return helper(lst, pos - 1) #changing the strings to integers and returning return [int(x) for x in helper(lst, num_of_digits - 1)] </code></pre>
[]
[ { "body": "<pre><code> #flattened list, reusing lst to save memory\n lst = []\n</code></pre>\n<p>That doesn't save memory. The caller of the current <code>helper</code> call still has a reference to the &quot;old&quot; list, so it'll remain in memory in addition to this new one. You'll have one list per call level. To actually save memory, you could do <code>lst.clear()</code> instead, so that all levels use the same single list.</p>\n<p>To further save memory, do <code>del ans, x, y</code> after you rebuilt <code>lst</code> from them before you call <code>helper</code> recursively, otherwise they'll remain in memory as well, again once per call level.</p>\n<p>For example for <code>lst = ['1' * 800] * 1000</code>, these improvements changed the peak memory usage from over 15 MB to less than 0.5 MB in this test of mine:</p>\n<pre><code>import tracemalloc\n\nlst = ['1' * 800] * 1000\ntracemalloc.start()\nradix_sort(lst)\npeak = tracemalloc.get_traced_memory()[1]\nprint(peak)\n</code></pre>\n<p>Or just do it iteratively instead of recursively, then you likely wouldn't have these issues in the first place and you wouldn't have to worry about recursion limit errors due to large numbers.</p>\n<p>Here's an iterative one with a few other changes:</p>\n<pre><code>def radix_sorted(lst):\n '''list -&gt; list'''\n lst = list(map(str, lst))\n width = max(map(len, lst))\n lst = [s.rjust(width, '0') for s in lst]\n for i in range(width)[::-1]:\n buckets = [[] for _ in range(10)]\n for s in lst:\n buckets[int(s[i])].append(s)\n lst = [s for b in buckets for s in b]\n return list(map(int, lst))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T23:04:57.660", "Id": "508790", "Score": "0", "body": "Oh, thanks! I thought it was saving memory, I guess I was completely wrong. This will help my memory usage a lot. By the way, is there really a chance that I'll get a recursion limit error? The recursion depth is 1,000 which means it'll only pass recursion depth for 1000+ digit numbers, am I wrong?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T00:04:31.393", "Id": "508793", "Score": "0", "body": "@SolaSky Yes, roughly at 1000 digits you'd hit the limit. Whether there's a chance that you have such numbers, I don't know, only you do :-). Btw I added an iterative one now." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T20:02:25.017", "Id": "257589", "ParentId": "257588", "Score": "1" } }, { "body": "<p>It isn't necessary to convert the numbers to strings and zero-pad them.</p>\n<pre><code>BASE = 10\n\ndef radix_sort(lst, base=BASE):\n biggest_number = max(lst)\n place = 1\n\n while place &lt;= biggest_number:\n buckets = [[] for _ in range(BASE)]\n for number in lst:\n index = number // place % BASE\n buckets[index].append(number)\n\n lst = []\n for bucket in buckets\n lst.extend(bucket)\n\n place *= BASE\n\n return lst\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T18:19:19.783", "Id": "510534", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why your solution is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T18:14:51.863", "Id": "258930", "ParentId": "257588", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T19:12:46.070", "Id": "257588", "Score": "4", "Tags": [ "python", "python-3.x", "sorting", "radix-sort" ], "Title": "Radix Sort Speed" }
257588
<p>I am writing an object oriented shape detector, first time in Python. I come from a Java background. Can you provide any coding advice?</p> <p><a href="https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/" rel="nofollow noreferrer">https://www.pyimagesearch.com/2016/02/08/opencv-shape-detection/</a></p> <pre><code>@dataclass class Coordinate: x_value: int y_value: int @dataclass class Rectangle: coordinate_upper_left: Coordinate width: float height: float from cv2 import cv2 from numpy.random import randint import constants.shape_constants as shape_constants from models.coordinate import Coordinate from models.rectangle import Rectangle class ShapeItem(): def __init__(self, curve_data): # these items must run in sequence to be set correctly self.curve_data = curve_data self.drawing_item_id = uuid.uuid4() self.approx_poly_dp = self.get_approx_poly() self.vertices = self.get_vertices() self.bounded_rectangle = self.get_bounded_rectangle() self.center_coordinate = self.get_center_coordinate() self.shape = self.get_shape() def get_approx_poly(self): perimeter_value = cv2.arcLength(self.curve_data, True) return cv2.approxPolyDP(self.curve_data, 0.04 * perimeter_value, True) def get_vertices(self): vertices_list : list[Coordinate] = [] vertices_data_curve = self.approx_poly_dp.tolist() for vertices_in_shape in [vertices_data_curve]: for vertices_shape_two_brackets in vertices_in_shape: for vertices_shape_one_bracket in vertices_shape_two_brackets: vertices_item = Coordinate(vertices_shape_one_bracket[0], vertices_shape_one_bracket[1]) vertices_list.append(vertices_item) return vertices_list def get_bounded_rectangle(self): (x_cv, y_cv, width_cv, height_cv) = cv2.boundingRect(self.approx_poly_dp) bounded_rectangle = Rectangle( coordinate_upper_left=Coordinate(x_cv, y_cv), width=width_cv, height=height_cv ) return bounded_rectangle def get_shape(self): shape_value: str if len(self.vertices) == 3: shape_value = shape_constants.TRIANGLE elif len(self.vertices) == 4: shape_value = shape_constants.RECTANGLE elif len(self.vertices) == 5: shape_value = shape_constants.PENTAGON else: shape_value = shape_constants.ELLIPSE return shape_value def get_secondary_shape(self): if self.shape == shape_constants.RECTANGLE and \ 0.95 &lt;= (self.bounded_rectangle.width / float(self.bounded_rectangle.height) &lt;= 1.05): return shape_constants.SQUARE else: return shape_constants.RECTANGLE def get_center_coordinate(self): moment_data = cv2.moments(self.curve_data) center_x = int((moment_data[&quot;m10&quot;] / moment_data[&quot;m00&quot;])) center_y = int((moment_data[&quot;m01&quot;] / moment_data[&quot;m00&quot;])) center_coordinate = Coordinate(center_x, center_y) return center_coordinate def set_background_color(self): random_color_index = randint(1, 10) return random_color_index </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T22:18:58.160", "Id": "508787", "Score": "1", "body": "Could you include your imports as well? Where is `DrawingItem` defined? What is `cv2`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T22:23:12.030", "Id": "508788", "Score": "0", "body": "just added @Linny" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T20:22:06.813", "Id": "257591", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Python shape detector code" }
257591
<p>I wrote an HTML parser in JavaScript, where it takes an a string that represents the HTML</p> <pre class="lang-js prettyprint-override"><code>const html = `&lt;div&gt; &lt;div&gt; foo &lt;/div&gt; &lt;div&gt; bar &lt;/div&gt; &lt;/div&gt;` </code></pre> <p>And it should output an object like this</p> <pre class="lang-js prettyprint-override"><code>{ children: [ { children: ['foo'], value: 'div' }, { children: ['bar'], value: 'div' }, ], value: 'div', } </code></pre> <p>here is my attempt</p> <pre class="lang-js prettyprint-override"><code>function parser(html) { const tokens = html.split('\n') const stack = [] tokens.forEach((token) =&gt; { if (token === '&lt;/div&gt;') { const children = [] while (stack[stack.length - 1] !== '&lt;div&gt;') { children.unshift(stack.pop()) } stack.pop() stack.push({ children, value: 'div', }) } else { stack.push(token) } }) return stack.pop() } </code></pre> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const html = `&lt;div&gt; &lt;div&gt; foo &lt;/div&gt; &lt;div&gt; bar &lt;/div&gt; &lt;/div&gt;` function parser(html) { const tokens = html.split('\n') const stack = [] tokens.forEach((token) =&gt; { if (token === '&lt;/div&gt;') { const children = [] while (stack[stack.length - 1] !== '&lt;div&gt;') { children.unshift(stack.pop()) } stack.pop() stack.push({ children, value: 'div', }) } else { stack.push(token) } }) return stack.pop() } console.log(parser(html))</code></pre> </div> </div> </p> <p>My questions are:</p> <ol> <li>How can I modify the code so it can become easily expandable for other HTML tag <code>body</code>, <code>div</code>, <code>span</code> etc.</li> <li>Right now the HTML string it takes has to be valid. How can I modify the code so it can detect invalid HTML</li> <li>Right now the HTML string it takes doesn't have any indentation. How can I modify the code so it can allow indentations in the input strings?</li> </ol>
[]
[ { "body": "<h2>General review points</h2>\n<ul>\n<li>Use semicolons</li>\n<li>Try to avoid Array iterator functions in favor of for of. Generally use array iterators when you want the iteration to be an expression.</li>\n</ul>\n<p>Apart from that the code looks good and is an elegant solution to parsing simple markup. It can be used as a base to provide the additional functionality you mention.</p>\n<h2>Questions</h2>\n<blockquote>\n<p><em>&quot;Right now the HTML string it takes doesn't have any indentation. How can I modify the code so it can allow indentations in the input strings?&quot;</em></p>\n</blockquote>\n<p>After you split the markup string you can remove white spaces using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String trim\">String.trim</a></p>\n<p>In the example parser (bottom of answer), the first expression uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array map\">Array.map</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array filter\">Array.filter</a> to trim white spaces and then remove empty lines.</p>\n<p>If you want to only remove white spaces using the same rules as HTML then you can use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. RegExp\">RegExp</a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String replace\">String.replace</a> to remove white spaces.</p>\n<h3>Token validator</h3>\n<blockquote>\n<p><em>&quot;How can I modify the code so it can become easily expandable for other HTML tag body, div, span etc.&quot;</em></p>\n</blockquote>\n<blockquote>\n<p><em>&quot;Right now the HTML string it takes has to be valid. How can I modify the code so it can detect invalid HTML&quot;</em></p>\n</blockquote>\n<p>For the other questions you will need to create an object that can validate tokens. The validators role is to recognize, valid tags, invalid tags, and content.</p>\n<p>It does this</p>\n<ul>\n<li>by keeping a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Set\">Set</a> of <code>tag</code> names</li>\n<li>providing a function to check a token. If the token is a valid closing tag it returns the token representing the opening tag.</li>\n<li>keeps the state of the token tested. If the token is <code>unknown</code> or a <code>tag</code> the semaphore are set appropriately.</li>\n</ul>\n<p>Your function has been modified to use the validator and check for various problems related to invalid markup.</p>\n<p>The function will return a simple error object containing the error description if the markup is invalid</p>\n<p>If the token validator checks a token that is unknown (not in name list and starts or ends with <code>&lt;</code> or <code>&gt;</code>) <code>unknown</code> is set <code>true</code>.</p>\n<p>If the token validator checks a known opening tag the semaphore <code>tag</code> is set <code>true</code>.</p>\n<p>The semaphore are reset on each token checked.</p>\n<h2>The Validator</h2>\n<p>Add the tags you wish to recognize to the <code>names</code> Set.</p>\n<p>Call <code>tokenValidator.token</code> to validate a token.</p>\n<p>It will return the opening tag as a token or <code>undefined</code>.</p>\n<p>If <code>undefined</code> the check the semaphores <code>tokenValidator.tag</code> and / or <code>tokenValidator.unknown</code> to determine what to do with the current token.</p>\n<pre><code>const tokenValidator = (() =&gt; {\n const names = new Set([&quot;div&quot;, &quot;span&quot;, &quot;p&quot;]);\n var unknown = false, tag = false;\n return {\n get unknown() { return unknown },\n get tag() { return tag },\n token(token) {\n tag = unknown = false;\n const hasEnd = token.endsWith(&quot;&gt;&quot;);\n if (token.startsWith(&quot;&lt;&quot;)) {\n if (token.startsWith(&quot;&lt;/&quot;) &amp;&amp; hasEnd) {\n const tokenName = token.slice(2,-1);\n if (names.has(tokenName)) { return &quot;&lt;&quot; + tokenName + &quot;&gt;&quot; }\n tag = unknown = true;\n } else if (hasEnd) {\n const tokenName = token.slice(1,-1);\n unknown = !names.has(tokenName);\n tag = true;\n return;\n }\n unknown = true;\n } else if (hasEnd) { tag = unknown = true }\n },\n };\n})();\n</code></pre>\n<h2>The Parser</h2>\n<p>The parses is based on your original code.</p>\n<p>It will either return the parsed markup or an error.</p>\n<p>Usage example</p>\n<pre><code>const result = parser(HTML);\nif (result.error) { console.log(result.message) }\nelse { console.log(result) }\n</code></pre>\n<p>To check for hanging tags (eg missing closing tags) the function counts up on opening tags and down on closing tag. The <code>countOpen</code> must be 0 when done or there is an error.</p>\n<p>Example Code</p>\n<pre><code>function parser(html) {\n const tokens = html.split('\\n').map(token =&gt; token.trim()).filter(token =&gt; token !== &quot;&quot;);\n const error = message =&gt; ({error: true, message: &quot;Invalid HTML. &quot; + message});\n const stack = [];\n var countOpen = 0;\n for (const token of tokens) {\n const openToken = tokenValidator.token(token);\n if (tokenValidator.unknown) { return error(&quot;Unknown tag: &quot; + token) }\n if (openToken) {\n const children = [];\n let stackToken = stack.pop();\n while (stackToken?.value !== openToken) {\n if (!stackToken) { return error(&quot;Tag order: &quot; + token) }\n children.unshift(stackToken);\n stackToken = stack.pop();\n }\n stack.push({value: openToken.slice(1, -1), children});\n countOpen--;\n } else if (tokenValidator.tag) {\n stack.push({value: token});\n countOpen ++;\n } else { stack.push(token) }\n }\n return countOpen ? error(&quot;Missing tag&quot;) : stack.pop();\n}\n</code></pre>\n<p>Note that the code does not cover all invalid markup. It is just an example intended to demonstrate how validation can be addressed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T17:54:47.810", "Id": "509089", "Score": "1", "body": "why are you still using `var`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T19:58:01.220", "Id": "509109", "Score": "0", "body": "@Joji I use function scoped variables when the (var)iable is scoped to the function, `var` is the better option, Why if you understand scope and closure would you not use them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T21:23:19.947", "Id": "509114", "Score": "0", "body": "but it seems like `let` would also work here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T22:46:32.667", "Id": "509116", "Score": "0", "body": "@Joji Use `let` if you prefer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T02:36:53.867", "Id": "257706", "ParentId": "257592", "Score": "3" } } ]
{ "AcceptedAnswerId": "257706", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-23T20:28:53.073", "Id": "257592", "Score": "3", "Tags": [ "javascript", "html", "json" ], "Title": "HTML parser written in JavaScript that takes in strings and output a DOM tree object" }
257592
<p>I have:</p> <ul> <li>A dataframe with Identifiers (<code>TermId</code>) and Search Terms (<code>SearchTerm</code>).</li> <li>A list of text strings (<code>MyText</code>). This likely would be a column (series) in a dataframe.</li> </ul> <p>I for every string in <code>MyText</code> I want to get a count of hits for every regex <code>SearchTerm</code>, producing a table of counts. This is a scaled down example. I'd have 10,000 of <code>Mytext</code> and 100s of <code>SearchTerm</code>s. I am newer to Python (from R) and would like to know where can I optimize the code to make it more performant? I'm open to what ever feedback people have to offer on all aspects of the code.</p> <pre><code>## Dependencies import re import pandas as pd ## Data MyText = ['I saw xx.yy and also xx.yyy', 'FireFly* this is xx_yy there', 'I xx$YY', 'I see x.yy now .NET', 'now xx.yyxx.yyxx.yy'] MyDictionary = pd.DataFrame({ 'TermId': ['SK_{}'.format(x) for x in list(range(0, 6))], 'SearchTerm': ['xx[.]yy', '[.]NET', 'A[+]', 'FireFly[*]', 'NetFlix[$]', 'Adobe[*]'] }) ## Convert Search Term to Compiled Regex Object MyDictionary['Regexes'] = [re.compile(s) for s in MyDictionary['SearchTerm']] ## List comprehension to double loop over the regexes &amp; ## elements of MyText to count hits out = {id: [len(regex.findall(s)) for s in MyText] for regex, id in zip(MyDictionary['Regexes'], MyDictionary['TermId'])} out = pd.DataFrame(out) out['MyText'] = MyText ## Results print(out) print(MyDictionary) </code></pre> <p>Which yields:</p> <pre><code> SK_0 SK_1 SK_2 SK_3 SK_4 SK_5 MyText 0 2 0 0 0 0 0 I saw xx.yy and also xx.yyy 1 0 0 0 1 0 0 FireFly* this is xx_yy there 2 0 0 0 0 0 0 I xx$YY 3 0 1 0 0 0 0 I see x.yy now .NET 4 3 0 0 0 0 0 now xx.yyxx.yyxx.yy </code></pre>
[]
[ { "body": "<p>An idiomatic approach would be to put <code>MyText</code> in a dataframe (if not already) and <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.assign.html\" rel=\"nofollow noreferrer\"><strong><code>assign()</code></strong></a> the results of <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.Series.str.count.html\" rel=\"nofollow noreferrer\"><strong><code>str.count()</code></strong></a>.</p>\n<p>I'd also suggest using an actual <code>dict</code> for the regex mapping. It's not strictly necessary, but the syntax is just cleaner given that this use case aligns with <code>dict</code>. (Here I created <code>terms</code> from <code>MyDictionary</code> just for continuity with the existing code.)</p>\n<pre class=\"lang-py prettyprint-override\"><code>terms = dict(zip(MyDictionary.TermId, MyDictionary.SearchTerm))\ndf = pd.DataFrame({'MyText': MyText})\n\ndf = df.assign(**{key: df.MyText.str.count(val) for key, val in terms.items()})\n\n# MyText SK_0 SK_1 SK_2 SK_3 SK_4 SK_5\n# 0 I saw xx.yy and also xx.yyy 2 0 0 0 0 0\n# 1 FireFly* this is xx_yy there 0 0 0 1 0 0\n# 2 I xx$YY 0 0 0 0 0 0\n# 3 I see x.yy now .NET 0 1 0 0 0 0\n# 4 now xx.yyxx.yyxx.yy 3 0 0 0 0 0\n<span class=\"math-container\">```</span>\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:45:28.743", "Id": "258819", "ParentId": "257601", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T01:59:00.400", "Id": "257601", "Score": "2", "Tags": [ "python", "beginner", "regex", "pandas" ], "Title": "Martix of Counts of Regex Hits Over a List of Strings" }
257601
<p>In this program, I have done automation using Selenium, to find english meaning of each sanskrit word from a dictionary website.</p> <p>The function <code>eng_meaning</code> accepts the word and using selenium and BeautifulSoup scarps the website and find english meaning.</p> <pre><code>def eng_meaning(word): &quot;&quot;&quot; returns english meaning of the sanskrit word passed &quot;&quot;&quot; url = 'https://www.learnsanskrit.cc/index.php?mode=3&amp;direct=au&amp;script=hk&amp;tran_input=' driver = webdriver.Chrome(&quot;/usr/bin/chromedriver&quot;) driver.get(url) meanings = [] try: #find text box where we enter the word text_box = driver.find_element_by_id(&quot;tran_input&quot;) #enter word in the text box text_box.send_keys(word) #clicking translate button buttons = driver.find_elements_by_tag_name(&quot;button&quot;) buttons[-1].click() html_page = driver.page_source #parse html page soup = BeautifulSoup(html_page, 'html.parser') #find table which holds meaning table = soup.body.find('table', attrs={'class':'table0 bgcolor0'}) table_body = table.find('tbody') #find rows of table which holds meaning rows = table_body.find_all('tr') process = True #will become false if word/sentence other then passed word is on table row_itr = 0 for row in rows: #find coulmns in the current row columns = row.find_all('td') i = 0 for col in columns: #split, join and strip the current snaskrit or english word and store in meaning meaning = &quot; &quot;.join(col.get_text().split()) meaning = meaning.strip() if (i == 0): tmp = meaning if (row_itr == 0): #add sanskrit word in the list. Only done once sanskrit_word = meaning elif (i == 2): if (row_itr == 0): #add english transliteration in list. Only done once english_transliteration = meaning if (word != meaning and word != tmp): #current word is process doesn't match with passed word. So stop processing process = False break elif (i == 3): #append sanskrit word and english transliteration in list. Done only once if (row_itr == 0): meanings.append(sanskrit_word) meanings.append(english_transliteration) #append the english meaning to list meanings.append(meaning) i+=1 if (process is False): #stop processing break row_itr += 1 return meanings except(Exception, AttributeError) as e: print(&quot;No meaning found for&quot;, word) finally: if len(meanings) != 0: print(&quot;meanings found&quot;) driver.quit() </code></pre> <p>The program <code>reading_writing_to_file.py</code> reads a sanskrit text file, remove duplicate words and store meaning of each word in another text file.</p> <pre><code>import sanskrit_to_english as se def remove_duplicates(file_name): &quot;&quot;&quot; Remove duplicate word from the file &quot;&quot;&quot; unique_words = set() with open(file_name, 'r') as file: for line in file: for word in line.split(): unique_words.add(word) file.close() return unique_words def eng_translation(file_name_r, file_name_w): &quot;&quot;&quot; Read sanskrit text file and find english meaning of each word &quot;&quot;&quot; words = list(remove_duplicates(file_name_r)) with open(file_name_w, 'w') as file: for word in words: meanings = se.eng_meaning(word) if (meanings): file.write(meanings[0]) file.write(&quot; - &quot;) file.write(meanings[1]) file.write(&quot; - &quot;) meanings_str = ' \\'.join([meanings[i] for i in range(2, len(meanings))]) file.write(meanings_str) file.write(&quot;\n&quot;) file.close() file_name_r = &quot;data.txt&quot; file_name_w = &quot;Sanskrit_english.txt&quot; eng_translation(file_name_r, file_name_w) </code></pre> <p>I am beginner in selenium. How can I improve run-time performance of this code. It takes approx. 5 minutes to find meaning of a word.</p> <p>Sanskrit dictionary website - <a href="https://www.learnsanskrit.cc/index.php?mode=3&amp;direct=au&amp;script=hk&amp;tran_input=" rel="nofollow noreferrer">learnsanskrit.cc</a></p>
[]
[ { "body": "<p>The most obvious bottleneck in your code is that you are calling the function <code>eng_meaning</code> in a loop, but that function creates a new Selenium instance everytime, which is an expensive operation. Imagine that you are searching in Google then systematically closing and reopening your browser after every search. Waste of time isn't it.</p>\n<p>What you should do is restructure your code to initiate Selenium once at the start of your program. Then all you have to do is change URL, submit new parameters etc while keeping the existing instance.</p>\n<p>This should speed up things markedly. I have not run your program, nor have I done any benchmarking. I recommend that you use the timeit module or similar to time the performance of your code, and figure out the sections where there are delays. Or at least add a few prints here and there in your code, showing the current execution step and a timestamp.</p>\n<p>5 minutes per word is really a lot, but it is also possible that the website is applying some form of <strong>rate limiting</strong> against heavy users or scrapers (that is you).</p>\n<h2>Misc remarks</h2>\n<p>Warning: you have some typos (misspellings).</p>\n<p>The naming conventions for functions or variables leave to desire.</p>\n<pre><code>except(Exception, AttributeError) as e:\n</code></pre>\n<p>is superfluous: Exception will catch everything, but you just can catch AttributeError in this context.</p>\n<p><code>file.close()</code> is not needed when you are using the context manager (<code>with</code>)</p>\n<p>In eng_meaning you have a loop on table rows which is somewhat convoluted. Variable names like tmp are not very intuitive. In spite of the comments, it is not immediately clear why variable <code>process</code> exists and what you are really trying to do.</p>\n<p>The way you are incrementing variables (row/column counters) is error-prone, especially with two nested loops with condition blocks. Instead of:</p>\n<pre><code>for row in rows:\n</code></pre>\n<p>you could have:</p>\n<pre><code>for row_counter, row in enumerate(rows, start=1):\n</code></pre>\n<p>then let Python take care of incrementation for you. It's possible that BS already has methods built-in to fetch row/column index, I'm not sure. But it's not something you should be handling manually.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T20:54:16.557", "Id": "257638", "ParentId": "257603", "Score": "3" } }, { "body": "<p>In addition to @Anonymous' answer, her are a few more observations.</p>\n<h3>Selenium - finding elements</h3>\n<p>Getting the translate button based on it being the last button on the page is rather brittle:</p>\n<pre><code> buttons = driver.find_elements_by_tag_name(&quot;button&quot;)\n buttons[-1].click()\n</code></pre>\n<p>If the web site rearranges things (something a designer could do), it would break the script. It is best to use an id or name, which, unfortunately the web page your scraping doesn't have. But Selenium can use CSS selectors too, like</p>\n<pre><code> button = driver.find_element_by_css_selector(&quot;button[@value='translate']&quot;)\n</code></pre>\n<p>Changing the button id, name, or, value would require changing the backend code, which is a more significant change. So the theory is that they will change less often.</p>\n<h3>Loops</h3>\n<p>A loop that does something different each time through the loop is a bit of a code smell. It makes it difficult to understand what the code does and doesn't really save any lines of code. If the first row needs special treatment write code for the first row and then a loop for the remaining rows. Put repeated code in functions:</p>\n<pre><code>SANSKRIT_COL = 0\nENGLISH_COL = 2\n\ndef clean_text(text):\n return &quot; &quot;.join(col.get_text().split()).strip()\n\ndef scrape_row(row):\n column = row.find_all('td')\n\n sanskrit = clean_text(column[SANSKRIT_COL])\n english = clean_text(column[ENGLISH_COL])\n\n return sanskrit, english\n</code></pre>\n<p>Then the nested loops can be replaced with something like this:</p>\n<pre><code> rows = table_body.find_all('tr')\n\n sanskrit, english = scrape_row(rows[0])\n meanings = [sanskrit, english]\n\n for row in rows[1:]:\n sanskrit, english = scrape_row(rows[0])\n \n if sanskrit != word:\n break\n\n meanings.append(english)\n \n return meanings\n</code></pre>\n<h3>try - except - else - finally</h3>\n<p>It is almost never a good idea to include <code>Exception</code> in an <code>except</code> clause. Doubly so when you don't print or log the exception. It will catch every exception including KeyboardInterrupt (e.g., Ctrl-C). Use the most specific Exception you can.</p>\n<p>In a <code>try-except-else-finally</code> statement, the <code>else</code> clause is executed if there are no exceptions in the <code>try</code> clause. The <code>finally</code> clause gets executed last, regardless of whether there was exception or not. So, in your code if an exception occurs after the first row is processed, the code would print &quot;No meaning found...&quot; in the <code>except</code> clause and then print &quot;meanings found&quot; in the <code>finally</code> clause.</p>\n<h3><code>set.union()</code></h3>\n<p><code>set.union()</code> can take an iterable, so the loop in <code>remove_duplicates()</code> can be:</p>\n<pre><code>for line in file:\n unique_words.union(line.split())\n</code></pre>\n<h3><code>with open(...) as file</code></h3>\n<p>When using <code>open</code> in a <code>with</code> statement (e.g., as a context manager), the file is automatically closed at the end of the block, so <code>file.close()</code> isn't necessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T23:38:41.330", "Id": "257701", "ParentId": "257603", "Score": "2" } } ]
{ "AcceptedAnswerId": "257638", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T06:37:21.280", "Id": "257603", "Score": "2", "Tags": [ "python", "performance", "beautifulsoup", "selenium", "automation" ], "Title": "Scrape and parse dictionary website and get meaning of each word in a text file" }
257603
<p>im developing a program that will read text files and convert it to JSON format dynamically. Users are able to input the key name and their respective digit to slice the index from a raw text file. Everything is working fine when reading a small size file, but whenever the text files is huge, the program will load like a few minute in order to proceed. I'm new to programming and have no experience to make a code more &quot;efficient&quot;. What my goal is to make the loop process (read file) to be more faster. Does anyone could help me ? Thanks in advance.</p> <p>My huge text files is around 200kb and 2000+ lines of log</p> <p><strong>My program:</strong> <a href="https://i.stack.imgur.com/0Xb6R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Xb6R.png" alt="enter image description here" /></a></p> <p><strong>After user click on &quot;Review JSON&quot; , the program will convert the text file to json format based on the index slices and print into terminal (this is where the process that I want to make it more faster)</strong> <a href="https://i.stack.imgur.com/ouVc4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ouVc4.png" alt="enter image description here" /></a></p> <p><strong>My Code:</strong></p> <pre><code> #Review JSON format def ReviewJson(): #if no selection is choosed if x == 183.0: tkMessageBox.showinfo(&quot;Error&quot;, &quot;You must select a file before can review.&quot;, icon=&quot;error&quot;) else: # ========valdiate buttons for create new profile try: ReviewJSON_button.configure(state=DISABLED) # Delete submit button when select existing value CreateJsonBtn.destroy() CreateNewJsonBtn.configure(state=NORMAL) except: pass global reviewjson, window window = Toplevel(root) window.minsize(800, 600) window.maxsize(800, 600) window.title(&quot;Foghorn Publisher - Review Json&quot; + &quot; &quot; + &quot;(&quot; + options.get() + &quot;)&quot;) window.protocol('WM_DELETE_WINDOW', destroyReviewJSON) reviewjson = Text(window, bg='black', foreground=&quot;white&quot;, height=&quot;20&quot;, width=&quot;500&quot;) reviewjson.pack() reviewjson.config(state=NORMAL) reviewjson.delete(&quot;1.0&quot;, &quot;end&quot;) file_data.clear() try: global datalist,cleandatalist datalist=[] for content in data2: #Key1name cant be empty if (key1EntryName.get()==&quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;,&quot;First key name cannot be empty&quot;,icon=&quot;error&quot;) #start index and end index cannot be empty after name is been declared elif(key1EntryName.get() != 0) and (key1EntryStartIndex.get() ==&quot;&quot;) and (key1EntryEndIndex.get() ==&quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Start index and end index cannot be empty after declaration of key name&quot;, icon=&quot;error&quot;) # check 1: check start to EOS elif (key1EntryEndIndex.get()) == &quot;&quot;: file_data[key1EntryName.get()] = content[int(key1EntryStartIndex.get()):] # check 1: check EOS to start elif (key1EntryStartIndex.get()) == &quot;&quot;: file_data[key1EntryName.get()] = content[:int(key1EntryEndIndex.get())] # check 1: normal status else: file_data[key1EntryName.get()] = content[int(key1EntryStartIndex.get()):int(key1EntryEndIndex.get())] ######################Check 2 ################################ #check 2: If all empty jiu dont call this part if(key2EntryName.get() or key2EntryStartIndex.get() or key2EntryEndIndex.get()) == &quot;&quot;: pass #check 2: start index and end index cannot be empty after name is been declared elif(key2EntryName.get() != 0) and (key2EntryStartIndex.get() ==&quot;&quot;) and (key2EntryEndIndex.get() ==&quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Start index and end index cannot be empty after declaration of key name&quot;, icon=&quot;error&quot;) elif (key2EntryName.get() == &quot;&quot;) and (key2EntryStartIndex.get() != 0) and ( key2EntryEndIndex.get() == &quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of start index&quot;, icon=&quot;error&quot;) elif (key2EntryName.get() == &quot;&quot;) and (key2EntryStartIndex.get() == &quot;&quot;) and ( key2EntryEndIndex.get() != 0): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of end index&quot;, icon=&quot;error&quot;) elif (key2EntryName.get() == &quot;&quot;) and (key2EntryStartIndex.get() != 0) and ( key2EntryEndIndex.get() != 0): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of start &amp; end index&quot;, icon=&quot;error&quot;) # check 2: check start to EOS elif (key2EntryEndIndex.get()) == &quot;&quot;: file_data[key2EntryName.get()] = content[int(key2EntryStartIndex.get()):] # check 2: check EOS to start elif (key2EntryStartIndex.get()) == &quot;&quot;: file_data[key2EntryName.get()] = content[:int(key2EntryEndIndex.get())] # check 2: normal status else: file_data[key2EntryName.get()] = content[int(key2EntryStartIndex.get()):int(key2EntryEndIndex.get())] ######################Check 3 ################################ # check 3: If all empty jiu dont call this part if (key3EntryName.get() or key3EntryStartIndex.get() or key3EntryEndIndex.get()) == &quot;&quot;: pass # check 3: start index and end index cannot be empty after name is been declared elif (key3EntryName.get() != 0) and (key3EntryStartIndex.get() == &quot;&quot;) and ( key3EntryEndIndex.get() == &quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Start index and end index cannot be empty after declaration of key name&quot;, icon=&quot;error&quot;) elif (key3EntryName.get() == &quot;&quot;) and (key3EntryStartIndex.get() != 0) and ( key3EntryEndIndex.get() == &quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of start index&quot;, icon=&quot;error&quot;) elif (key3EntryName.get() == &quot;&quot;) and (key3EntryStartIndex.get() == &quot;&quot;) and ( key3EntryEndIndex.get() != 0): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of end index&quot;, icon=&quot;error&quot;) elif (key3EntryName.get() == &quot;&quot;) and (key3EntryStartIndex.get() != 0) and ( key3EntryEndIndex.get() != 0): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of start &amp; end index&quot;, icon=&quot;error&quot;) # check 3: check start to EOS elif (key3EntryEndIndex.get()) == &quot;&quot;: file_data[key3EntryName.get()] = content[int(key3EntryStartIndex.get()):] # check 3: check EOS to start elif (key3EntryStartIndex.get()) == &quot;&quot;: file_data[key3EntryName.get()] = content[:int(key3EntryEndIndex.get())] # check 3: normal status else: file_data[key3EntryName.get()] = content[ int(key3EntryStartIndex.get()):int(key3EntryEndIndex.get())] ######################Check 4 ################################ # check 4: If all empty jiu dont call this part if (key4EntryName.get() or key4EntryStartIndex.get() or key4EntryEndIndex.get()) == &quot;&quot;: pass # check 4: start index and end index cannot be empty after name is been declared elif (key4EntryName.get() != 0) and (key4EntryStartIndex.get() == &quot;&quot;) and ( key4EntryEndIndex.get() == &quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Start index and end index cannot be empty after declaration of key name&quot;, icon=&quot;error&quot;) elif (key4EntryName.get() == &quot;&quot;) and (key4EntryStartIndex.get() != 0) and ( key4EntryEndIndex.get() == &quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of start index&quot;, icon=&quot;error&quot;) elif (key4EntryName.get() == &quot;&quot;) and (key4EntryStartIndex.get() == &quot;&quot;) and ( key2EntryEndIndex.get() != 0): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of end index&quot;, icon=&quot;error&quot;) elif (key4EntryName.get() == &quot;&quot;) and (key4EntryStartIndex.get() != 0) and ( key4EntryEndIndex.get() != 0): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of start &amp; end index&quot;, icon=&quot;error&quot;) # check 4: check start to EOS elif (key4EntryEndIndex.get()) == &quot;&quot;: file_data[key4EntryName.get()] = content[int(key4EntryStartIndex.get()):] # check 4: check EOS to start elif (key4EntryStartIndex.get()) == &quot;&quot;: file_data[key4EntryName.get()] = content[:int(key4EntryEndIndex.get())] # check 4: normal status else: file_data[key4EntryName.get()] = content[int(key4EntryStartIndex.get()):int( key4EntryEndIndex.get())] ######################Check 5 ################################ # check 5: If all empty jiu dont call this part if (key5EntryName.get() or key5EntryStartIndex.get() or key5EntryEndIndex.get()) == &quot;&quot;: pass # check 5: start index and end index cannot be empty after name is been declared elif (key5EntryName.get() != 0) and (key5EntryStartIndex.get() == &quot;&quot;) and ( key5EntryEndIndex.get() == &quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Start index and end index cannot be empty after declaration of key name&quot;, icon=&quot;error&quot;) elif (key5EntryName.get() == &quot;&quot;) and (key5EntryStartIndex.get() != 0) and ( key5EntryEndIndex.get() == &quot;&quot;): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of start index&quot;, icon=&quot;error&quot;) elif (key5EntryName.get() == &quot;&quot;) and (key5EntryStartIndex.get() == &quot;&quot;) and ( key5EntryEndIndex.get() != 0): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of end index&quot;, icon=&quot;error&quot;) elif (key5EntryName.get() == &quot;&quot;) and (key5EntryStartIndex.get() != 0) and ( key5EntryEndIndex.get() != 0): window.destroy() ReviewJSON_button.configure(state=NORMAL) tkMessageBox.showinfo(&quot;Error&quot;, &quot;Key name cannot be empty after declaration of start &amp; end index&quot;, icon=&quot;error&quot;) # check 5: check start to EOS elif (key5EntryEndIndex.get()) == &quot;&quot;: file_data[key5EntryName.get()] = content[int(key5EntryStartIndex.get()):] # check 5: check EOS to start elif (key5EntryStartIndex.get()) == &quot;&quot;: file_data[key5EntryName.get()] = content[:int(key5EntryEndIndex.get())] # check 5: normal status else: file_data[key5EntryName.get()] = content[int(key5EntryStartIndex.get()):int( key5EntryEndIndex.get())] # output to JSON global tmp tmp = json.dumps(file_data, ensure_ascii=False, indent=&quot;\t&quot;) datalist.append(tmp) # We want to strip all elements in this list clearslashN = [i.replace('\n','') for i in datalist] cleandatalist = [i.replace('\t', '') for i in clearslashN] print(cleandatalist) except: raise <span class="math-container">```</span> </code></pre>
[]
[ { "body": "<ul>\n<li><p>Keys names, and start and end indices do not ever change. It makes no sense to test them at each iteration. Move all the error checking fragments outside of the loop.</p>\n<p>Same applies to <code>content</code> slicing. Compute the boundaries beforehand.</p>\n</li>\n<li><p>The first line of your data file is aligned differently. I bet its json is incorrect.</p>\n<p>Instead of slicing <code>content</code> at columns, use a regex, e.g.</p>\n<pre><code> r'([^ ]+) ([^;]+);([^ ]+) ([^ ]+) (.*)$'\n</code></pre>\n</li>\n<li><p>Do not strip the entire <code>datalist</code> over and over again. Only strip <code>tmp</code>, before adding it to the datalist.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T06:06:13.817", "Id": "508921", "Score": "0", "body": "the reason why I need to have user input for key names and start,end index is because user are able to choose different raw files to be convert and not only this files." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T22:49:59.033", "Id": "257642", "ParentId": "257604", "Score": "1" } } ]
{ "AcceptedAnswerId": "257642", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T06:46:16.153", "Id": "257604", "Score": "0", "Tags": [ "python", "json" ], "Title": "Make a loop faster when reading large text files" }
257604
<p><em>Why after declaring a variable for String array, it can be passed to a method that accepts object array? Now, <code>String</code> is a class by itself so I assumed a long time ago that all variable is object at a sense. But many argued with me about it. But here it shows the same kind of behaviour.</em></p> <p><strong>Below is given the code where the passing works and the comments point them out.</strong></p> <pre><code>public class Knuth { private Knuth() { } // HERE SHOWS IT TAKES OBJECT public static void shuffle(Object[] a) { int n = a.length; for (int i = 0; i &lt; n; i++) { int r = (int) (Math.random() * (i + 1)); Object swap = a[r]; a[r] = a[i]; a[i] = swap; } } public static void shuffleAlternate(Object[] a) { int n = a.length; for (int i = 0; i &lt; n; i++) { int r = i + (int) (Math.random() * (n - i)); Object swap = a[r]; a[r] = a[i]; a[i] = swap; } } public static void main(String[] args) { // HERE SHOWS IT IS PASSING STRING ARRAY String[] a = StdIn.readAllStrings(); Knuth.shuffle(a); for (int i = 0; i &lt; a.length; i++) StdOut.println(a[i]); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T10:32:34.770", "Id": "508831", "Score": "3", "body": "Did you write this? Do you always indent your code like this? What is the goal of the code? Please take a look at the [help/on-topic]." } ]
[ { "body": "<p>String extends Object type: <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/String.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/7/docs/api/java/lang/String.html</a>\nThis means that String's superclass is Object, so any function that requires an Object as parameter will accept String as parameter also. You can read here about inheritance for example: <a href=\"https://www.tutorialspoint.com/java/java_inheritance.htm\" rel=\"nofollow noreferrer\">https://www.tutorialspoint.com/java/java_inheritance.htm</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T09:12:59.603", "Id": "257608", "ParentId": "257605", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T08:15:45.970", "Id": "257605", "Score": "-1", "Tags": [ "java", "object-oriented" ], "Title": "Can A String array be passed as a parameter to a method that takes object array as argument?" }
257605
<p>I asked <a href="https://stackoverflow.com/questions/66769861/how-is-my-almostincreasingsequencesequence-code-incorrect-codesignal">this</a> question on Stackoverflow as well, but I think it's best suited here because my code needs optimization instead of error checking (that I previously thought).</p> <p>I've made changes to my code as well. But the logic is pretty much the same:</p> <ul> <li>My code first checks the length of the provided sequence, if it is 2 or less it automatically returns <code>True</code>.</li> <li>Next, it creates a <code>newlist</code> with the first element removed and checks if the rest of the list is in ascending order.</li> <li>If the sequence is not in order, the iteration <code>breaks</code> and a <code>newlist</code> is generated again and this time with the next element removed.</li> <li>This continues until there are no more elements to remove (i.e. <code>i == len(sequence) - 1</code>), which ultimately returns as <code>False</code></li> <li>If in any of the iterations, the list is found to be in ascending order(i.e. <code>in_order</code> remains <code>True</code>), the function returns <code>True</code>.</li> </ul> <pre><code>def almostIncreasingSequence(sequence): # return True for lists with 2 or less elements. if len(sequence) &lt;= 2: return True # Outerloop, removes i-th element from sequence at each iteration for i in range(len(sequence)): newlist = sequence[:i] + sequence[i+1:] # Innerloop, checks if the sequence is in ascending order j = 0 in_order = True while j &lt; len(newlist) - 1: if newlist[j+1] &lt;= newlist[j]: in_order = False break j += 1 if in_order == True: return True elif i == len(sequence)-1: return False </code></pre> <hr /> <p>I received a suggestion that <strong>I should only use one loop</strong>, but I cannot think of a way to implement that. Nested loops seems necessary because of the following assumptions:</p> <ol> <li>I have to remove every next element from the original sequence. (outer loop)</li> <li>I need to check if all the elements are in order. (inner loop)</li> </ol> <p><a href="https://stackoverflow.com/questions/43017251/solve-almostincreasingsequence-codefights">This</a> is a brief on <code>almostIncreasingSequence()</code> my code follows the logic provided in the answer here, it solves almost all of the Tests as well, but it is too slow for larger lists (that are approx 10000+ elements).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:17:58.013", "Id": "510470", "Score": "0", "body": "Please define \"almost\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:18:54.193", "Id": "510471", "Score": "0", "body": "Since full sorting is known to be O(N*logN), you have to do at least that good. Your description sounds like O(N*N)." } ]
[ { "body": "<h2>Checking if a list is strictly increasing</h2>\n<p>The inner loop checks if a list (in this case <code>newList</code>) is strictly increasing:</p>\n<pre class=\"lang-py prettyprint-override\"><code>j = 0\nin_order = True\nwhile j &lt; len(newlist) - 1:\n if newlist[j+1] &lt;= newlist[j]:\n in_order = False\n break\n j += 1\nif in_order == True:\n return True\n</code></pre>\n<ol>\n<li>In general variable names should use underscores, so <code>newlist</code> becomes <code>new_list</code>. <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">PEP 8</a>.</li>\n<li>It can be simplified with a <code>for-else</code>:</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>for j in range(len(new_list) - 1):\n if new_list[j+1] &lt;= new_list[j]:\n break\nelse:\n return True\n</code></pre>\n<p>Or using <code>all</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if all(new_list[i] &gt; new_list[i - 1] for i in range(1, len(new_list))):\n return True\n</code></pre>\n<h2>Optimization</h2>\n<p>As you said, the solution is too slow for large input due to the inner loop that runs every time, making the overall complexity <span class=\"math-container\">\\$O(n^2)\\$</span>.</p>\n<p>The current solution follows this approach:</p>\n<ol>\n<li>For each element of the input list</li>\n<li>Build a new list without such element and check if strictly increasing</li>\n</ol>\n<p>Consider simplifying the approach like the following:</p>\n<ol>\n<li>Find the first pair that is not strictly increasing</li>\n<li>Build a new list without the first element of the pair and check if it is increasing</li>\n<li>Build a new list without the second element of the pair and check if it is increasing</li>\n</ol>\n<p>For example:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def almostIncreasingSequence(sequence):\n def is_increasing(l):\n return all(l[i] &gt; l[i - 1] for i in range(1, len(l)))\n\n if is_increasing(sequence):\n return True\n\n # Find non-increasing pair\n left, right = 0, 0\n for i in range(len(sequence) - 1):\n if sequence[i] &gt;= sequence[i + 1]:\n left, right = i, i + 1\n break\n\n # Remove left element and check if it is strictly increasing\n if is_increasing(sequence[:left] + sequence[right:]):\n return True\n\n # Remove right element and check if it is strictly increasing\n if is_increasing(sequence[:right] + sequence[right + 1:]):\n return True\n\n return False\n</code></pre>\n<p>I believe there should be an approach that doesn't build the two additional lists to reduce the space complexity, but I'll leave that to you.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T05:52:20.457", "Id": "257660", "ParentId": "257606", "Score": "2" } } ]
{ "AcceptedAnswerId": "257660", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T08:26:16.123", "Id": "257606", "Score": "3", "Tags": [ "performance", "python-3.x" ], "Title": "My 'almostIncreasingSequence(sequence)' code is too slow for lists that have 10000+ elements. [CodeSignal]" }
257606
<p>I want to use <code>python -c</code> to remove wheel files from the <code>dist/</code> directory in my project. (*)</p> <p>Actually, I use the following command:</p> <pre class="lang-sh prettyprint-override"><code>python -c &quot;from pathlib import Path; [p.unlink() for p in Path('dist').glob('Pascal_Scraper-*.whl')]&quot; </code></pre> <p>Is there a shorter/cleaner way to do that?</p> <hr /> <p>(*) the setuptools command <code>python setup.py rotate --keep=1 --match=.whl</code> doesn't work for me.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T09:25:02.513", "Id": "508824", "Score": "0", "body": "Is there a reason you want to use `python -c` for this? I think `rm dist/Pascal_Scaper-*.whl` would be clearer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T13:43:43.733", "Id": "508842", "Score": "0", "body": "Because `rm` is not available on Windows." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T13:56:57.320", "Id": "508844", "Score": "0", "body": "`del dist\\Pascal_Scraper-*.whl` ? Or is this supposed to be crossplatform?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T14:04:16.563", "Id": "508846", "Score": "0", "body": "Cross-platform, of course." } ]
[ { "body": "<p>If you need to use python for being crossplattform and if you need to do this in one line then this is the way to go, yes.</p>\n<p>For some reason</p>\n<p>Alternatives to consider:</p>\n<ul>\n<li>put the code in a file so you can make it more readable</li>\n<li>create a Makefile and run this under a target (like <code>clean:</code>)</li>\n<li>use <a href=\"https://docs.python.org/3/library/pathlib.html#correspondence-to-tools-in-the-os-module\" rel=\"nofollow noreferrer\">os instead of pathlib</a> to see if you like that better (pathlib is fine, though)</li>\n<li>use <code>map</code> and a <code>lambda</code> instead of list comprehension, to see if you like that better (probably not though)</li>\n</ul>\n<p>I would have expected that a one-line for loop would work, but it doesn't seem to in <code>python -c</code> when there is a command before it.</p>\n<p>I think there is no much cleaner solution</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T12:19:26.390", "Id": "508953", "Score": "0", "body": "This command should live in a `tox.ini` file. So a makefile is not necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T12:28:43.760", "Id": "508954", "Score": "0", "body": "`map` is an iterator, so I would use it like this: `list(map(Path.unlink, Path('dist').glob('Pascal_Scraper-*.whl')))` which is not very clear, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T04:58:57.617", "Id": "509024", "Score": "0", "body": "I think you could make an argument for map, but if it is not clear for you then it is not a good solution for you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T12:16:39.913", "Id": "257674", "ParentId": "257607", "Score": "2" } } ]
{ "AcceptedAnswerId": "257674", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T09:07:16.300", "Id": "257607", "Score": "0", "Tags": [ "python", "python-3.x", "console" ], "Title": "for loop in one line (for python -c)" }
257607
<p>Pydantic is a Python package used for data validation and settings management using Python type annotations. Enforcing typehints and providing errors when invalid data is encountered at runtime.</p> <p>The package is also available as plugin.</p> <p><a href="https://pydantic-docs.helpmanual.io/" rel="nofollow noreferrer">Docs</a> <a href="https://pypi.org/project/pydantic/" rel="nofollow noreferrer">PyPi</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T10:38:17.013", "Id": "257610", "Score": "0", "Tags": null, "Title": null }
257610
Package for data validation and settings management.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T10:38:17.013", "Id": "257611", "Score": "0", "Tags": null, "Title": null }
257611
<p>I have written my own take on <a href="https://semver.org/" rel="nofollow noreferrer">semantic versioning</a>. Parsing it is not really hard, but I feel like my parsing could be more optimal, more readable and feel more like a parser. Currently, there is this <code>unread</code> method that I don't see in most parser so if possible I would like to get rid of it, and the two methods <code>readPrerelease()</code> and <code>readBuild()</code> feel too complex.</p> <p>I'm only interested in parsing so my <code>Version</code> class got cleaned of <code>equals</code>, <code>hashCode</code>, <code>compareTo</code> and <code>toString</code> methods and I removed the related tests. If required I could re-add them, but to me that is superfluous in this code review request.</p> <p>For this code review, I would like to:</p> <ul> <li>Make the code more readable</li> <li>Let the code go forward and avoid going backwards (remove <code>unread</code> and all those <code>currentPosition - 1</code>), unless necessary.</li> <li>Avoid having so many booleans in the methods <code>readPreRelease()</code> and <code>readBuild()</code>.</li> <li>Write general remarks about the code if any.</li> </ul> <p>My code provides three classes:</p> <ul> <li>the <code>VersionParser</code> which do the actual parsing.</li> <li>the <code>Version</code> class, which was dumbed down because I don't want that to be code-reviewed, it's rather easy but the goal here is for the parser. The parsing entry point is here, through the <code>valueOf</code> method.</li> <li>the testing class I used to make sure my parsing is correct.</li> </ul> <p>Below those classes, you can see the BNF grammar for reference.</p> <p>Please note that I removed comments, as I want my code to be self-explanatory, so if it's unclear, that something that should be factored in the review.</p> <pre class="lang-java prettyprint-override"><code>import java.util.ArrayList; import java.util.List; import static java.util.Objects.requireNonNull; final class VersionParser { private final String source; private int currentPosition = 0; VersionParser(String source) { this.source = requireNonNull(source); } Version parse() { var major = readNumericIdentifier(); consume('.'); var minor = readNumericIdentifier(); consume('.'); var patch = readNumericIdentifier(); var preRelease = List.&lt;String&gt;of(); if (peek() == '-') { consume('-'); preRelease = readPreReleases(); } var build = List.&lt;String&gt;of(); if (peek() == '+') { consume('+'); build = readBuilds(); } check(isAtEnd(), &quot;Unexpected characters in \&quot;%s\&quot; at %d&quot;, source, currentPosition - 1); return new Version(major, minor, patch, preRelease, build); } private boolean isDigit(int c) { return '0' &lt;= c &amp;&amp; c &lt;= '9'; } private boolean isAlpha(int c) { return ('a' &lt;= c &amp;&amp; c &lt;= 'z') || ('A' &lt;= c &amp;&amp; c &lt;= 'Z'); } private boolean isNonDigit(int c) { return isAlpha(c) || c == '-'; } private boolean isAtEnd() { return currentPosition &gt;= source.length(); } private int advance() { var c = source.charAt(currentPosition); currentPosition++; return c; } private int peek() { if (isAtEnd()) { return -1; } return source.charAt(currentPosition); } private void unread() { currentPosition--; } private void check(boolean expression, String messageFormat, Object... arguments) { if (!expression) { var message = String.format(messageFormat, arguments); throw new IllegalArgumentException(message); } } private void consume(char expected) { check(!isAtEnd(), &quot;Early end in \&quot;%s\&quot;&quot;, source); var c = advance(); check(c == expected, &quot;Expected %c, got %c in \&quot;%s\&quot; at position %d&quot;, expected, c, source, currentPosition - 1); } private int readNumericIdentifier() { check(!isAtEnd(), &quot;Early end in \&quot;%s\&quot;&quot;, source); var start = currentPosition; var c = advance(); check(isDigit(c), &quot;Expected a digit, got %c in \&quot;%s\&quot; at position %d&quot;, c, source, currentPosition - 1); if (c == '0') { return 0; } while (!isAtEnd()) { c = advance(); if (!isDigit(c)) { unread(); break; } } var string = source.substring(start, currentPosition); return Integer.parseInt(string); } private List&lt;String&gt; readPreReleases() { var preReleases = new ArrayList&lt;String&gt;(); preReleases.add(readPreRelease()); while (true) { if (peek() != '.') { return preReleases; } consume('.'); preReleases.add(readPreRelease()); } } /* * Basically, should be a valid number (without leading 0, unless for 0) or should contain at least one letter or dash. */ private String readPreRelease() { var start = currentPosition; var isAllDigit = true; var startsWithZero = false; var isEmpty = true; while (!isAtEnd()) { var c = advance(); var isDigit = isDigit(c); var isNonDigit = isNonDigit(c); if (!isDigit &amp;&amp; !isNonDigit) { unread(); break; } if (isEmpty &amp;&amp; c == '0') { startsWithZero = true; } isEmpty = false; isAllDigit &amp;= isDigit; } check(!isEmpty, &quot;Empty preRelease part in \&quot;%s\&quot; at %d&quot;, source, currentPosition - 1); var length = currentPosition - start; var doesNotStartWithZero = !isAllDigit || !startsWithZero || length == 1; check(doesNotStartWithZero, &quot;Numbers may not start with 0 except 0 in \&quot;%s\&quot; at position %d&quot;, source, start); return source.substring(start, currentPosition); } private List&lt;String&gt; readBuilds() { var builds = new ArrayList&lt;String&gt;(); builds.add(readBuild()); while (true) { if (peek() != '.') { return builds; } consume('.'); builds.add(readBuild()); } } private String readBuild() { var start = currentPosition; var isEmpty = true; while (!isAtEnd()) { var c = advance(); var isDigit = isDigit(c); var isNonDigit = isNonDigit(c); if (!isDigit &amp;&amp; !isNonDigit) { unread(); break; } isEmpty = false; } check(!isEmpty, &quot;Empty build part in \&quot;%s\&quot; at %d&quot;, source, currentPosition - 1); return source.substring(start, currentPosition); } } </code></pre> <p>The <code>Version</code> class that hides the parser.</p> <pre class="lang-java prettyprint-override"><code>import java.util.List; public final class Version { public static Version valueOf(String s) { return new VersionParser(s).parse(); } private final int major; private final int minor; private final int patch; private final List&lt;String&gt; preRelease; private final List&lt;String&gt; build; Version(int major, int minor, int patch, List&lt;String&gt; preRelease, List&lt;String&gt; build) { this.major = major; this.minor = minor; this.patch = patch; this.preRelease = List.copyOf(preRelease); this.build = List.copyOf(build); } // getters, equals, hashCode, toString, compareTo (+ implement Comparable) } </code></pre> <p>The test class to make sure the parsing works. Requires Junit and AssertJ.</p> <pre class="lang-java prettyprint-override"><code>import org.junit.jupiter.params.*; import org.junit.jupiter.params.provider.*; import java.util.*; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.*; class VersionTest { @ParameterizedTest @MethodSource(&quot;provideCorrectVersions&quot;) void testVersion_correct(String correctVersion) { assertThat(be.imgn.common.base.Version.valueOf(correctVersion)) .isNotNull(); } private static List&lt;Arguments&gt; provideCorrectVersions() { var versions = new String[] { &quot;0.0.4&quot;, &quot;1.2.3&quot;, &quot;10.20.30&quot;, &quot;1.1.2-prerelease+meta&quot;, &quot;1.1.2+meta&quot;, &quot;1.1.2+meta-valid&quot;, &quot;1.0.0-alpha&quot;, &quot;1.0.0-beta&quot;, &quot;1.0.0-alpha.beta&quot;, &quot;1.0.0-alpha.beta.1&quot;, &quot;1.0.0-alpha.1&quot;, &quot;1.0.0-alpha0.valid&quot;, &quot;1.0.0-alpha.0valid&quot;, &quot;1.0.0-alpha-a.b-c-somethinglong+build.1-aef.1-its-okay&quot;, &quot;1.0.0-rc.1+build.1&quot;, &quot;2.0.0-rc.1+build.123&quot;, &quot;1.2.3-beta&quot;, &quot;10.2.3-DEV-SNAPSHOT&quot;, &quot;1.2.3-SNAPSHOT-123&quot;, &quot;1.0.0&quot;, &quot;2.0.0&quot;, &quot;1.1.7&quot;, &quot;2.0.0+build.1848&quot;, &quot;2.0.1-alpha.1227&quot;, &quot;1.0.0-alpha+beta&quot;, &quot;1.2.3----RC-SNAPSHOT.12.9.1--.12+788&quot;, &quot;1.2.3----R-S.12.9.1--.12+meta&quot;, &quot;1.2.3----RC-SNAPSHOT.12.9.1--.12&quot;, &quot;1.0.0+0.build.1-rc.10000aaa-kk-0.1&quot;, &quot;999999999.999999999.999999999&quot;, &quot;1.0.0-0A.is.legal&quot; }; return Arrays.stream(versions) .map(Arguments::of) .collect(toList()); } @ParameterizedTest @MethodSource(&quot;provideIncorrectVersions&quot;) void testVersion_incorrect(String incorrectVersion) { assertThatThrownBy(() -&gt; Version.valueOf(incorrectVersion)) .isInstanceOf(IllegalArgumentException.class) .hasNoSuppressedExceptions(); } private static List&lt;Arguments&gt; provideIncorrectVersions() { var versions = new String[] { &quot;1&quot;, &quot;1.2&quot;, &quot;1.2.3-0123&quot;, &quot;1.2.3-0123.0123&quot;, &quot;1.1.2+.123&quot;, &quot;1.2.3+&quot;, &quot;+invalid&quot;, &quot;-invalid&quot;, &quot;-invalid+invalid&quot;, &quot;-invalid.01&quot;, &quot;alpha&quot;, &quot;alpha.beta&quot;, &quot;alpha.beta.1&quot;, &quot;alpha.1&quot;, &quot;alpha+beta&quot;, &quot;alpha_beta&quot;, &quot;alpha.&quot;, &quot;alpha..&quot;, &quot;beta&quot;, &quot;1.0.0-alpha_beta&quot;, &quot;-alpha.&quot;, &quot;1.0.0-alpha..&quot;, &quot;1.0.0-alpha..1&quot;, &quot;1.0.0-alpha...1&quot;, &quot;1.0.0-alpha....1&quot;, &quot;1.0.0-alpha.....1&quot;, &quot;1.0.0-alpha......1&quot;, &quot;1.0.0-alpha.......1&quot;, &quot;01.1.1&quot;, &quot;1.01.1&quot;, &quot;1.1.01&quot;, &quot;1.2&quot;, &quot;1.2.3.DEV&quot;, &quot;1.2-SNAPSHOT&quot;, &quot;1.2.31.2.3----RC-SNAPSHOT.12.09.1--..12+788&quot;, &quot;1.2-RC-SNAPSHOT&quot;, &quot;-1.0.3-gamma+b7718&quot;, &quot;+justmeta&quot;, &quot;9.8.7+meta+meta&quot;, &quot;9.8.7-whatever+meta+meta&quot;, &quot;999999999999999999.999999999999999999.999999999999999999&quot;, &quot;999999999.999999999.999999999----RC-SNAPSHOT.12.09.1-------------..12&quot; }; return Arrays.stream(versions) .map(Arguments::of) .collect(toList()); } } </code></pre> <p><a href="https://semver.org/#backusnaur-form-grammar-for-valid-semver-versions" rel="nofollow noreferrer">The Backus–Naur Form grammar</a>, as taken from the semver.org website.</p> <pre class="lang-bnf prettyprint-override"><code>&lt;valid semver&gt; ::= &lt;version core&gt; | &lt;version core&gt; &quot;-&quot; &lt;pre-release&gt; | &lt;version core&gt; &quot;+&quot; &lt;build&gt; | &lt;version core&gt; &quot;-&quot; &lt;pre-release&gt; &quot;+&quot; &lt;build&gt; &lt;version core&gt; ::= &lt;major&gt; &quot;.&quot; &lt;minor&gt; &quot;.&quot; &lt;patch&gt; &lt;major&gt; ::= &lt;numeric identifier&gt; &lt;minor&gt; ::= &lt;numeric identifier&gt; &lt;patch&gt; ::= &lt;numeric identifier&gt; &lt;pre-release&gt; ::= &lt;dot-separated pre-release identifiers&gt; &lt;dot-separated pre-release identifiers&gt; ::= &lt;pre-release identifier&gt; | &lt;pre-release identifier&gt; &quot;.&quot; &lt;dot-separated pre-release identifiers&gt; &lt;build&gt; ::= &lt;dot-separated build identifiers&gt; &lt;dot-separated build identifiers&gt; ::= &lt;build identifier&gt; | &lt;build identifier&gt; &quot;.&quot; &lt;dot-separated build identifiers&gt; &lt;pre-release identifier&gt; ::= &lt;alphanumeric identifier&gt; | &lt;numeric identifier&gt; &lt;build identifier&gt; ::= &lt;alphanumeric identifier&gt; | &lt;digits&gt; &lt;alphanumeric identifier&gt; ::= &lt;non-digit&gt; | &lt;non-digit&gt; &lt;identifier characters&gt; | &lt;identifier characters&gt; &lt;non-digit&gt; | &lt;identifier characters&gt; &lt;non-digit&gt; &lt;identifier characters&gt; &lt;numeric identifier&gt; ::= &quot;0&quot; | &lt;positive digit&gt; | &lt;positive digit&gt; &lt;digits&gt; &lt;identifier characters&gt; ::= &lt;identifier character&gt; | &lt;identifier character&gt; &lt;identifier characters&gt; &lt;identifier character&gt; ::= &lt;digit&gt; | &lt;non-digit&gt; &lt;non-digit&gt; ::= &lt;letter&gt; | &quot;-&quot; &lt;digits&gt; ::= &lt;digit&gt; | &lt;digit&gt; &lt;digits&gt; &lt;digit&gt; ::= &quot;0&quot; | &lt;positive digit&gt; &lt;positive digit&gt; ::= &quot;1&quot; | &quot;2&quot; | &quot;3&quot; | &quot;4&quot; | &quot;5&quot; | &quot;6&quot; | &quot;7&quot; | &quot;8&quot; | &quot;9&quot; &lt;letter&gt; ::= &quot;A&quot; | &quot;B&quot; | &quot;C&quot; | &quot;D&quot; | &quot;E&quot; | &quot;F&quot; | &quot;G&quot; | &quot;H&quot; | &quot;I&quot; | &quot;J&quot; | &quot;K&quot; | &quot;L&quot; | &quot;M&quot; | &quot;N&quot; | &quot;O&quot; | &quot;P&quot; | &quot;Q&quot; | &quot;R&quot; | &quot;S&quot; | &quot;T&quot; | &quot;U&quot; | &quot;V&quot; | &quot;W&quot; | &quot;X&quot; | &quot;Y&quot; | &quot;Z&quot; | &quot;a&quot; | &quot;b&quot; | &quot;c&quot; | &quot;d&quot; | &quot;e&quot; | &quot;f&quot; | &quot;g&quot; | &quot;h&quot; | &quot;i&quot; | &quot;j&quot; | &quot;k&quot; | &quot;l&quot; | &quot;m&quot; | &quot;n&quot; | &quot;o&quot; | &quot;p&quot; | &quot;q&quot; | &quot;r&quot; | &quot;s&quot; | &quot;t&quot; | &quot;u&quot; | &quot;v&quot; | &quot;w&quot; | &quot;x&quot; | &quot;y&quot; | &quot;z&quot; <span class="math-container">````</span> </code></pre>
[]
[ { "body": "<p>On the whole, the code was easy to read, and the tests were concise (apart from the fully qualified <code>be.imgn.common.base.Version.valueOf</code> call. Here's a few things to think about.</p>\n<h2>Object Lifetime</h2>\n<p>The <code>VersionParser</code> class takes in a <code>String</code> and then provides a <code>parse</code> method which actually does the parsing work. However, this method can only ever be called once. If it's called more than once, then it fails, because the source string has already been parsed and the method assumes that it's only called on a newly constructed parser. This feels wrong. It's relying on the clients knowing too much about how the class works. A better approach might have been to make the class constructor private and have a static <code>parse</code> method for the interface, which spun up the data, if required, and performed the parse. Alternately, <code>parse</code> could simply reset processed back to the beginning of the source data an reprocess it, or even return a cached version...</p>\n<h2>Circular Dependency</h2>\n<p>Circular dependencies as a general rule are bad. They have a tendency to result in tightly coupled code that bites you, just as you decide you want do reuse a bit of the code somewhere else. As it stands, you've got a circular dependency. Your <code>Version</code> calls <code>VersionParser</code> which then creates a <code>Version</code>. To me, it seems like a <code>VersionParser</code> might need to know about a <code>Version</code>, in order to construct it, but a <code>Version</code> shouldn't really need to know about a <code>VersionParser</code>.</p>\n<h2>If it's <code>!isDigit &amp;&amp; !isNonDigit</code> what is it?</h2>\n<p>One of your goals is self explanatory code. If found this line less than obvious, my instinct was non-digit is the same as not-a-digit, which is everything that isn't a digit... However that's clearly not the case. A NonDigit, appears to be an alpha, or '-'. A better name might help, however you only actually seem to use it in this check. Maybe a method <code>isValidVersionCharacter</code> which evaluated digits and 'non digits', would be clearer...</p>\n<h2>Check</h2>\n<p>There's quite a lot of <code>!</code> in your code. For me, this made some of the calls to <code>check</code> awkward to process.</p>\n<pre><code>check(!isAtEnd(), &quot;Early end in \\&quot;%s\\&quot;&quot;, source);\n</code></pre>\n<p>I'm not sure if it's that <code>check</code> sounds a bit like <code>if</code>, so I'm expecting it to perform the print/throw action if the condition is true, or if it's that &quot;Check not is at end&quot; sounds awkward. <code>verify</code> would work better for me I think, because it's closer to assert, so I'm of a mindset that it's expecting the condition to be true, or it will perform the print/throw action (i.e. the opposite of the <code>if</code> processing). I suspect this is very subjective, but possibly something to consider.</p>\n<p>Since I'm thinking about <code>check</code>, its first parameter is <code>boolean expression</code>. This is a bit misleading. It doesn't take an expression, it takes in a boolean value that if it isn't true will result in an exception. A better name for the parameter may help with some of my previous misunderstandings.</p>\n<hr />\n<p>To get a feel for possible approaches for the negatives, I went through the code and noticed several possible small refactorings, with a goal of making small improvements.</p>\n<ul>\n<li>Replaced your <code>while</code> constructs with <code>do..while</code>, the operation is always performed once.</li>\n<li><code>isAtEnd</code> seemed to result in a lot of <code>!isAtEnd</code>, so I inverted it to <code>isMoreToProcess</code></li>\n<li>I think you’re missing three invalid test cases, so I added them: “01.0.4”, “0.01.4”, “0.0.04”</li>\n<li><code>unread</code> and <code>peek</code> seem to be doing the same thing in different ways. I removed <code>unread</code> to make the approach more straightforward to follow</li>\n<li>Since I used <code>peek</code>, which checks if we’re at the end as part of it, didn’t need to check if we have reached the end during loops</li>\n<li>The isEmpty variables make your iterations busier than they need to be, so I extracted them from the loop</li>\n<li><code>doesNotStartWithZero</code> had a lot of negatives, so I inverted it to <code>numberWithZeroPrefix</code></li>\n<li>I removed the construction requirement for the parser, so that <code>parse</code> takes the information it’s expected to parse. This makes calling <code>parse</code> more consistent (you get the same behaviour if you call it once or 5 times)</li>\n</ul>\n<p>The resulting code:</p>\n<pre><code>final class VersionParser {\n\n private String source;\n private int currentPosition = 0;\n\n Version parse(String source) {\n this.source = requireNonNull(source);\n var major = readNumericIdentifier();\n consume('.');\n var minor = readNumericIdentifier();\n consume('.');\n var patch = readNumericIdentifier();\n var preRelease = List.&lt;String&gt;of();\n if (peek() == '-') {\n consume('-');\n preRelease = readPreReleases();\n }\n var build = List.&lt;String&gt;of();\n if (peek() == '+') {\n consume('+');\n build = readBuilds();\n }\n check(!isMoreToProcess(), &quot;Unexpected characters in \\&quot;%s\\&quot; at %d&quot;, source, currentPosition - 1);\n return new Version(major, minor, patch, preRelease, build);\n }\n\n private boolean isDigit(int c) {\n return '0' &lt;= c &amp;&amp; c &lt;= '9';\n }\n\n private boolean isAlpha(int c) {\n return ('a' &lt;= c &amp;&amp; c &lt;= 'z') || ('A' &lt;= c &amp;&amp; c &lt;= 'Z');\n }\n\n private boolean isNonDigit(int c) {\n return isAlpha(c) || c == '-';\n }\n\n private boolean isMoreToProcess() {\n return !(currentPosition &gt;= source.length());\n }\n\n private int advance() {\n var c = source.charAt(currentPosition);\n currentPosition++;\n return c;\n }\n\n private int peek() {\n if (!isMoreToProcess()) {\n return -1;\n }\n return source.charAt(currentPosition);\n }\n\n private void check(boolean expression, String messageFormat, Object... arguments) {\n if (!expression) {\n var message = String.format(messageFormat, arguments);\n throw new IllegalArgumentException(message);\n }\n }\n\n private void consume(char expected) {\n check(isMoreToProcess(), &quot;Early end in \\&quot;%s\\&quot;&quot;, source);\n var c = advance();\n check(c == expected, &quot;Expected %c, got %c in \\&quot;%s\\&quot; at position %d&quot;, expected, c, source, currentPosition - 1);\n }\n\n private boolean isDigitNext() {\n return isDigit(peek());\n }\n private boolean isValidIdentifierCharacterNext() {\n var nextCharacter = peek();\n return isDigit(nextCharacter) || isNonDigit(nextCharacter);\n }\n\n private int readNumericIdentifier() {\n check(isMoreToProcess(), &quot;Early end in \\&quot;%s\\&quot;&quot;, source);\n var start = currentPosition;\n var c = advance();\n check(isDigit(c), &quot;Expected a digit, got %c in \\&quot;%s\\&quot; at position %d&quot;, c, source, currentPosition - 1);\n if (c == '0') {\n return 0;\n }\n while (isDigitNext()) {\n advance();\n }\n var string = source.substring(start, currentPosition);\n return Integer.parseInt(string);\n }\n\n private List&lt;String&gt; readPreReleases() {\n var preReleases = new ArrayList&lt;String&gt;();\n do {\n preReleases.add(readPreRelease());\n if (peek() != '.') {\n return preReleases;\n }\n consume('.');\n } while(true);\n }\n\n /*\n * Basically, should be a valid number (without leading 0, unless for 0) or should contain at least one letter or dash.\n */\n private String readPreRelease() {\n var start = currentPosition;\n var isAllDigit = true;\n check(isValidIdentifierCharacterNext(), &quot;Empty preRelease part in \\&quot;%s\\&quot; at %d&quot;, source, currentPosition - 1);\n boolean startsWithZero = peek() == '0';\n while (isValidIdentifierCharacterNext()) {\n var c = advance();\n\n isAllDigit &amp;= isDigit(c);\n }\n var length = currentPosition - start;\n var numberWithZeroPrefix = isAllDigit &amp;&amp; startsWithZero &amp;&amp; length != 1;\n check(!numberWithZeroPrefix, &quot;Numbers may not start with 0 except 0 in \\&quot;%s\\&quot; at position %d&quot;, source, start);\n\n return source.substring(start, currentPosition);\n }\n\n private List&lt;String&gt; readBuilds() {\n var builds = new ArrayList&lt;String&gt;();\n do {\n builds.add(readBuild());\n if (peek() != '.') {\n return builds;\n }\n consume('.');\n }\n while(true);\n }\n\n private String readBuild() {\n var start = currentPosition;\n check(isValidIdentifierCharacterNext(), &quot;Empty build part in \\&quot;%s\\&quot; at %d&quot;, source, currentPosition - 1);\n while (isValidIdentifierCharacterNext()) {\n advance();\n }\n return source.substring(start, currentPosition);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T15:16:39.847", "Id": "508855", "Score": "0", "body": "Thank you for this analysis. You have only valid points. Regarding the circular dependency, would it help if I move the Parser as a nested class of Version? Or should they really be kept separated? The digit/non-digit duality is from the spec. I tried to keep the names as much as possible, but actually, there is a \"wrapper\" in the spec for that: `<identifier character>` so I'll use that one. The quantity of `!` is indeed one driver for this code review request, that's some of it that made me think my code isn't really a fully readable parser. The `check` idea comes from Guava, but I'll fix it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:13:56.460", "Id": "508862", "Score": "0", "body": "I disagree with the circular dependency assertion. In general, yes, they should be avoided, in this case, the impact is completely neglectable as `Version` does not depend on implementation details of `VersionParser` at all. Additionally, it leads to easier to use code as one can do `Version version = Version.parse(value)` instead of `Version version = new VersionParser(value).parse()` or `Version version = VersionParser.parse(value)`. That there *is* `VersionParser` seems like something that must not necessarily be known to the user of `Version`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T17:29:39.503", "Id": "508877", "Score": "0", "body": "@Bobby If `Version.valueOf` called `VersionParser.parse` then I think you'd have a stronger case. In its current form though, `Version` both constructs and calls `parse`. To me this is a dependency to be aware of. Adding a `JSON` parser for constructing a `Version` would currently require changing logic in the `Version` class. As you've said, it *may* not be a problem in this case, however to me it's still a circle." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T17:30:15.493", "Id": "508878", "Score": "0", "body": "@OlivierGrégoire making the parser a nested class would signal your intent more strongly that the two classes are intertwined (the `Version` constructor could be `private`). You could argue you already do this through package, rather than `public` visibility, or that the current dependency isn’t a problem because you have more knowledge of the domain. That’s why it’s a consideration, rather than a concrete rule." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T21:32:59.673", "Id": "508890", "Score": "1", "body": "@OlivierGrégoire I've added some additional refactoring suggestions." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T14:55:15.633", "Id": "257620", "ParentId": "257614", "Score": "5" } } ]
{ "AcceptedAnswerId": "257620", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T12:24:32.300", "Id": "257614", "Score": "3", "Tags": [ "java" ], "Title": "Parsing Semver versions" }
257614
<p>I created a simple minesweeper game in c#, and wanted to know how to improve it. I didn't really understand how to make it so everything besides the zero opens up.</p> <p>How would I make my class Board better?</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Minesweeper_trial { class Board { public int[,] BoardPeices = new int[5, 5]; //-------------------------------------------------------------------------------------- public void AddMine(Mine mine1) { BoardPeices[mine1.PositionX, mine1.PositionY] = 9; } //-------------------------------------------------------------------------------------- public void PrintBoard() { for (int y = 0; y &lt; 5; y++) { for (int x = 0; x &lt; 5; x++) { Console.Write(BoardPeices[x,y]); } Console.Write(Environment.NewLine); } } //-------------------------------------------------------------------------------------- public void SetBoard() { for (int y = 0; y &lt; 5; y++) { for (int x = 0; x &lt; 5; x++) { BoardPeices[x, y] = 0; } } } //-------------------------------------------------------------------------------------- public void NumberBesideMine(Mine mine1) { if (mine1.PositionX == 4 &amp;&amp; mine1.PositionY == 4) { BoardPeices[mine1.PositionX - 1, mine1.PositionY]++; BoardPeices[mine1.PositionX, mine1.PositionY - 1]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY - 1]++; } else if (mine1.PositionX == 0 &amp;&amp; mine1.PositionY == 0) { BoardPeices[mine1.PositionX + 1, mine1.PositionY]++; BoardPeices[mine1.PositionX, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX + 1, mine1.PositionY + 1]++; } else if (mine1.PositionX == 0 &amp;&amp; mine1.PositionY == 4) { BoardPeices[mine1.PositionX + 1, mine1.PositionY]++; BoardPeices[mine1.PositionX, mine1.PositionY - 1]++; BoardPeices[mine1.PositionX + 1, mine1.PositionY - 1]++; } else if (mine1.PositionX == 4 &amp;&amp; mine1.PositionY == 0) { BoardPeices[mine1.PositionX - 1, mine1.PositionY]++; BoardPeices[mine1.PositionX, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY + 1]++; } else if (mine1.PositionY == 4) { BoardPeices[mine1.PositionX + 1, mine1.PositionY]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY]++; BoardPeices[mine1.PositionX, mine1.PositionY - 1]++; BoardPeices[mine1.PositionX + 1, mine1.PositionY - 1]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY - 1]++; } else if (mine1.PositionX == 4) { BoardPeices[mine1.PositionX - 1, mine1.PositionY]++; BoardPeices[mine1.PositionX, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX, mine1.PositionY - 1]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY - 1]++; } else if (mine1.PositionY == 0) { BoardPeices[mine1.PositionX + 1, mine1.PositionY]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY]++; BoardPeices[mine1.PositionX, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX + 1, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY + 1]++; } else if (mine1.PositionX == 0) { BoardPeices[mine1.PositionX + 1, mine1.PositionY]++; BoardPeices[mine1.PositionX, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX, mine1.PositionY - 1]++; BoardPeices[mine1.PositionX + 1, mine1.PositionY - 1]++; BoardPeices[mine1.PositionX + 1, mine1.PositionY + 1]++; } else { BoardPeices[mine1.PositionX + 1, mine1.PositionY]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY]++; BoardPeices[mine1.PositionX, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX, mine1.PositionY - 1]++; BoardPeices[mine1.PositionX + 1, mine1.PositionY - 1]++; BoardPeices[mine1.PositionX + 1, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY + 1]++; BoardPeices[mine1.PositionX - 1, mine1.PositionY - 1]++; } } } } </code></pre> <p><a href="https://github.com/ArtificialDog/MineSweeper" rel="nofollow noreferrer">Link to full code</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T14:48:07.627", "Id": "508850", "Score": "1", "body": "Ok, i will edit it" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:22:59.380", "Id": "508864", "Score": "4", "body": "Please add the full code, and not via a URL which can deprecate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T18:19:43.930", "Id": "508882", "Score": "1", "body": "`BoardPeices` is that supposed to be `BoardPieces`? At least you've been consistent, but I'm not familiar with that spelling." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T21:08:33.630", "Id": "508888", "Score": "0", "body": "Sorry, I suck at english." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T05:51:54.520", "Id": "508916", "Score": "0", "body": "`wanted to know how to improve [a simple minesweeper game/board]` define *good*/*better*, and let in those you ask for ideas." } ]
[ { "body": "<p>As far I understand you need to intersect your 5x5 board with a 3x3 square with a center in <code>mine1</code>.<br />\nIt could be achieved via 2D loop (2 nested loops).</p>\n<ol>\n<li><p>First (optional), if you use an old version of .NET that don't have the <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.math.clamp\" rel=\"nofollow noreferrer\"><code>Math.Clamp</code></a> method, let's create a simple method to clamp a value <code>x</code> into the range <code>[min, max]</code>.</p>\n<pre><code>private static T Clamp&lt;T&gt;(T x, T min, T max)\n where T : IComparable&lt;T&gt;\n{\n return x.CompareTo(min) &lt; 0 ? min : x.CompareTo(max) &gt; 0 ? max : x;\n}\n</code></pre>\n</li>\n<li><p>Next, let's find a boundaries.</p>\n<pre><code>int maxX = BoardPeices.GetLength(0) - 1; // Should be 4\nint maxY = BoardPeices.GetLength(1) - 1; // Should be 4\n\nint left = Clamp(mine1.PositionX - 1, 0, maxX);\nint right = Clamp(mine1.PositionX + 1, 0, maxX);\nint top = Clamp(mine1.PositionY - 1, 0, maxY);\nint bottom = Clamp(mine1.PositionY - 1, 0, maxY);\n</code></pre>\n</li>\n<li><p>Finally, let's iterate.</p>\n<pre><code>for (j = top; &lt;= bottom; ++j)\n{\n for (i = left; &lt;= right; ++i)\n {\n ++BoardPeices[i, j];\n }\n}\n--BoardPeices[mine1.PositionX, mine1.PositionY]; // undo the mine1 cell increment\n</code></pre>\n</li>\n</ol>\n<p>Thus, items 2 and 3 together replace your <code>NumberBesideMine</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T00:04:15.503", "Id": "508902", "Score": "0", "body": "Why not `Math.Clamp`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T12:06:36.967", "Id": "508949", "Score": "1", "body": "@aepot Indeed. It appeared in .NET Standard already. I missed that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T20:59:24.937", "Id": "257639", "ParentId": "257615", "Score": "2" } } ]
{ "AcceptedAnswerId": "257639", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T13:20:37.570", "Id": "257615", "Score": "2", "Tags": [ "c#", "game", "console", "minesweeper" ], "Title": "Minesweeper in C# Console - Board Implementation" }
257615
<p>I have a class that inherits from Dictionary&lt;Tkey, TValue&gt;.</p> <p>I need my Value part of the KeyValue pair to be a a Tuple (int, bool )</p> <pre><code>public class IssueRowValidationDictionary : Dictionary&lt;string, (int, bool)&gt; { public IssueRowValidationDictionary() : base() { } internal void Add(string issueReference, int rawRowNumber, bool v) { Add(issueReference, (rawRowNumber, v)); } } </code></pre> <p>In my code there are cases where I need to get the int Value part of the dictionary Element</p> <pre><code> var intValue = issueRowValidationDictionary['keyRef'].Item1; </code></pre> <p>Is there a more elegant way for Example to create a specific property that will only return the int part of the value. Any suggestions for improvement of my code are welcomed</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T15:07:08.747", "Id": "508852", "Score": "1", "body": "Far from PC but try `Dictionary<string, (int RowNumber, bool Value)>`, then try `issueRowValidationDictionary['keyRef'].RowNumber`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T18:53:53.613", "Id": "508886", "Score": "7", "body": "Don't inherit Dictionary. Don't use tuple. Define a simple data structure with two properties and on the consumer side work with the generic IDictionary<string, YourStruct>." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T14:45:47.577", "Id": "257619", "Score": "1", "Tags": [ "c#" ], "Title": "Inheriting from Dictionary class with tuple as value" }
257619
<p>Is there a better way to refactor my below code where I have many conditions in if and else statement</p> <p>The reason for refactoring is to make code cleaner and readable</p> <pre><code> public static PaymentOptions GetPaymentOptions_Auto(TestConfigurationCDO testConfiguration, int siteId) { var paymentOptions = new PaymentOptions(); var paymentOptionList = SitePaymentRepository.GetSitePaymentInfoBySiteId( testConfiguration, siteId); var lowestPriority = paymentOptionList.Min(x =&gt; x.Priority); var paymentAuto = paymentOptionList.Where(x =&gt; x.Priority == lowestPriority).FirstOrDefault(); if (paymentAuto.PaymentType == PaymentMethod.Klarna) { paymentOptions = new KlarnaOptions(); } else if (paymentAuto.PaymentType == PaymentMethod.PayPalDirect || paymentAuto.PaymentType == PaymentMethod.Braintree || paymentAuto.PaymentType == PaymentMethod.BankTransfer || paymentAuto.PaymentType == PaymentMethod.AdyenDropIn) { paymentOptions = new ClientCheckoutOptions() { paymentMethod = paymentAuto.PaymentType }; } else if (paymentAuto.PaymentType == PaymentMethod.PayPalExpress) { paymentOptions = new PaypalOptions(); } else { paymentOptions = new PaypalOptions(); } return paymentOptions; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:36:58.553", "Id": "508868", "Score": "0", "body": "@canton7 - Can you please help me?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T17:03:28.377", "Id": "508873", "Score": "0", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state the task accomplished by the code. Please see [How do I ask a good question?](https://codereview.stackexchange.com/help/how-to-ask), as well as [How to get the best value out of Code Review: Asking Questions](https://codereview.meta.stackexchange.com/q/2436/120114) for guidance on writing good question titles." } ]
[ { "body": "<ol>\n<li><p>Extract the statements into methods.\nLike:\n<code>paymentAuto.IsKlarnaPayment()</code></p>\n<p>This would shorten the <code>if</code> statements a bit.</p>\n</li>\n<li><p>At the end you have</p>\n<pre><code>else if (paymentAuto.PaymentType == PaymentMethod.PayPalExpress)\n{\n paymentOptions = **new PaypalOptions()**;\n}\nelse\n{\n paymentOptions = **new PaypalOptions()**;\n}\n</code></pre>\n<p>This returns the same <code>PaymentOption</code>. So it would be better to remove the last <code>else if</code> statement.</p>\n</li>\n<li><p><code>paymentAuto</code> can be null in this scenario (<strong><code>FirstOrDefault()</code></strong>). This can lead to null reference exception.</p>\n</li>\n<li><p>You can combine this:</p>\n<p><code>paymentOptionList.Where(x =&gt; x.Priority == lowestPriority).FirstOrDefault();</code></p>\n<p>into</p>\n<p><code>paymentOptionList.FirstOrDefault(x =&gt; x.Priority == lowestPriority);</code></p>\n</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T17:50:47.890", "Id": "508879", "Score": "0", "body": "Thank you for your answer...\n\n paymentOptionList.FirstOrDefault(x => x.Priority == lowestPriority);\n\nWorked wonders!!!!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:40:22.163", "Id": "257622", "ParentId": "257621", "Score": "1" } }, { "body": "<p>You've got lots of tests for <code>paymentAuto.PaymentType</code> there, and many of the cases are the same. A switch statement will neaten that up, as it only names <code>paymentAuto.PaymentType</code> once, and it encourages you to put all of the cases nicely aligned together in code:</p>\n<pre><code>public static PaymentOptions GetPaymentOptions_Auto(TestConfigurationCDO testConfiguration, int siteId)\n{\n var paymentOptionList = SitePaymentRepository.GetSitePaymentInfoBySiteId(\n testConfiguration,\n siteId);\n\n var lowestPriority = paymentOptionList.Min(x =&gt; x.Priority);\n var paymentAuto = paymentOptionList.First(x =&gt; x.Priority == lowestPriority);\n\n PaymentOptions paymentOptions;\n \n switch (paymentAuto.PaymentType)\n {\n case PaymentMethod.PayPalDirect:\n case PaymentMethod.Braintree:\n case PaymentMethod.BankTransfer:\n case PaymentMethod.AdyenDropIn:\n paymentOptions = new ClientCheckoutOptions()\n {\n paymentMethod = paymentAuto.PaymentType\n };\n break;\n\n case PaymentMethod.Klarna:\n paymentOptions = new KlarnaOptions();\n break;\n\n case PaymentMethod.PayPalExpress:\n default:\n paymentOptions = new PaypalOptions();\n break;\n }\n}\n</code></pre>\n<p>The initial value you were assigning to <code>paymentOptions</code> wasn't used, so you can leave that variable uninitialised. The compiler will moan at you if you forget to initialise it somewhere in the <code>switch</code> statement.</p>\n<p>That <code>.FirstOrDefault()</code> <em>shouldn't</em> fail to find a matching item. To make sure of this, I changed it to <code>.First()</code>, which throws an exception if it can't find a match. <code>.Where(...).First()</code> is the same as <code>.First(...)</code> (but a bit more expensive), so I changed that as well.</p>\n<p>Annoyingly there's no <code>.MinBy</code> method in Linq (there are plenty of examples of implementations around, though). If you have this, you can write <code>var paymentAuto = paymentOptionList.MinBy(x =&gt; x.Priority)</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:43:59.527", "Id": "508870", "Score": "0", "body": "Thank you @canton7 - This will work like charm!!!! and more readability and more simpler" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:59:24.913", "Id": "508872", "Score": "1", "body": "Not able to upvote it:(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T17:14:10.920", "Id": "508875", "Score": "0", "body": "How do I mark this question as resolved" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T17:16:04.350", "Id": "508876", "Score": "0", "body": "You've done that, by marking this answer as the accepted answer" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:41:48.393", "Id": "257623", "ParentId": "257621", "Score": "2" } } ]
{ "AcceptedAnswerId": "257622", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:34:17.777", "Id": "257621", "Score": "1", "Tags": [ "c#" ], "Title": "Is there a way to refactor the c# code having multiple conditions?" }
257621
<p>This is my first attempt at open source contribution via a Python discord bot, built to analyse user-uploaded log files and give quick, at-a-glance information for support staff.</p> <p>The PR is here: <a href="https://github.com/Ryujinx/ryuko-ng/pull/3" rel="nofollow noreferrer">https://github.com/Ryujinx/ryuko-ng/pull/3</a></p> <p>My main concerns are:</p> <ul> <li>Is this structured properly?</li> <li>What could I improve? I've attempted to make use of things like list comprehensions instead of relying too much on regex, but sometimes it's unavoidable.</li> <li>I've been reading into things like decorators, and wondering if they could be used here, but I've not grasped how to use them, or if they're even applicable here.</li> </ul> <p>Without further ado:</p> <pre class="lang-py prettyprint-override"><code>import logging from typing import Type import discord from discord.ext.commands import Cog import re import aiohttp import config logging.basicConfig( format=&quot;%(asctime)s (%(levelname)s) %(message)s (Line %(lineno)d)&quot;, level=logging.DEBUG, ) class LogFileReader(Cog): def __init__(self, bot): self.bot = bot # Allows log analysis in #support and #patreon-support channels respectively self.bot_log_allowed_channels = config.bot_log_allowed_channels self.uploaded_log_filenames = [] async def download_file(self, log_url): async with aiohttp.ClientSession() as session: # Grabs first and last few bytes of log file to prevent abuse from large files headers = {&quot;Range&quot;: &quot;bytes=0-25000, -6000&quot;} async with session.get(log_url, headers=headers) as response: return await response.text(&quot;UTF-8&quot;) async def log_file_read(self, message): self.embed = { &quot;hardware_info&quot;: { &quot;cpu&quot;: &quot;Unknown&quot;, &quot;gpu&quot;: &quot;Unknown&quot;, &quot;ram&quot;: &quot;Unknown&quot;, &quot;os&quot;: &quot;Unknown&quot;, }, &quot;emu_info&quot;: { &quot;ryu_version&quot;: &quot;Unknown&quot;, &quot;ryu_firmware&quot;: &quot;Unknown&quot;, &quot;logs_enabled&quot;: None, }, &quot;game_info&quot;: { &quot;game_name&quot;: &quot;Unknown&quot;, &quot;errors&quot;: &quot;No errors found in log&quot;, &quot;mods&quot;: &quot;No mods found&quot;, &quot;notes&quot;: [], }, &quot;user_settings&quot;: [ { &quot;pptc&quot;: &quot;Unknown&quot;, &quot;audio_backend&quot;: &quot;Unknown&quot;, &quot;docked&quot;: &quot;Unknown&quot;, &quot;vsync&quot;: &quot;Unknown&quot;, } ], } attached_log = message.attachments[0] author_name = f&quot;@{message.author.name}&quot; log_file = await self.download_file(attached_log.url) # Large files show a header value when not downloaded completely # this regex makes sure that the log text to read starts from the first timestamp, ignoring headers log_file_header_regex = re.compile(r&quot;\d{2}:\d{2}:\d{2}\.\d{3}.*&quot;, re.DOTALL) log_file = re.search(log_file_header_regex, log_file).group(0) def get_hardware_info(log_file): try: self.embed[&quot;hardware_info&quot;][&quot;cpu&quot;] = ( re.search(r&quot;CPU:\s([^;\r]*)&quot;, log_file, re.MULTILINE) .group(1) .rstrip() ) self.embed[&quot;hardware_info&quot;][&quot;ram&quot;] = ( re.search(r&quot;RAM:(\sTotal)?\s([^;\r]*)&quot;, log_file, re.MULTILINE) .group(2) .rstrip() ) self.embed[&quot;hardware_info&quot;][&quot;os&quot;] = ( re.search(r&quot;Operating System:\s([^;\r]*)&quot;, log_file, re.MULTILINE) .group(1) .rstrip() ) self.embed[&quot;hardware_info&quot;][&quot;gpu&quot;] = ( re.search( r&quot;PrintGpuInformation:\s([^;\r]*)&quot;, log_file, re.MULTILINE ) .group(1) .rstrip() ) except AttributeError: pass def get_ryujinx_info(log_file): try: self.embed[&quot;emu_info&quot;][&quot;ryu_version&quot;] = [ line.split()[-1] for line in log_file.splitlines() if &quot;Ryujinx Version:&quot; in line ][0] self.embed[&quot;emu_info&quot;][&quot;logs_enabled&quot;] = ( re.search(r&quot;Logs Enabled:\s([^;\r]*)&quot;, log_file, re.MULTILINE) .group(1) .rstrip() ) self.embed[&quot;emu_info&quot;][&quot;ryu_firmware&quot;] = [ line.split()[-1] for line in log_file.splitlines() if &quot;Firmware Version:&quot; in line ][0] except (AttributeError, IndexError): pass def format_log_embed(): cleaned_game_name = re.sub( r&quot;\s\[(64|32)-bit\]$&quot;, &quot;&quot;, self.embed[&quot;game_info&quot;][&quot;game_name&quot;] ) self.embed[&quot;game_info&quot;][&quot;game_name&quot;] = cleaned_game_name hardware_info = &quot;\n&quot;.join( ( f&quot;**CPU:** {self.embed['hardware_info']['cpu']}&quot;, f&quot;**GPU:** {self.embed['hardware_info']['gpu']}&quot;, f&quot;**RAM:** {self.embed['hardware_info']['ram']}&quot;, f&quot;**OS:** {self.embed['hardware_info']['os']}&quot;, ) ) user_settings_info = &quot;\n&quot;.join( ( f&quot;**Audio Backend:** `{self.embed['user_settings'][0]['audio_backend']}`&quot;, f&quot;**Console Mode:** `{self.embed['user_settings'][0]['docked']}`&quot;, f&quot;**PPTC:** `{self.embed['user_settings'][0]['pptc']}`&quot;, f&quot;**V-Sync:** `{self.embed['user_settings'][0]['vsync']}`&quot;, ) ) ryujinx_info = &quot;\n&quot;.join( ( f&quot;**Version:** {self.embed['emu_info']['ryu_version']}&quot;, f&quot;**Firmware:** {self.embed['emu_info']['ryu_firmware']}&quot;, ) ) log_embed = discord.Embed( title=f&quot;{cleaned_game_name}&quot;, colour=discord.Colour(0x4A90E2) ) log_embed.set_footer(text=f&quot;Log uploaded by {author_name}&quot;) log_embed.add_field(name=&quot;Hardware Info&quot;, value=hardware_info) log_embed.add_field(name=&quot;Ryujinx Info&quot;, value=ryujinx_info) if cleaned_game_name == &quot;Unknown&quot;: log_embed.add_field( name=&quot;Empty Log&quot;, value=&quot;&quot;&quot;This log file appears to be empty. To get a proper log, follow these steps: \n 1) Start a game up. \n 2) Play until your issue occurs. \n 3) Upload your log file.&quot;&quot;&quot;, inline=False, ) log_embed.add_field( name=&quot;Settings&quot;, value=user_settings_info, inline=False, ) log_embed.add_field( name=&quot;Latest Error Snippet&quot;, value=self.embed[&quot;game_info&quot;][&quot;errors&quot;], inline=False, ) log_embed.add_field( name=&quot;Mods&quot;, value=self.embed[&quot;game_info&quot;][&quot;mods&quot;], inline=False ) log_embed.add_field( name=&quot;Notes&quot;, value=&quot;\n&quot;.join(game_notes), inline=False, ) return log_embed def analyse_log(log_file): self.embed[&quot;game_info&quot;][&quot;game_name&quot;] = ( re.search( r&quot;Loader LoadNca: Application Loaded:\s([^;\r]*)&quot;, log_file, re.MULTILINE, ) .group(1) .rstrip() ) for setting in self.embed[&quot;user_settings&quot;]: # Some log info may be missing for users that use older versions of Ryujinx, so reading the settings is not always possible. # As ['user_setting'] is initialized with &quot;Unknown&quot; values, False should not be an issue for setting.get() try: switch_mode = [ line.split()[-1] for line in log_file.splitlines() if &quot;IsDocked&quot; in line ][-1] if switch_mode and setting.get(&quot;docked&quot;): setting[ &quot;docked&quot; ] = f&quot;{'Docked' if switch_mode == 'True' else 'Handheld'}&quot; pptc_setting = re.search( r&quot;Ptc Initialize:.+\(enabled:\s(.+?)\)[^;\r]&quot;, log_file, re.MULTILINE, ).group(1) if pptc_setting and setting.get(&quot;pptc&quot;): setting[ &quot;pptc&quot; ] = f&quot;{'Enabled' if pptc_setting == 'True' else 'Disabled'}&quot; audio_setting = [ line.split()[-1] for line in log_file.splitlines() if &quot;AudioBackend&quot; in line ][-1] if audio_setting and setting.get(&quot;audio_backend&quot;): setting[&quot;audio_backend&quot;] = audio_setting # Take note of the difference between 'Vsync' and 'VSyncStatus' capitalization in both initial and toggle settings vsync_setting = [ line.split()[-1] for line in log_file.splitlines() if &quot;Vsync&quot; in line or &quot;VSyncStatus_Clicked&quot; in line ][-1] if vsync_setting and setting.get(&quot;vsync&quot;): setting[ &quot;vsync&quot; ] = f&quot;{'Enabled' if vsync_setting == 'True' else 'Disabled'}&quot; except (AttributeError, IndexError) as error: print(f&quot;User settings exception: {logging.warn(error)}&quot;) continue def analyse_error_message(log_file): try: errors = [] curr_error_lines = [] for line in log_file.splitlines(): if line == &quot;&quot;: continue if &quot;|E|&quot; in line: curr_error_lines = [line] errors.append(curr_error_lines) elif line[0] == &quot; &quot; or line == &quot;&quot;: curr_error_lines.append(line) shader_cache_collision = bool( [ line for line in errors if any(&quot;Cache collision found&quot; in string for string in line) ] ) last_errors = &quot;\n&quot;.join( errors[-1][:2] if &quot;|E|&quot; in errors[-1][0] else &quot;&quot; ) except IndexError: last_errors = None return (last_errors, shader_cache_collision) # Finds the lastest error denoted by |E| in the log and its first line # Also warns of shader cache collisions last_error_snippet, shader_cache_warn = analyse_error_message(log_file) if last_error_snippet: self.embed[&quot;game_info&quot;][&quot;errors&quot;] = f&quot;```{last_error_snippet}```&quot; else: pass if shader_cache_warn: shader_cache_warn = f&quot;⚠️ Cache collision detected. Investigate possible shader cache issues&quot; self.embed[&quot;game_info&quot;][&quot;notes&quot;].append(shader_cache_warn) def mods_information(log_file): mods_regex = re.compile(r&quot;Found mod\s\'(.+?)\'\s(\[.+?\])&quot;) matches = re.findall(mods_regex, log_file) if matches: mods = [{&quot;mod&quot;: match[0], &quot;status&quot;: match[1]} for match in matches] mods_status = [ f&quot;ℹ️ {i['mod']} ({'ExeFS' if i['status'] == '[E]' else 'RomFS'})&quot; for i in mods ] return mods_status # Find information on installed mods game_mods = mods_information(log_file) if game_mods: self.embed[&quot;game_info&quot;][&quot;mods&quot;] = &quot;\n&quot;.join(game_mods) else: pass controllers_regex = re.compile(r&quot;Hid Configure: ([^\r\n]+)&quot;) controllers = re.findall(controllers_regex, log_file) if controllers: input_status = [f&quot;ℹ {match}&quot; for match in controllers] # Hid Configure lines can appear multiple times, so converting to dict keys removes duplicate entries, # also maintains the list order input_status = list(dict.fromkeys(input_status)) input_string = &quot;\n&quot;.join(input_status) else: input_string = &quot;⚠️ No controller information found&quot; self.embed[&quot;game_info&quot;][&quot;notes&quot;].append(input_string) try: ram_avaliable_regex = re.compile(r&quot;Available\s(\d+)(?=\sMB)&quot;) ram_avaliable = re.search(ram_avaliable_regex, log_file)[1] if int(ram_avaliable) &lt; 8000: ram_warning = &quot;⚠️ Less than 8GB RAM avaliable&quot; self.embed[&quot;game_info&quot;][&quot;notes&quot;].append(ram_warning) except TypeError: pass if &quot;Darwin&quot; in self.embed[&quot;hardware_info&quot;][&quot;os&quot;]: mac_os_warning = &quot;**❌ macOS is currently unsupported**&quot; self.embed[&quot;game_info&quot;][&quot;notes&quot;].append(mac_os_warning) if &quot;Intel&quot; in self.embed[&quot;hardware_info&quot;][&quot;gpu&quot;]: if ( &quot;Darwin&quot; in self.embed[&quot;hardware_info&quot;][&quot;os&quot;] or &quot;Windows&quot; in self.embed[&quot;hardware_info&quot;][&quot;os&quot;] ): intel_gpu_warning = &quot;**⚠️ Intel iGPUs are known to have driver issues, consider using a discrete GPU**&quot; self.embed[&quot;game_info&quot;][&quot;notes&quot;].append(intel_gpu_warning) # Find information on logs, whether defaults are enabled or not default_logs = [&quot;Info&quot;, &quot;Warning&quot;, &quot;Error&quot;, &quot;Guest&quot;, &quot;Stub&quot;] user_logs = ( self.embed[&quot;emu_info&quot;][&quot;logs_enabled&quot;] .rstrip() .replace(&quot; &quot;, &quot;&quot;) .split(&quot;,&quot;) ) disabled_logs = set(default_logs).difference(set(user_logs)) if disabled_logs: logs_status = [f&quot;⚠️ {log} log is not enabled&quot; for log in disabled_logs] log_string = &quot;\n&quot;.join(logs_status) else: log_string = &quot;✅ Default logs enabled&quot; self.embed[&quot;game_info&quot;][&quot;notes&quot;].append(log_string) if self.embed[&quot;emu_info&quot;][&quot;ryu_firmware&quot;] == &quot;Unknown&quot;: firmware_warning = f&quot;**❌ Nintendo Switch firmware not found**&quot; self.embed[&quot;game_info&quot;][&quot;notes&quot;].append(firmware_warning) def severity(log_note_string): symbols = [&quot;❌&quot;, &quot;⚠️&quot;, &quot;ℹ&quot;, &quot;✅&quot;] return next( i for i, symbol in enumerate(symbols) if symbol in log_note_string ) game_notes = [note for note in self.embed[&quot;game_info&quot;][&quot;notes&quot;]] ordered_game_notes = sorted(game_notes, key=severity) return ordered_game_notes get_hardware_info(log_file) get_ryujinx_info(log_file) game_notes = analyse_log(log_file) return format_log_embed() @Cog.listener() async def on_message(self, message): await self.bot.wait_until_ready() if message.author.bot: return # If message has an attachment try: author_mention = message.author.mention filename = message.attachments[0].filename # Any message over 2000 chars is uploaded as message.txt, so this is accounted for log_file_regex = re.compile(r&quot;^Ryujinx_.*\.log|message\.txt$&quot;) is_log_file = re.match(log_file_regex, filename) if message.channel.id in self.bot_log_allowed_channels and is_log_file: if filename not in self.uploaded_log_filenames: reply_message = await message.channel.send( &quot;Log detected, parsing...&quot; ) try: embed = await self.log_file_read(message) if &quot;Ryujinx_&quot; in filename: self.uploaded_log_filenames.append(filename) # Avoid duplicate log file analysis, at least temporarily; keep track of the last few filenames of uploaded logs # this should help support channels not be flooded with too many log files # fmt: off self.uploaded_log_filenames = self.uploaded_log_filenames[-5:] # fmt: on return await reply_message.edit(content=None, embed=embed) except UnicodeDecodeError: return await message.channel.send( f&quot;This log file appears to be invalid {author_mention}. Please re-check and re-upload your log file.&quot; ) except Exception as error: await reply_message.edit( content=f&quot;Error: Couldn't parse log; parser threw {type(error).__name__} exception.&quot; ) print(logging.warn(error)) else: await message.channel.send( f&quot;The log file `{filename}` appears to be a duplicate {author_mention}. Please upload a more recent file.&quot; ) elif not is_log_file: return await message.channel.send( f&quot;{author_mention} Your file does not match the Ryujinx log format. Please check your file.&quot; ) else: return await message.channel.send( f&quot;{author_mention} Please upload log files to {' or '.join([f'&lt;#{id}&gt;' for id in self.bot_log_allowed_channels])}&quot; ) except IndexError: pass def setup(bot): bot.add_cog(LogFileReader(bot)) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T16:47:00.230", "Id": "257625", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Nintendo Switch emulator log analysis Discord bot" }
257625
<p>Please review my php paypal payment gateway code.</p> <p>Are there any bugs in the code? Any security risks? How could this code be improved?</p> <p>Brief instructions to be able to run the code:</p> <ol> <li>install xampp and configure</li> <li>create directory within htdocs dir named innovations-r-us</li> <li>cd into innovations-r-us and run cmd: composer require paypal/rest-api-sdk-php</li> <li>Copy php files below into the innovations-r-us folder.</li> <li>To be able to use the email facility may require some xampp tweaking.</li> <li>You will need to have a merchant Paypal account and setup a sandbox for testing.</li> </ol> <p>paymentdemo.php:</p> <pre><code>&lt;?php session_start(); require __DIR__ . '/vendor/autoload.php'; require 'CreateOrder.php'; require 'CaptureOrder.php'; use PaypalHelpers\CreateOrder; use PaypalHelpers\CaptureOrder; define('FROM_EMAIL', 'Example Person &lt;person@example.com&gt;'); define('TO_EMAIL', 'Example Recipient &lt;recipient@example.com&gt;'); function GetRequestScheme() { if ( (! empty($_SERVER['REQUEST_SCHEME']) &amp;&amp; $_SERVER['REQUEST_SCHEME'] == 'https') || (! empty($_SERVER['HTTPS']) &amp;&amp; $_SERVER['HTTPS'] == 'on') || (! empty($_SERVER['SERVER_PORT']) &amp;&amp; $_SERVER['SERVER_PORT'] == '443') ) { return 'https'; } else { return 'http'; } } function ProcessOrder($brand, $referenceid, $description, $currencycode, $amount) { $return_url = GetRequestScheme() . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']; $error_url = GetRequestScheme() . '://' . $_SERVER['HTTP_HOST'] . '/innovations-r-us/paymenterror.php'; $order = CreateOrder::createOrder($return_url, // 'https://localhost/innovations-r-us/paymentdemo.php' $error_url, // 'https://localhost/innovations-r-us/paymenterror.php' $brand, // 'Fab Toasters' $referenceid, // 'TOAST7' $description, // 'Toasters that really toast' $currencycode, // 'GBP' $amount); // '5.00' if ($order-&gt;statusCode == 201) { $_SESSION['orderid'] = $order-&gt;result-&gt;id; for ($i = 0; $i &lt; count($order-&gt;result-&gt;links); ++$i) { $link = $order-&gt;result-&gt;links[$i]; if ($link -&gt;rel == &quot;approve&quot; ) { $_SESSION['approvelink'] = $link-&gt;href; break; } } // redirect to Paypal buy page header(&quot;location: &quot; . $_SESSION['approvelink']); } else { echo &quot;An error occurred, createOrder returned: $order-&gt;statusCode&quot;; } } function EmailOrder($subject, $message) { $to = TO_EMAIL; $headers = &quot;MIME-Version: 1.0&quot; . &quot;\r\n&quot;; $headers .= 'Content-Type: text/plain; charset=utf-8' . &quot;\r\n&quot;; $headers .= 'From: ' . FROM_EMAIL . &quot;\r\n&quot;; mail($to,$subject,$message,$headers); } // user clicked buy button if (isset($_POST['buy'])) { ProcessOrder($_POST['brand'], $_POST['referenceid'], $_POST['description'], $_POST['currencycode'], $_POST['amount']); } // when called back by Paypal PayerID GET param set and orderid should be saved from ProcessOrder if (isset($_GET['PayerID']) &amp;&amp; isset($_SESSION['orderid'])) { // if we have been called back by Paypal gateway, then we capture the order $response = CaptureOrder::captureOrder($_SESSION['orderid']); if ($response-&gt;statusCode == 201) { $_SESSION['orderstatus'] = $response-&gt;result-&gt;status; $_SESSION['orderjson'] = $response-&gt;result; EmailOrder('New order for product', &quot;Order details\n&quot; . json_encode($response-&gt;result)); session_destroy(); } } ?&gt; &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Paypal Create Order Demo&lt;/title&gt; &lt;style&gt; label { display: inline-block; width: 110px; } input[type=text] { width: 75%; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Paypal Create Order Demo&lt;/h1&gt; &lt;p&gt;demo of creating an order then redirecting so that customer can confirm order via paypal&lt;/p&gt; &lt;form method=&quot;POST&quot;&gt; &lt;label for=&quot;amount&quot;&gt;Amount: &lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;amount&quot; value=&quot;5.00&quot;&gt; &lt;br&gt; &lt;label for=&quot;brand&quot;&gt;Brand name: &lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;brand&quot; value=&quot;Innovations R Us Widget X&quot;&gt; &lt;br&gt; &lt;label for=&quot;referenceid&quot;&gt;Reference ID: &lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;referenceid&quot; value=&quot;WIDGETX&quot;&gt; &lt;br&gt; &lt;label for=&quot;description&quot;&gt;Description: &lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;description&quot; value=&quot;Does widget X type things you won&amp;apos;t believe&quot;&gt; &lt;br&gt; &lt;label for=&quot;currencycode&quot;&gt;Currency Code: &lt;/label&gt; &lt;input type=&quot;text&quot; name=&quot;currencycode&quot; value=&quot;GBP&quot;&gt; &lt;br&gt; &lt;input type=&quot;submit&quot; name=&quot;buy&quot; value=&quot;Buy&quot;&gt; &lt;/form&gt; &lt;div id=&quot;status&quot;&gt; &lt;?php if (isset($_GET['PayerID']) &amp;&amp; isset($_SESSION['orderstatus']) ) { echo 'PayerId: ' . $_GET['PayerID'] . ', Order status: ' . $_SESSION['orderstatus']; } ?&gt; &lt;/div&gt; &lt;div id=&quot;responsejson&quot;&gt; &lt;?php if ( isset($_SESSION['orderjson']) ) { echo json_encode($_SESSION['orderjson'], JSON_PRETTY_PRINT), &quot;\n&quot;; } ?&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>paymenterror.php:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Paypal Order Error&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Order Processing Error Encountered&lt;/h1&gt; &lt;p&gt;An error occurred processing your order. Please follow the link below to retry&lt;/p&gt; &lt;a href=&quot;paymentdemo.php&quot;&gt;Back to Payment Demo&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The other php files are small changes to samples provided.</p> <p>CaptureOrder.php:</p> <pre><code>&lt;?php namespace PaypalHelpers; require __DIR__ . '/vendor/autoload.php'; use PaypalHelpers\PayPalClient; use PayPalCheckoutSdk\Orders\OrdersCaptureRequest; class CaptureOrder { /** * This function can be used to capture an order payment by passing the approved * order id as argument. * * @param orderId * @param debug * @returns */ public static function captureOrder($orderId, $debug=false) { $request = new OrdersCaptureRequest($orderId); $client = PayPalClient::client(); $response = $client-&gt;execute($request); if ($debug) { print &quot;Status Code: {$response-&gt;statusCode}\n&quot;; print &quot;Status: {$response-&gt;result-&gt;status}\n&quot;; print &quot;Order ID: {$response-&gt;result-&gt;id}\n&quot;; print &quot;Links:\n&quot;; foreach($response-&gt;result-&gt;links as $link) { print &quot;\t{$link-&gt;rel}: {$link-&gt;href}\tCall Type: {$link-&gt;method}\n&quot;; } print &quot;Capture Ids:\n&quot;; foreach($response-&gt;result-&gt;purchase_units as $purchase_unit) { foreach($purchase_unit-&gt;payments-&gt;captures as $capture) { print &quot;\t{$capture-&gt;id}&quot;; } } // To toggle printing the whole response body comment/uncomment below line echo json_encode($response-&gt;result, JSON_PRETTY_PRINT), &quot;\n&quot;; } return $response; } } </code></pre> <p>CreateOrder.php:</p> <pre><code>&lt;?php namespace PaypalHelpers; //namespace Sample\CaptureIntentExamples; require __DIR__ . '/vendor/autoload.php'; require_once 'PayPalClient.php'; use PaypalHelpers\PayPalClient; use PayPalCheckoutSdk\Orders\OrdersCreateRequest; class CreateOrder { /** * Setting up the JSON request body for creating the Order. The Intent in the * request body should be set as &quot;CAPTURE&quot; for capture intent flow. * */ private static function buildRequestBody($return_url, $cancel_url, $brand_name, $reference_id, $description, $currency_code, $amount) { return array( 'intent' =&gt; 'CAPTURE', 'application_context' =&gt; array( 'return_url' =&gt; $return_url, 'cancel_url' =&gt; $cancel_url, 'brand_name' =&gt; $brand_name, 'locale' =&gt; 'en-US', 'landing_page' =&gt; 'BILLING', 'shipping_preference' =&gt; 'NO_SHIPPING', 'user_action' =&gt; 'PAY_NOW', ), 'purchase_units' =&gt; array( 0 =&gt; array( 'reference_id' =&gt; $reference_id, 'description' =&gt; $description, 'amount' =&gt; array( 'currency_code' =&gt; $currency_code, 'value' =&gt; $amount, 'breakdown' =&gt; array( 'item_total' =&gt; array( 'currency_code' =&gt; $currency_code, 'value' =&gt; $amount, ), ), ), ), ), ); } /** * This is the sample function which can be sued to create an order. It uses the * JSON body returned by buildRequestBody() to create an new Order. */ public static function createOrder($return_url, $cancel_url, $brand_name, $reference_id, $description, $currency_code, $amount, $debug=false) { $request = new OrdersCreateRequest(); $request-&gt;headers[&quot;prefer&quot;] = &quot;return=representation&quot;; $request-&gt;body = self::buildRequestBody($return_url, $cancel_url, $brand_name, $reference_id, $description, $currency_code, $amount); $client = PayPalClient::client(); $response = $client-&gt;execute($request); if ($debug) { print &quot;Status Code: {$response-&gt;statusCode}\n&quot;; print &quot;Status: {$response-&gt;result-&gt;status}\n&quot;; print &quot;Order ID: {$response-&gt;result-&gt;id}\n&quot;; print &quot;Intent: {$response-&gt;result-&gt;intent}\n&quot;; print &quot;Links:\n&quot;; foreach($response-&gt;result-&gt;links as $link) { print &quot;\t{$link-&gt;rel}: {$link-&gt;href}\tCall Type: {$link-&gt;method}\n&quot;; } // To toggle printing the whole response body comment/uncomment below line echo json_encode($response-&gt;result, JSON_PRETTY_PRINT), &quot;\n&quot;; } return $response; } } </code></pre> <p>PayPalClient.php:</p> <pre><code>&lt;?php namespace PaypalHelpers; use PayPalCheckoutSdk\Core\PayPalHttpClient; use PayPalCheckoutSdk\Core\SandboxEnvironment; use PayPalCheckoutSdk\Core\ProductionEnvironment; ini_set('error_reporting', E_ALL); // or error_reporting(E_ALL); ini_set('display_errors', '1'); ini_set('display_startup_errors', '1'); class PayPalClient { private static $envType = &quot;sandbox&quot;; // change to &quot;production&quot; to use for real /** * Returns PayPal HTTP client instance with environment which has access * credentials context. This can be used invoke PayPal API's provided the * credentials have the access to do so. */ public static function client() { return new PayPalHttpClient(self::environment()); } /** * Setting up and Returns PayPal SDK environment with PayPal Access credentials. * For demo purpose, we are using SandboxEnvironment. In production this will be * ProductionEnvironment. */ public static function environment() { if (self::$envType == &quot;sandbox&quot;) { $clientId = getenv(&quot;CLIENT_ID&quot;) ?: &quot;Enter your sandbox client ID here&quot;; $clientSecret = getenv(&quot;CLIENT_SECRET&quot;) ?: &quot;Enter your sandbox client secret here&quot;; return new SandboxEnvironment($clientId, $clientSecret); } else if (self::$envType == &quot;production&quot;) { $clientId = getenv(&quot;CLIENT_ID&quot;) ?: &quot;&lt;&lt;Production client ID&gt;&gt;&quot;; $clientSecret = getenv(&quot;CLIENT_SECRET&quot;) ?: &quot;&lt;&lt;Production secret&gt;&gt;&quot;; return new ProductionEnvironment($clientId, $clientSecret); } else { echo &quot;!!! Error: environment not set!!!&quot;; } } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T17:40:39.783", "Id": "257626", "Score": "0", "Tags": [ "php", "e-commerce" ], "Title": "PHP paypal payment processing code" }
257626
<p>Given two vectors of ints, write a program to determine whether one vector is a prefix of the other.</p> <ul> <li>For vectors of unequal length, compare the number of elements of the smaller vector.</li> <li>For example, given the vectors containing 0, 1, 1, 2, and 0, 1, 1, 2, 3, 5, 8, respectively, your program should return true.</li> </ul> <hr /> <pre class="lang-cpp prettyprint-override"><code>#include &lt;vector&gt; #include &lt;iostream&gt; int main() { const std::vector&lt;int&gt; ivec1 = { 0, 1, 1, 2 }; const std::vector&lt;int&gt; ivec2 = { 0, 1, 1, 2, 3, 5, 8 }; const decltype(ivec1.size()) size = ivec1.size() &lt; ivec2.size() ? ivec1.size() : ivec2.size(); const std::vector&lt;int&gt;&amp; smallVec = ivec1.size() &lt; ivec2.size() ? ivec1 : ivec2; const std::vector&lt;int&gt;&amp; bigVec = smallVec == ivec1 ? ivec2 : ivec1; bool bPrefix = true; for(decltype(ivec1.size()) i = 0; i &lt; size; ++i) { if(smallVec[i] != bigVec[i]) { bPrefix = false; break; } } std::cout &lt;&lt; &quot;small vector:\n&quot;; for (const auto i : smallVec) std::cout &lt;&lt; i &lt;&lt; &quot;, &quot;; std::cout &lt;&lt; &quot;\nIs prefix of big vector:\n&quot;; for (const auto i : bigVec) std::cout &lt;&lt; i &lt;&lt; &quot;, &quot;; std::cout &lt;&lt; &quot;\n&quot; &lt;&lt; (bPrefix ? &quot;true&quot; : &quot;false&quot;) &lt;&lt; std::endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T15:26:48.647", "Id": "508961", "Score": "0", "body": "The title is a bit ambiguous. Do you mean that for two vectors you need to figure out which is a prefix, or **if** one is a prefix of the other? If so, do you need to tell which one?" } ]
[ { "body": "<pre><code>const decltype(ivec1.size()) size = ivec1.size() &lt; ivec2.size() ? ivec1.size() : ivec2.size();\n</code></pre>\n<p>Could just be:</p>\n<pre><code>const auto size = std::min(ivec1.size(), ivec2.size());\n</code></pre>\n<hr />\n<pre><code>const std::vector&lt;int&gt;&amp; bigVec = smallVec == ivec1 ? ivec2 : ivec1;\n</code></pre>\n<p><code>operator==</code> for <code>std::vector</code> doesn't compare the reference, it checks that the contents of the two vectors are the same. (i.e. it checks the length, then iterates through every element). This isn't what we want.</p>\n<hr />\n<p>We can use the <code>&lt;algorithm&gt;</code> header to do this task more easily:</p>\n<p>For example <a href=\"https://en.cppreference.com/w/cpp/algorithm/equal\" rel=\"noreferrer\"><code>std::equal</code></a>:</p>\n<pre><code>auto const size = std::min(ivec1.size(), ivec2.size());\nauto const is_prefix = std::equal(ivec1.begin(), ivec1.begin() + size, ivec2.begin(), ivec2.begin() + size);\n</code></pre>\n<p>or <a href=\"https://en.cppreference.com/w/cpp/algorithm/mismatch\" rel=\"noreferrer\"><code>std::mismatch</code></a>:</p>\n<pre><code>auto const mismatch = std::mismatch(ivec1.begin(), ivec1.end(), ivec2.begin(), ivec2.end());\nauto const is_prefix = (mismatch.first == ivec1.end() || mismatch.second == ivec2.end());\n</code></pre>\n<p>(Note that before C++14, we would have to ensure that the first sequence passed to <code>std::mismatch</code> was shorter than the second. Afterwards, it doesn't matter).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:11:48.553", "Id": "509002", "Score": "1", "body": "Yes - `std::mismatch` is the tool for this job. No need to even look at the size." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T19:20:56.473", "Id": "257633", "ParentId": "257629", "Score": "5" } }, { "body": "<p>The review from user673679 is good and covers most of the important points. If you have a C++20 compiler, you can get even better compiler optimizations using <code>std::ranges</code>. Here's an example:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;array&gt;\n#include &lt;iterator&gt;\n#include &lt;iostream&gt;\n#include &lt;ranges&gt;\n\nint main()\n{\n constexpr std::array&lt;int, 4&gt; vec1{ 0, 1, 1, 2 };\n constexpr std::array&lt;int, 7&gt; vec2{ 0, 1, 1, 2, 3, 5, 8 };\n constexpr auto minsize = std::min(vec1.size(), vec2.size());\n constexpr auto result{std::ranges::equal(vec1 | std::views::take(minsize),\n vec2 | std::views::take(minsize))};\n\n#if PRINT_RESULTS\n std::cout &lt;&lt; &quot;vec1 = { &quot;;\n std::copy(vec1.begin(), vec1.end(), std::ostream_iterator&lt;int&gt;{std::cout, &quot;, &quot;});\n std::cout &lt;&lt; &quot;}\\nvec2 = { &quot;;\n std::copy(vec2.begin(), vec2.end(), std::ostream_iterator&lt;int&gt;{std::cout, &quot;, &quot;});\n std::cout &lt;&lt; &quot;}\\nisPrefix = &quot; &lt;&lt; std::boolalpha &lt;&lt; result &lt;&lt; '\\n';\n#else\n return result;\n#endif\n}\n</code></pre>\n<p><a href=\"http://coliru.stacked-crooked.com/a/4bc819538d9e36d7\" rel=\"noreferrer\">Try it live</a> on CoLiRu.</p>\n<p>Even more fun is that because everything is <code>constexpr</code> here, all of the calculation is done at compile time. Here is <a href=\"https://godbolt.org/z/raGEqcMfE\" rel=\"noreferrer\">an example</a> that shows that the <code>main</code> above that simply returns the result is literally two machine language instructions!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T23:46:55.017", "Id": "508900", "Score": "1", "body": "You could also use `std::ranges::copy`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T20:17:45.397", "Id": "257635", "ParentId": "257629", "Score": "6" } }, { "body": "<ol>\n<li><p>Embrace <code>auto</code>. Not only is it shorter, but avoids embarrassing bugs in choosing the wrong type.<br />\n<code>decltype()</code> is generally much more cumbersome.</p>\n</li>\n<li><p>Embrace abstraction. Solving the task itself deserves its own re-usable function. Good naming even reduces the need for comments, which can get out-of-sync.</p>\n</li>\n<li><p>Embrace the standard library. It is well-tested and well-known. Reinventing wheels for no reason is a poor use of time.</p>\n</li>\n<li><p>You refrained from using <code>std::endl</code> until your last line. No need to use it at all, ending the program flushed the output too.</p>\n</li>\n<li><p><code>std::boolalpha</code> is the tool of choice for streaming a <code>bool</code> as <code>&quot;true&quot;</code> or <code>&quot;false&quot;</code>.</p>\n</li>\n<li><p>Combine <code>std::copy()</code> and <code>std::ostream_iterator</code> for streaming an iterator-range.</p>\n</li>\n</ol>\n<pre><code>#include &lt;vector&gt;\n#include &lt;iostream&gt;\n#include &lt;algorithm&gt;\n\ntemplate &lt;class T, class U&gt;\nconstexpr bool is_shorter_prefix(const T&amp; a, const U&amp; b) noexcept {\n const auto n = std::min(std::size(a), std::size(b));\n return std::equal(std::begin(a), std::begin(a) + n, std::begin(b));\n}\n\ntemplate &lt;class T&gt;\nvoid output_range(std::ostream&amp; os, const T&amp; t) {\n using U = decltype(*std::begin(t));\n std::copy(std::begin(t), std::end(t), std::ostream_iterator&lt;U&gt;(os, &quot;, &quot;));\n}\n\nint main() {\n const std::vector&lt;int&gt; a = { 0, 1, 1, 2 };\n const std::vector&lt;int&gt; b = { 0, 1, 1, 2, 3, 5, 8 };\n\n const auto is_prefix = is_shorter_prefix(a, b);\n\n std::cout &lt;&lt; &quot;small vector:\\n&quot;;\n output_range(std::cout, a.size() &lt;= b.size() ? a : b);\n std::cout &lt;&lt; &quot;\\nIs prefix of big vector:\\n&quot;;\n output_range(std::cout, a.size() &gt; b.size() ? a : b);\n std::cout &lt;&lt; &quot;\\n&quot; &lt;&lt; std::boolalpha &lt;&lt; is_prefix &lt;&lt; &quot;\\n&quot;;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T20:23:39.727", "Id": "257637", "ParentId": "257629", "Score": "9" } }, { "body": "<p>The problem statement in the question says</p>\n<blockquote>\n<ul>\n<li>For example, given the vectors containing <code>0, 1, 1, 2</code> and <code>0, 1, 1, 2, 3, 5, 8</code> respectively, your program should return true.</li>\n</ul>\n</blockquote>\n<p>The implication is that your program should <em>return false</em> if neither vector is a prefix of the other. In C++, we do that by returning <code>EXIT_FAILURE</code>, or indeed any non-zero value.</p>\n<p>The simplest means to achieve that is to add</p>\n<pre><code>return !bPrefix;\n</code></pre>\n<p>at the end of <code>main()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:16:34.017", "Id": "257694", "ParentId": "257629", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T17:59:41.163", "Id": "257629", "Score": "4", "Tags": [ "c++", "vectors", "iteration" ], "Title": "Given two vectors of ints, determine whether one vector is a prefix of the other" }
257629
<p>I'm working on a solution that is correct but inefficient.</p> <p><a href="https://app.codility.com/programmers/task/leader_slice_inc/" rel="nofollow noreferrer">https://app.codility.com/programmers/task/leader_slice_inc/</a></p> <p>This is my code :</p> <pre><code>public static void main(String[] args) { int[] A = { 2, 1, 3, 1, 2, 2, 3 }; int[] B = null; int M = 5, K = 3; int array_lengh = A.length; Map&lt;Integer, Integer&gt; counter = null; Set&lt;Integer&gt; listaLideres = new LinkedHashSet&lt;Integer&gt;(); // valor minimo =0 ; valor maximo = Longitud del array - k; // el lider sera aquel que ocurra mas de longitud/2 for (int i = 0; i &lt; array_lengh - K + 1; i++) { B = Arrays.copyOf(A, array_lengh); counter = new HashMap&lt;Integer, Integer&gt;(); for (int j = i; j &lt; i + K; j++) { B[j] = B[j] + 1; } for (int n = 0; n &lt; array_lengh; n++) { int repeticones = counter.get(B[n]) == null ? 0 : counter.get(B[n]); counter.put(B[n], repeticones + 1); } int liderProvisional = 0; for (Map.Entry&lt;Integer, Integer&gt; valorRepeticion : counter.entrySet()) { liderProvisional = valorRepeticion.getValue(); if (liderProvisional &gt; array_lengh / 2) { listaLideres.add(valorRepeticion.getKey()); } } } List&lt;Integer&gt; listaLideresOrdenada = new ArrayList&lt;Integer&gt;(); listaLideresOrdenada.addAll(listaLideres); listaLideresOrdenada.sort(Comparator.naturalOrder()); for (Integer integer : listaLideresOrdenada) { System.out.println(integer); } } </code></pre>
[]
[ { "body": "<p>Nice solution, find below my suggestions.</p>\n<hr />\n<p>Creating a list from a set:</p>\n<pre><code>List&lt;Integer&gt; listaLideresOrdenada = new ArrayList&lt;Integer&gt;();\nlistaLideresOrdenada.addAll(listaLideres);\n</code></pre>\n<p>The set can be passed directly to the constructor of <code>ArrayList</code>:</p>\n<pre><code>List&lt;Integer&gt; listaLideresOrdenada = new ArrayList&lt;Integer&gt;(listaLideres);\n</code></pre>\n<hr />\n<p>Copying the input array <code>A</code> to <code>B</code>:</p>\n<pre><code>B = Arrays.copyOf(A, array_lengh);\n</code></pre>\n<p>This can be avoided since <code>A</code> can be modified in place in this problem.</p>\n<hr />\n<p>Getting a value of a map or a default:</p>\n<pre><code>int repeticones = counter.get(B[n]) == null ? 0 : counter.get(B[n]);\n</code></pre>\n<p>Since Java 8 <code>Map</code> offers <code>getOrDefault</code>:</p>\n<pre><code>int repeticones = counter.getOrDefault(B[n], 0);\n</code></pre>\n<h2>Optimization</h2>\n<p>The current solution uses this approach:</p>\n<ol>\n<li>For each sliding window in <code>A</code></li>\n<li>Increment all elements of the sliding window by 1</li>\n<li>Calculate the frequencies of all elements in <code>A</code></li>\n<li>Update the result if a leader is found</li>\n</ol>\n<p>It can be considered a <span class=\"math-container\">\\$O(n^2)\\$</span> brute force approach, typically not enough to solve a HARD problem on Codility.</p>\n<p>Consider this approach: every time the sliding window moves to the right, the element on the left leaves the window, and the element on the right enters the windows. Therefore it is enough to update the frequencies of only these two numbers.</p>\n<p>This approach improves the complexity to <span class=\"math-container\">\\$O(n*log(n))\\$</span>. The sorting operation is now the bottleneck.</p>\n<p>A trick to avoid sorting is to use an array (for example, <code>leaders</code>) of size <code>M</code> (which is the value of the biggest element in <code>A</code>). Every time a leader <code>x</code> is found add it to <code>leaders</code> like <code>leaders[x] = true</code>. Finally, iterate on <code>leaders</code> and collect the results in order.</p>\n<p>Getting rid of the sorting operation improves the complexity to <span class=\"math-container\">\\$O(m)\\$</span>, but it's still too slow! The solution needs to run in less than 0.1 seconds for an input array <code>A</code> of 100K elements.</p>\n<p>So as a last optimization we can get rid of the map for counting the frequencies and use a simple array <code>freq</code>. Although updating a map is a very quick operation, updating an array is faster.</p>\n<h2>Reworked code</h2>\n<pre><code>public static int[] solution(int K, int M, int[] A) {\n boolean[] leaders = new boolean[M + 2];\n int[] freq = new int[M + 2];\n int threshold = A.length / 2;\n\n // Increment initial sliding window by 1\n for (int i = 0; i &lt; K; A[i]++, i++);\n\n // Calculate frequencies of all elements in A\n for (int i = 0; i &lt; A.length; freq[A[i]]++, i++);\n\n // If there are leaders save them\n for (int i = 0; i &lt; freq.length; i++) {\n leaders[i] = freq[i] &gt; threshold || leaders[i];\n }\n\n for (int i = 1; i &lt; A.length - K + 1; i++) {\n // Update frequency of element (on the left) leaving the sliding window\n int left = i - 1;\n freq[A[left]]--;\n A[left]--;\n freq[A[left]]++;\n\n // Update frequency of element (on the right) entering the sliding window\n int right = i + K - 1;\n freq[A[right]]--;\n A[right]++;\n freq[A[right]]++;\n\n // If there are new leaders save them\n leaders[A[right]] = freq[A[right]] &gt; threshold || leaders[A[right]];\n leaders[A[left]] = freq[A[left]] &gt; threshold || leaders[A[left]];\n }\n // Collect the leaders (in order)\n return IntStream.range(0, leaders.length)\n .filter(i -&gt; leaders[i])\n .toArray();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T18:33:58.160", "Id": "510262", "Score": "0", "body": "really awesome solution, just one thing I dont understand, why m+2 on freq and leaders? boolean[] leaders = new boolean[M + 2];\n int[] freq = new int[M + 2];" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T02:06:57.313", "Id": "510284", "Score": "1", "body": "@AntonioDiaz I am glad I could help. +1 because the array is zero-indexed. +1 because the sliding window is going to increase all elements by 1. So total +2." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T15:48:26.273", "Id": "257736", "ParentId": "257630", "Score": "1" } } ]
{ "AcceptedAnswerId": "257736", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T18:02:18.423", "Id": "257630", "Score": "2", "Tags": [ "java", "performance", "programming-challenge", "array" ], "Title": "Molybdenum2019 challenge efficient implementation" }
257630
<p>I have some code that manipulates a Pandas Dataframe containing Covid-19 vaccine data and displays it on Matplotlib.</p> <p>The data is here: <a href="https://covid.ourworldindata.org/data/owid-covid-data.csv" rel="nofollow noreferrer">https://covid.ourworldindata.org/data/owid-covid-data.csv</a> (downloads CSV).</p> <p>I have manipulated the data so that it only shows countries whose <strong>current vaccine per hundred rate is less than 10</strong> (so it can't remove all vaccine rates less than ten, it has to go through each country, get the latest vaccine per hundred rate, and if it is less than ten, remove that country from the graph).</p> <p>This is highly time-sensitive and needs to be done as quickly as possible.</p> <p>Code:</p> <pre><code>import pandas as pd import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator import datetime df = pd.read_csv( &quot;https://covid.ourworldindata.org/data/owid-covid-data.csv&quot;, usecols=[&quot;date&quot;, &quot;location&quot;, &quot;total_vaccinations_per_hundred&quot;], parse_dates=[&quot;date&quot;]) df = df[df[&quot;total_vaccinations_per_hundred&quot;].notna()] countries = df[&quot;location&quot;].unique().tolist() countries_copy = countries.copy() main_country = &quot;United States&quot; for country in countries: if country in countries: df_with_current_country = df[df['location']==country] if df_with_current_country[df[&quot;date&quot;]==df_with_current_country[&quot;date&quot;].max()][&quot;total_vaccinations_per_hundred&quot;].tolist()[0] &lt; 10: if country != main_country: countries_copy.remove(country) countries = countries_copy df = df[df[&quot;location&quot;].isin(countries)] pivot = pd.pivot_table( data=df, # What dataframe to use index=&quot;date&quot;, # The &quot;rows&quot; of your dataframe columns=&quot;location&quot;, # What values to show as columns values=&quot;total_vaccinations_per_hundred&quot;, # What values to aggregate aggfunc=&quot;mean&quot;, # How to aggregate data ) pivot = pivot.fillna(method=&quot;ffill&quot;) # Step 4: Plot all countries fig, ax = plt.subplots(figsize=(12,8)) fig.patch.set_facecolor(&quot;#F5F5F5&quot;) # Change background color to a light grey ax.patch.set_facecolor(&quot;#F5F5F5&quot;) # Change background color to a light grey for country in countries: if country == main_country: country_color = &quot;#129583&quot; alpha_color = 1.0 else: country_color = &quot;grey&quot; alpha_color = 0.75 ax.plot( pivot.index, # What to use as your x-values pivot[country], # What to use as your y-values color=country_color, # How to color your line alpha=alpha_color # What transparency to use for your line ) if country_color != &quot;grey&quot;: ax.text( x = pivot.index[-1] + datetime.timedelta(days=2), # Where to position your text relative to the x-axis y = pivot[country].max(), # How high to position your text color = country_color, # What color to give your text s = country, # What to write alpha=alpha_color # What transparency to use ) # Step 5: Configures axes ## A) Format what shows up on axes and how it&quot;s displayed date_form = DateFormatter(&quot;%Y-%m-%d&quot;) ax.xaxis.set_major_locator(WeekdayLocator(byweekday=(0), interval=1)) ax.xaxis.set_major_formatter(date_form) plt.xticks(rotation=45) plt.ylim(0,100) ## B) Customizing axes and adding a grid ax.spines[&quot;top&quot;].set_visible(False) ax.spines[&quot;right&quot;].set_visible(False) ax.spines[&quot;bottom&quot;].set_color(&quot;#3f3f3f&quot;) ax.spines[&quot;left&quot;].set_color(&quot;#3f3f3f&quot;) ax.tick_params(colors=&quot;#3f3f3f&quot;) ax.grid(alpha=0.1) ## C) Adding a title and axis labels plt.ylabel(&quot;Total Vaccinations per 100 People&quot;, fontsize=12, alpha=0.9) plt.xlabel(&quot;Date&quot;, fontsize=12, alpha=0.9) plt.title(&quot;COVID-19 Vaccinations over Time&quot;, fontsize=18, weight=&quot;bold&quot;, alpha=0.9) # D) Celebrate! plt.show() </code></pre>
[]
[ { "body": "<p>The loop and <code>countries</code> section can be replaced with a single <a href=\"https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.core.groupby.DataFrameGroupBy.filter.html\" rel=\"nofollow noreferrer\"><strong><code>DataFrameGroupBy.filter</code></strong></a>:</p>\n<ul>\n<li><code>.groupby('location')</code> - group by country</li>\n<li><code>.sort_values('date')</code> - sort country by date (newest at end)</li>\n<li><code>.tail(1) &gt;= 10</code> - only keep countries whose newest rate is at least 10</li>\n<li><code>| (country.name == main_country)</code> - always keep <code>main_country</code></li>\n</ul>\n<pre class=\"lang-py prettyprint-override\"><code>df2 = df.copy() # deep copy original df before loop (only to compare later)\n\ndf2 = df2.groupby('location').filter(lambda country:\n (country.sort_values('date').total_vaccinations_per_hundred.tail(1) &gt;= 10)\n | (country.name == main_country)\n)\n\n# location date total_vaccinations_per_hundred\n# 1930 Andorra 2021-01-25 0.75\n# 1937 Andorra 2021-02-01 1.34\n# ... ... ... ...\n# 74507 Uruguay 2021-03-26 14.31\n# 74508 Uruguay 2021-03-27 14.68\n# \n# [3507 rows x 3 columns]\n</code></pre>\n<p>And if we run the <code>countries</code> section, we can verify that the filtered <code>df2</code> matches the looped <code>df</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>df2.equals(df) # compare with df after loop\n\n# True\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T04:06:10.290", "Id": "510289", "Score": "1", "body": "Nice answer; small comment: the original code kept `main_country` even if it had less than 10 vaccinations per 100." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T04:28:21.363", "Id": "510290", "Score": "0", "body": "@RootTwo Ah good catch, fixed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T17:29:57.600", "Id": "258808", "ParentId": "257631", "Score": "2" } } ]
{ "AcceptedAnswerId": "258808", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T19:12:04.580", "Id": "257631", "Score": "3", "Tags": [ "python", "csv", "pandas", "matplotlib" ], "Title": "Manipulating Pandas Dataframe with vaccination data from CSV to display on matplotlib" }
257631
<p>While posting this, I noticed there are <em>quite</em> a few similar C hash table implementations here already. So I figured one more wouldn't hurt. :-) In any case, I'm writing a teaching article on &quot;how to implement a hash table in C&quot;, and I'm wondering if I can get some feedback on my implementation (<code>ht.h</code> and <code>ht.c</code>, with a usage example in <code>demo.c</code>). The goal is <em>not</em> maximum performance, but simplicity and good style.</p> <p>This hash table is a very simple array of entries that uses open addressing and linear probing, and the FNV-1 hash function. The capacity is always a power of two, and it automatically expands and re-hashes when it's half full.</p> <p>A few notes about the C API design:</p> <ul> <li>For simplicity, we use C-style NUL-terminated strings. I know there are more efficient approaches to string handling, but this fits with C's standard library.</li> <li>The <code>ht_set</code> function allocates and copies the key (if inserting for the first time). Usually you don't want the caller to have to worry about this, or ensuring the key memory stays around. Note that <code>ht_set</code> returns a pointer to the duplicated key. This is mainly used as an &quot;out of memory&quot; error signal -- it returns NULL on failure.</li> <li>Values can't be NULL. This makes the return value of <code>ht_get</code> slightly simpler (NULL means not present and can't mean a NULL value). I'm not sure whether this is a good idea or not.</li> <li>There are various ways I could have done iteration. Using an explicit iterator type with a while loop seems simple and natural in C (see the example below). The value returned from <code>ht_iterator</code> is a value, not a pointer, both for efficiency and so the caller doesn't have to free anything.</li> <li>There's no <code>ht_remove</code> to remove an item from the hash table. It wouldn't be hard to write, but I don't often need to remove items when using a hash table, so for simplicity I've left it out.</li> </ul> <p><strong>ht.h:</strong></p> <pre class="lang-c prettyprint-override"><code>#ifndef _HT_H #define _HT_H #include &lt;stdbool.h&gt; #include &lt;stddef.h&gt; // Hash table entry (this is not actually part of the public API). typedef struct { char* key; void* value; } _ht_entry; // Hash table structure: create with ht_create, free with ht_destroy. typedef struct { // Don't use these fields directly. _ht_entry* _entries; // hash buckets (entry.key != NULL if populated) size_t _capacity; // size of _entries array size_t _length; // number of items in hash table } ht; // Hash table iterator: create with ht_iterator, iterate with ht_next. typedef struct { char* key; // current key void* value; // current value // Don't use these fields directly. ht* _table; // reference to hash table being iterated size_t _index; // current index into ht._entries } hti; // Create new hash table and return pointer to it, or NULL if out of // memory. ht* ht_create(void); // Free memory allocated for hash table, including allocated keys. void ht_destroy(ht* table); // Get item with given key (NUL-terminated) from hash table. Return // value (which was set with ht_set), or NULL if key not found. void* ht_get(ht* table, const char* key); // Set item with given key (NUL-terminated) to value (which must not // be NULL). If not already present in table, key is copied to newly // allocated memory (keys are freed automatically when ht_destroy is // called). Return address of copied key, or NULL if out of memory. const char* ht_set(ht* table, const char* key, void* value); // Return number of items in hash table. size_t ht_length(ht* table); // Return new hash table iterator (for use with ht_next). hti ht_iterator(ht* table); // Move iterator to next item in hash table, update iterator's key // and value to current item, and return true. If there are no more // items, return false. Don't call ht_set during iteration. bool ht_next(hti* it); #endif // _HT_H </code></pre> <p><strong>ht.c:</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;ht.h&quot; #include &lt;assert.h&gt; #include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define INITIAL_SIZE 8 static ht* _ht_create(size_t size) { // Allocate space for hash table struct. ht* table = malloc(sizeof(ht)); if (table == NULL) { return NULL; } table-&gt;_length = 0; table-&gt;_capacity = size * 2; // Allocate (zero'd) space for entry buckets. table-&gt;_entries = calloc(table-&gt;_capacity, sizeof(_ht_entry)); if (table-&gt;_entries == NULL) { free(table); // error, free table before we return! return NULL; } return table; } ht* ht_create(void) { return _ht_create(INITIAL_SIZE); } void ht_destroy(ht* table) { // First free allocated keys. for (size_t i = 0; i &lt; table-&gt;_capacity; i++) { if (table-&gt;_entries[i].key != NULL) { free(table-&gt;_entries[i].key); } } // Then free entries array and table itself. free(table-&gt;_entries); free(table); } #define FNV_OFFSET 14695981039346656037UL #define FNV_PRIME 1099511628211UL // Return 64-bit FNV-1 hash for key (NUL-terminated). See description at: // https://en.wikipedia.org/wiki/Fowler–Noll–Vo_hash_function static uint64_t _hash(const char* key) { uint64_t hash = FNV_OFFSET; for (const char* p = key; *p; p++) { hash *= FNV_PRIME; hash ^= (uint64_t)(*p); } return hash; } void* ht_get(ht* table, const char* key) { // AND hash with capacity-1 to ensure it's within entries array. uint64_t hash = _hash(key); size_t index = (size_t)(hash &amp; (uint64_t)(table-&gt;_capacity - 1)); // Loop till we find an empty entry. while (table-&gt;_entries[index].key != NULL) { if (strcmp(key, table-&gt;_entries[index].key) == 0) { // Found key, return value. return table-&gt;_entries[index].value; } // Key wasn't in this slot, move to next (linear probing). index++; if (index &gt;= table-&gt;_capacity) { // At end of entries array, wrap around. index = 0; } } return NULL; } // Expand hash table to twice its current size. Return true on success, // false if out of memory. static bool _ht_expand(ht* table) { // Creating new table so we can use ht_set to move items into it. ht* new_table = _ht_create(table-&gt;_capacity); if (new_table == NULL) { return false; } // Iterate entries, move all non-empty ones to new table's entries. for (size_t i = 0; i &lt; table-&gt;_capacity; i++) { _ht_entry entry = table-&gt;_entries[i]; if (entry.key != NULL) { const char* key = ht_set(new_table, entry.key, entry.value); if (key == NULL) { ht_destroy(new_table); return false; } } } // Free old entries array and update this table's details. free(table-&gt;_entries); table-&gt;_entries = new_table-&gt;_entries; table-&gt;_capacity = new_table-&gt;_capacity; // Free new table structure (we've updated the existing one). free(new_table); return true; } const char* ht_set(ht* table, const char* key, void* value) { assert(value != NULL); if (value == NULL) { return NULL; } // AND hash with capacity-1 to ensure it's within entries array. uint64_t hash = _hash(key); size_t index = (size_t)(hash &amp; (uint64_t)(table-&gt;_capacity - 1)); // If length will exceed half of current capacity, expand it. if (table-&gt;_length &gt;= table-&gt;_capacity / 2) { if (!_ht_expand(table)) { return NULL; } // Recalculate index as capacity has changed. index = (size_t)(hash &amp; (uint64_t)(table-&gt;_capacity - 1)); } // Loop till we find an empty entry. while (table-&gt;_entries[index].key != NULL) { if (strcmp(key, table-&gt;_entries[index].key) == 0) { // Found key (it already exists), update value. table-&gt;_entries[index].value = value; return table-&gt;_entries[index].key; } // Key wasn't in this slot, move to next (linear probing). index++; if (index &gt;= table-&gt;_capacity) { // At end of entries array, wrap around. index = 0; } } // Didn't find key, allocate/copy key and insert it. char* key_copy = strdup(key); if (key_copy == NULL) { return NULL; } table-&gt;_entries[index].key = key_copy; table-&gt;_entries[index].value = value; table-&gt;_length++; // be sure to update length return key_copy; } size_t ht_length(ht* table) { return table-&gt;_length; } hti ht_iterator(ht* table) { hti it; it._table = table; it._index = 0; return it; } bool ht_next(hti* it) { // Loop till we've hit end of entries array. ht* table = it-&gt;_table; while (it-&gt;_index &lt; table-&gt;_capacity) { size_t i = it-&gt;_index; it-&gt;_index++; if (table-&gt;_entries[i].key != NULL) { // Found next non-empty item, update iterator key and value. _ht_entry entry = table-&gt;_entries[i]; it-&gt;key = entry.key; it-&gt;value = entry.value; return true; } } return false; } </code></pre> <p>And now for a simple example of usage:</p> <p><strong>demo.c:</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;../ht.h&quot; #include &lt;ctype.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; // Example: // $ echo 'foo bar the bar bar bar the' | ./demo // bar 4 // foo 1 // the 2 // 3 void exit_nomem(void) { fprintf(stderr, &quot;out of memory\n&quot;); exit(1); } int main(void) { ht* counts = ht_create(); if (counts == NULL) { exit_nomem(); } // Read next word from stdin (at most 100 chars long). char word[101]; while (scanf(&quot;%100s&quot;, word) != EOF) { // Look up word. void* value = ht_get(counts, word); if (value != NULL) { // Already exists, increment int that value points to. int* pcount = (int*)value; (*pcount)++; continue; } // Word not found, allocate space for new int and set to 1. int* pcount = malloc(sizeof(int)); if (pcount == NULL) { exit_nomem(); } *pcount = 1; if (ht_set(counts, word, pcount) == NULL) { exit_nomem(); } } // Print out words and frequencies, freeing values as we go. hti it = ht_iterator(counts); while (ht_next(&amp;it)) { printf(&quot;%s %d\n&quot;, it.key, *(int*)it.value); free(it.value); } // Show the number of unique words. printf(&quot;%d\n&quot;, (int)ht_length(counts)); ht_destroy(counts); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:27:08.533", "Id": "509007", "Score": "1", "body": "Is there any reason why you would use FNV1 and not use FNV1a?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:45:05.083", "Id": "509012", "Score": "1", "body": "I've actually switched to 1a! After testing average probe length, I noticed 1 wasn't good with similar keys like \"word1\", \"word2\", etc, whereas 1a did fine with those (and normal words). Not very scientific, but yeah, 1a, seems better. https://github.com/benhoyt/ht/commit/bf83fb7fd27e636a09822a31cf8617f311121c3d" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T19:59:17.383", "Id": "509110", "Score": "0", "body": "Article published: https://benhoyt.com/writings/hash-table-in-c/ I included a bunch of changes based on this feedback, notably: fixing the memory leak, moving (most) struct internals to `ht.c`, dropping the `_` prefix on internal names, and fixing the sign extension issue in `_hash`. Thanks for the feedback!" } ]
[ { "body": "<ul>\n<li><p><code>// Don't use these fields directly</code> means that they do not belong to the public interface. Consider declaring</p>\n<pre><code> typedef struct ht ht;\n</code></pre>\n<p>in <code>ht.h</code>, and spelling it out in <code>ht.c</code>. Ditto for <code>hti</code>.</p>\n<p><code>_ht_entry</code> shall not be visible to the client at all; move its declaration to <code>ht.c</code> as well.</p>\n</li>\n<li><p><code>ht_set</code> calls <code>_ht_expand</code>. In turn, <code>_ht_expand</code> calls <code>ht_set</code>. Even though it is (apparently) safe, it still looks eery.</p>\n<p>What worse, <code>ht_set</code> does <code>strdup(key)</code>, but <code>_ht_expand</code> does not free the old keys. Memory leak it is.</p>\n</li>\n<li><p>The values must be persistent, and I don't see the way for the client to not <code>malloc</code> them (the demo code seems to agree with me). However <code>ht_destroy</code> does not free them. This is yet another avenue for a memory leak.</p>\n</li>\n<li><p>I am not sure you should force FNV. The user - who knows the nature of the keys distribution - may want to use different hashing algorithm. Besides, FNV is well-scattered across the entire 64-bit space. I have serious doubts that it will perform well after clipping to the narrower space.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T00:36:00.593", "Id": "508904", "Score": "0", "body": "Thanks! Good points about moving non-public things to ht.c. Good find on the `_ht_expand` memory leak! I'm not sure about `ht_destroy` freeing values -- the user might malloc a block of values and point into that, so needs control. Re FNV and clipping - interesting point. Looks like http://www.isthe.com/chongo/tech/comp/fnv/ has useful info." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T00:48:18.313", "Id": "508905", "Score": "0", "body": "FNV seems to have pretty good \"dispersion\" (as it's called) for hashes that are powers of two. However, I just noticed FNV-1a works much better than FNV-1 for similar keys like `key1`, `key2`, etc. So I think I'll switch to 1a." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T00:24:40.447", "Id": "257649", "ParentId": "257634", "Score": "5" } }, { "body": "<p><strong>Good header file</strong></p>\n<p>.... aside from the <code>struct</code> definitions that belong in the .c file.</p>\n<p><strong>Weak hash</strong></p>\n<p>OP's code only uses the least few bits of <code>hash</code> to form <code>index</code> and so this <code>ht</code> exercise entirely relies on the quality of <code>_hash()</code>.</p>\n<pre><code>// Only uses a few bits of `hash`\nsize_t index = (size_t)(hash &amp; (uint64_t)(table-&gt;_capacity - 1));\n</code></pre>\n<p>Consider a <a href=\"https://stackoverflow.com/a/32915815/2410359\">mod by prime</a> for general hash functions. I'd use a look-up table of primes just under a power-of-4 and grow the hash table approximately 4x when needed.</p>\n<p><strong>Size to the referenced object, not the type.</strong></p>\n<p>Consider the below. Is <code>sizeof(_ht_entry)</code> correct? To check, I needed to search for the type of <code>table</code> (somewhere at the start of the function) , find <code>ht</code>, search for <code>ht</code> definition (it is in another file).</p>\n<pre><code>// size by type: easy to code worng, slow to review, more maintenance on change.\ntable-&gt;_entries = calloc(table-&gt;_capacity, sizeof(_ht_entry));\n</code></pre>\n<p>Instead, consider</p>\n<pre><code>table-&gt;_entries = calloc(table-&gt;_capacity, sizeof table-&gt;_entries[0]);\n// or\ntable-&gt;_entries = calloc(table-&gt;_capacity, sizeof *(table-&gt;_entries));\n</code></pre>\n<p>Easy to code right, review and maintain. No need to look up <code>table</code>, nor <code>_entries</code> definition.</p>\n<p><strong>Keep empty tables small</strong></p>\n<p>A <em>successful</em> container can get used <em>a lot</em>. The more it is used, more likely <em>many</em> instances remain empty thought out their life.</p>\n<p>The initial <code>_ht_create(INITIAL_SIZE)</code> waste memory in those cases. Consider <code>_ht_create(0)</code> instead and adjust code accordingly. That first allocation before need does not buy much.</p>\n<p><strong>Corner case bug</strong></p>\n<p>(OP does not use <code>_ht_create(0)</code> yet, but ...)</p>\n<p>Below tests for out-of-memory by <code>table-&gt;_entries == NULL</code>, yet a <code>NULL</code> is an acceptable return value when <code>table-&gt;_capacity == 0</code>. (C17 somewhat addresses this, but not enough).</p>\n<pre><code>table-&gt;_entries = calloc(table-&gt;_capacity, sizeof(_ht_entry));\n// if (table-&gt;_entries == NULL) {\n// Suggest\nif (table-&gt;_entries == NULL &amp;&amp; table-&gt;_capacity &gt; 0) {\n</code></pre>\n<p><strong>Drop the _ prefix</strong></p>\n<p>No need for it.</p>\n<p><strong>How to set/get <code>NULL</code> data</strong></p>\n<p>I disagree with restricting use with &quot;Values can't be NULL&quot;.</p>\n<p>With &quot;NULL if key not found&quot;, implies ambiguity if the value stored prior was <code>NULL</code>.</p>\n<p>Rather than mix the result of the <code>get()</code> with a reserved pointer value, separate the error flag from data. The data value should be allowed to be <em>any</em> <code>void *</code>.</p>\n<p><strong><code>const</code></strong></p>\n<p>Function deserves to be <code>const</code> for the usual reasons of self-documentation and expanded use.</p>\n<pre><code>// size_t ht_length(ht* table);\nsize_t ht_length(const ht* table);\n</code></pre>\n<p><strong>Initialize all of the iterator</strong></p>\n<pre><code>hti ht_iterator(ht* table) {\n //hti it;\n //it._table = table;\n //it._index = 0;\n hti it = { ._table = table, ._index = 0 }; // other members become 0\n return it;\n}\n</code></pre>\n<p><strong>Shrink</strong></p>\n<p>I look forward to <code>ht_remove()</code>.</p>\n<p>No support to remove entries or shrink the table other than to destroy.</p>\n<p><strong>Minor: <code>L</code> not needed</strong></p>\n<pre><code>//#define FNV_OFFSET 14695981039346656037UL\n//#define FNV_PRIME 1099511628211UL\n#define FNV_OFFSET 14695981039346656037U\n#define FNV_PRIME 1099511628211U\n</code></pre>\n<p><strong>Minor: Avoid sign extension</strong></p>\n<pre><code>// hash ^= (uint64_t)(*p);\nhash ^= *(unsigned char *)p;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T11:07:20.473", "Id": "508942", "Score": "0", "body": "Thanks! I'll make some of these updates. Good call on the hashing sign extension bug -- I actually noticed that myself just before reading your reply. It gives an incorrect hash as a result (though it didn't seem to matter to much in practice). I've updated my code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T06:22:18.450", "Id": "257662", "ParentId": "257634", "Score": "4" } } ]
{ "AcceptedAnswerId": "257649", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T20:10:19.577", "Id": "257634", "Score": "5", "Tags": [ "c", "hash-map", "collections" ], "Title": "Hash table implemented in C with open addressing" }
257634
<p>Background: In tcsh we can use single quotes inside single quote like this (like it said <a href="https://unix.stackexchange.com/questions/187651/how-to-echo-single-quote-when-using-single-quote-to-wrap-special-characters-in">here</a>):</p> <pre><code>echo 'It'\''s Shell Programming' </code></pre> <p>I want to create a method which escapes single quotes and prints it into a tcsh script I build on fly with Java. It should do:</p> <ol> <li>If there is a <code>\'</code> (two chars) in the string, it will escape it so: <code>\'\''</code>.</li> <li>If there is a <code>'</code> (one char with no <code>\</code> before it) in the string, it will escape it so <code>'\''</code>.</li> </ol> <p>I wrote the following method to do so:</p> <pre><code>private static String escapeStr(final String str) { String result = &quot;&quot;; for (int index = 0; index &lt; str.length(); ++index) { if (str.charAt(index) == '\\') { if (index + 1 &lt; str.length() &amp;&amp; str.charAt(index + 1) == '\'') { result += &quot;\\'\\\''&quot;; index++; } else { result += str.charAt(index); } } else if (str.charAt(index) == '\'') { result += &quot;'\\\''&quot;; } else { result += str.charAt(index); } } return result; } </code></pre> <p>It looks like it does the job but I really don't like how I implemented it. It's hard to read as it has quite a lot of <code>\</code> chars. Also I do <code>index++</code> inside the loop which feels like bad design. Is there a better approach here?</p> <p>I will add that I want to call the method like so:</p> <pre><code>fileWriter.write(&quot;echo '&quot; + escapeStr(cmd) + &quot;'\n&quot;); </code></pre> <p>The whole point of this part is so the escape will print the <code>cmd</code> as-is. I wrap the command with <code>'</code> so it won't evaluate stuff like environment variables. So if the cmd already contains single quote it will fail. I will need to escape single quotes and that what I tried to do.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T08:57:19.993", "Id": "508936", "Score": "0", "body": "Beside the fact that I find it weird do do this \"on the fly\" in Java (outside of a more complex application) have you ever heard of [regular expressions](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/regex/Pattern.html) and their [look ahead/behind](https://www.rexegg.com/regex-lookarounds.html) feature?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T11:08:25.000", "Id": "508944", "Score": "0", "body": "@TimothyTruckle My tool written in Java and creates tcsh scripts (aside with other stuff it does). How would you use look_ahead/behind here?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T12:09:34.103", "Id": "508950", "Score": "0", "body": "Sometimes the idea that comes to mind first is not the best, so look ahead/behind may not hold the expectation... ;o)" } ]
[ { "body": "<p>I'd suggest a Solution based on <em>regular expressions</em> like this:</p>\n<pre><code>import static org.junit.Assert.assertThat;\n\nimport java.util.Optional;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\nimport org.hamcrest.CoreMatchers;\nimport org.junit.Test;\n\npublic class EscapeQuotesTest {\n\n Pattern escapedQuotePattern = Pattern.compile(&quot;(\\\\\\\\)?(')(')&quot;);\n\n private String escapeString(String input) {\n Matcher escapedQuote = escapedQuotePattern.matcher(input);\n escapedQuote.find();\n Optional&lt;String&gt; escapeChar = Optional.ofNullable(escapedQuote.group(1));\n String result = String.format(&quot;%s%s\\\\'%s&quot;, escapeChar.orElse(&quot;&quot;), escapedQuote.group(2), escapedQuote.group(3));\n return result;\n }\n\n @Test\n public void preseveLeadingBackslash() {\n String input = &quot;\\\\''&quot;;\n String result = escapeString(input);\n assertThat(&quot; The escape char survived&quot;, result, CoreMatchers.containsString(&quot;\\\\'\\\\''&quot;));\n }\n\n @Test\n public void noLeadingBackslash() {\n String input = &quot;''&quot;;\n String result = escapeString(input);\n assertThat(&quot;no escape char at beginning&quot;, result, CoreMatchers.containsString(&quot;'\\\\''&quot;));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T14:29:17.867", "Id": "508957", "Score": "0", "body": "It's still hard to read and also you will need to add try-catch no?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T14:48:04.503", "Id": "508959", "Score": "0", "body": "@vesii *\"It's still hard to read\"* yes, you cannot go around the combined escaping needs for Java Strings and Regular Expression special chars. **---** *\"you will need to add try-catch no?\"* I wrote an SSCCE so no, a `try/catch` block is not needed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T12:10:18.997", "Id": "257673", "ParentId": "257636", "Score": "3" } }, { "body": "<p>When you find the <code>\\'</code> sequence, you're handling it all in one go. This seems to be the source of your <code>index++</code> issue. It also means that you've got the repeated <code>else</code> clause in there. A small improvement would be to only handle the <code>\\</code> when you encounter <code>\\'</code>, then handle the subsequent <code>'</code> on the next pass around the loop. As far as I can tell handling for <code>'</code> doesn't really depend on what character was before it. So, you'd end up with:</p>\n<pre><code>private static String escapeStr(final String str) {\n String result = &quot;&quot;;\n for (int index = 0; index &lt; str.length(); ++index) {\n if (str.charAt(index) == '\\\\' &amp;&amp;\n (index + 1 &lt; str.length() &amp;&amp; str.charAt(index + 1) == '\\'')) {\n result += &quot;\\\\&quot;;\n } else if (str.charAt(index) == '\\'') {\n result += &quot;'\\\\''&quot;;\n } else {\n result += str.charAt(index);\n }\n }\n return result;\n}\n</code></pre>\n<p>You're also building up a <code>String</code> in a loop, rather than using a <code>StringBuilder</code>. For small strings this probably won't make a lot of difference, however it can add up for big ones. If you wanted to use <code>StringBuilder</code> it would look like:</p>\n<pre><code>private static String escapeStr(final String str) {\n StringBuilder result = new StringBuilder();\n for (int index = 0; index &lt; str.length(); ++index) {\n if (str.charAt(index) == '\\\\' &amp;&amp;\n (index + 1 &lt; str.length() &amp;&amp; str.charAt(index + 1) == '\\'')) {\n result.append(&quot;\\\\&quot;);\n } else if (str.charAt(index) == '\\'') {\n result.append(&quot;'\\\\''&quot;);\n } else {\n result.append(str.charAt(index));\n }\n }\n return result.toString();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:48:07.920", "Id": "508985", "Score": "0", "body": "Is it recommended to use StringBuilder here? If so, how would you do it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:53:57.320", "Id": "508986", "Score": "1", "body": "@vesii I've added the StringBuilder version. Generally, StringBuilder is faster when you're building up large Strings, bit by bit because it optimises out a lot of the reallocations which are required by immutable `Strings`. When you're performing a small number there's not a lot of difference, and ocassionally using Strings will be faster, but generally if you're looping I'd expect a `StringBuilder` (but you have a better idea how big the scripts are and if it'll really make a difference). `StringBuilder`s can be harder for some people to read than normal `String` concatenation." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:46:39.990", "Id": "257692", "ParentId": "257636", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T20:22:40.217", "Id": "257636", "Score": "6", "Tags": [ "java" ], "Title": "Implementing a method that escapes single quotes in a string" }
257636
<p>I'm pretty darn new to C# and to be honest in programming.</p> <p>I'm experimenting on making a cash register type program and I picked WPF because its been recommended as better than Forms when it comes to resizing and graphics stuff.</p> <p>I'm looking for feedback on how I could better my XAML.</p> <pre><code> &lt;Page x:Class=&quot;Registry_Project.RightPanel_Menu&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; xmlns:mc=&quot;http://schemas.openxmlformats.org/markup-compatibility/2006&quot; xmlns:d=&quot;http://schemas.microsoft.com/expression/blend/2008&quot; xmlns:local=&quot;clr-namespace:Registry_Project&quot; mc:Ignorable=&quot;d&quot; d:DesignHeight=&quot;450&quot; d:DesignWidth=&quot;800&quot; Title=&quot;RightPanel_Menu&quot; MinHeight=&quot;720&quot; MinWidth=&quot;340&quot;&gt; &lt;Grid Background=&quot;Black&quot;&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height=&quot;320*&quot;/&gt; &lt;RowDefinition Height=&quot;120&quot;/&gt; &lt;RowDefinition Height=&quot;300&quot;/&gt; &lt;/Grid.RowDefinitions&gt; &lt;ListBox Grid.Row=&quot;0&quot; x:Name=&quot;LBoxOrder&quot; Margin=&quot;10&quot;/&gt; &lt;StackPanel Grid.Row=&quot;1&quot; Orientation=&quot;Horizontal&quot; HorizontalAlignment=&quot;Center&quot;&gt; &lt;Button Margin=&quot;10,0,10,0&quot; Width=&quot;70&quot; Background=&quot;#FFF13C3C&quot;&gt; &lt;TextBlock Text=&quot;Remove Item&quot; TextWrapping=&quot;Wrap&quot; TextAlignment=&quot;Center&quot; FontSize=&quot;18&quot;/&gt; &lt;/Button&gt; &lt;Grid Margin=&quot;5&quot; ShowGridLines=&quot;True&quot; HorizontalAlignment=&quot;Center&quot; &gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width=&quot;80&quot;/&gt; &lt;ColumnDefinition Width=&quot;70&quot;/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height=&quot;auto&quot;/&gt; &lt;RowDefinition Height=&quot;auto&quot;/&gt; &lt;RowDefinition Height=&quot;auto&quot;/&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBlock Text=&quot;Total:&quot; Margin=&quot;5&quot; Grid.Row=&quot;0&quot; Grid.Column=&quot;0&quot; Foreground=&quot;White&quot; HorizontalAlignment=&quot;Left&quot; FontSize=&quot;20&quot;/&gt; &lt;TextBlock Text=&quot;Cash:&quot; Margin=&quot;5&quot; Grid.Row=&quot;1&quot; Grid.Column=&quot;0&quot; Foreground=&quot;White&quot; HorizontalAlignment=&quot;Left&quot; FontSize=&quot;20&quot;/&gt; &lt;TextBlock Text=&quot;Change:&quot; Margin=&quot;5&quot; Grid.Row=&quot;2&quot; Grid.Column=&quot;0&quot; Foreground=&quot;White&quot; HorizontalAlignment=&quot;Left&quot; FontSize=&quot;20&quot;/&gt; &lt;TextBlock Text=&quot;9999&quot; Margin=&quot;5&quot; Grid.Row=&quot;0&quot; Grid.Column=&quot;1&quot; Foreground=&quot;White&quot; HorizontalAlignment=&quot;Right&quot; FontSize=&quot;20&quot;/&gt; &lt;TextBlock x:Name=&quot;CashBlock&quot; Text=&quot;9999&quot; Margin=&quot;5&quot; Grid.Row=&quot;1&quot; Grid.Column=&quot;1&quot; Foreground=&quot;White&quot; HorizontalAlignment=&quot;Right&quot; FontSize=&quot;20&quot;/&gt; &lt;TextBlock Text=&quot;9999&quot; Margin=&quot;5&quot; Grid.Row=&quot;2&quot; Grid.Column=&quot;1&quot; Foreground=&quot;White&quot; HorizontalAlignment=&quot;Right&quot; FontSize=&quot;20&quot;/&gt; &lt;/Grid&gt; &lt;Button Content=&quot;PAY&quot; Margin=&quot;10,0,10,0&quot; FontSize=&quot;30&quot; Background=&quot;#FF49DA29&quot; Width=&quot;70&quot;/&gt; &lt;/StackPanel&gt; &lt;Grid Grid.Row=&quot;2&quot; HorizontalAlignment=&quot;Center&quot; VerticalAlignment=&quot;Center&quot; &gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width=&quot;auto&quot;/&gt; &lt;ColumnDefinition Width=&quot;auto&quot;/&gt; &lt;ColumnDefinition Width=&quot;auto&quot;/&gt; &lt;ColumnDefinition Width=&quot;auto&quot;/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height=&quot;auto&quot;/&gt; &lt;RowDefinition Height=&quot;auto&quot;/&gt; &lt;RowDefinition Height=&quot;auto&quot;/&gt; &lt;RowDefinition Height=&quot;auto&quot;/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Button Content=&quot;1&quot; FontSize=&quot;20&quot; Grid.Column=&quot;0&quot; Grid.Row=&quot;2&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;2&quot; FontSize=&quot;20&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;2&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;3&quot; FontSize=&quot;20&quot; Grid.Column=&quot;2&quot; Grid.Row=&quot;2&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;4&quot; FontSize=&quot;20&quot; Grid.Column=&quot;0&quot; Grid.Row=&quot;1&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;5&quot; FontSize=&quot;20&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;1&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;6&quot; FontSize=&quot;20&quot; Grid.Column=&quot;2&quot; Grid.Row=&quot;1&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;7&quot; FontSize=&quot;20&quot; Grid.Column=&quot;0&quot; Grid.Row=&quot;0&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;8&quot; FontSize=&quot;20&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;0&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;9&quot; FontSize=&quot;20&quot; Grid.Column=&quot;2&quot; Grid.Row=&quot;0&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;0&quot; FontSize=&quot;20&quot; Grid.Column=&quot;0&quot; Grid.Row=&quot;3&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;.&quot; FontSize=&quot;20&quot; Grid.Column=&quot;1&quot; Grid.Row=&quot;3&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;NumEvent&quot;/&gt; &lt;Button Content=&quot;Clear&quot; FontSize=&quot;18&quot; Grid.Column=&quot;2&quot; Grid.Row=&quot;3&quot; Margin=&quot;2&quot; Width=&quot;50&quot; Height=&quot;50&quot; Click=&quot;clik_Clear&quot;/&gt; &lt;/Grid&gt; &lt;/Grid&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T23:03:35.450", "Id": "508895", "Score": "2", "body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/257643/2) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T08:38:18.117", "Id": "508935", "Score": "2", "body": "IMHO the best way is to avoid complicated Grids, they tend to be unwieldy. Look at the other ways to construct a UI, e.g. StackPanels etc. Unfortunately you are new to programming, otherwise I'd advise you to use the MVVM pattern when doing WPF. https://docs.microsoft.com/en-us/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T23:49:51.973", "Id": "509018", "Score": "0", "body": "sorry for the late reply and thank you for the feedback... ill be sure to look into it as part of my learning experience." } ]
[ { "body": "<p>Have you tried <strong>Suggested Actions</strong></p>\n<p>There is a new feature called <strong>Suggested Actions</strong> that enables easy access to common properties when a control is selected. This feature is available in <a href=\"https://visualstudio.microsoft.com/vs/preview/\" rel=\"nofollow noreferrer\">Visual Studio 2019 Preview</a> version 16.6 and later. To use it, first enable it through <strong>Options &gt; Preview Features &gt; XAML Suggested Actions</strong>.Once enabled, click on a supported control and use the “light bulb” to expand and interact with the Suggested Actions UI.</p>\n<p><a href=\"https://i.stack.imgur.com/AK3IG.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AK3IG.png\" alt=\"enter image description here\" /></a></p>\n<p>More information about this feature can be found <a href=\"https://devblogs.microsoft.com/visualstudio/improvements-to-xaml-tooling-in-visual-studio-2019-version-16-7-preview-1/\" rel=\"nofollow noreferrer\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T05:06:24.270", "Id": "257657", "ParentId": "257643", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T22:50:43.310", "Id": "257643", "Score": "2", "Tags": [ "c#", "beginner", "wpf", "xaml" ], "Title": "Cash register form" }
257643
<p>Many times I have copy and pasted from a guide that had the following instruction:</p> <blockquote> <p>$ echo &quot;Execute xyz&quot;</p> </blockquote> <p>and would get the error</p> <blockquote> <p>$: command not found</p> </blockquote> <p>So I created a bash script to ignore the '$' at the beginning; The solution is as follows:</p> <ol> <li>Put the below script in a file called '$' <ul> <li><code>vim $</code></li> </ul> </li> <li>Make it executable <ul> <li><code>chmod +x $</code></li> </ul> </li> <li>Add it to your bin <ul> <li><code>sudo cp $ /usr/bin/$</code></li> </ul> </li> </ol> <p>The script:</p> <pre class="lang-bsh prettyprint-override"><code>#!/bin/bash eval $@ </code></pre>
[]
[ { "body": "<p>Cute idea. It's not so simple, though.</p>\n<p>For example, compare the outputs of</p>\n<pre><code>echo 'a b'\n</code></pre>\n<p>with</p>\n<pre><code>$ echo 'a b'\n</code></pre>\n<p>(because of word splitting).</p>\n<p>Also, it fails for compound commands like</p>\n<pre><code>for i in a b c ; do echo $i ; done\n</code></pre>\n<p>(because everything after the first <code>;</code> is another command).</p>\n<p>Some commands might fail depending on the contents of the current directory, e.g.</p>\n<pre><code>$ [[ a = ? ]]\n</code></pre>\n<p>(if it works, try running <code>touch 1 2 3</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T23:08:24.367", "Id": "508896", "Score": "0", "body": "Oh I hadn't thought of that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T23:12:30.383", "Id": "508897", "Score": "0", "body": "Updated with some more problematic cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T23:18:54.970", "Id": "508898", "Score": "0", "body": "To solve the first case, we can do Line 1: `#!/bin/bash` Line 2: `\"$@\"`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T23:05:22.227", "Id": "257646", "ParentId": "257645", "Score": "1" } }, { "body": "<p>Change the script to simply <code>&quot;$@&quot;</code> and it should work <em>for commands other than shell builtins.</em> Showing a session with <code>PS1='\\$ '</code>:</p>\n<pre><code>$ cat '/usr/bin/$'\n#!/usr/bin/env bash\n&quot;$@&quot;\n$ $ echo 'a b'\na b\n$ $ [[ a = b ]]\n/usr/bin/$: line 2: [[: command not found\n</code></pre>\n<p><strong>Caveat:</strong> While this is a neat trick it encourages dangerous behaviour. Copying and pasting from sources which are not completely trusted is a big security risk (<a href=\"https://thejh.net/misc/website-terminal-copy-paste\" rel=\"nofollow noreferrer\">1</a>, <a href=\"https://security.stackexchange.com/q/39118/1220\">2</a>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:29:02.093", "Id": "508977", "Score": "0", "body": "Some other commands from my reply still wouldn't work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:33:20.150", "Id": "508982", "Score": "0", "body": "It won't work on builtins, no. But it's as close as you're ever going to get." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T00:57:02.403", "Id": "257651", "ParentId": "257645", "Score": "1" } }, { "body": "<p>While I understand why you're trying to do what you do, but honestly, I'd really avoid masking something as critical as a sigil. Before you know it, you'll end up doing something similar for <code>#</code> (as some commands out there assume you're running them as root). That's just going to be a mess.</p>\n<p>What you could do instead, is write a script that processes (and if needed) trims whatever is in your clipboard. I'm going to assume you're running some flavour of Linux for the purposes of simplicity. There are similar utilities for OSX, so if needed you can just modify the approach suggested here to fit your system.</p>\n<h3>Simple and risky</h3>\n<p>Apart from what you already have, install <code>xclip</code>, a command that allows you to interact with your system clipboard from the command line (e.g. <code>xclip -selection c file.txt</code> saves contents of file.txt to clipboard).</p>\n<p>Now <code>xclip</code> can also print out (and as such access) whatever is in your clipboard by running <code>xclip -o</code> or <code>xclip -out</code>, so let's start with that:</p>\n<pre><code>#!/usr/bin/env bash\n\nstr=&quot;$(xclip -o)&quot;\n</code></pre>\n<p>Great, so now <code>str</code> contains whatever is in your system clipboard. Now if you've accidentally selected the leading <code>$</code>, chances are you've accidentally selected the space before it, or maybe even a line-break. To be safe, it's probably best we trim the string in question. There's ways to do this with bash's many weird and wacky string manipulation constructs, but keeping it simple, we can just use <code>xargs</code> which, if no other arguments are provided, will trim the input string and return it as-is:</p>\n<pre><code>str=&quot;$(xclip -o | xargs)&quot;\n</code></pre>\n<p>OK, so now we can check to see if the string in question starts with a <code>$</code>:</p>\n<pre><code>if [[ &quot;${str:0:1}&quot; == '$' ]]; then\n str=&quot;${str:1}&quot;\nfi\n</code></pre>\n<p>So if the first character of our string is <code>$</code>, we're cutting it off, and setting <code>str</code> to be equal to <code>str</code> minus the first character, getting rid of the dollar sign. You could add something like:</p>\n<pre><code>if [[ &quot;${str:0:1}&quot; == '$' ]] || [[ &quot;${str:0:1}&quot; == '#' ]] ; then\n str=&quot;${str:1}&quot;\nfi\n</code></pre>\n<p>To account for the aforementioned leading <code>#</code> characters you may have accidentally copied. At this point, you're ready to do what you're currently doing:</p>\n<pre><code>## Either using eval:\neval $str\n## or the shorter, but equally risky\n$str\n</code></pre>\n<p>Make the script executable and call it something short and to the point:</p>\n<pre><code>$ vim ~/bin/execpaste\n\n#!/usr/bin/env bash\n\nstr=&quot;$(xclip -o | xargs)&quot;\nif [[ &quot;${str:0:1}&quot; == '$' ]] || [[ &quot;${str:0:1}&quot; == '#' ]]; then\n str=&quot;${str:1}&quot;\nfi\n\necho &quot;Executing ${str}...&quot;\n$str\n</code></pre>\n<p>Make the script executable (<code>$ chmod +x ~/bin/execpaste</code>), and add <code>~/bin</code> to your path (rather than adding scripts directly to <code>/usr/bin</code>) by adding this to your <code>.bashrc</code> or <code>.profile</code> file:</p>\n<pre><code>export PATH=&quot;${PATH}:${HOME}/bin&quot;\n</code></pre>\n<h3>Slightly less risky</h3>\n<p>Personally, though, I prefer to be able to see what I'm pasting in my terminal before executing it. Just to be sure... In that case, I'd keep the first part of the script, but call it <code>prepclip</code> or something (short for prepare clipboard). Most of it would remain the same, apart from the last part (where the command is actually executed). I'd just write it back to my clipboard instead:</p>\n<pre><code>#!/usr/bin/env bash\n\nstr=&quot;$(xclip -o | xargs)&quot;\nif [[ &quot;${str:0:1}&quot; == '$' ]] || [[ &quot;${str:0:1}&quot; == '#' ]]; then\n str=&quot;${str:1}&quot;\nfi\n\n# send updated string to clipboard\necho &quot;${str}&quot; | xclip -selection c\n</code></pre>\n<p>In terms of actually using this script, it does indeed take 2 steps:</p>\n<pre><code>$ prepclip\n$ &lt;paste&gt;\n</code></pre>\n<p>But the second step, to me, is a worthwhile sanity check.</p>\n<h2>MacOS</h2>\n<p>MacOS, as far as I know has 2 commands to paste and copy that you can use instead. Below is the MacOS version of the last script (cleaning up clipboard input and writes in back to the clipboard), just in case you're on MacOS:</p>\n<pre><code>#!/usr/bin/env bash\n\nstr=&quot;$(pbpaste | xargs)&quot;\nif [[ &quot;${str:0:1}&quot; == '$' ]] || [[ &quot;${str:0:1}&quot; == '#' ]]; then\n str=&quot;${str:1}&quot;\nfi\n\necho &quot;${str}&quot; | pbcopy\n</code></pre>\n<p>That should give you everything you need, without messing with sigils.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:02:39.807", "Id": "508973", "Score": "0", "body": "That's a little inconvenient, because then you have to remember to pass everything through the `CLIPBOARD` selection instead of the more natural `PRIMARY` one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:07:02.317", "Id": "508974", "Score": "0", "body": "If you're using Bash, then simply substituting `str=${str##[#$] }` should be simpler than the substring stuff. You likely want to apply it to each line; I'd probably just pay the cost of passing it through `sed` then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T19:13:53.680", "Id": "508992", "Score": "0", "body": "I have found this https://stackoverflow.com/questions/51528677/is-there-a-way-to-make-bash-ignore-the-from-copied-commands" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T17:45:27.657", "Id": "257688", "ParentId": "257645", "Score": "0" } }, { "body": "<p>There's a straightforward flaw that needs fixing - outside of quotes, <code>$@</code> behaves like <code>$*</code>, so you've lost the word boundaries. What you really wanted was</p>\n<pre><code>#!/bin/sh\nexec &quot;$@&quot;\n</code></pre>\n<p>Note that plain shell is appropriate here, as the invoking shell has already done all the shelly things with the arguments, such as word splitting and the various expansions. You certainly didn't want <code>eval</code>!</p>\n<p>The other case where this program doesn't achieve the advertised results are when the pasted commands are intended to <em>change the state of the shell</em> - for example by setting environment variables. With the code here, those modifications happen in the process running the <code>$</code> program, not the calling shell.</p>\n<p>What would probably work better is a <strong>shell function</strong> called <code>$</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:31:02.883", "Id": "508979", "Score": "0", "body": "This still fails with some of the examples in my reply." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:32:54.860", "Id": "508981", "Score": "0", "body": "You can't create a Bash function or alias with the name `$`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T19:16:53.270", "Id": "508993", "Score": "1", "body": "It looks like you can do `alias \"$\"=\"\"` in zsh (tested, I was using the gnome shell at the time of writing)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:00:06.420", "Id": "508999", "Score": "0", "body": "@choroba, yes absolutely. There's no way in shell that I know of that even the function approach would work with flow-control commands. I tried to give useful feedback that could improve other shell scripts, even though this one is doomed (or at least severely limited)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:02:39.320", "Id": "509000", "Score": "0", "body": "@l0b0, I thought that might be impossible with unmodified Bash, but wasn't sufficiently certain I could prove it, given ways to sneak functions in through the environment for example. Of course, if it matters enough to someone, it wouldn't be too hard to modify a shell to accept `$` as a function identifier. I still wouldn't recommend it!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:22:25.683", "Id": "509004", "Score": "0", "body": "@Alex, I didn't expect that it would be a legal name in any common shell - thanks for educating me today!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:01:25.820", "Id": "257690", "ParentId": "257645", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-24T22:58:32.727", "Id": "257645", "Score": "0", "Tags": [ "bash", "linux" ], "Title": "Linux bash script to ignore '$'" }
257645
<p>A couple months ago I made an interactive dijktra visualizer that allowed the user to setup the map nodes and run the algorithm. I thought it was a good way to solidify my algorithm and html/css knowledge. I'd like for you guys to test my application out and give any advice in any way I could make it better.</p> <p>One particular element that i'd like to improve is the map rendering, which I did by making a table and updating it's rows and columns. This solution worked out good but I found it to be slow with maps with larger dimensions.</p> <pre><code>function render () { let html = '' for (let row = 0; row &lt; mapHeight; row++) { html += '&lt;tr&gt;' for (let column = 0; column &lt; mapWidth; column++) { // Ignore &quot;nodeIndex&quot;, &quot;colorIndex&quot; and such nodeIndex = column + ( row * mapWidth ) let colorIndex = myNodes[nodeIndex].colorIndex html += `&lt;td style=&quot;background-color:${nodeColors[colorIndex]};&quot;&gt;&lt;/td&gt;` } html += '&lt;/tr&gt;' } //&quot;mapTable&quot; being the element in which this table is rendered mapTable.innerHTML = html } </code></pre> <p>Hope you guys like it and please feel welcome to give any criticism, have fun!</p> <p><strong>My page:</strong> <a href="https://github.com/Tlomoloko/Dijkstra_Visualizer" rel="nofollow noreferrer">https://github.com/Tlomoloko/Dijkstra_Visualizer</a></p>
[]
[ { "body": "<p>I don't know if there is a way to avoid the nested loop in this case because you need to do a calc that involves every inner loop index with every outer loop index.</p>\n<p>But I think that is not necessary to calculate <code>row * mapWidth</code> in every iteration in the inner loop, once that both variables are available outside it</p>\n<pre><code>for (let row = 0; row &lt; mapHeight; row++) {\n //...\n let cached = row * mapWidth;\n\n for (let column = 0; column &lt; mapWidth; column++) {\n nodeIndex = column + cached;\n let colorIndex = myNodes[nodeIndex].colorIndex;\n\n //...\n }\n//...\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T04:50:37.120", "Id": "257656", "ParentId": "257650", "Score": "2" } }, { "body": "<h2>Use DOM not markup</h2>\n<p>Your code builds DOM by building a string containing markup. Markup is intended as a transport format eg between server and client and you should avoid using markup to build page content when you have access to the DOM.</p>\n<h2>Building a table.</h2>\n<p>Generally building page content is best done using the DOM interface rather than creating a string containing the markup.</p>\n<p>For example to create a table and insert row then cells you would</p>\n<pre><code>function createTable(width, height, colors) {\n var r = , c; // row column\n const table = document.createElement(&quot;table&quot;);\n while (r &lt; height) {\n const row = table.insertRow();\n c = 0;\n while (c &lt; width) {\n cell = row.insertCell();\n cell.style.background = colors[c + r * width];\n c ++;\n }\n r ++;\n }\n document.appendChild(table);\n}\n</code></pre>\n<p>The references for calls and interfaces used are</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Node appendChild\">Node.appendChild</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Document createElement\">Document.createElement</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTableElement\">HTMLTableElement</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableElement/insertRow\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTableElement insertRow\">HTMLTableElement.insertRow</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTableRowElement\">HTMLTableRowElement</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableRowElement/insertCell\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTableRowElement insertCell\">HTMLTableRowElement.insertCell</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLTableCellElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLTableCellElement\">HTMLTableCellElement</a> inherits from <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLElement\">HTMLElement</a></li>\n</ul>\n<p>This will improve performance as there is no need to parse the markup.</p>\n<p>However as tables get larger them become slower and slower. A grid based path finding solution these days can contains 100,000+ cells which is well beyond the practical limit of a table.</p>\n<h2>A better way</h2>\n<p>Tables are complicated entities when all you display is color information. The optimal method to show a grid of pixels is to use a bitmap. In this case a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's HTMLCanvasElement\">HTMLCanvasElement</a> provides both a pixel store and an interface <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D\" rel=\"nofollow noreferrer\" title=\"MDN Web API's CanvasRenderingContext2D\">CanvasRenderingContext2D</a> to change pixel content as needed.</p>\n<h3>Create Canvas</h3>\n<p>To create a canvas and prepare a canvas</p>\n<pre><code>function createCanvas(container, width, height) {\n const canvas = Object.assign(document.createElement(&quot;canvas&quot;), {width, height});\n container.appendChild(canvas);\n return canvas;\n}\n</code></pre>\n<p>To be practical the canvas pixels need to be of a discernible size. We can do this by sizing the canvas using a CSS rule. Because images are interpolated (smoothed) we also need to ensure pixels use the correct rendering rule.</p>\n<pre><code>canvas {\n width: 100%;\n height: 100%;\n image-rendering: pixelated; \n}\n</code></pre>\n<h3>Cells and pixels</h3>\n<p>The issue now is the pixel colors. The array <code>nodeColors</code> (not passed to the function you provide) contains strings representing a CSS color. This is unfortunately not a RGBA8 pixel value. <code>nodeColors</code> ideally should be an array of 32bit Unsigned ints each int representing a pixel.</p>\n<p>To convert from a CSS # color (in the form <code>#RRGGBBAA</code>) to a RGBA8 pixel</p>\n<pre><code>function CSStoPixel(cssHashColor) {\n return parseInt(cssHashColor.slice(1,3), 16) + \n ((parseInt(cssHashColor.slice(3,5), 16) &lt;&lt; 8) + \n ((parseInt(cssHashColor.slice(5,7), 16) &lt;&lt; 16) + \n ((parseInt(cssHashColor.slice(5,7), 16) &lt;&lt; 24);\n}\n</code></pre>\n<p>Ideally you would use the raw channel values and build the RGBA8 pixels</p>\n<pre><code>function RGBAtoPixel(r, g, b, a) { // each 8 bit in range 0 - 255\n return (a &lt;&lt; 24) + (b &lt;&lt; 16) + (g &lt;&lt; 8) + r;\n}\n</code></pre>\n<p>Then use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Uint32Array\">Uint32Array</a> to create the <code>nodeColors</code> to hold each pixel</p>\n<pre><code>const nodeColors = new Uint32Array(width * height); // colors are defaulted to transparent black\n</code></pre>\n<h3>Rendering</h3>\n<p>Once you have setup the canvas and the pixel color array it then is trivial to transfer the pixels from the color array to the canvas display buffer.</p>\n<p>To...</p>\n<ul>\n<li>get canvas pixels use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData\" rel=\"nofollow noreferrer\" title=\"MDN Web API's CanvasRenderingContext2D getImageData\">ctx.getImageData</a></li>\n<li>or create a buffer <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/createImageData\" rel=\"nofollow noreferrer\" title=\"MDN Web API's CanvasRenderingContext2D createImageData\">ctx.createImageData</a></li>\n<li>get a 32bit view of a 8bit buffer create the array from the image data <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/buffer\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Uint8ClampedArray buffer\">Uint8ClampedArray.buffer</a></li>\n<li>set pixels using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Uint32Array set\">Uint32Array.set</a></li>\n<li>move pixels to canvas store send the image data using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData\" rel=\"nofollow noreferrer\" title=\"MDN Web API's CanvasRenderingContext2D setImageData\">ctx.putImageData</a></li>\n</ul>\n<pre><code>// Assumes pixel array size matches canvas pixel count\nfunction displayPixelArray(pixels, canvas) {\n const ctx = canvas.getContext(&quot;2d&quot;);\n const imgBuf = ctx.getImageData(0, 0, canvas.width, canvas.height);\n new Uint32Array(imgBuf.data.buffer).set(pixels);\n ctx.putImageData(imgBuf, 0, 0);\n}\n</code></pre>\n<h2>Example</h2>\n<p>The example below intends to only show how the methods above can be used to animate complex grid based data with a low rendering overhead.</p>\n<p>It does not implement Dijkstra's algorithm but rather a derived path finding solution.</p>\n<p>It converts a path finding function into a generator function so that the solution can be paused at defined steps so that the partial solution can be displayed</p>\n<p>There are various other minor differences between the description in my answer and the implementations below.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ctx = canvas.getContext(\"2d\");\nfunction resized() {\n canvas.width = innerWidth;\n canvas.height = innerHeight;\n}\nresized();\naddEventListener(\"resize\", resized);\nconst MAP_WIDTH = 128; // in pixels\nconst MAP_HEIGHT = 128; // in pixels\nconst DEMO_STEP_TIME = 34; // in ms\nconst DEMO_RESTART_TIME = 1000; // in ms\nconst DENO_PX_PER_STEP = 96;\nconst DEMO_WALL_COUNT = 160;\nconst randUint = (m, M) =&gt; Math.random() * (M - m) + m | 0;\nconst randOdds = (odds) =&gt; Math.random() &lt; 1 / odds;\nconst P2 = (x, y) =&gt; ({x, y});\nconst pathCols = new Uint32Array(MAP_WIDTH * MAP_HEIGHT);\nconst worldMap = new Uint32Array(MAP_WIDTH * MAP_HEIGHT);\nconst worldMapImg = createCanvas(MAP_WIDTH, MAP_HEIGHT);\nconst pathColImg = createCanvas(MAP_WIDTH, MAP_HEIGHT);\nconst start = P2(10, 10);\nconst end = P2(MAP_WIDTH - 10, MAP_HEIGHT - 10);\nvar demoQuickRestart = false;\n\ndemo();\nfunction stepPathFinding(pathSolver) {\n if (pathSolver.next().value !== undefined) {\n setTimeout(stepPathFinding, DEMO_STEP_TIME, pathSolver);\n } else {\n setTimeout(demo, demoQuickRestart ? 18 : DEMO_RESTART_TIME) \n }\n displayPathing(ctx, pathCols, pathColImg, worldMapImg);\n}\nfunction demo() {\n createRandomMap(worldMapImg, worldMap, pathColImg);\n const pathSolver = findShortest(pathCols, worldMap, start, end, MAP_WIDTH, MAP_HEIGHT);\n stepPathFinding(pathSolver); \n}\nfunction createRandomMap(mapImg, map) {\n const w = mapImg.width, h = mapImg.height;\n mapImg.ctx.clearRect(0, 0, w, h);\n mapImg.ctx.fillStyle = \"#0C0\";\n mapImg.ctx.fillRect(0, 0, w, h);\n mapImg.ctx.clearRect(2, 2, w-4, h-4);\n mapImg.ctx.beginPath();\n var c = DEMO_WALL_COUNT, wW, wH; // w for wall\n while (c--) {\n if (randOdds(2)) {\n wW = 1;\n wH = randUint(9, 26);\n } else {\n wH = 1;\n wW = randUint(9, 26);\n }\n mapImg.ctx.rect(randUint(0, w - wW), randUint(0, h - wH), wW, wH);\n }\n mapImg.ctx.fill();\n map.set(new Uint32Array(mapImg.ctx.getImageData(0, 0, w, h).data.buffer));\n}\nfunction createCanvas(width, height) {\n const canvas = Object.assign(document.createElement(\"canvas\"), {width, height});\n canvas.ctx = canvas.getContext(\"2d\");\n return canvas;\n}\nfunction displayPathing(ctx, cols, colsImg, wMapImg) {\n ctx.imageSmoothingEnabled = false;\n const w = ctx.canvas.width, h = ctx.canvas.height;\n ctx.clearRect(0, 0, w, h);\n ctx.drawImage(wMapImg, 0, 0, w, h);\n const imgBuf = colsImg.ctx.getImageData(0, 0, colsImg.width, colsImg.height);\n new Uint32Array(imgBuf.data.buffer).set(cols);\n colsImg.ctx.putImageData(imgBuf, 0, 0);\n ctx.drawImage(colsImg, 0, 0, w, h)\n}\n\n\nfunction *findShortest(dMap, wMap, start, end, w, h) {\n // name rules use in this function are u,l,r,d for up, left, right, down\n var pxCount = 0, idx, minDist;\n dMap.fill(0); \n const worldSize = w * h;\n const markWalls = () =&gt; {\n var idx = worldSize;\n while (idx--) { dMap[idx] = wMap[idx] !== 0 ? 0x1FFFFFF : 0 }\n }\n markWalls();\n const endIdx = end.x + end.y * w;\n const startIdx = start.x + start.y * w;\n const stack = [startIdx];\n if (dMap[startIdx] !== 0 || dMap[endIdx] !== 0) { demoQuickRestart = true; return; } // no solution.\n demoQuickRestart = false;\n dMap[startIdx] = 0xFF000000;\n const nextNode = (idx, dist) =&gt; {\n if (!dMap[idx] &amp;&amp; !wMap[idx]) {\n dMap[idx] = 0xFF000000 + dist + 32;\n stack.push(idx);\n return 1;\n }\n return 0;\n }\n const checkHomeStep = (currentIdx, nextIdx) =&gt; {\n const dist = dMap[nextIdx] &amp; 0xFFFF;\n if (dist &lt;= minDist) {\n if (dist &lt; minDist || randOdds(2)) {\n minDist = dist;\n return nextIdx;\n }\n } \n return currentIdx;\n }\n while (stack.length) {\n const pxIdx = stack.shift();\n const dist = dMap[pxIdx] &amp; 0xFFFF;\n const u = pxIdx - w, d = pxIdx + w, l = pxIdx - 1, r = pxIdx + 1;\n u &gt;= 0 &amp;&amp; nextNode(u, dist);\n d &lt; worldSize &amp;&amp; nextNode(d, dist);\n l % w &gt; 0 &amp;&amp; nextNode(l, dist);\n r % w &lt; w - 1 &amp;&amp; nextNode(r, dist); \n (pxCount++ % DENO_PX_PER_STEP) === 0 &amp;&amp; (yield pxIdx);\n }\n \n // find path home\n idx = endIdx;\n if (dMap[idx] &gt; 0) { // only if a clear path found;\n while (idx !== startIdx) {\n const u = idx - w, d = idx + w, l = idx - 1, r = idx + 1;\n minDist = dMap[u] &amp; 0xFFFF;\n idx = u;\n idx = checkHomeStep(idx, d);\n idx = checkHomeStep(idx, l);\n idx = checkHomeStep(idx, r);\n dMap[idx] = 0xFFFFFFFF;\n yield idx;\n }\n }\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas {\n position: absolute;\n top: 0px;\n left: 0px; \n background: #036;\n image-rendering: pixelated; \n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;canvas id=\"canvas\"&gt;&lt;/canvas&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T00:27:36.333", "Id": "509020", "Score": "0", "body": "Thank you so much for taking your time to answer my question so thoroughly! I really had no idea how to make this faster. I'll take a look at these elements that you mentioned, I'm sure they will be of great help" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T15:48:02.820", "Id": "257681", "ParentId": "257650", "Score": "2" } } ]
{ "AcceptedAnswerId": "257681", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T00:43:56.917", "Id": "257650", "Score": "1", "Tags": [ "javascript", "html", "css" ], "Title": "Dijktra's Algorithm Visualizer" }
257650
<p>Here is my shot at <a href="https://www.cis.upenn.edu/%7Ecis194/spring13/hw/08-IO.pdf" rel="nofollow noreferrer">Homework 8</a> of <a href="https://www.cis.upenn.edu/%7Ecis194/spring13/hw/08-IO.pdf" rel="nofollow noreferrer">CIS-194</a> (from Spring '13). The problem is about a hierarchy of employees at a company (a tree), each node being of type <a href="https://www.cis.upenn.edu/%7Ecis194/spring13/extras/08-IO/Employee.hs" rel="nofollow noreferrer"><code>Employee</code></a>, each described by a label (<code>empName :: String</code>) and an integer value (<code>empFun :: Integer</code>). We need to choose a subset of employees so that no two chosen employees have a parent-child relationship within the tree and the sum of <code>empFun</code>s of the chosen employees is maximised.</p> <p>Some of the outline and structure of this code is based on what was suggested by the document, but I am curious to know if the rest of it is consistent and idiomatic Haskell. I'm not sure what I'm expecting as feedback, but any is welcome.</p> <pre><code>module Party where import Data.List ( sort ) import Data.Tree ( Tree(Node) ) import Employee ( Employee(empFun, empName), Fun, GuestList(..) ) instance Semigroup GuestList where (GL a b) &lt;&gt; (GL c d) = GL (a ++ c) (b + d) instance Monoid GuestList where mempty = GL [] 0 glCons :: Employee -&gt; GuestList -&gt; GuestList glCons emp (GL a b) = GL (a ++ [emp]) (empFun emp) moreFun :: GuestList -&gt; GuestList -&gt; GuestList moreFun = max treeFold :: (a -&gt; [b] -&gt; b) -&gt; Tree a -&gt; b treeFold f (Node label subtree) = f label (map (treeFold f) subtree) nextLevel :: Employee -&gt; [(GuestList, GuestList)] -&gt; (GuestList, GuestList) nextLevel emp subList = (glCons emp (foldMap snd subList), foldMap (uncurry max) subList) maxFun :: Tree Employee -&gt; GuestList maxFun tree = uncurry moreFun $ treeFold nextLevel tree getFormattedGL :: GuestList -&gt; String getFormattedGL gl = unlines ((&quot;Total fun &quot; ++ show (fun gl)) : sort (map empName (emps gl))) where fun (GL _ fun) = fun emps (GL emps _) = emps work :: [Char] -&gt; String work = getFormattedGL . maxFun . read main :: IO () main = readFile &quot;company.txt&quot; &gt;&gt;= putStrLn . work </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T09:29:02.293", "Id": "508938", "Score": "0", "body": "@bisserlis \"Employee\" in my post is a URL that leads to the file https://www.cis.upenn.edu/~cis194/spring13/extras/08-IO/Employee.hs" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T19:29:15.533", "Id": "509105", "Score": "0", "body": "Oops! Somehow I glossed right over that." } ]
[ { "body": "<p>Unfortunately, there is a bug in <code>glCons</code>. The employee's fun should get added, not replace the current fun level:</p>\n<pre><code>glCons :: Employee -&gt; GuestList -&gt; GuestList\nglCons emp (GL a b) = GL (a ++ [emp]) (empFun emp)\n -- ^\n</code></pre>\n<p>But let's stay on <code>glCons</code>. We can expect <code>glCons</code> to be used via <code>foldr</code>. However, the <a href=\"https://stackoverflow.com/questions/12296694/the-performance-of-with-lazy-evaluation\"><code>++</code> operator leads to quadratic behaviour</a>. When we add a single element, we should therefore use <code>(:)</code> (and <code>reverse</code>, if the order matters):</p>\n<pre><code>glCons :: Employee -&gt; GuestList -&gt; GuestList\nglCons emp (GL a b) = GL (emp : a) (empFun emp + b)\n</code></pre>\n<p>Other than that the code seems fine.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T16:52:57.483", "Id": "258807", "ParentId": "257652", "Score": "1" } } ]
{ "AcceptedAnswerId": "258807", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T01:43:36.243", "Id": "257652", "Score": "2", "Tags": [ "beginner", "haskell", "tree", "dynamic-programming" ], "Title": "Haskell Dynamic Programming on a Tree" }
257652
<p>I'm a beginner both in Python and Tensorflow.</p> <p>I made a toy neural network to learn both.</p> <p>The objective of the NN is to identify the module c, or separation between lines defined by random points, and the width ε of each line, as show on this image, which shows a single sample taken from the ones used to train the network:</p> <p><a href="https://i.stack.imgur.com/O3OBl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O3OBl.png" alt="screenshot" /></a></p> <p>Because I generate the samples, I have unlimited samples. But the network gives very poor results.</p> <p>Here is a plot of c_predicted/c, for each c. A good result would be to get c_predicted/c≈1 for all values of c</p> <p>EDIT: fixed a bug on this chart plotting, and updated the chart</p> <p><a href="https://i.stack.imgur.com/PrgM3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PrgM3.png" alt="screenshot" /></a></p> <p>I got even worse errors by normalizing the data, and by using batch normalization layers.</p> <p>Tensorflow rapidly fills the memory even when small networks, so to save memory, I reused one layer &quot;named convI&quot;</p> <p>&quot;convI&quot; layer is expected to enhance the output of a layer which &quot;almost&quot; has the answer. For that reason, I have 3 output layers, which all should output the same result, but are followed by a convI layer, and after convI, the output is calculated again, expecting to be an improved guess, compared to the former output.</p> <p><a href="https://i.stack.imgur.com/KhdS2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KhdS2.png" alt="screenshot" /></a></p> <p>I read and tried to follow tensorflow best practices, but I'm doing something horribly wrong, and I don't know what.</p> <p>Here is the code. I used &quot;if True:&quot; statements to indent blocks of code, to make it more readable.</p> <pre><code>#Ejemplo tomado de #https://keras.io/examples/timeseries/timeseries_classification_from_scratch/ import tensorflow as tf tf.keras.backend.clear_session() #Releases rsources lockedby older crashed processes #this code is needed to avoid crashes due to a bug in tensorflow gpus = tf.config.list_physical_devices('GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) from tensorflow import keras from tensorflow.keras import layers from tensorflow.keras import mixed_precision policy = mixed_precision.Policy('mixed_float16') mixed_precision.set_global_policy(policy) print(&quot;-&quot; * 50)#prints a line print('Compute dtype: %s' % policy.compute_dtype) print('Variable dtype: %s' % policy.variable_dtype) print(&quot;-&quot; * 50) import numpy as np import inspect import matplotlib.pyplot as plt class Dataset(object): numberOfSamples = 10000 sampleShape = [4000,1] cMin = 0.1 cMax = 10 εMin = 0 εMax = 0.4 fractionOfTrainVsTest = 0.9 rangeOfSamples = range(numberOfSamples) indexofSplit=numberOfSamples*fractionOfTrainVsTest #c&amp;ε used for training c=None ε=None x=None x_normalized=None#x as x_test for NN y_normalized=None#y as y_test for NN StdDevX_i=None StdDevX_global=None#Standard deviation (of the standard deviation) of the entire samples used in training. def __init__(self): pass def CreateDataset(self, numberOfSamples=10000, sampleShape=[4000,1], cMin=0.1,cMax=10, εMin=0,εMax=0.4, fractionOfTrainVsTest=0.9): #copies all parameters to the class instance parameters = inspect.getfullargspec(self.CreateDataset) [setattr(self, &quot;self.&quot; + var, value) for var , value in zip(list(parameters[0][1:]) ,list(parameters[3]))] [print(name,&quot;==&quot;,value) for name,value in vars(self).items()] self.rangeOfSamples = range(self.numberOfSamples) print(&quot;Generating samples&quot;) if True: #c[i] is the module (separation between &quot;lines&quot; to be found by the NN self.c = [np.random.uniform(self.cMin,self.cMax) for n in self.rangeOfSamples] #ε[i] is noise amplitude (error) as fraction of c self.ε = [np.random.uniform(self.εMin,self.εMax) for n in self.rangeOfSamples] #Number of lines of each sample NLines = [np.random.randint(5,50) for n in self.rangeOfSamples] #x for x_train (is an y coordinate) #x=c*±(pick one line from NLines)+ε #x[i].shape==sampleShape self.x = [self.c[r] * (np.diff(np.sort(np.random.randint(-NLines[r],NLines[r],size=self.sampleShape)),append=0) + self.ε[r] * np.random.uniform(-1 , 1,self.sampleShape))\ for r in self.rangeOfSamples] #sort_x = False#ToDo: explore if sorting enhances performance of the NN, as base data or extra feature. #if sort_x: # x = [np.sort(x_i,axis=0) for x_i in x] self.StdDevX_i = [np.std(self.x[r]) for r in self.rangeOfSamples] self.StdDevX_global = np.std(self.StdDevX_i) self.x_normalized = [self.x[r] / self.StdDevX_i[r] for r in self.rangeOfSamples]# / self.StdDevX_global#supossed to be already averaged to 0 self.c_normalized = [self.c[r] / self.StdDevX_i[r] for r in self.rangeOfSamples]# / self.StdDevX_global self.ε_normalized = [self.ε[r] * self.c_normalized[r] for r in self.rangeOfSamples] #import Plotear as pt #pt.PlotearXY(Y=self.StdDevX_i/self.StdDevX_global,scatter=True) ##ExtraFeatures #Δ_sorted_self.x_normalized = [np.diff(np.sort(sample,axis=0),axis=0) for sample in self.x_normalized] #ToDo: reduce to unique [values, counts = np.unique(words, return_counts=True)] ##Export to excel and open #if True: # import os # myPath=os.path.join(os.environ['temp'], 'Dataset.xlsx') # df.to_excel(myPath,sheet_name=&quot;Python data&quot;,engine='xlsxwriter') # os.startfile(myPath) #import Plotear as pt #i = np.random.randint(len(x)) #pt.PlotearXY(Y=x[i],Title=&quot;c=&quot; + str(c[i]) + &quot;; ε=&quot; + str(ε[i]) + &quot;; N° lines=&quot; + str(NLines[i]),scatter=True) #pt.PlotearXY(Y=self.x_normalized[0],Title=&quot;c=&quot; + str(c[0]) + &quot;; ε=&quot; + str(ε[0]) + &quot;; N° lines=&quot; + str(NLines[0]),scatter=True) if True:#Format data for Keras self.indexofSplit = int(self.fractionOfTrainVsTest * len(self.x)) self.x_normalized = np.asarray(self.x_normalized) self.y_normalized = np.asarray([ [self.c_normalized[r], self.ε_normalized[r]] for r in self.rangeOfSamples])#Esta normalizado entre 0 y 1 x_train = self.x_normalized[:self.indexofSplit].astype('float32') x_test = self.x_normalized[self.indexofSplit:].astype('float32') y_train = self.y_normalized[:self.indexofSplit].astype('float32') y_test = self.y_normalized[self.indexofSplit:].astype('float32') print(&quot;Datos generados&quot;) return x_train, y_train, x_test, y_test def Predict(self, model, NotNormalized_X): stdevX=np.std(NotNormalized_X,axis=1,keepdims=True) NormalizedX=np.divide(NotNormalized_X,stdevX)#/self.StdDevX_global#chequear == self.x_normalized Prediction=model.predict(NormalizedX)[-1]*np.squeeze(stdevX,axis=2)#*self.StdDevX_global# return Prediction myData = Dataset() x_train, y_train, x_test, y_test = myData.CreateDataset() if True:#Build a model def make_model_feedback_output(input_shape, output_shape): #Modern NVIDIA GPUs use a special hardware unit called Tensor Cores that can multiply float16 matrices very quickly. However, Tensor Cores requires certain dimensions of tensors to be a multiple of 8. #tf.keras.layers.Dense(units=64) #tf.keras.layers.Conv2d(filters=48, kernel_size=7, stride=3) #tf.keras.layers.LSTM(units=64) #tf.keras.Model.fit(epochs=2, batch_size=128) input_layer = keras.layers.Input(input_shape) #-------------------------------------------------------------------------------------- conv0 = keras.layers.Conv1D(filters=64, kernel_size=16, padding=&quot;valid&quot;, activation=&quot;swish&quot;)(input_layer) conv1 = keras.layers.Conv1D(filters=64, kernel_size=16, padding=&quot;valid&quot;, activation=&quot;swish&quot;)(conv0) #conv1 = keras.layers.BatchNormalization()(conv1) #conv1 = keras.layers.LeakyReLU()(conv1) #-------------------------------------------------------------------------------------- convI = keras.layers.Conv1D(filters=64, kernel_size=16, padding=&quot;valid&quot;, activation=&quot;swish&quot;) #-------------------------------------------------------------------------------------- conv2 = convI(conv1) #conv2 = keras.layers.BatchNormalization()(conv2) #conv2 = keras.layers.LeakyReLU()(conv2) gap1 = keras.layers.GlobalAveragePooling1D()(conv2) #Output dtype needs to be dtype='float32' for mixed_precision output_layer1 = keras.layers.Dense(output_shape[0], activation='swish',dtype='float32', name='output_layer1')(gap1) #-------------------------------------------------------------------------------------- conv3 = convI(conv2) #conv3 = keras.layers.BatchNormalization()(conv3) #conv3 = keras.layers.LeakyReLU()(conv3) gap2 = keras.layers.GlobalAveragePooling1D()(conv3) #Output dtype tiene que ser dtype='float32' para que funcione mixed_precision output_layer2 = keras.layers.Dense(output_shape[0], activation='swish',dtype='float32', name='output_layer2')(gap2) #-------------------------------------------------------------------------------------- conv4 = convI(conv3) #conv4 = keras.layers.BatchNormalization()(conv4) #conv4 = keras.layers.LeakyReLU()(conv4) gap3 = keras.layers.GlobalAveragePooling1D()(conv4) #Output dtype tiene que ser dtype='float32' para que funcione mixed_precision output_layer3 = keras.layers.Dense(output_shape[0], activation='swish',dtype='float32', name='output_layer3')(gap3) #-------------------------------------------------------------------------------------- return keras.models.Model(inputs=input_layer, outputs=[output_layer1, output_layer2, output_layer3]) model = make_model_feedback_output(input_shape=x_train.shape[1:],output_shape=y_train.shape[1:]) if True:#Train the model Epochs = 100 Patience = 100 batch_size = 128#Has to be multiple of 8 to take advantage of mixed_precision pathForSavingFile = &quot;z:\\best_model.h5&quot; callbacks = [keras.callbacks.ModelCheckpoint(pathForSavingFile, save_best_only=True, monitor=&quot;val_loss&quot;), keras.callbacks.ReduceLROnPlateau(monitor=&quot;val_loss&quot;, factor=0.5, patience=Patience, min_lr=0.0001), keras.callbacks.EarlyStopping(monitor=&quot;val_loss&quot;, patience=Patience, verbose=1),] model.compile(optimizer=&quot;adam&quot;, loss={'output_layer1': 'MeanSquaredError', 'output_layer2': 'MeanSquaredError', 'output_layer3': 'MeanSquaredError'}, metrics={'output_layer1': 'MeanSquaredError', 'output_layer2': 'MeanSquaredError', 'output_layer3': 'MeanSquaredError'},) print(&quot;Training start...&quot;) print(model.summary()) print('\a')#beep import time start_time = time.time() history = model.fit(x_train, [y_train for i in range(3)], batch_size=batch_size, epochs=Epochs, callbacks=callbacks, validation_split=0.1, verbose=2,) print(&quot;Training ended&quot;) print(&quot;--- %s minutes ---&quot; % ((time.time() - start_time) / 60)) print('\a')#beep if True:#Evaluate model on test data model = keras.models.load_model(pathForSavingFile) Losses = model.evaluate(x_test, [y_test,y_test,y_test]) test_loss, test_acc = (Losses[0] , Losses[-1]) print(&quot;Test accuracy&quot;, test_acc) print(&quot;Test loss&quot;, test_loss) if True:#Plot the model's training and validation loss metric = &quot;mean_squared_error&quot; Loss_result = &quot;val_mean_squared_error&quot; plt.figure() plt.plot(history.history['output_layer3_loss']) plt.plot(history.history[&quot;val_output_layer3_mean_squared_error&quot;]) plt.title(&quot;model &quot; + metric) plt.ylabel(metric, fontsize=&quot;large&quot;) plt.xlabel(&quot;epoch&quot;, fontsize=&quot;large&quot;) plt.legend([&quot;train; min=&quot; + str(min(history.history['output_layer3_loss'])), &quot;val; min=&quot; + str(min(history.history[&quot;val_output_layer3_mean_squared_error&quot;]))], loc=&quot;best&quot;) plt.show() plt.close() if True:#Plot percentage of error of predicted c Prediction = myData.Predict(model,np.asarray(myData.x)) PredictionC, Predictionε = [Prediction[:,i][:] for i in range(2)] PercentErrorIn_C = np.divide( PredictionC,np.asarray(myData.c)) #myData.y_normalized is guaranteed to be &gt;0 if True:#Coordinates for plotting a predicted example YY = PercentErrorIn_C[myData.indexofSplit:] XX = np.asarray(myData.c[myData.indexofSplit:] ) fig = plt.figure() fig.tight_layout() fig.subplots_adjust(bottom=0.2) ax = plt.gca() ax.scatter(XX,YY,marker='o',s=0.5) plt.legend([&quot;Ratio of error: c_estimated/c&quot;], loc=&quot;best&quot;) plt.title(&quot;Error c_predicted/c&quot;) #plt.draw() plt.show() plt.close() if True:#Plot an example index_random = np.random.randint(myData.indexofSplit,len(myData.x_normalized)) Prediction = myData.Predict(model,myData.x[index_random-1:index_random]) #Prediction = (model.predict(myData.x_normalized)[index_random])[-1]#Only last output (output3) if True:#Coordinates for plotting a predicted example YY = myData.x[index_random] XX = np.arange(0,len(YY)) #c_predicted,ε_predicted = (-0.5+Prediction[0]) * MaxAbsX[index_random]*2, Prediction[1] #c_predicted,ε_predicted = (-0.5 + Prediction[0,0]) * MaxAbsX[index_random] * 2, Prediction[0,1] #c_predicted,ε_predicted = ( Prediction[0,0]) * MaxAbsX[index_random] , Prediction[0,1] c_predicted,ε_predicted = Prediction[0,0] , Prediction[0,1] cX = np.array([0,XX[-1]]) cY = np.array([1,1]) * c_predicted εX = np.array([1,1]) * XX[-1] / 2 εY = cY + np.array([-1,1]) * ε_predicted #ε is noise amplitude as a fraction of c fig = plt.figure() fig.tight_layout() fig.subplots_adjust(bottom=0.2) ax = plt.gca() ax.scatter(XX,YY,marker='o',s=1)#.abs() ax.plot(cX,cY,marker='|',markersize=10) ax.plot(εX,εY,marker='_',markersize=10) plt.title('c=' + '{0:.2f}'.format(myData.c[index_random]) + &quot;; c predicted=&quot; + '{0:.2f}'.format(c_predicted) + &quot;; c_predicted/c=&quot; + '{0:.2f}'.format(c_predicted/myData.c[index_random])) #plt.draw() plt.show() plt.close() pass </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T03:21:45.157", "Id": "257653", "Score": "3", "Tags": [ "beginner", "python-3.x", "tensorflow" ], "Title": "Toy neural network give poor results" }
257653
<h1>Introduction</h1> <p>I have implemented an algorithm that applies auto tiling to a 2D tile map for a game, selecting the correct tiles according to their neighborhood. Given a string representation in a classic roguelike form such as this</p> <p><a href="https://i.stack.imgur.com/G9q8D.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G9q8D.png" alt="Input" /></a></p> <p>the algorithm yields a generated map with properly connected tiles as follows</p> <p><a href="https://i.stack.imgur.com/oR6SN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oR6SN.png" alt="Output" /></a></p> <h1>Algorithm</h1> <p>The general idea of the algorithm is to create a distinct bitmask that indicates in which directions neighbors of the same kind are already available.</p> <p><a href="https://i.stack.imgur.com/9p0st.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9p0st.png" alt="Setup" /></a></p> <p>In the sample image a tile in the center has a value based on its adjacent tiles (and corners under a particular conditition described later). Since the adjacent tiles at N, NE and E are of the same kind the tile has a total value of 2 + 4 + 16.</p> <p>Corners only contribute to the value of a tile if their cardinal neighbors connecting the corners to the center are of the same kind as well. Therefore the SE and SW tiles would not be considered for calculation of the tile value no matter their kind unlike the NE tile.</p> <p>The mapping of adjacencies to tiles is visualized in my use case as follows:</p> <p><a href="https://i.stack.imgur.com/j3IXI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/j3IXI.png" alt="Mapping" /></a></p> <h1>Implementation</h1> <p>Using this algorithm one has 48 different configurations and mappings of tile value to actual tile/sprite from the tileset. I have cleaned some parts of my code and would like to receive further input what may be improved. The core problem was to compute the atlas index to deduce the coordinates in the atlas via the <code>std::unordered_map</code>.</p> <p>All unrelated data and methods have been removed from the code for review purposes:</p> <pre class="lang-cpp prettyprint-override"><code>class TileMap : public sf::Drawable, public sf::Transformable { public: auto loadFromString(const std::string &amp;String, const sf::Vector2&lt;uint16&gt; Size) -&gt; bool { Data = String; Width = Size.x; Height = Size.y; // ... snip ... for (auto Column = 0; Column &lt; Width; ++Column) { for (auto Row = 0; Row &lt; Height; ++Row) { auto Tile = Data[Column + Row * Width]; // ... snip ... auto Index = atlasIndexAt(Column, Row, Tile); auto AtlasPosition = Atlas[Index]; // ... snip ... } } return true; } private: auto atlasIndexAt(const uint16 Column, const uint16 Row, const char Tile) -&gt; uint8 { auto T = tileValueAt(Column, Row - 1, Tile); auto L = tileValueAt(Column - 1, Row, Tile); auto R = tileValueAt(Column + 1, Row, Tile); auto B = tileValueAt(Column, Row + 1, Tile); // Corners are only relevant if both cardinals connecting the corner to the // center tile have positive value. auto TL = (T == 0 || L == 0) ? 0 : tileValueAt(Column - 1, Row - 1, Tile); auto TR = (T == 0 || R == 0) ? 0 : tileValueAt(Column + 1, Row - 1, Tile); auto BL = (B == 0 || L == 0) ? 0 : tileValueAt(Column - 1, Row + 1, Tile); auto BR = (B == 0 || R == 0) ? 0 : tileValueAt(Column + 1, Row + 1, Tile); return TL * 1 + T * 2 + TR * 4 + L * 8 + R * 16 + BL * 32 + B * 64 + BR * 128; } auto tileValueAt(const uint16 Column, const uint16 Row, const char Tile) -&gt; uint8 { if (Column &gt;= Width || Row &gt;= Height || Column == std::numeric_limits&lt;uint16&gt;::max() || Row == std::numeric_limits&lt;uint16&gt;::max()) { return 1; } return Data[Column + Row * Width] == Tile ? 1 : 0; } // ... snip ... uint16 Width; uint16 Height; std::string Data; std::unordered_map&lt;uint8, sf::Vector2&lt;uint8&gt;&gt; Atlas{ {208, sf::Vector2&lt;uint8&gt;(0, 0)}, {248, sf::Vector2&lt;uint8&gt;(1, 0)}, {104, sf::Vector2&lt;uint8&gt;(2, 0)}, // ... snip ... }; }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-21T11:38:18.173", "Id": "512538", "Score": "0", "body": "You could also just create a giant jump table with all possible combinations for your algorithm." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T04:33:04.837", "Id": "257655", "Score": "3", "Tags": [ "c++", "c++17", "iteration" ], "Title": "Algorithm for auto tiling of tiles in a 2D tile map" }
257655
<p>I'm a rookie in c++ programming. Recently, caesar ciphers caught my eye. I ended up making a rot&lt;N&gt; text converter, where N is any value between 2 and 25. Please keep in mind that I'm still new to programming and don't know advanced level stuff. All your feedbacks will be appreciated. FYI, this was developed in Visual Studio 2019.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; std::string user_input;//user input string std::string output_str;//output ciphertext int x;//loop counter int corres_num[1500000] = {};//corresponding number according to alphabets int cipher_value;//the cipher rotation value void termclr()//terminal clear function { #ifdef __linux__ system(&quot;clear&quot;); #elif _WIN32 system(&quot;cls&quot;); #endif } void convertion()//user input convertion { std::string output_str_assign = &quot;&quot;;//assigns individual ciphered characters to main ciphertext int calc = 0;//contributes in assigning &lt;output&gt; int output = 0;//assigns individual cipher characters if (user_input[x] == 'A' || user_input[x] == 'a') { corres_num[x] = 1; } else if (user_input[x] == 'B' || user_input[x] == 'b') { corres_num[x] = 2; } else if (user_input[x] == 'C' || user_input[x] == 'c') { corres_num[x] = 3; } else if (user_input[x] == 'D' || user_input[x] == 'd') { corres_num[x] = 4; } else if (user_input[x] == 'E' || user_input[x] == 'e') { corres_num[x] = 5; } else if (user_input[x] == 'F' || user_input[x] == 'f') { corres_num[x] = 6; } else if (user_input[x] == 'G' || user_input[x] == 'g') { corres_num[x] = 7; } else if (user_input[x] == 'H' || user_input[x] == 'h') { corres_num[x] = 8; } else if (user_input[x] == 'I' || user_input[x] == 'i') { corres_num[x] = 9; } else if (user_input[x] == 'J' || user_input[x] == 'j') { corres_num[x] = 10; } else if (user_input[x] == 'K' || user_input[x] == 'k') { corres_num[x] = 11; } else if (user_input[x] == 'L' || user_input[x] == 'l') { corres_num[x] = 12; } else if (user_input[x] == 'M' || user_input[x] == 'm') { corres_num[x] = 13; } else if (user_input[x] == 'N' || user_input[x] == 'n') { corres_num[x] = 14; } else if (user_input[x] == 'O' || user_input[x] == 'o') { corres_num[x] = 15; } else if (user_input[x] == 'P' || user_input[x] == 'p') { corres_num[x] = 16; } else if (user_input[x] == 'Q' || user_input[x] == 'q') { corres_num[x] = 17; } else if (user_input[x] == 'R' || user_input[x] == 'r') { corres_num[x] = 18; } else if (user_input[x] == 'S' || user_input[x] == 's') { corres_num[x] = 19; } else if (user_input[x] == 'T' || user_input[x] == 't') { corres_num[x] = 20; } else if (user_input[x] == 'U' || user_input[x] == 'u') { corres_num[x] = 21; } else if (user_input[x] == 'V' || user_input[x] == 'v') { corres_num[x] = 22; } else if (user_input[x] == 'W' || user_input[x] == 'w') { corres_num[x] = 23; } else if (user_input[x] == 'X' || user_input[x] == 'x') { corres_num[x] = 24; } else if (user_input[x] == 'Y' || user_input[x] == 'y') { corres_num[x] = 25; } else if (user_input[x] == 'Z' || user_input[x] == 'z') { corres_num[x] = 26; } else { output_str_assign = user_input[x]; }//keeping user input intact if user input is not within a-z calc = corres_num[x] + cipher_value;//assigning &lt;calc&gt; value if (calc &gt; 26)//setting value if &lt;calc&gt; goes over 26 { output = calc - 26; } else if (calc &lt;= 26 &amp;&amp; calc &gt; 0)//maintaing &lt;calc&gt; value if within range { output = calc; } switch (output)//assigning individual cipher characters { case 1:if (isupper(user_input[x])) { output_str_assign = &quot;A&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;a&quot;; } break; case 2:if (isupper(user_input[x])) { output_str_assign = &quot;B&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;b&quot;; } break; case 3:if (isupper(user_input[x])) { output_str_assign = &quot;C&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;c&quot;; } break; case 4:if (isupper(user_input[x])) { output_str_assign = &quot;D&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;d&quot;; } break; case 5:if (isupper(user_input[x])) { output_str_assign = &quot;E&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;e&quot;; } break; case 6:if (isupper(user_input[x])) { output_str_assign = &quot;F&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;f&quot;; } break; case 7:if (isupper(user_input[x])) { output_str_assign = &quot;G&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;g&quot;; } break; case 8:if (isupper(user_input[x])) { output_str_assign = &quot;H&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;h&quot;; } break; case 9:if (isupper(user_input[x])) { output_str_assign = &quot;I&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;i&quot;; } break; case 10:if (isupper(user_input[x])) { output_str_assign = &quot;J&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;j&quot;; } break; case 11:if (isupper(user_input[x])) { output_str_assign = &quot;K&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;k&quot;; } break; case 12:if (isupper(user_input[x])) { output_str_assign = &quot;L&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;l&quot;; } break; case 13:if (isupper(user_input[x])) { output_str_assign = &quot;M&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;m&quot;; } break; case 14:if (isupper(user_input[x])) { output_str_assign = &quot;N&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;n&quot;; } break; case 15:if (isupper(user_input[x])) { output_str_assign = &quot;O&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;o&quot;; } break; case 16:if (isupper(user_input[x])) { output_str_assign = &quot;P&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;p&quot;; } break; case 17:if (isupper(user_input[x])) { output_str_assign = &quot;Q&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;q&quot;; } break; case 18:if (isupper(user_input[x])) { output_str_assign = &quot;R&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;r&quot;; } break; case 19:if (isupper(user_input[x])) { output_str_assign = &quot;S&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;s&quot;; } break; case 20:if (isupper(user_input[x])) { output_str_assign = &quot;T&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;t&quot;; } break; case 21:if (isupper(user_input[x])) { output_str_assign = &quot;U&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;u&quot;; } break; case 22:if (isupper(user_input[x])) { output_str_assign = &quot;V&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;v&quot;; } break; case 23:if (isupper(user_input[x])) { output_str_assign = &quot;W&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;w&quot;; } break; case 24:if (isupper(user_input[x])) { output_str_assign = &quot;X&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;x&quot;; } break; case 25:if (isupper(user_input[x])) { output_str_assign = &quot;Y&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;y&quot;; } break; case 26:if (isupper(user_input[x])) { output_str_assign = &quot;Z&quot;; } else if (islower(user_input[x])) { output_str_assign = &quot;z&quot;; } break; } output_str += output_str_assign;//adding to output ciphertext } int main() { bool run = true;//run validator char run_again;//user choice for run again while (run)//will run while &lt;run&gt; is true { std::cout &lt;&lt; std::endl; std::cout &lt;&lt; &quot; Cipher value (rot[2-25]): &quot;; std::cin &gt;&gt; cipher_value;//user input while (cipher_value &gt; 25 || cipher_value &lt; 2)//checking illegal input { std::cout &lt;&lt; &quot; Invalid...cipher value can only be between 2-25: &quot;; std::cin &gt;&gt; cipher_value;//user input } std::cin.ignore(1000, '\n'); std::cout &lt;&lt; std::endl &lt;&lt; std::endl; std::cout &lt;&lt; &quot; Input====&gt; &quot;; std::getline(std::cin, user_input);//user input for (x = 0; x &lt; user_input.size(); x++) { user_input[x]; convertion();//calling string convertion } std::cout &lt;&lt; &quot; Output===&gt; &quot; &lt;&lt; output_str &lt;&lt; std::endl; std::cout &lt;&lt; std::endl &lt;&lt; std::endl; std::cout &lt;&lt; &quot; Press any key to continue . . .&quot;; _getwch(); std::cout &lt;&lt; std::endl; termclr();//clear screen std::cout &lt;&lt; std::endl; std::cout &lt;&lt; &quot; Run again? (Y/N): &quot;; run_again = toupper(_getwche());//user input std::cout &lt;&lt; std::endl; while (run_again != 'Y' &amp;&amp; run_again != 'N')//checking illegal input { std::cout &lt;&lt; &quot; Invalid...try again (Y/N): &quot;; run_again = toupper(_getwche());//user input std::cout &lt;&lt; std::endl; } termclr();//clear screen output_str = &quot;&quot;; if (run_again == 'Y') { run = true;//will run again } else if (run_again == 'N') { run = false;//wont run again } } return 0; } </code></pre>
[]
[ { "body": "<pre><code>std::string user_input;//user input string\n</code></pre>\n<p>In C++ you don't need to declare variables before you use them. I would strongly recommend doing so, otherwise readers will have problems with the text. You certainly should not use namespace / global variables unless they are required - and here they are certainly not. Use method parameters and local variables instead.</p>\n<p>Furthermore, the comment is entirely unnecessary. Commenting is good, but only if it adds information to the information available from the code / identifier names themselves.</p>\n<pre><code>int corres_num[1500000] = {};//corresponding number according to alphabets\n</code></pre>\n<p>This doesn't mean a thing to me. Corresponding to what? Why is it this number?</p>\n<p>It is generally also a bad idea to assign default values (in this case the empty array).</p>\n<pre><code>system(&quot;clear&quot;);\n</code></pre>\n<p>Always try and avoid system dependent calls. Rather use a console library to perform the work; consoles have escape codes to perform clearance where required. Or simply don't clear the screen.</p>\n<pre><code>void convertion()//user input convertion\n</code></pre>\n<p>Here you do add information to the code, but why not just use <code>convert_user_input</code>? Methods should have verbs as names as they are <em>doing</em> things.</p>\n<pre><code>if (user_input[x] == 'A' || user_input[x] == 'a') { corres_num[x] = 1; }\n...\nelse if (user_input[x] == 'Z' || user_input[x] == 'z') { corres_num[x] = 26; }\n</code></pre>\n<p>Real programmers don't use 1-based indexing. Real programmers do use 0-based indexing.</p>\n<p>Gets repetitive doesn't it? Can you think of another way to convert a character to an index? Maybe the character is already assigned a number value and you can convert that to the index? And maybe that should be put in a function of itself?</p>\n<p>If you ever need long <code>if ... else</code> lines (not here) then remember the <code>switch</code> and <code>case</code> keywords.</p>\n<p>Note that it is a good thing that you convert to an index before doing the calculations!</p>\n<pre><code>else { output_str_assign = user_input[x]; }//keeping user input intact if user input is not within a-z\n</code></pre>\n<p>That comment would be perfect for a comment of a function.</p>\n<pre><code>calc = corres_num[x] + cipher_value;//assigning &lt;calc&gt; value\nif (calc &gt; 26)//setting value if &lt;calc&gt; goes over 26\n{\n output = calc - 26;\n}\nelse if (calc &lt;= 26 &amp;&amp; calc &gt; 0)//maintaing &lt;calc&gt; value if within range\n{\n output = calc;\n}\n</code></pre>\n<p>Here you might want to look up how to perform modular calculations. Again, this might be put into another function. Programming is all about splitting up your problem into smaller problems (and putting those together in a well structured way).</p>\n<pre><code>switch (output)//assigning individual cipher characters\n</code></pre>\n<p>Ah, you <em>do</em> know about switch. However, this is still better calculated. Hint: I generally use things like <code>index + 'A'</code> or <code>index + 'a'</code>.</p>\n<pre><code>case 1:if (isupper(user_input[x])) { output_str_assign = &quot;A&quot;; }\n</code></pre>\n<p>Maybe you can simply remember the case instead. So a boolean <code>is_lower_case</code> would be perfect here. Now you have multiple checks for the same thing.</p>\n<pre><code>std::cout &lt;&lt; &quot; Cipher value (rot[2-25]): &quot;;\n</code></pre>\n<p>What's exactly wrong with rot1?</p>\n<pre><code>run_again = toupper(_getwche());//user input\n</code></pre>\n<p>Try not to mix high level (<code>std::cout</code> and low level code (<code>_getwche()</code>) too much. What about <code>std::cin</code>?</p>\n<hr />\n<p>To give you an idea on how to code this, here's some pseudo code for Caesar cipher:</p>\n<pre class=\"lang-none prettyprint-override\"><code>\ncaesar_encrypt(text, key)\n{\n ciphertext = empty\n for (each char in text)\n {\n if (char is not in alphabet)\n add char to ciphertext\n continue; // quickly exit the current scope, it is handled now\n\n index = char_to_index(char)\n newIndex = index + key (modulus the size of the alphabet)\n newChar = index_to_char(newIndex)\n add char to ciphertext\n }\n return ciphertext\n}\n</code></pre>\n<p>The input / output handling goes into the main function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-10T15:01:19.057", "Id": "259311", "ParentId": "257659", "Score": "2" } }, { "body": "<p>Far too many global variables - a simple text filter shouldn't need any.</p>\n<p>There's a complete lack of checking that input operations succeeded. I would expect a few more <code>if (!std::cin)</code> tests to catch invalid user input.</p>\n<p>Misspelt <code>std::system()</code> and failed to include <code>&lt;cstdlib&gt;</code> that declares it.</p>\n<p>Also failed to include <code>&lt;cctype&gt;</code> for declaration of <code>std::isupper()</code> and <code>std::islower()</code> (which are also misspelt throughout).</p>\n<p>No declaration for non-standard function <code>_getwche()</code> - if that's something you wrote, change its name to one you're allowed to use (not beginning with <code>_</code>).</p>\n<p>When using the functions in <code>&lt;cctype&gt;</code>, remember that they take the <em>unsigned</em> value of a character in an <code>int</code> variable, so plain <code>char</code> needs to be converted to <code>unsigned char</code> before promotion.</p>\n<p>This code is very verbose:</p>\n<blockquote>\n<pre><code>if (run_again == 'Y')\n{\n run = true;//will run again\n}\nelse if (run_again == 'N')\n{\n run = false;//wont run again\n}\n</code></pre>\n</blockquote>\n<p>Given that we've already limited <code>run_again</code> to those two values, a concise equivalent is simply</p>\n<pre><code>run = run_again == 'Y';\n</code></pre>\n<p>This is inefficient:</p>\n<blockquote>\n<pre><code>std::cout &lt;&lt; std::endl &lt;&lt; std::endl;\n</code></pre>\n</blockquote>\n<p>There's really no need to flush the stream twice like that. Ordinary newlines would be a better choice (for both).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T20:20:12.323", "Id": "267766", "ParentId": "257659", "Score": "1" } }, { "body": "<blockquote>\n<p>Please keep in mind that I'm still new to programming and don't know advanced level stuff.</p>\n</blockquote>\n<p><strong>Important lesson:</strong> Decompose a problem using <em>top down decomposition</em>. Meanwhile, each function should <em>do one thing</em>.</p>\n<p>You are separating the I/O and user interface logic from the main problem OK, by putting your actual cypher in <code>conversion</code>. But that function is doing too many different things. Clearly you can break it out into major pieces, which you should put into separate named functions rather than just flowing from one to another.</p>\n<p><strong>Lesson:</strong> functions should take input in the form of parameters, and return results via its return value.</p>\n<p>Your <code>conversion</code> function just operates on fixed global variables. You should <em>pass in</em> the string to operate on, and <em>return</em> the result. Try writing it with <strong>no global variables</strong> at all.</p>\n<hr />\n<p>Your huge blocks of code to convert between numbers and letters should raise a red flag. This should be built into any good programming language; typically they would be called <code>chr</code> and <code>ord</code> or something like that.</p>\n<p>But in C++, which comes from C, it is implicit. A character <em>is</em> a small integer. You don't need a separate named function, you just cast (or implicitly convert) between the types.</p>\n<p>In the <em>vast majority</em> of environments, the source character set will be a superset of ASCII, in which the codes for the letters <code>a</code> through <code>z</code> are consecutive; likewise for <code>A</code> through <code>Z</code>. If you want to be portable to exotic systems with source code saved in <a href=\"https://en.wikipedia.org/wiki/EBCDIC\" rel=\"nofollow noreferrer\">a strange character set</a>, as of C++17 you can write a <a href=\"https://en.cppreference.com/w/cpp/language/character_literal\" rel=\"nofollow noreferrer\">character literal with the <code>u8</code> prefix</a> to explicitly specify that it's an ASCII value (One-byte <a href=\"https://en.wikipedia.org/wiki/UTF-8\" rel=\"nofollow noreferrer\">UTF-8</a> characters are ASCII).<sup>※</sup></p>\n<p>If you had broken out your code to</p>\n<ul>\n<li>convert character to numeric value</li>\n<li>do the arithmetic</li>\n<li>convert number to character</li>\n</ul>\n<p>as separate functions, then <em>even if</em> you wrote them out the hard way like you did in the OP, you could easily just replace the implementation of the first and third function with one-liners.</p>\n<p>You're case-folding when doing the <code>ord</code> step, but then referring back to the input to see whether it was upper or lower case when doing the <code>chr</code> step. You should not have dependency between the old and new data like that; rather, flow cleanly from one step to the next.</p>\n<p>To <em>decompose</em> the problem down to the most basic form, consider encoding a <em>single capital letter</em>. Write this as a function that takes and returns a value:</p>\n<pre><code>char encypher_one_capital_letter (char c, int CeasarShift=3)\n{\n int n = c-u8'A'; // A becomes 0, B=1, ... Z=25\n n += CeasarShift;\n if (n &gt;= 26) n -= 26; // roll over\n else if (n &lt; 0) n += 26; // allow for negative shifts and easily use the same code to decode\n return char(n+u8'A');\n}\n</code></pre>\n<p>Notice that the amount to shift was also passed in as a parameter. The code <em>needs</em> this value, so where does it come from? It should be supplied by the caller, <em>as a parameter</em>.</p>\n<p>Now, <em>given this</em> (which you can try and TEST BY ITSELF and make sure it all works OK before you continue), you want to handle upper and lower case letters by preserving case, and pass through everything else unchanged.</p>\n<p>That's another step of responsibility, and can be built on top of the more primitive function above.</p>\n<pre><code>char encypher_one_character (char c, int CeasarShift=3)\n{\n if(!isletter(c)) return c; // pass through things that are not letters\n ⋮\n</code></pre>\n<p>note that the &quot;negative&quot; is tested, and decisive action taken. That is, put simple things first. Now the rest of the function can proceed under the assumption that it <em>is</em> a letter.</p>\n<pre><code> ⋮\n if (isupper(c)) return encypher_one_capital_letter(c, CeasarShift);\n // must be an lower-case letter: preserve the case\n return to_lower(encypher_one_capital_letter(to_upper(c), CeasarShift));\n}\n</code></pre>\n<p>Again, you can test this with examples of each case (pun intended) and make sure all is correct before continuing.</p>\n<p>aside: what is <code>to_upper</code> and <code>to_lower</code>? Are those supplied library functions or something you need to write also? Either way, just <em>assume that exists</em> to do <strong>top-down decomposition</strong>.</p>\n<p>Next, you want to process an entire string.</p>\n<p><strong>The best way to take general string input is using a <code>std::string_view</code></strong> (by value). This will accept a <code>std::string</code> without having to copy anything, and also takes a lexical literal string <code>&quot;like this&quot;</code> efficiently, again without having to copy those chars into a <code>std::string</code> object.</p>\n<pre><code>string encypher (string_view input, int CeasarShift=3)\n{\n ⋮\n</code></pre>\n<p>This needs to iterate over each input character and append an output character. You should expect that expressing this ought to be a very simple thing to do. If it seems complex, look for the right tool for the job. Going through all the items in a collection is a fundamental and very common thing to do.</p>\n<pre><code> ⋮\n string result;\n for (char c : input) {\n char f = encypher_one_character(c,CeasarShift));\n result.push_back(f);\n // BTW, the output is called f because that is c encyphered \n }\n return result;\n}\n</code></pre>\n<p>Now consider the testing program for this final step: you don't want to have to manually type each test case each time you try it! Rather than getting input from the user, have automated test cases.</p>\n<p>Now the final program. Looping and asking &quot;Y/N to enter another&quot; and prompting for input is busywork that is not part of this problem. And is that really what you want in a <em>useful</em> program? The Unix tools <em>never</em> do that! Just read from standard input (no prompts) and process each line, and stop when you hit EOF.</p>\n<p>You can test it by redirecting input from a file, and enter text manually if you wanted to do that, using ctrl-d (on Unix; ctrl-z on Windows) when done.</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>&gt; ./mycypherprogram 3 &lt;inputs.txt\n</code></pre>\n<hr />\n<p>Good luck, and keep at it.</p>\n<h1>Footnote</h1>\n<p><strong>※</strong> Though you'll have other problems to worry about. When I was an intern at IBM, it was rather difficult to discuss C++ on the internal mailing list because <a href=\"https://en.wikipedia.org/wiki/IBM_3270#3270_character_set\" rel=\"nofollow noreferrer\">the character set</a> did not even have square bracket (<code>[</code> and <code>]</code>) characters! That is why C has <a href=\"https://en.cppreference.com/w/c/language/operator_alternative#Trigraphs\" rel=\"nofollow noreferrer\">trigraphs</a>.</p>\n<h1>about your original code</h1>\n<pre><code>for (x = 0; x &lt; user_input.size(); x++)\n {\n user_input[x];\n convertion();//calling string convertion\n }\n</code></pre>\n<p>The line <code>user_input[x];</code> doesn't do anything!<br />\nInside the <code>convertion</code> [sic] you are stashing an intermediate value in <code>corres_num[x]</code> but only use the one cell of the array. There is no need to have an array of <code>corres_num</code>, since this pass of the function only ever looks at one character.</p>\n<p>I think you got confused as to how the program worked, trying to do too much all at once. By doing <strong>top-down decomposition</strong> you can focus on one responsibility at a time. Learning that is more important than any single program. By implementing the simplified essence first, you simply did not have arrays to worry about! One char in, one char out, as if that's the only thing in the world. You had <em>only</em> the information you needed, and a <em>single</em> (simple) responsibility to perform. Thus, the code is simple and readable. By doing bottom-up implementation, you can test as you go: make sure that simplified thing works, then add the layer around it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T08:14:30.700", "Id": "528839", "Score": "0", "body": "Do you have a reference for your claim \"_In standard C++, it is guaranteed that the codes for the letters `a` through `z` are consecutive; likewise for `A` through `Z`_\" ? My understanding that the single sequential guarantee on the execution character set applies [only to the digits `0`..`9`](https://eel.is/c++draft/lex.charset#3). Standard C++ doesn't even require `'A' < 'Z'`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T14:02:06.217", "Id": "528866", "Score": "0", "body": "@TobySpeight I must have mis-remembered. Or the proposal was dropped (thank-you IBM) with `u8` literals being added to fill the same demand." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T00:03:43.820", "Id": "267842", "ParentId": "257659", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T05:38:31.443", "Id": "257659", "Score": "1", "Tags": [ "c++", "beginner", "caesar-cipher" ], "Title": "caesar cipher (rot<2-25>)" }
257659
<p>I'd like to emplace a lambda which captured a unique-pointer into a container, but it failed to compile under GCC 7.3.0 as C++17. From the error messages, it's calling the copy constructor of <code>unique_ptr</code> when constructing function.</p> <p><a href="https://wandbox.org/permlink/ECFI05J8obWMqhxE" rel="nofollow noreferrer">compile</a></p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;memory&gt; #include &lt;functional&gt; #include &lt;string&gt; #include &lt;queue&gt; int main (){ auto ptr = std::make_unique&lt;std::string&gt;(&quot;123456&quot;); auto l = [p = std::move(ptr)] () mutable { p.reset(); }; std::queue&lt;std::function&lt;void()&gt;&gt; q; q.emplace(std::move(l)); return 0; } </code></pre> <p>Actually, I have many lambdas with the same parameter list and same return type, and I need to emplace them to <strong>one</strong> container. So I need a common type to wrap, like <code>std::function&lt;void()&gt;</code>.</p> <p>In addition, I don't want add something else, like using <code>std::shared_ptr</code> to make it copyable, or using another lambda to wrap again.</p> <p>Based on the above, I designed <code>LambdaWrapper</code> to use instead of <code>std::function</code>. The variable which captured won't be copied, because of the non-copyable <code>LambdaWrapper</code>.</p> <pre class="lang-cpp prettyprint-override"><code>class LambdaWrapper { public: template &lt;class T, typename = std::is_invocable&lt;decltype(std::mem_fn(&amp;T::operator()))&gt;&gt; LambdaWrapper(T&amp;&amp; lambda) { MemberFunction memfn; // This forced type conversion is refers to std::_Function_base::_Base_manager::_M_init_functor new (&amp;memfn)(decltype(&amp;T::operator()))(&amp;T::operator()); // Member function pointer is 16B. The first 8B is the address of function, and the last 8B is the offset of this pointer. Because the lambda type is not inherited from other classes, the offset is 0 and it can be ignored. new (&amp;func_) void*(memfn.func); new (&amp;deleter_)(void (*)(T*))(&amp;DeleterImpl&lt;T&gt;::f); data_ = malloc(sizeof(T)); new (data_) T(std::forward&lt;T&gt;(lambda)); } ~LambdaWrapper() { if (data_ != nullptr &amp;&amp; deleter_ != nullptr) { deleter_(data_); } else if (data_ != nullptr || deleter_ != nullptr) { // something wrong } } void operator()() { func_(data_); } LambdaWrapper(LambdaWrapper&amp;&amp; T) { data_ = T.data_; func_ = T.func_; deleter_ = T.deleter_; T.data_ = nullptr; T.func_ = nullptr; T.deleter_ = nullptr; } LambdaWrapper&amp; operator=(LambdaWrapper&amp;&amp; T) { data_ = T.data_; func_ = T.func_; deleter_ = T.deleter_; T.data_ = nullptr; T.func_ = nullptr; T.deleter_ = nullptr; return *this; } private: LambdaWrapper(const LambdaWrapper&amp;) = delete; LambdaWrapper&amp; operator=(const LambdaWrapper&amp;) = delete; struct MemberFunction { void* func; void* ptr; }; void (*func_)(void*); void (*deleter_)(void*); void* data_; template &lt;class T&gt; struct DeleterImpl { static void f(T* t) { delete t; } }; }; </code></pre> <p>Finally, is there any better solution? And is there any problem with <code>LambdaWrapper</code>?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T07:33:47.507", "Id": "508928", "Score": "1", "body": "Welcome to CodeReview. Please try to stick to use english only." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:24:52.567", "Id": "509005", "Score": "0", "body": "Interesting. The `LambdaWrapper<>` looks suspiciously like a `unique_ptr<>`. Maybe it should be called `unique_function<>`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:26:57.253", "Id": "509006", "Score": "0", "body": "Ah, this might be a duplicate of https://stackoverflow.com/questions/25330716/move-only-version-of-stdfunction. Also, it seems a `std::unique_function<>` was proposed, but it's not in C++20: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0228r3.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T13:02:56.357", "Id": "509060", "Score": "0", "body": "To me, it looks like a `std::function` without the requirement to be copy-constructible or copy-assignable. Which is something I had naively assumed that the standard function would be when wrapping a move-only type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T13:04:38.323", "Id": "509062", "Score": "2", "body": "@G.Sliepen, \"duplicate\" is probably the wrong word there, as this is Code Review. \"A solution to\" might be more accurate." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T07:04:43.673", "Id": "257663", "Score": "5", "Tags": [ "c++", "lambda" ], "Title": "Emplace a lambda which captured a unique_ptr into container like queue" }
257663
<p>here I leave my code for a repository pattern with NHibernate and Autofac. I would like to receive some feedback about it. Especially about the session handling with NHibernate. By now I don't like the way that is implemented. Currently the session is created in an IHttpModule on the beginning of the request. Could this session be created with Autofac?.</p> <p>ISessionModule</p> <pre><code>public class ISessionModule : IHttpModule { public void Init(HttpApplication context) { context.BeginRequest += context_BeginRequest; context.RequestCompleted += context_requestCompleted; } private void context_BeginRequest(object sender, EventArgs e) { NHibernateHelper.GetCurrentSession(); } private void context_requestCompleted(object sender, EventArgs e) { NHibernateHelper.CloseSessionFactory(); } public void Dispose() { //throw new NotImplementedException(); } } </code></pre> <p>Repository class</p> <pre><code>public class BaseRepository&lt;T,TId&gt; : IRepository&lt;T, TId&gt; where T : class { protected ISession session = HttpContext.Current.Items[&quot;nhibernate.current_session&quot;] as ISession; protected ITransaction transaction = null; public BaseRepository() { //session = NHibernateHelper.OpenSession(); transaction = session.BeginTransaction(); } public async void Create(T entity) { await session.SaveOrUpdateAsync(entity); await transaction.CommitAsync(); } public async void DeleteAsync(TId key) { var entity = await session.LoadAsync&lt;T&gt;(key); await session.DeleteAsync(entity); await transaction.CommitAsync(); } public async Task&lt;List&lt;T&gt;&gt; FindAll() { return await session.Query&lt;T&gt;().ToListAsync(); } public async Task&lt;T&gt; FindOne(TId key) { return await session.GetAsync&lt;T&gt;(key); } public async void Update(T entity) { await session.SaveOrUpdateAsync(entity); await transaction.CommitAsync(); } } </code></pre> <p>Example of the controller</p> <pre><code>public class ContractsController : ODataController { private readonly BaseRepository&lt;Contract, int&gt; contractRepository; public ContractsController(BaseRepository&lt;Contract, int&gt; contractRepository) { this.contractRepository = contractRepository; } public async Task&lt;IHttpActionResult&gt; Get([FromODataUri] int key) { var contract = await contractRepository.FindOne(key); if (contract == null) { return StatusCode(HttpStatusCode.NotFound); } return Ok(contract); } </code></pre> <p>Global.asax</p> <pre><code> public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { var builder = new ContainerBuilder(); builder.RegisterGeneric(typeof(BaseRepository&lt;,&gt;)).As(typeof(BaseRepository&lt;,&gt;)).InstancePerRequest(); builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); var container = builder.Build(); var webApiResolver = new AutofacWebApiDependencyResolver(container); GlobalConfiguration.Configuration.DependencyResolver = webApiResolver; GlobalConfiguration.Configure(WebApiConfig.Register); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T08:00:25.147", "Id": "257665", "Score": "2", "Tags": [ "c#", ".net", "asp.net-web-api", "autofac" ], "Title": "How to make a good session handling with NHibernate?" }
257665
<p>this is my very first pandas/matplotlib code and I would be grateful if you can review my code and share your thoughts or ideas for improvement. Please focus on code, not the features of resulting chart. Thank you for you opinion.</p> <p>The purpose of code is to create <a href="https://en.wikipedia.org/wiki/Gantt_chart" rel="nofollow noreferrer">Gantt chart</a> showing my planning for 2021 education courses. Input data is <a href="https://github.com/jaroslavhradsky/datascience/blob/main/charts/Gantt/test-data.xlsx" rel="nofollow noreferrer">here</a></p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from IPython.core.display import display, HTML display(HTML(&quot;&lt;style&gt;.container { width:100% !important; }&lt;/style&gt;&quot;)) # Resize notebook screen df = pd.read_excel('test-data.xlsx') df.dropna(how='all', inplace=True) # Drop empty lines df['Duration'] = df['Duration'].fillna(1).astype(np.int32) # Replace missing duration with 1 (one hour) an change column type to integer df['Category'] = df['Category'].fillna('Other') # Replace missing category name with Other df['Start'] = df['Start'].fillna(min(df['Start'])) # Replace missing start time with min date df['End'] = df['Start'] + df['Duration'] * pd.Timedelta(days=1) # Helper column with task end date fig, ax = plt.subplots(figsize = (20, 20)) ax.axis('off') # Today line today = pd.Timestamp.today() today_line_length = len(df) + len(df['Category'].unique()) * 4 + 6 # Number of tasks + 4 * number of groups + margins ax.vlines(today, ymin=-3, ymax=today_line_length, color='yellow', lw=2, zorder=-1) # Draw vertical line on today's mark ax.text(today, -3, today.date(), fontweight='bold') ax.text(today, today_line_length + 1, today.date(), fontweight='bold') # Quarters bars q = pd.date_range(min(df['Start']), freq='QS', periods=(max(df['End']) - min(df['Start'])).days//91+1) for i, quarter in enumerate(q): if (i % 2 == 1) and (i&lt;len(q)-1): ax.fill_between((q[i],q[i+1]), -5, today_line_length+2.5, facecolor='tab:cyan', alpha = 0.2) quarter_label = 'Q'+str(quarter.quarter)+'-'+str(quarter.year) ax.text(quarter + pd.DateOffset(days=45), -4, quarter_label, ha='center') # Display today's date on top ax.text(quarter + pd.DateOffset(days=45), today_line_length+2, quarter_label, ha='center') # Dsiplay today's date in bottom ax.invert_yaxis() # y axis starts at top and ends in bottom group_start_y = -1 # Where to start plotting first group # Main loop, for each group draw the group summary and all the tasks for group in df.groupby('Category', sort=False): # Don't sort, by default i would be sorted alphabetically group_name = group[0] # Group name df_g = group[1] # Group dataframe group_size_y = len(df_g) + 1 # Count of group members + 1 row margin group_start_x = min(df_g['Start']).date() # Soonest date in the group group_end_x = max(df_g['End']).date() # Latest date in group (max start date + duration) # Display group name and summary ax.text(group_start_x, group_start_y, group_name, size='large', fontweight='bold') # Group name group_duration_str = str(group_start_x) + ' to ' + str(group_end_x) # Group start and end date ax.text(group_start_x, group_start_y+1, group_duration_str) # Group duration ax.text(group_start_x, group_start_y+2, str(int(len(df_g[~df_g['Completed'].isnull()])/len(df_g) *100)) + '% completed') # Completion percentage group_start_y += 3 # Where to start with tasks ax.hlines(group_start_y + group_size_y - 0.5, xmin=min(df['Start']), xmax=max(df['End']), color='tab:grey', alpha=0.5) # Display each task for i, task_name in enumerate(df_g['Name']): task = df_g.iloc[i] # Get bar color task_color = 'tab:grey' # Planned if task['End'] &lt; today: task_color = 'tab:red' # Overdue if task['Completed'] &lt; today: task_color = 'tab:green' # Completed ax.broken_barh([(task['Start'],task['Duration'])],(group_start_y+i,1), color=task_color) # Draw bar ax.text(task['Start']+task['Duration'] * pd.DateOffset(days=1) + pd.DateOffset(days=2),group_start_y+i+0.6,task_name, va='center') # bar label - task name group_start_y += group_size_y + 1 # One row space between group end and start of another group plt.savefig('gantt.png', format='png') # Save chart to PNG </code></pre> <p>The code above produces following picture <a href="https://i.stack.imgur.com/ND8Zl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ND8Zl.png" alt="enter image description here" /></a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T18:29:59.710", "Id": "510261", "Score": "1", "body": "Note that your `Duration` is small enough to be `.astype('uint8')`. Also you can encode your `Category` explicitly `.astype('category')`. Not too relevant for this data, but useful as the data gets larger: [Reducing pandas memory usage #1](https://pythonspeed.com/articles/pandas-load-less-data/)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T08:03:49.570", "Id": "257666", "Score": "3", "Tags": [ "python", "pandas", "matplotlib" ], "Title": "Modified Gantt Chart" }
257666
<p>I want to generate wind data with the use of MCMC. The results I am getting are quite off from the measured mean values not sure why.</p> <h3>SIMULATE WIND DATA</h3> <pre><code>## Import the packages ######## from sklearn.cluster import KMeans ### Let's generate some &quot;wind&quot; data from Weibul ### Wind_sim=np.random.weibull(5, size=1250)## 1250 Wind values (measured data) ### Cluster the simulated wind in 20 clusters kmeans = KMeans(n_clusters=20).fit(Wind_sim.reshape(-1,1)) labels=kmeans.labels_### Get the labels of categories ##### centers=kmeans.cluster_centers_### Get the centroids of the clusters </code></pre> <p>#################### Build the Markov Chain transition matrix #######</p> <pre><code>def transition_matrix(transitions): n = 1+ max(transitions) #number of states M = [[0]*n for _ in range(n)] for (i,j) in zip(transitions,transitions[1:]): M[i][j] += 1 #now convert to probabilities: for row in M: s = sum(row) if s &gt; 0: row[:] = [f/s for f in row] return M m = transition_matrix(labels) #### Get the MC transitions ####### </code></pre> Build the cummulative transition matrix <pre><code>cum_sum=[] for i in range(len(m)): ss=np.cumsum(m[i]) cum_sum.append(np.ravel(ss)) P = np.diff(np.hstack([np.zeros((len(cum_sum), 1)), cum_sum]), axis=1) i = 0; path = [0] I = np.arange(len(P)) for _ in range(1250): i = np.random.choice(I, p = P[i]) path.append(i); simulated=centers[path].ravel() measured=Wind_sim np.mean(measured) np.mean(simulated) </code></pre> <p>Comparing the means of simulated vs measured is quite off. Is there a better approach to achieve more accuracy?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T08:43:28.273", "Id": "257667", "Score": "0", "Tags": [ "python-3.x", "markov-chain" ], "Title": "Markov Chain Monte Carlo (MCMC) wind simulate" }
257667
<p>I am currently using a <code>SimpleConnectionPool</code> from <code>psycopg2</code> to lease transactions to a PostgreSQL database and would like a review of my current implementation.</p> <h3>Code</h3> <pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager from dataclasses import dataclass from psycopg2.pool import SimpleConnectionPool @dataclass class PostgreSQLSimplePool: pool: SimpleConnectionPool @contextmanager def transact_session(self, commit: bool = False): conn = self.pool.getconn() try: yield conn if commit: conn.commit() except Exception: conn.rollback() raise finally: self.pool.putconn(conn) </code></pre> <h3>Config</h3> <pre class="lang-py prettyprint-override"><code>simple_pool = psycopg2.pool.SimpleConnectionPool( # testing purposes 1, 20, user=POSTGRES_USER, password=POSTGRES_PASS, host=POSTGRES_HOST, port=POSTGRES_PORT, dbname=POSTGRES_DB_NAME, sslmode='require' ) repo = PostgreSQLSimplePool(pool=simple_pool) </code></pre> <h3>Usage</h3> <pre class="lang-py prettyprint-override"><code>with repo.transact_session() as connection: with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: # do some stuff with the cursor... </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T11:44:35.803", "Id": "257671", "Score": "2", "Tags": [ "python", "postgresql", "connection-pool" ], "Title": "Simple Connection Pooling with psycopg2" }
257671
<p>I created a tic-tac-toe game implementaiton in rust. What I can do to make this tic-tac-toe code a better code?</p> <p><strong>game.rs</strong></p> <pre><code>pub struct Board { board: Vec&lt;Vec&lt;char&gt;&gt;, } pub struct Cell { x: usize, y: usize, } pub enum ErrCoordinates { InvalidSub, } pub enum ErrBoard { OutOfBounds, PossitionTaken, } impl Cell { pub fn new() -&gt; Cell { Cell { x: 0, y: 0 } } pub fn index_to_coordinates(&amp;mut self, i: usize) -&gt; Result&lt;(), ErrCoordinates&gt; { let i = i.checked_sub(1); match i { Some(u) =&gt; { self.x = u / 3; self.y = u % 3; Ok(()) } None =&gt; Err(ErrCoordinates::InvalidSub), } } } impl Board { pub fn new() -&gt; Board { Board { board: vec![vec!['\u{25A2}'; 3]; 3], } } pub fn print_a_board(&amp;self) { for i in 0..3 { for j in 0..3 { print!(&quot;{:2}&quot;, self.board[i][j]); } println!(); } } pub fn place_a_sign(&amp;mut self, cell: &amp;mut Cell, sign: &amp;mut char) -&gt; Result&lt;(), ErrBoard&gt; { match self.board.get(cell.x) { Some(_) =&gt; match self.board[cell.x].get(cell.y) { Some(_) =&gt; { if self.board[cell.x][cell.y] == '\u{25A2}' { self.board[cell.x][cell.y] = *sign; if *sign == 'X' { *sign = 'O'; } else { *sign = 'X'; } } else { return Err(ErrBoard::PossitionTaken); } Ok(()) } None =&gt; Err(ErrBoard::OutOfBounds), }, None =&gt; Err(ErrBoard::OutOfBounds), } } pub fn check_for_win(&amp;mut self) -&gt; Option&lt;char&gt; { //check for a horizontal win for row in self.board.iter() { if !row.iter().any(|i| *i == '\u{25A2}') &amp;&amp; row.iter().all(|&amp;x| x == row[0]) { return Some(row[0]); } } //check for a vertical win for (i, enumerator) in self.board.iter().enumerate() { if !self.board.iter().any(|row| row[i] == '\u{25A2}') &amp;&amp; self.board.iter().all(|x| x[i] == enumerator[i]) { return Some(enumerator[i]); } } //check for a diagonal(upper left to lower right) win for (i, enumerator) in self.board.iter().enumerate() { if !self .board .iter() .enumerate() .any(|(i_inner, row)| row[i_inner] == '\u{25A2}') &amp;&amp; self .board .iter() .enumerate() .all(|(i_iner, row)| row[i_iner] == enumerator[i]) { return Some(enumerator[i]); } } //check for a diagonal (lower left to upper right) win for (i, enumerator) in self.board.iter().rev().enumerate() { if !self .board .iter() .rev() .enumerate() .any(|(i_inner, row)| row[i_inner] == '\u{25A2}') &amp;&amp; self .board .iter() .rev() .enumerate() .all(|(i_inner, row)| row[i_inner] == enumerator[i]) { return Some(enumerator[i]); } } //ceck for a tie if self .board .iter() .all(|x| x.iter().all(|&amp;y| y != '\u{25A2}')) { return Some('T'); } None } } </code></pre> <p><strong>main.rs</strong></p> <pre><code>use std::io; mod game; use game::*; fn main() { println!(&quot;\tTIC-TAC-TOE&quot;); println!( &quot;The rulse: \rEvery turn you asked where you want to place your sign(O or X). \rIf you fill any row column or horizontal with your signs you win.&quot; ); let mut b = Board::new(); let mut sign: char = 'X'; let mut cell = Cell::new(); loop { b.print_a_board(); eprint!(&quot;Enter a cell number:&quot;); let mut cell_index = String::new(); io::stdin() .read_line(&amp;mut cell_index) .expect(&quot;Error reading the input!&quot;); match cell_index.trim().parse::&lt;usize&gt;() { Ok(i) =&gt; match cell.index_to_coordinates(i) { Ok(a) =&gt; a, Err(ErrCoordinates::InvalidSub) =&gt; { eprintln!(&quot;Enter a valid number!&quot;); continue; } }, Err(_) =&gt; { eprintln!(&quot;Enter a valid number!&quot;); continue; } } match sign { 'X' =&gt; match b.place_a_sign(&amp;mut cell, &amp;mut sign) { Ok(a) =&gt; a, Err(ErrBoard::PossitionTaken) =&gt; { eprintln!(&quot;This possition is already taken! Try another one!&quot;); continue; } Err(ErrBoard::OutOfBounds) =&gt; { eprintln!(&quot;Enter a valid number!&quot;); continue; } }, 'O' =&gt; match b.place_a_sign(&amp;mut cell, &amp;mut sign) { Ok(a) =&gt; a, Err(ErrBoard::PossitionTaken) =&gt; { eprintln!(&quot;This possition is already taken! Try another one!&quot;); continue; } Err(ErrBoard::OutOfBounds) =&gt; { eprintln!(&quot;Enter a valid number!&quot;); continue; } }, _ =&gt; panic!(&quot;Unpresented player &quot;), } if let Some(winer) = b.check_for_win() { b.print_a_board(); if winer == 'T' { println!(&quot;It's a tie!&quot;); break; } println!(&quot;{} won the game!&quot;, winer); break; } } } </code></pre>
[]
[ { "body": "<p>I see you've absorbed many things I mentioned in my <a href=\"https://codereview.stackexchange.com/a/257434/188857\">last review</a>\n— well done!</p>\n<p>Coincidentally (or perhaps not, since tic-tac-toe is a common exercise\nfor beginners), I wrote <a href=\"https://codereview.stackexchange.com/q/241643/188857\">my version of tic-tac-toe</a> last year. I\nstill considered myself a <a href=\"https://users.rust-lang.org/t/twir-quote-of-the-week/328/822\" rel=\"nofollow noreferrer\">nauplius</a> at that time, but I hope you\nfind certain aspects of my code worth learning from. Notably, there\nwas a lot of overengineering, since I was trying to make the most out\nof the exercise.</p>\n<p>Let's look for more opportunities for improvement. This time, we'll\nstart from the big picture and proceed to the details after.</p>\n<h1>Using <code>enum</code>s</h1>\n<p>The current player, which you represent with the <code>char</code> values <code>'X'</code>\nand <code>'O'</code>, is best represented as an <code>enum</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>enum Player {\n Cross,\n Nought,\n}\n</code></pre>\n<p>with a <code>Display</code> implementation that converts the values into their\ncorresponding signs.</p>\n<p>The status of the game can be represented as an <code>Option&lt;Event&gt;</code>, where\n<code>Event</code> records events that require action:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>enum Event {\n Win(Player),\n Tie,\n}\n</code></pre>\n<p>The same goes for each cell of the board:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>enum Cell {\n Occupied(Player),\n Vacant,\n}\n</code></pre>\n<p>With these <code>enum</code> definitions, you will see that <code>match</code> expressions\nseamlessly match the logic of your code.</p>\n<h1>Managing game state</h1>\n<p>The game has, explicitly or implicitly, two values to keep track of:\nthe contents of the board and the current player. It is a good idea\nto group the mutable game state into a <code>struct</code>:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>struct Game {\n board: Board,\n current_player: Player,\n}\n</code></pre>\n<p>and define methods that operate on a <code>&amp;mut Game</code>.</p>\n<h1>The <code>main</code> function</h1>\n<p>As was the case for last time, the biggest problem of the <code>main</code>\nfunction is that its general structure is not clearly represented.\nLet's sort out the logic first:</p>\n<ul>\n<li><p>print the welcome message;</p>\n</li>\n<li><p>enter the game loop:</p>\n<ul>\n<li><p>input the position;</p>\n</li>\n<li><p>place a mark at the specified location;</p>\n</li>\n<li><p>check for a win or a tie.</p>\n</li>\n</ul>\n</li>\n</ul>\n<p>(See my last review for an example function that inputs a value.)</p>\n<p>Compare your <code>main</code> function to my <code>Session::run</code> function, which\nplays a similar role:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn run(&amp;mut self) -&gt; Result {\n let mut current_player = self.first_player;\n\n loop {\n self.process_move(current_player);\n\n if let Some(player) = self.resigned {\n utility::clear_screen();\n print!(&quot;{}&quot;, self.board);\n\n let winner = player.toggle();\n println!(&quot;{} wins by resignation.&quot;, winner);\n return Result::Win(winner);\n } else if self.board.wins(current_player) {\n utility::clear_screen();\n print!(&quot;{}&quot;, self.board);\n println!(&quot;{} wins.&quot;, current_player);\n return Result::Win(current_player);\n } else if self.board.is_draw() {\n utility::clear_screen();\n print!(&quot;{}&quot;, self.board);\n println!(&quot;It's a draw.&quot;);\n return Result::Draw;\n }\n\n current_player = current_player.toggle()\n }\n}\n</code></pre>\n<p>There is less clutter in my code, but the logic would have been even\nclearer if the whole <code>if</code> chain were extracted into a dedicated\nfunction <code>check_status</code>.</p>\n<p>The two arms of <code>match sign</code> are identical — combine them into a\nsingle <code>'X' | 'O' =&gt; { ... }</code> arm. Alternatively, the match can be\neliminated if you use an <code>enum</code>, as mentioned before.</p>\n<h1><code>struct Board</code></h1>\n<p><code>Vec&lt;Vec&lt;char&gt;&gt;</code> is a very inefficient way to represent the board\nstate — consider <code>[char; 9]</code>, or, better, <code>[Cell; SIZE]</code>, where\n<code>Cell</code> is a dedicated <code>enum</code> and <code>SIZE</code> is a <code>const</code>.</p>\n<h1><code>struct Cell</code></h1>\n<p>I can't say this is a cell:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub struct Cell {\n x: usize,\n y: usize,\n}\n</code></pre>\n<p>Instead, it is a position, or a coordinate. Since there isn't really\na default position in the board, just leave out <code>fn new</code>.</p>\n<p><code>index_to_coordinates</code>, renamed to <code>from_index</code> by convention, is\nconsidered a constructor. Instead of modifying the value of a mutable\nvariable, constructors create a new value and return it by value. It\nalso checks whether the coordinate is indeed a valid one, not just\nthat it is <code>&gt;= 1</code>. The equivalent from my version is, after\noptimization:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>// a position on the board\n// 1 2 3\n// 4 5 6\n// 7 8 9\n#[derive(Clone, Copy, Debug, Eq, PartialEq)]\npub struct Pos(usize);\n\nimpl Pos {\n pub fn new(pos: usize) -&gt; Option&lt;Pos&gt; {\n if (1..=Board::SIZE).contains(&amp;pos) {\n Some(Pos(pos))\n } else {\n None\n }\n }\n}\n</code></pre>\n<p>A <code>Result&lt;Pos, PosError&gt;</code> would be fine too.</p>\n<h1>Status check</h1>\n<p><code>fn check_for_win</code> looks rather convoluted — methods like <code>step</code>\nand <code>take</code> will come in handy if you use a flat representation <code>[Cell; 9]</code>.</p>\n<h1>Error handling</h1>\n<p>I highly recommended the <a href=\"https://docs.rs/anyhow\" rel=\"nofollow noreferrer\"><code>anyhow</code></a> and <a href=\"https://docs.rs/thiserror\" rel=\"nofollow noreferrer\"><code>thiserror</code></a> crates for\nhandling errors and creating error types — see their\ndocumentation for details.</p>\n<h1>Magic numbers</h1>\n<p>Replace <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic numbers</a> with named <code>const</code>s.</p>\n<pre class=\"lang-rust prettyprint-override\"><code>const BOARD_SIZE: usize = 3;\nconst VACANT_CELL: char = '\\u{25A2}';\n// etc.\n</code></pre>\n<h1>Miscellaneous</h1>\n<p>Typos: <code>possition =&gt; position</code>, <code>winer =&gt; winner</code>.</p>\n<p>It is unnecessary to repeat the type in the name of method: instead of\n<code>b.print_a_board()</code>, it is more natural to rename <code>b</code> to <code>board</code> and\nwrite <code>board.print()</code>.</p>\n<p>The <a href=\"https://docs.rs/indoc\" rel=\"nofollow noreferrer\"><code>indoc</code></a> crate helps to write multiline string literals in an\naesthetically pleasing manner without hacks like <code>\\r</code>.</p>\n<p>The distinction between <code>print!</code> vs. <code>eprint!</code>, I think, is less\nimportant this time, since the user interface isn't designed for\nautomation anyway.</p>\n<hr />\n<p>There are some details that I didn't go into because of time\nconstraint, so feel free to ping me if you need any clarification.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T10:56:20.420", "Id": "259006", "ParentId": "257672", "Score": "1" } } ]
{ "AcceptedAnswerId": "259006", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T11:59:50.973", "Id": "257672", "Score": "3", "Tags": [ "beginner", "rust", "tic-tac-toe" ], "Title": "Tic-tac-toe implementation" }
257672
<p>I have a below snippet, here I am using <code>array.find</code> to find the first success case and end it. So here is the code snippet</p> <pre><code>const USERS_LIST = [ { key: &quot;john&quot;, location: &quot;dublin&quot;, }, { key: &quot;joe&quot;, subKeys: [ { key: &quot;jane&quot;, locaction: &quot;washington&quot;, }, { key: &quot;mary&quot;, location: &quot;newyork&quot;, }, ], }, { key: &quot;chris&quot;, location: &quot;amsterdam&quot;, }, ]; </code></pre> <p>so what I am trying here is I go through each object in USERS_LIST and check for a <code>subKeys</code> property. If a <code>subKeys</code> property is present, loop through that and check whether that key is eligible. If it's eligible then I need to stop it or it will pass to the next subkey. If I don't find any <code>subKeys</code> eligible then iterate to the next USERS_LIST object then it takes the key and checks for eligible, whichever I find the first I do a callback and stop executing.</p> <p>I am able to solve this with this snippet</p> <pre><code>USERS_LIST.find((user) =&gt; { if (user?.subKeys) { user.subKeys.find((subUser) =&gt; { let subUserStatus = checkEligible({ action: subUser.key, }); if (subUserStatus) { callback(subUser.location); return true; } return false; }); } else { let userAccess = checkEligible({ action: user.key }); if (userAccess) { callback(user.location); return true; } } return false; }); </code></pre> <p>Is there a better way using with <code>array.some</code> or any other functions where I can achieve the same output.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T14:26:46.177", "Id": "508956", "Score": "0", "body": "Welcome to Code Review! To give reviewers a better picture of what the code does please describe how the result of calling `USERS_LIST.find()` is ultimately used, as well as defining `callback` and `checkEligible`. Please read [this meta post for more information](https://codereview.meta.stackexchange.com/a/3652)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T14:30:44.233", "Id": "508958", "Score": "0", "body": "Basically need to find the first key which do some check in checkEligible, basically checkEligible returns either true or false, and callback is a function to execute some other code snippets, so here should i just replace .find with .some is thats the only change if i use array.some method any other changes required, also to achieve the same is there any better way @SᴀᴍOnᴇᴌᴀ" } ]
[ { "body": "<p>Another way to write the same thing is:</p>\n<pre><code>const findUser = list =&gt; list.find(u =&gt; {\n if(u.subKeys) {\n return findUser(u.subKeys);\n }\n if(checkEligible({action: u.key}) {\n callback(u);\n return true; // necessary to stop the loop\n }\n});\n\nfindUser(USERS_LIST);\n</code></pre>\n<p>Once that you only need to receive a list, check if is eligible and do something with this, you can use recursion to avoid the callback repeating in <code>user.subKeys.find</code> and <code>USERS_LIST.find</code>.</p>\n<p>Also, the <code>return false</code> is not necessary because the iteration of <code>Array.prototype.find</code> will only stop when there is a return value equivalent to <code>true</code> and a function without a explicit return statement will have the implicit return value of <code>undefined</code>:</p>\n<pre><code>const noop = () =&gt; {};\nconsole.log(noop()) // undefined\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T19:03:29.673", "Id": "508988", "Score": "0", "body": "This helped me a lot :) thanks lucas, just one doubt if i use .some or .find both works, so which method i should use, since i thought that since find is defined as to find the first one but some is more of more than one so just a confusion" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T19:12:49.890", "Id": "508991", "Score": "0", "body": "If we use .some also internally no need to return false isn't, it will behave the same as like the .find, correct me if am wrong on this. Just curious :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T13:20:04.580", "Id": "509065", "Score": "0", "body": "No prob, John, I am glad that I could help! About your doubt, I think that in this case there is no difference in use .find or .some. As you said, they will behave the same way, but you can think that the difference is that .some will return a boolean if it finds an element that satisfies the callback return statement and .find will return the first element which satisfies the return statement. So, it depends of what you want to do with the return value of those methods." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T16:54:58.933", "Id": "257685", "ParentId": "257675", "Score": "1" } } ]
{ "AcceptedAnswerId": "257685", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T12:52:12.943", "Id": "257675", "Score": "2", "Tags": [ "javascript" ], "Title": "Finding the right property value from array of objects" }
257675
<p>I'm currently trying to do data quality checks in python primarily using <code>Pandas</code>.</p> <p>The code below is fit for purpose. The idea is to do the checks in Python and export to an Excel file, for audit reasons.</p> <p>I perform checks like the below in 4 different files, sometimes checking if entries in one are also in the other, etc.</p> <p><code>df_symy</code> is just another DataFrame that I imported inside the same class.</p> <br> <p>I'm wondering if there's a <strong>better way</strong> to do this task, for example:</p> <ul> <li>create a function for each check</li> <li>create a more meaningful way to check the data and present the results, etc</li> </ul> <br> <pre><code>def run_sharepoint_check(self) -&gt; pd.DataFrame: &quot;&quot;&quot;Perform checks on data extracted from SharePoint. Check 1: Amount decided is 0 or NaN Check 2: Invalid BUS ID Check 3: Duplicated entries. It also tags the latest entry Check 4: SYMY Special not in SharePoint &quot;&quot;&quot; # Use this function to check the data we have from SharePoint # and return DF with checks in the excel file # Another function will be used to process the data and produce # the final list df = self.sharepoint_data.copy() df_symy = self.symy_data df_symy = df_symy.loc[df_symy['COMMITMENT_TYPE'].str[0] == 'S'] symy_cols = ['BUYER_NUMBER', 'Balloon ID', 'CLD_TOTAL_AMOUNT', 'POLICY_CURRENCY'] df = df.merge(right=df_symy[symy_cols], how='outer', left_on=['Balloon ID', 'BUS ID'], right_on=['Balloon ID', 'BUYER_NUMBER']) check_1 = df['Amount decided'] == 0 | df['Amount decided'].isna() df.loc[check_1, 'check_1'] = 'Amount decided is 0 or NaN' check_2 = df['BUS ID'].isna() df.loc[check_2, 'check_2'] = 'Invalid BUS ID' check_3 = df.duplicated(subset=['Balloon ID', 'BUS ID'], keep=False) df.loc[check_3, 'check_3'] = 'Duplicated entry' check_3_additional = ~df.duplicated( subset=['Balloon ID', 'BUS ID'], keep='first' ) # Filter only the entries that are duplicated # Out of those, the first one is the latest df.loc[(check_3) &amp; (check_3_additional), 'check_3'] = 'Duplicated entry (Latest)' # Match Balloon+BUSID (SYMY) to SharePoint check_4 = (~df.duplicated(subset=['Balloon ID', 'BUS ID'], keep='first')) &amp; (df['BUS ID'].isna()) df.loc[check_4, 'check_4'] = 'SYMY SA not in SharePoint' check_cols = ['check_1', 'check_2', 'check_3', 'check_4'] # .fillna('OK') just for visual purposes in Excel. df[check_cols] = df[check_cols].fillna('OK') # self.data_checks_dfs in the init method is an empty dictionary. self.data_checks_dfs['SharePoint_checks'] = df return df </code></pre> <p>So, how can I improve this?</p> <p>Does anyone have this type of task that has been automated using Python?</p>
[]
[ { "body": "<p>It seems difficult to comment on the <em>meaningfulness</em> of your proposed solution. You are the one to decide on that since you know the context around your problem. With that being said, I'm afraid there is not much to go on here.</p>\n<p>Nevertheless, one observation I make about your code is that the checks use <code>.loc</code> to locate rows that receive a &quot;non-OK&quot;, and finally, after all checks, you use a fill to turn nans into &quot;OK&quot;. To make your code more concise and likely faster, consider using <a href=\"https://numpy.org/doc/stable/reference/generated/numpy.where.html\" rel=\"nofollow noreferrer\"><code>np.where</code></a>. So for instance, your <code>check_1</code> would be turned into:</p>\n<pre><code>df[&quot;check_1&quot;] = np.where(\n (df['Amount decided'] == 0) | (df['Amount decided'].isna()),\n &quot;Amount decided is 0 or NaN&quot;, &quot;OK&quot;)\n</code></pre>\n<p>Also, I would rename <code>check_N</code> into something that actually means a little more, like <code>amount_check</code> for <code>check_1</code> and so on.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T20:12:47.440", "Id": "510976", "Score": "0", "body": "Thanks for answering the question. I know it's a little abstract. I guess I doubt myself too much when it comes to writing these codes, and I'm always looking for validation to see if what I'm doing is correct or not, and what I can improve." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T19:31:35.447", "Id": "258980", "ParentId": "257676", "Score": "0" } } ]
{ "AcceptedAnswerId": "258980", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T14:45:01.970", "Id": "257676", "Score": "0", "Tags": [ "python", "pandas" ], "Title": "Function to perform checks on data" }
257676
<p>don't blame me I am trying to learn, the code works but I am not sure it is well optimized. Please tell me if you see something wrong. My goal is to achieve most optimized code (and learn something in between).</p> <ol> <li>User register -&gt; check if username or email exists , if not = insert into database</li> <li>User login -&gt; check database if username exists, then verify password, let them in :)</li> </ol> <h3>Login.php</h3> <pre><code>&lt;?php session_start(); .... &lt;form....&gt;// https://stackoverflow.com/questions/11974613/pdo-php-check-if-row-exist $stmt = $link-&gt;prepare('SELECT * FROM users WHERE username=? LIMIT 1'); $stmt-&gt;bindParam(1, $username, PDO::PARAM_STR); $stmt-&gt;execute(); $row = $stmt-&gt;fetch(PDO::FETCH_ASSOC); //$rows = $stmt-&gt;fetchAll(PDO::FETCH_ASSOC); if( $row ) { if (password_verify($_POST['password'], $row['password'])) { // ============================== session_regenerate_id(); // https://www.php.net/manual/en/function.session-regenerate-id.php $_SESSION[&quot;loggedin&quot;] = true; // Store data in session variables $_SESSION[&quot;id&quot;] = $row['id']; $_SESSION[&quot;username&quot;] = $_POST[&quot;username&quot;]; //$form-&gt;printr($_SESSION); // for debug header(&quot;location: profile.php&quot;); // ============================== } else { $form-&gt;error_message(&quot;Паролата не е вярна.&quot;); } // User ok , pass not valid } else { $form-&gt;error_message(&quot;Няма такъв акаунт в системата.&quot;); } // No such user $link = null; // close pdo connection </code></pre> <h3>Register.php</h3> <pre><code>&lt;?php session_start(); ... &lt;form...&gt;// /* https://stackoverflow.com/questions/11974613/pdo-php-check-if-row-exist $sql = 'SELECT 1 from table WHERE id = ? LIMIT 1'; //$sql = 'SELECT COUNT(*) from table WHERE param = ?'; // for checking &gt;1 records $stmt = $conn-&gt;prepare($sql); $stmt-&gt;bindParam(1, $_GET['id'], PDO::PARAM_INT); $stmt-&gt;execute(); if($stmt-&gt;fetchColumn()) echo 'found'; */ $stmt = $link-&gt;prepare(&quot;SELECT 1 from users WHERE username=? or email=? LIMIT 1&quot;); $stmt-&gt;execute(array($username,$email)); if ($stmt-&gt;fetchColumn() &gt; 0) { $form-&gt;add_to_errors('Името или Имейла вече е зает, моля опитайте с друг.'); // Username taken } else { $data = ['name' =&gt; $username,'email' =&gt; $email, 'pass' =&gt; $password]; // INSERT INTO DATABASE $sql = &quot;INSERT INTO users (username, email, password) VALUES (:name, :email, :pass)&quot;; // =========================================================== $stmt= $link-&gt;prepare($sql); //$stmt-&gt;execute($data); if ($stmt-&gt;execute($data)) { //success $form-&gt;success_message(&quot;Добре дошъл в системата: &lt;b&gt;&quot;.$username.&quot;&lt;/b&gt;&quot;); //session_regenerate_id(); } else { $form-&gt;add_to_errors('Проблем със заявката за регистрация, моля опитайте по-късно или се свържете с администратор.'); } // failed } $link = null; // close pdo connection </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T21:37:57.010", "Id": "510385", "Score": "0", "body": "Perhaps you're thinking why nobody is responding to your question? Well, I think it's because there's not much to comment on. You've used prepared statements and the standard way to hash passwords. If there's anything to say, it would be that your code looks a bit messy. Indentation could be better and lots of the comments are superfluous. Apart from that, you've given us very little to work with." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T07:03:08.857", "Id": "510726", "Score": "0", "body": "I'am interested in best possible way to optimize the code, to check if user exists in db, and for registration form too(best optimizations)\nthere are tons of examples and all are different.\nSome use fetchAll others rowCount , some use SELECT 1 in query other LIMIT 1\nall all do the same , but i wounder what is the best" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T07:07:05.463", "Id": "510727", "Score": "0", "body": "\"Optimize\" is not a very accurate word. You could optimize for readability, speed or security. Some people even consider the shortest code as being optimal. It basically means you want the best code, whatever that is. I've given you two suggestions: _\"Indentation could be better and lots of the comments are superfluous.\"_ Does that help?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T07:09:35.670", "Id": "510728", "Score": "0", "body": "What you think of this i kinda change some of the code https://pastebin.com/CkggrHSA" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T14:48:46.100", "Id": "257677", "Score": "1", "Tags": [ "performance", "php", "pdo" ], "Title": "Registration and login via PDO" }
257677
<p>I am cleaning a HTML string to encode the less than sign (&lt;) to a HTML entity (<code>&amp;lt;</code>), but leaving the HTML tags as they are. An example is converting <code>&quot;&lt;div&gt;Total &lt; 500&lt;/div&gt;&quot;</code> to <code>&quot;&lt;div&gt;Total &amp;lt; 500&lt;/div&gt;&quot;</code>.</p> <p>There's a number of posts addressing this including: <a href="https://stackoverflow.com/questions/5464686/html-entity-encode-text-only-not-html-tag">https://stackoverflow.com/questions/5464686/html-entity-encode-text-only-not-html-tag</a>, <a href="https://stackoverflow.com/questions/2245066/encode-html-in-asp-net-c-sharp-but-leave-tags-intact">https://stackoverflow.com/questions/2245066/encode-html-in-asp-net-c-sharp-but-leave-tags-intact</a>, <a href="https://stackoverflow.com/questions/28301206/how-to-encode-special-characters-in-html-but-exclude-tags">https://stackoverflow.com/questions/28301206/how-to-encode-special-characters-in-html-but-exclude-tags</a> Each post points to using the Html Agility Pack and specifically the <code>HtmlEntity.Entitize(html)</code> method. This doesn't work for me because it actually ignores the &lt; and &amp; signs and using the above example, the output was the same as the input! I may be missing the point of how to use this method, but the code was simply this:</p> <pre><code>public static string EntitizeHtml( this string html ) { return HtmlEntity.Entitize( html ); } </code></pre> <p>I decided to write my own method to find the less than symbols and convert them to the HTML entity equivalent. It works, but it seems very clunky (a loop inside a loop and lots of string manipulation). I avoided Regex to keep it faster and more readable. I fully appreciate that manipulating HTML strings is often fraught with problems thanks to differing HTML versions and malformed HTML, but for my purpose this method solves my problem based on a discrete set of HTML tags. The following method will convert <code>&quot;&lt;div&gt;Total &lt; 500&lt;/div&gt;&quot;</code> to <code>&quot;&lt;div&gt;Total &amp;lt; 500&lt;/div&gt;&quot;</code> as expected.</p> <p>If anyone can improve the efficiency of this method I'd be very grateful.</p> <pre><code> public static string EncodeLessThanEntities( this string html ) { if( !html.Contains( &quot;&lt;&quot; ) ) { return html; } // get the full html length int length = html.Length; // set a limit on the tag string to compare to reduce the // string size (i.e. the longest tags are &lt;center&gt; and &lt;strong&gt;) int tagLength = 6; // gather all the included html tags to check string s = &quot;div|span|p|br|ol|ul|li|center|font|strong|em|sub|sup&quot;; string[] tags = s.Split( '|' ).ToArray( ); // find all the indices of the less than entity or tag var indices = AllIndexesOf( html, &quot;&lt;&quot; ); // initiate a list of indices to be replaced var replaceable = new List&lt;int&gt;( ); // loop through the indices foreach( var index in indices ) { // store the potential tag (up to the tag length) if( length - ( index + 1 ) &lt; tagLength ) tagLength = length - ( index + 1 ); string possibleTag = html.Substring( index + 1, tagLength ); // automatically ignore any closing tags if( possibleTag.Substring( 0, 1 ) == &quot;/&quot; ) { continue; } bool match = false; // loop through each html tag to find a match foreach( var tag in tags ) { if( possibleTag.StartsWith( tag ) ) { match = true; break; } } if( !match ) { // if there is no match to a html tag, store the index replaceable.Add( index ); } } if( replaceable?.Any( ) ?? false ) { // loop through each index and replace the '&lt;' with '&amp;lt;' foreach( var index in Enumerable.Reverse( replaceable ) ) { html = html.ReplaceAt( index, 1, &quot;&amp;lt;&quot; ); } } return html; } public static List&lt;int&gt; AllIndexesOf( this string input, string value ) { List&lt;int&gt; indexes = new List&lt;int&gt;( ); if( string.IsNullOrEmpty( value ) ) { return indexes; } for( int index = 0; ; index += value.Length ) { index = input.IndexOf( value, index ); if( index == -1 ) { return indexes; } indexes.Add( index ); } } public static string ReplaceAt( this string str, int index, int length, string replace ) { return str.Remove( index, Math.Min( length, str.Length - index ) ).Insert( index, replace ); } </code></pre> <p>I'm hoping there is a way to make the above method more efficient. Or maybe this is as good as it gets? I know there are a lot of very smart guys out there with a lot more experience and I don't include myself in that group!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T15:24:29.033", "Id": "508960", "Score": "2", "body": "Welcome to CodeReview! Have you tested your implementation against other inputs as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T20:17:52.433", "Id": "508997", "Score": "0", "body": "did you try `HtmlEntity.Entitize(html, true, true);` e.g. for inner HTML of the tag pair? Btw, `<div>Total < 500</div>` isn't valid HTML, probably de-entitizing problem. It's better to fix such HTML source first." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T20:46:05.087", "Id": "508998", "Score": "0", "body": "What about `a` tag, or `img`, maybe `table`?...`thead`, `tbody`, `th`, `tr`, `td`, `b`, `i`, finally `html`, `head`, `body`, `meta`, `title`, `script`, `style`, [another tags](https://www.w3schools.com/tags/ref_byfunc.asp)? Also the solution at least isn't compartible with HTML5 because any single word can be HTML a valid tag e.g. `<aepot>some text</aepot>` is valid HTML5." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:33:10.583", "Id": "509008", "Score": "0", "body": "Hi guys, thanks for the welcome! I've tested this extensively against many inputs and I have now fixed the source HTML from this point on. The issue is that I am dealing with a few instances of malformed HTML from historical records. The set of tags I am dealing with are discrete and based on a WYSIWYG editor input so these tags are the only ones that I need to evaluate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:33:59.127", "Id": "509009", "Score": "0", "body": "Additionally, I acknowledge that my solution is 100% not bulletproof given the possibility of a user typing in text (not HTML) such as '<Parts', but this is a very low risk and one that can be easily dealt with. In simple terms, the method catches those highly unusual cases of malformed HTML input and then has about a 98% chance of fixing it. Very low risk, but good QA (i.e. better than nothing)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T21:36:47.623", "Id": "509010", "Score": "0", "body": "Thanks @aepot, I actually did try `HtmlEntity.Entitize(html, true, true)` and it doesn't work to my requirements because it simply encodes everything, which is not what I need. I may as well use `HtmlEncode(html)`, which produces the same result." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T23:00:11.937", "Id": "509015", "Score": "0", "body": "No chance to fix the editor? (Or alter to something that works fine). Anyway, the code above can't guarantee the proper result as source HTML is not suitable for that. Thus, the solution can't become production-ready. That's why i can't write the code review: I can't fix it. In detailed view, it looks almost fine for me, as it intended to handle not so large texts which will consume acceprable amount of RAM. But yes, it can be somewhat optimized with no visible difference on performance (at least for texts of <1M length). As alternative solution I suggest ReGex, not better but option." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T23:27:18.873", "Id": "509017", "Score": "0", "body": "Thanks @aepot. The editor is fine. It's the historical records that are a problem. it's complicated because the data works fine in a browser, but we then use the data in a reporting tool that switches between a text display field and a html display field. Some input is text and some input is html. The report fields are dynamic so I need to work out which data fields are text and which are html and display them appropriately. I have got that working almost perfectly except for the extremely odd occasion where a user mixes html with an unencoded <. This method handles that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T00:02:22.913", "Id": "509019", "Score": "0", "body": "OK then. Btw, i see an old syntax formatting. Old Visual Studio? Consider to update. What is .NET version? I'll try to optimize the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T02:11:34.273", "Id": "509022", "Score": "1", "body": "Thanks @aepot. It's VS 2019 .and NET 4.72 and C# 7.3." } ]
[ { "body": "<ul>\n<li><p>Every time you call <code>Substring</code>, <code>Remove</code>, <code>Replace</code> or any other method which modifies the <code>string</code>, you create new <code>string</code> instance with new memory allocation. Because <code>string</code> is immutable. All <code>string</code> operations are (relativley to numeric) are slow/expensive. But that's OK if you keep in mind this issue and agree with it.</p>\n</li>\n<li><p><code>html.Contains</code>, <code>AllIndexesOf</code>, <code>foreach(var index in indices)</code> - 2.5 scans of the same string.</p>\n</li>\n<li><p><code>possibleTag.Substring(0, 1) == &quot;/&quot;</code>, why not <code>possibleTag[0] == '/'</code>? It would be faster.</p>\n</li>\n<li><p><code>if (replaceable?.Any() ?? false)</code> 1) <code>replaceable</code> cannot be <code>null</code>, then <code>if (replaceable.Any())</code> is almost fine 2) but it just check is <code>List</code> contains any elements, then <code>if (replaceable.Length &gt; 0)</code> is better. 3) but <code>foreach</code> will not process the collection if it's empty, even <code>Enumerable.Reverse</code> call is fine for the empty collection. Thus you may wipe the <code>if</code> statement completely.</p>\n</li>\n<li><p>The fastest way to construct some string from data in .NET Framework is <code>StringBuilder</code>. (.NET Core and newer .NET has <code>Span</code>-based method <code>string.Create</code> which is faster in some cases)</p>\n</li>\n</ul>\n<p>And finally, here's my version of the implementation</p>\n<pre class=\"lang-cs prettyprint-override\"><code>// required array can be created once per application start\nprivate static readonly string[] tags = &quot;div span p br ol ul li center font strong em sub sup&quot;.Split();\n\npublic static string EncodeLessThanEntities(this string html)\n{\n if (html.Length &lt; 8) // the shortest valid html is &lt;p&gt;&lt;/p&gt;: 7 chars but there's no room for other chars\n return html;\n StringBuilder sb = new StringBuilder(html.Length); // spawn StringBuilder with initial capacity, this will reduce amount of memory allocations\n int i;\n for (i = 0; i &lt; html.Length - 2; i++)\n {\n if (html[i] == '&lt;' &amp;&amp; !tags.Any(tag =&gt; html.StartsWithAt(i + (html[i + 1] == '/' ? 2 : 1), tag)))\n sb.Append(&quot;&amp;lt;&quot;);\n else\n sb.Append(html[i]);\n }\n // 'i' has value 'html.Length - 2' here, append two last chars without changes\n return sb.Append(html[i]).Append(html[i + 1]).ToString();\n}\n\n// same as `String.StartsWith` but accepts a start index\npublic static bool StartsWithAt(this string text, int startIndex, string value)\n{\n if (text.Length - startIndex &lt; value.Length)\n return false;\n\n for (int i = 0; i &lt; value.Length; i++)\n {\n if (text[startIndex + i] != value[i])\n return false;\n }\n return true;\n}\n</code></pre>\n<p>I didn't test it a lot but you may.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T15:51:06.980", "Id": "510175", "Score": "1", "body": "Thanks @aepot. This is brilliant! Not only does it work well, your explanation has given me a much greater insight and appreciation for writing better code. Thank you so much for taking the time to improve my code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T15:53:58.537", "Id": "257737", "ParentId": "257678", "Score": "1" } } ]
{ "AcceptedAnswerId": "257737", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T14:54:44.387", "Id": "257678", "Score": "1", "Tags": [ "c#", "strings", "html", "encoding" ], "Title": "Method encodes all less than (<) characters in a HTML string, but not the HTML tags" }
257678
<p>I have a dataframe <code>data</code> with several columns and for each columns there are 10 years of daily data on average, something around 4000 rows then. The dataframe looks like this:</p> <pre><code>Date A B C ... YYYY-MM-DD 123.4 56.7 89.0 YYYY-MM-DD 12.34 -5.6 NaN ... </code></pre> <p>Date is <code>datetime64</code>, every value is a <code>float</code> (positive and negative, they are real numbers), there could be <code>NaN</code>, there are no upside or downside boundaries.</p> <p>I have this function :</p> <pre><code>def fct(data, name_a, name_b, param_a, param_b, param_c, param_d): df = data.loc[(data[name_a].notnull()) &amp; (data[name_b].notnull()),[name_a, name_b]] df_corr = pd.DataFrame() df_corr[name_a] = df[name_a] df_corr[name_b] = df[name_b].shift(param_a) print(df_corr.corr().iloc[0,1]) df['pct'] = df[name_a].pct_change() df['name_b_delta'] = df[name_b].shift(2+param_a)-df[name_b].shift(2+param_a+param_b) df['is_ok'] = df['name_b_delta'].apply(lambda x : np.sign(x+(-param_c))) if param_d: df['results'] = df['is_ok'] * (-1) * df['pct'] else: df['results'] = df['is_ok'] * df['pct'] df['cumul_results'] = df['results'].cumsum() return df </code></pre> <p>and currently, to optimize the <code>cumul_results</code> for differents pairs of <code>name_a</code> and <code>name_b</code>, I search for the best params using those nested loops :</p> <pre><code>name_a_list = ['a_dozen_of_elements_here'] name_b_list= ['25_elements_here'] df_line= [] df_index = [] for name_a in name_a_list : for name_b in name_b_list : for param_a in range(0,15): for param_b in range(1,15): for param_c in range (-2, 3, 1): for param_d in [True, False]: df = fct(data, name_a, name_b, param_a, param_b, param_c/1000, param_d): df_index.append(f&quot;{name_a}-{name_b}&quot;) df_line.append([df['cumul_results'].iloc[-1], param_a, param_b, param_c, param_d]) results = pd.DataFrame(index=df_index, data=df_line, columns=['final result', 'param_a', 'param_b', 'param_c', 'param_d']) </code></pre> <p>It's more than 840 000 calls of the function <code>fct</code> and takes around 4 hours. I was wondering then if I could increase the performance of this code to reduce time. Thanks !</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T14:00:36.533", "Id": "510510", "Score": "2", "body": "You're doing exhaustive search which is the \"last resort\" of numerical optimization. How smooth are your data? How likely is it that a more traditional numerical optimizer would find a false positive on a local minimum?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T14:38:58.330", "Id": "510511", "Score": "0", "body": "`name_b_list` contains columns with relatively (~30 days rolling) smoothed data but not `name_a_list` (stocks prices). I would say that for `param_a` and `param_b` maybe we could do the loop with a step of 2, but a bigger step could miss some results i would have selected i think, that's why i did the exhaustive way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T01:55:22.063", "Id": "510582", "Score": "0", "body": "It's also worth saying that this is precariously close to running afoul of the 'hypothetical code' policy of CR. All of your column names are clearly placeholders; `data` is undefined; and so this code will not run as-is. I can guess my way through but that's not going to do you any favours. If possible just use the actual column names, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T01:57:20.763", "Id": "510583", "Score": "0", "body": "p.s. the colon at the end of the `df = fct` statement furthers the idea that this is hypothetical code, will not execute, and is difficult to review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T02:22:11.033", "Id": "510584", "Score": "0", "body": "Yet another thing missing is what's actually done with `results`. It's difficult to see how this is serving the purpose of finding the four best parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T02:26:19.447", "Id": "510585", "Score": "0", "body": "How is this calling the function 840,000 times? 12*25*15*14*5*2 == 630,000." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T07:12:02.857", "Id": "510610", "Score": "0", "body": "It's hypothetical code regarding the variable names but it's the same code i use, I can't write the real names in regard to the company where i work, but it doesn't change the idea i guess ? I'm just trying to find the best parameter to optimize the results of `fct`. For the number of calling i wrote a dozen for `name_a_list` because it can vary a bit and when i count it was with more elements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T15:01:38.673", "Id": "510644", "Score": "0", "body": "I downvoted your question because I've read your question twice on two different occasions and I still don't have a clue what you're doing. I've salvaged many a bad question before, but I can't make heads of your question. What does your code do, please ELI5?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T15:17:54.320", "Id": "510645", "Score": "0", "body": "@Peilonrayz it creates some signal based on the difference of value between two days of `name_b`. But the value of the signal and the value of the difference differ in regard to the params value, so it impacts the final results because i multiply the signal to the column `name_a`." } ]
[ { "body": "<p><strong>Answer, part one</strong></p>\n<p>It looks like about half the loops can be avoided by doing the <code>True</code> and <code>False</code> cases at the same time. These differ only by the multiplication by -1 at the end of <code>fct</code>. That suggests that results of of a <code>True</code> invocation can be used to shortcut the computations of the immediately following invocation of <code>fct</code>.</p>\n<p>Is there a reason to not cache the results of the several array accesses? That is, for example, <code>df[name_a]</code>, <code>df[name_b]</code>, and others?</p>\n<p>Can the <code>apply</code> and <code>lambda</code> be avoided? This seems overly complex (meaning, slow) way to perform the computation.</p>\n<p>I presume the <code>print</code> invocation is not there usually. IO in the inner loop would slow things down considerably.</p>\n<p><strong>Answer, part 2</strong></p>\n<p>Sample code. This runs for me, but I haven't verified that it produces exactly the same results.</p>\n<p>I made two kinds of updates: Values which were shared across loops were lifted to the most common loop. The <code>True</code> and <code>False</code> cases were collapsed into a single function call which returns the <code>True</code> and <code>False</code> results using multiple values.</p>\n<p>Ignore my comment re: apply.</p>\n<p>My gut tells me that at least the innermost <code>shift</code> invocation ought to be unnecessary, but I haven't figured how to write a correct <code>apply</code> that would remove it. (I need the apply iteration index to be passed in as an extra parameter.)</p>\n<p>I added a number of print statements for debugging which you will want to remove.</p>\n<pre><code>import pandas as pd\nimport numpy as np \n\ndef fct_tf(data, name_a, name_b, param_a, param_b, param_c, df_common, df_shift):\n &quot;Compute results for two sets of parameters&quot;\n\n df_false = df_common.copy()\n\n # Lift one of the shifts up a loop.\n # Still working on removing the shifts altogether.\n # df_false['name_b_delta'] = df_false[name_b].shift(2+param_a)-df_false[name_b].shift(2+param_a+param_b)\n df_false['name_b_delta'] = df_shift - df_shift.shift(param_b)\n df_false['is_ok'] = df_false['name_b_delta'].apply(lambda x : np.sign(x+(-param_c)))\n\n df_false['results'] = df_false['is_ok'] * df_false['pct']\n df_false['cumul_results'] = df_false['results'].cumsum()\n\n df_true = df_false.copy()\n df_true['results'] = -1 * df_false['results']\n df_true['cumul_results'] = -1 * df_false['cumul_results']\n\n return df_true, df_false\n\ndef fct(data, name_a, name_b, param_a, param_b, param_c, param_d):\n &quot;Compute results for one set of parameters&quot;\n\n df = data.loc[(data[name_a].notnull()) &amp; (data[name_b].notnull()),[name_a, name_b]]\n\n df['pct'] = df[name_a].pct_change() \n df['name_b_delta'] = df[name_b].shift(2+param_a)-df[name_b].shift(2+param_a+param_b)\n df['is_ok'] = df['name_b_delta'].apply(lambda x : np.sign(x+(-param_c)))\n\n if param_d:\n df['results'] = df['is_ok'] * (-1) * df['pct'] \n else:\n df['results'] = df['is_ok'] * df['pct'] \n\n df['cumul_results'] = df['results'].cumsum() \n \n return df\n\ndef compute(data, names_a, names_b):\n &quot;Compute results ...&quot;\n\n df_line= []\n df_index = []\n\n for name_a in names_a :\n print('name_a: ' + name_a)\n for name_b in names_b :\n print('name_b: ' + name_b)\n\n # 'df_common' will have just one column if the names are the same.\n # Then, an exception occurs when invoking 'pct_change()'.\n if ( name_a == name_b ):\n continue\n\n # This part of the results data is common across the parameters.\n df_common = data.loc[(data[name_a].notnull()) &amp; (data[name_b].notnull()),[name_a, name_b]]\n print('Common data:')\n print(df_common)\n\n # The percent change is also common. Note that the values are not free from\n # a dependence on 'name_b', since the null check can change which rows are selected.\n # That means this value cannot be lifted to the 'name_a' loop.\n df_common['pct'] = df_common[name_a].pct_change()\n print(&quot;Common data[pct]:&quot;)\n print(df_common['pct'])\n\n for param_a in range(0,15):\n # Reduce the number of shifts\n # In theory, this shift should be avoidable, but I'm still figuring\n # how to remove it.\n df_shift = df_common[name_b].shift(2+param_a)\n\n for param_b in range(1,15):\n for param_c in range (-2, 3, 1):\n # The computations for 'False' and 'True' are the same, except\n # for a change in sign.\n # for param_d in [True, False]:\n # df = fct(data, name_a, name_b, param_a, param_b, param_c/1000, param_d)\n # df_index.append(f&quot;{name_a}-{name_b}&quot;)\n # df_line.append([df['cumul_results'].iloc[-1], param_a, param_b, param_c, param_d])\n\n df_true, df_false = fct_tf(data, name_a, name_b, param_a, param_b, param_c/1000, df_common, df_shift)\n\n df_index.append(f&quot;{name_a}-{name_b}&quot;)\n df_line.append([df_true['cumul_results'].iloc[-1], param_a, param_b, param_c, True])\n\n df_index.append(f&quot;{name_a}-{name_b}&quot;)\n df_line.append([df_false['cumul_results'].iloc[-1], param_a, param_b, param_c, False])\n\n results = pd.DataFrame(index=df_index, data=df_line, columns=['final result', 'param_a', 'param_b', 'param_c', 'param_d'])\n\n return results\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T16:47:20.047", "Id": "510522", "Score": "0", "body": "For the first point you mean doing something like `df_true = fct(data, name_a, name_b, param_a, param_b, param_c/1000, True)` and `df_false = fct(data, name_a, name_b, param_a, param_b, param_c/1000, False)` just after `param_c in range (-2, 3, 1):`?\nWhat do you mean by \"not to cache\" ? For the `apply` and `lambda`, i thought vectorization was the fastest ? And yes `print` is just a check I added after but it was not in the search of parameters." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T17:42:42.247", "Id": "510532", "Score": "0", "body": "Try putting the code within `fct(..., True)` next to the code within `fct(..., False)`, and see how much of the computation is repeated." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T07:13:45.473", "Id": "510611", "Score": "0", "body": "Yes i see your point, so it would be better to output before the `param_d` check and then append `True` and `False` value at the same time ? Could you write an example for the caching results thing you mentionned ? Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T17:39:29.163", "Id": "510770", "Score": "0", "body": "Thanks for your edit with the code, there are pertinent changes. Let me know if you find for the `shift` and `apply` things, thanks !" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T03:03:47.380", "Id": "510807", "Score": "1", "body": "Something to consider: If the print out can display the common data just once, then display the results for each of the parameter combinations, then copies of the common data can be avoided, which should save both time and resources." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T15:35:51.097", "Id": "258924", "ParentId": "257682", "Score": "2" } } ]
{ "AcceptedAnswerId": "258924", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T16:01:39.923", "Id": "257682", "Score": "0", "Tags": [ "python", "performance" ], "Title": "Find the 4 best parameters of a function to have the best cumulative sum" }
257682
<p>Staying true to the mantra: <em>&quot;The third time you do something, you automate&quot;</em>, I've built up a decent collection of shell scripts that live in <code>~/bin</code>. Some of these scripts contain useful boilerplate code, or just stuff I can't bring myself to memorise (like colour output stuff). Other scripts I find myself elaborating on from time to time. Though not a great pain, I am very lazy. Rather than typing <code>vim ~/bin/some_script</code>, I've written yet another script that expands <code>some_script</code> to its full path (using <code>which</code>), and opens it in vim. I'm perfectly happy with how the script works, and added a few basic creature-comforts, like checking if any (valid) arguments were provided and so on. Truth be told, I've not been writing that much bash in recent years, and some of the expressions/tricks I found myself using feel clunky. I know I used to have something like this in my <code>.profile</code>, but that particular incarnation of the script/function never made it to my github misc repo.</p> <p>In short, I'd like to know if there's some stuff I could improve on. First the code, then some specific things that just don't feel right to me.</p> <pre><code>Usage() { cat &lt;&lt;-__EOF_ ${0##*/} finds executables in PATH and opens them in vim - useful to quickly edit your scripts -o : opens all scripts using o flag (equivalent to vim -o &lt;paths&gt;) -O : similar to -o, but uses -O flag (so vim -O &lt;paths&gt;) -h : Display help message __EOF_ exit &quot;${1:-0}&quot; } flags=&quot;&quot; paths=&quot;&quot; while getopts :oOh f; do case $f in o) flags=&quot;-o&quot; ;; O) flags=&quot;-O&quot; ;; h) Usage ;; *) echo &quot;Unknown flag ${f}${OPTARG}&quot; Usage 1 ;; esac shift done [ $# -lt 1 ] &amp;&amp; echo &quot;No arguments given&quot; &amp;&amp; Usage 2 for b in &quot;$@&quot;; do p=$(which &quot;${b}&quot;) &amp;&amp; paths=&quot;${paths} ${p}&quot; done [ ${#paths} -gt 0 ] || :(){ echo &quot;No valid executables found in path&quot; &amp;&amp; exit 3; };: # We want globbing and word splitting here # shellcheck disable=SC2086 vim $flags $paths </code></pre> <p>Things that just feel a tad off would be:</p> <ul> <li><code>[ $# -lt 1 ] &amp;&amp; echo &quot;No arguments given&quot; &amp;&amp; Usage 2</code> I do this all the time, and it works just fine, but chaining together 3 commands with <code>&amp;&amp;</code> like this just looks ugly. If there's a cleaner, more concise way to do the same thing, I'm all ears.</li> <li><code>p=$(which &quot;${b}&quot;) &amp;&amp; paths=&quot;${paths} ${p}&quot;</code>. I'm not sold on the use of the subshell here. I'm using <code>#!/usr/bin/env bash</code> for my hashbang, I'm not sure I need the subshell. If not, what would be the alternative? What are the pro's, what are the con's?</li> <li><code>[ ${#paths} -gt 0 ] || :(){ echo &quot;No valid executables found in path&quot; &amp;&amp; exit 3; };:</code> same as chaining things, only this time, because I'm using an <code>||</code>, then an <code>&amp;&amp;</code>, I just wrap the last 2 expressions in a function and call it. This smells IMO. I could change it to <code>[ ${#paths} -le 0 ] &amp;&amp; ...</code>, but then it's just another chain. Personally, I prefer <code>-gt</code> over <code>-le</code> or <code>-eq</code> in this case. I also prefer to have the eventual command (<code>vim</code>) to be the last one, so that the exit code of vim is passed back on success (without needing an explicit exit like <code>[ ${#paths} -gt 0 ] &amp;&amp; vim $flags $paths &amp;&amp; exit</code> or <code>exit $?</code> if want to be super-explicit)</li> </ul> <p>There might be other things I can improve on, so feel free to point them out.</p>
[]
[ { "body": "<p><strike>Use a shebang</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>#!/usr/bin/env bash\n</code></pre>\n<p></strike> I see you're already doing that.</p>\n<p>In bash, prefer <code>[[...]]</code> over <code>[...]</code>. The double bracket <a href=\"https://www.gnu.org/software/bash/manual/bash.html#index-_005b_005b\" rel=\"nofollow noreferrer\">conditional\ncommand</a>\ngives you more features (including regular expression matching), and fewer\nsurprises (particularly about unquoted variables).</p>\n<p>With a <code>getopts</code> loop, I prefer to <code>shift</code> at the end:</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>while getopts ...; do\n case $opt in\n ...\n esac\ndone\nshift $((OPTIND - 1))\n</code></pre>\n<p>Allow the Usage function to take an error message:</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>Usage() {\n [[ -n $2 ]] &amp;&amp; echo &quot;$2&quot; &gt;&amp;2\n # ... rest is the same\n}\n</code></pre>\n<p>That simplifies some assertions</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>(( $# &gt; 0 )) || Usage 2 &quot;No arguments given&quot;\n</code></pre>\n<p><a href=\"https://stackoverflow.com/q/592620/7552\">Use <code>command -v</code> instead of <code>which</code></a></p>\n<p>Use an array to hold the paths. There's no other good way to hold a list of things where any of them might contain whitespace.</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>paths=()\nfor b in &quot;$@&quot;; do\n p=$( command -v &quot;$b&quot; ) &amp;&amp; paths+=(&quot;$p&quot;)\ndone\n</code></pre>\n<p>You do need to command substitution (aka subshell) so you can capture the output.</p>\n<p>The &quot;colon&quot; function makes me cringe.\nFor clarity, use <code>if</code> instead of long boolean chains</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>if (( ${#paths[@]} == 0 )); then\n echo &quot;No valid executables found in PATH&quot; &gt;&amp;2\n exit 3\nfi\n</code></pre>\n<p>And <a href=\"https://unix.stackexchange.com/questions/171346/security-implications-of-forgetting-to-quote-a-variable-in-bash-posix-shells\">prefer quoting over word splitting</a>:</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>vim $flags &quot;${paths[@]}&quot;\n</code></pre>\n<p>Yes, the script will exit with vim's exit status. If you want to be super tidy, you could <em>replace</em> the script process with vim:</p>\n<pre class=\"lang-bsh prettyprint-override\"><code>exec vim $flags &quot;${paths[@]}&quot;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T17:55:18.773", "Id": "508972", "Score": "0", "body": "Thanks for the input. The colon function felt dirty to write indeed. Just out of curiosity: any specific reason to use `(())` for numeric comparisons over `[ -eq ]` & co? I get why one would prefer using `>` of `-gt`, but oddly enough, I find myself making less silly mistakes using the latter (I probably mess up `<` vs `>` at least once a week - embarrassing, I know)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:34:12.570", "Id": "508983", "Score": "0", "body": "Just a personal preference. `((...))` allow you to assign variables within it , and also to refer to variables without `$` to create readable C-like expressions -- `((sum += hours * hourly_rate))`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:36:55.660", "Id": "508984", "Score": "0", "body": "`((...))` does not play well with `set -e` though: if the arithmetic expression evaluates to zero, the return status is 1 -- makes it good for conditions, but can be confusing source of errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T19:04:43.860", "Id": "508989", "Score": "0", "body": "cheers. In that case, I'll stick to the square brackets for bash scripts. Implemented pretty much all of the other suggestions you made." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T17:39:56.137", "Id": "257687", "ParentId": "257683", "Score": "1" } } ]
{ "AcceptedAnswerId": "257687", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T16:11:16.673", "Id": "257683", "Score": "0", "Tags": [ "bash", "shell" ], "Title": "Small bash script to quickly edit scripts in $PATH" }
257683
<p>The Julia package <a href="https://github.com/JuliaDynamics/DrWatson.jl" rel="nofollow noreferrer">DrWatson.jl</a> is aimed at scientific computing and data analysis. It describes itself as &quot;scientific project assistant software&quot;. I recently decided giving it a try and like the functionality so far.</p> <p>Useful features, in my opinion, include the <code>safesave</code> method, which saves dictionaries to <code>JLD</code> files while making sure no data is lost, and the <code>@tag!</code> macro, which adds key-value pairs to a dictionary that include, e.g., the current git commit hash, as well as a warning, together with a &quot;gitpatch&quot; showing the differences, in case of a dirty repository. It also provides tools to collect the results from all these files back together into <code>DataFrame</code> objects.</p> <p>I use scripts that have a lot of adjustable parameters and need to run on cluster machines for days to produce output. Shortly after starting a given simulation, I want to be as sure as possible that (assuming the simulation itself runs fine) my program will not crash in the end when trying to save stuff, and that it's easy to keep track of where the result files went, when looking at the console output of a run.</p> <p>My current workflow is tending into the direction of using <code>DrWatson</code> to just carelessly dump all input parameters and all results of my simulations into <code>.jld</code> files as <code>Dict</code> objects. It may be better to use some kind of JSON-based format to save all simulation parameters. However, I have a lot of different simulations that have mostly disjoint sets of input parameters and results. Overall, putting in the time to develop some kind of system to save all the metadata seems like a major distraction from my actual work (That's what she said while writing a CodeReview post about tools to simplify and automate workflow...).</p> <h2>The issue</h2> <p>While <code>DrWatson</code> seems useful, when adopting it in my code-base, I ended up producing insane amounts of boilerplate code. The repository containing the simulation scripts doesn't contain any of the simulation code and refers to other repositories (Julia packages). Thus, my &quot;simulations&quot; project consists of many completely independent and disjoint scripts, each of which looked like this (notice the boilerplate):</p> <pre><code>using DrWatson @quickactivate &quot;PROJECTNAME&quot; println(repeat(&quot;-&quot;, 80)) println(repeat(&quot;-&quot;, 10), &quot; Script $(@__FILE__)&quot;) println(repeat(&quot;-&quot;, 80)) using SparseArrays using JLD using Pkg @info(&quot;Status of custom simulation packages used:&quot;) Pkg.status(&quot;&lt;SOMESTUFF&gt;&quot;) # ... function main() p = 32 # blahblahblah q = 4 # ... # many more parameters... # some of these parameters get organized into `struct`'s simul_params = DrWatson.@strdict p q # a LOT more stuff. # Multiple lines of listed parameters, easy to forget something... @tag!(simul_params) # add git commit information, etc. output_file_name = DrWatson.savename(&lt;important parameters&gt;, &quot;.jld&quot;) println(&quot;Output file complete results: '$output_file_name'&quot;) # ... simulations can take days to complete # some of the simulations actually internally save intermediate results # to paths that are part of the parameters. result1 = external_library.some_simulation(parameters) result2 = external_library.other_simulation(result1, other_parameters) simul_params[&quot;result1&quot;] = result1 simul_params[&quot;result2&quot;] = result2 # ... # you get the idea output_file_path = DrWatson.datadir(&quot;sims&quot;, &quot;script_name&quot;, filename), simul_params) DrWatson.safesave(output_file_path, simul_params) end main() </code></pre> <h2>Proposed solution</h2> <p>What I ended up doing is a bit similar to <a href="http://%20https://codereview.stackexchange.com/questions/138246/saving-the-values-of-all-variabled-declared-in-a-block" rel="nofollow noreferrer">this codereview post</a> (I actually don't fully understand what is being done there). However, using <code>DrWatson</code> I get a lot more metadata and my approach seems much more radical in that I save <em>all</em> available variables. Perhaps an approach like the linked post is actually objectively better, I'm not sure how much the dangers/downsides of saving <em>absolutely everything</em> will come back to bite me.</p> <p>In any case, the below code defines macros that either return as a <code>Dict</code> (or save directly to a <code>JLD</code> file) <strong>all global and local variables</strong> (except functions, modules, variables with special names, etc.). This is done by using <code>Base.@local</code> to get local variables in the caller's scope and <code>getfield</code> to get global variables of the calling module. The use of <code>getfield</code> is inspired from the source of <a href="https://github.com/JuliaIO/JLD2.jl/blob/f7535ab19cb65e703ce4f1f2209ccd32e5b9287f/src/loadsave.jl#L78" rel="nofollow noreferrer">JLD2.jl</a>.</p> <pre><code>&quot;&quot;&quot; This file is to be `include`'d into all simulation scripts. It makes sure that the DrWatson package and its required imports are available. &quot;&quot;&quot; using DrWatson @quickactivate &quot;LDPC4QKD&quot; using SparseArrays using JLD using Pkg @info(&quot;Status of RateAdaptiveLDPC used:&quot;) Pkg.status(&quot;RateAdaptiveLDPC&quot;) &quot;&quot;&quot; Provides macros for obtaining `Dict`'s of selected local (potentially also global) variables. &quot;&quot;&quot; module ScopeCrawler using DrWatson using SparseArrays using JLD export @all_vars_dict export @safesave_vars &quot;&quot;&quot; macro safesave_vars(out_path=&quot;&quot;, save_globals=true) Saves the outputs of `@all_vars_dict` to a `JLD` file as a `Dict{String, Any}`. &quot;&quot;&quot; macro safesave_vars(out_path=&quot;&quot;, save_globals=true) return quote output_file_path = $(esc(out_path)) # auto-generate path if none given. if output_file_path == &quot;&quot; output_file_path = datadir(&quot;autoname&quot;, &quot;$(basename(string(__source__.file)))_line$(__source__.line)_$(__module__).jld&quot;) @warn(&quot;@safesave_locals received empty destination path from $(__source__.file). Auto-generated path: '$output_file_path'&quot;) end # make sure the file path has '.jld' extension. if length(output_file_path) &lt; 4 || output_file_path[end - 3:end] != &quot;.jld&quot; @warn(&quot;Appending extension '.jld' to output file path '$output_file_path'.&quot;) output_file_path *= &quot;.jld&quot; end results = @all_vars_dict($(esc(save_globals))) DrWatson.@tag!(results) if isfile(output_file_path) @warn(&quot;The requested output path $output_file_path already exists. Final path is chosen by `DrWatson.safesave` and will (probably) be $(abspath(DrWatson.recursively_clear_path(output_file_path)))&quot;) else @info(&quot;Final output file destination: $(abspath(output_file_path))&quot;) end DrWatson.safesave( output_file_path, results ) end end &quot;&quot;&quot; macro all_vars_dict(save_globals=true) Returns all local variables (with reasonable names, no functions and no modules) in the caller scope and global variables of the module in a `Dict{String, Any}` (with some additional meta-information). Note: this is slow and not optimized. Meant to be called rarely! TODO: test properly TODO specify additional information &quot;&quot;&quot; macro all_vars_dict(save_globals=true) # Note: output_file_path should evaluate to a String. sourcefile = &quot;unknown&quot; sourceline = &quot;unknown&quot; try sourcefile = basename(string(__source__.file)) sourceline = __source__.line catch e @warn(&quot;macro received invalid __source__: $e&quot;) end # could add additional metadata that the macro has access to additional_info = Dict{String,Any}() try additional_info[&quot;#source#&quot;] = repr(__source__) additional_info[&quot;#module#&quot;] = repr(__module__) additional_info[&quot;#stacktrace#&quot;] = stacktrace() catch e @warn(&quot;Failed to privide additional info in safesave_locals. Reason: $e&quot;) end # helper functions symbol_dict_to_strdict(dict::Dict{Symbol,T} where T) = Dict(string(key) =&gt; val for (key, val) in dict) function combine_conflicting_keys(x, y) # when globals and conflict, resolve @warn(&quot;Name conflict found between global/local variables while saving: $x vs $y.&quot;) return Dict(&quot;local&quot; =&gt; x, &quot;global&quot; =&gt; y) end # Generate expression. # Basic idea: # Evaluate `Base.@locals` and function `get_globals_dict` in the scope of the caller. return quote globals_dict = Dict{String, Any}() if $(esc(save_globals)) globals_dict = $get_globals_dict(@__MODULE__) end merge($combine_conflicting_keys, # `Any` makes sure the right method is for `merge` is called: Dict{String, Any}(), $symbol_dict_to_strdict(Base.@locals), $additional_info, globals_dict ) end end &quot;&quot;&quot; function get_globals_dict(m::Module) Returns a `Dict{String, Any}` containing global fields of a module that are likely to be user-defined variables. Ignores modules, functions and non-standard names. Note: inspired from JLD2.jl, see https://github.com/JuliaIO/JLD2.jl/blob/f7535ab19cb65e703ce4f1f2209ccd32e5b9287f/src/loadsave.jl#L78 &quot;&quot;&quot; function get_globals_dict(m::Module) results = Dict{String,Any}() try for vname in names(m; all=true) s = string(vname) if (!occursin(r&quot;^_+[0-9]*$&quot;, s) # skip IJulia history vars &amp;&amp; !occursin(r&quot;[@#$%^&amp;*()?|\\/,.&lt;&gt;]&quot;, s)) # skip variables with special characters v = getfield(m, vname) if !isa(v, Module) &amp;&amp; !isa(v, Function) try results[s] = v catch e if isa(e, PointerException) @warn(&quot;Saving globals, skipping $vname because it contains a pointer.&quot;) else @warn(&quot;Saving globals, skipping $vname because $e&quot;) end end end end end catch e @warn(&quot;Saving globals failed because: $e&quot;) end return results end end # module ScopeCrawler &quot;&quot;&quot; poor man's unit tests for the above Note: running this test at the start of each job using the functionality makes sense because if this stuff crashes at the end of a simulation, all the work is lost. &quot;&quot;&quot; module TestingScopeCrawler using Test using ..ScopeCrawler using JLD tmptmp_global_var_for_test = &quot;tmptmp_global_var_for_test&quot; @testset &quot;testing @all_vars_dict&quot; begin local_var = 3 othervar = &quot;asdf&quot; @testset &quot;no args&quot; begin allvarsdict = @all_vars_dict @test allvarsdict[&quot;local_var&quot;] == 3 @test allvarsdict[&quot;othervar&quot;] == &quot;asdf&quot; @test allvarsdict[&quot;tmptmp_global_var_for_test&quot;] == &quot;tmptmp_global_var_for_test&quot; end @testset &quot;arg: true&quot; begin allvarsdict = @all_vars_dict true @test allvarsdict[&quot;local_var&quot;] == 3 @test allvarsdict[&quot;othervar&quot;] == &quot;asdf&quot; @test allvarsdict[&quot;tmptmp_global_var_for_test&quot;] == &quot;tmptmp_global_var_for_test&quot; end @testset &quot;arg: false&quot; begin allvarsdict = @all_vars_dict false @test allvarsdict[&quot;local_var&quot;] == 3 @test allvarsdict[&quot;othervar&quot;] == &quot;asdf&quot; @test_throws(KeyError, allvarsdict[&quot;tmptmp_global_var_for_test&quot;] == &quot;tmptmp_global_var_for_test&quot;) end @testset &quot;arg: variable name&quot; begin variable_containing_false = false allvarsdict = @all_vars_dict variable_containing_false @test allvarsdict[&quot;local_var&quot;] == 3 @test allvarsdict[&quot;othervar&quot;] == &quot;asdf&quot; @test_throws(KeyError, allvarsdict[&quot;tmptmp_global_var_for_test&quot;] == &quot;tmptmp_global_var_for_test&quot;) end end @testset &quot;testing @safesave_locals&quot; begin try local_var = 3 othervar = &quot;asdf&quot; dest_path = &quot;tmptmp_test_safesave_locals.jld&quot; @safesave_vars dest_path @test isfile(&quot;tmptmp_test_safesave_locals.jld&quot;) loadagain = load(&quot;tmptmp_test_safesave_locals.jld&quot;) @test loadagain[&quot;local_var&quot;] == 3 @test loadagain[&quot;othervar&quot;] == &quot;asdf&quot; @test loadagain[&quot;tmptmp_global_var_for_test&quot;] == &quot;tmptmp_global_var_for_test&quot; finally rm(&quot;tmptmp_test_safesave_locals.jld&quot;) # throws exception `IOError` if the file does not exist. end end end # module TestingScopeCrawler </code></pre> <h2>How to use:</h2> <p>With my boilerplate script, the code above simplifies to</p> <pre><code>include(&quot;dr_watson_boilerplate.jl&quot;) function main() p = 32 # blahblahblah q = 4 # ... # many more parameters... # some of these parameters get organized into `struct`'s output_file_name = DrWatson.savename(&lt;important parameters&gt;, &quot;.jld&quot;) println(&quot;Output file complete results: '$output_file_name'&quot;) # ... simulations can take days to complete # some of the simulations actually internally save intermediate results # to paths that are part of the parameters. result1 = external_library.some_simulation(parameters) result2 = external_library.other_simulation(result1, other_parameters) output_file_path = DrWatson.datadir(&quot;sims&quot;, &quot;script_name&quot;, filename), simul_params) ScopeCrawler.@safesave_vars output_file_path end main() </code></pre> <p>What do you think?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T17:46:25.197", "Id": "257689", "Score": "0", "Tags": [ "macros", "julia" ], "Title": "Automatic saving of workspace variables for `DrWatson.jl`" }
257689
<p>Hi everyone I'm trying to reduce the complexity of some of my Python code. The function below aims to compute the validation and test loss for a variety of PyTorch time series forecasting models. I won't go into all the intricacies but needs to support models that return multiple targets, an output distribution + std (as opposed to a single tensor), and models that require masked elements of the target sequence. This over time has resulted in long if else blocks and lots of other bad practices.</p> <p>I've used dictionaries before to map long if else statements but due to the nested nature of this code it doesn't seem like it would work well here. I also don't really see the point in just creating more functions as that just moves the if else statements somewhere else and requires passing more parameters around. Does anyone have any ideas? There are several unit tests that run from the different paths in this code now. However, it is still cumbersome to read. Plus soon I will have even more model variations to expand and support. <a href="https://github.com/AIStream-Peelout/flow-forecast/blob/0093228fca0bc6915162c21d192d65be11a15fdb/flood_forecast/pytorch_training.py#L357" rel="nofollow noreferrer">Full code can in context can be seen at this link.</a></p> <pre><code>def compute_validation(validation_loader: DataLoader, model, epoch: int, sequence_size: int, criterion: Type[torch.nn.modules.loss._Loss], device: torch.device, decoder_structure=False, meta_data_model=None, use_wandb: bool = False, meta_model=None, multi_targets=1, val_or_test=&quot;validation_loss&quot;, probabilistic=False) -&gt; float: &quot;&quot;&quot;Function to compute the validation loss metrics :param validation_loader: The data-loader of either validation or test-data :type validation_loader: DataLoader :param model: model :type model: [type] :param epoch: The epoch where the validation/test loss is being computed. :type epoch: int :param sequence_size: The number of historical time steps passed into the model :type sequence_size: int :param criterion: The evaluation metric function :type criterion: Type[torch.nn.modules.loss._Loss] :param device: The device :type device: torch.device :param decoder_structure: Whether the model should use sequential decoding, defaults to False :type decoder_structure: bool, optional :param meta_data_model: The model to handle the meta-data, defaults to None :type meta_data_model: PyTorchForecast, optional :param use_wandb: Whether Weights and Biases is in use, defaults to False :type use_wandb: bool, optional :param meta_model: Whether the model leverages meta-data, defaults to None :type meta_model: bool, optional :param multi_targets: Whether the model, defaults to 1 :type multi_targets: int, optional :param val_or_test: Whether validation or test loss is computed, defaults to &quot;validation_loss&quot; :type val_or_test: str, optional :param probabilistic: Whether the model is probablistic, defaults to False :type probabilistic: bool, optional :return: The loss of the first metric in the list. :rtype: float &quot;&quot;&quot; print('Computing validation loss') unscaled_crit = dict.fromkeys(criterion, 0) scaled_crit = dict.fromkeys(criterion, 0) model.eval() output_std = None multi_targs1 = multi_targets scaler = None if validation_loader.dataset.no_scale: scaler = validation_loader.dataset with torch.no_grad(): i = 0 loss_unscaled_full = 0.0 for src, targ in validation_loader: src = src if isinstance(src, list) else src.to(device) targ = targ if isinstance(targ, list) else targ.to(device) # targ = targ if isinstance(targ, list) else targ.to(device) i += 1 if decoder_structure: if type(model).__name__ == &quot;SimpleTransformer&quot;: targ_clone = targ.detach().clone() output = greedy_decode( model, src, targ.shape[1], targ_clone, device=device)[ :, :, 0] elif type(model).__name__ == &quot;Informer&quot;: multi_targets = multi_targs1 filled_targ = targ[1].clone() pred_len = model.pred_len filled_targ[:, -pred_len:, :] = torch.zeros_like(filled_targ[:, -pred_len:, :]).float().to(device) output = model(src[0].to(device), src[1].to(device), filled_targ.to(device), targ[0].to(device)) labels = targ[1][:, -pred_len:, 0:multi_targets] src = src[0] multi_targets = False else: output = simple_decode(model=model, src=src, max_seq_len=targ.shape[1], real_target=targ, output_len=sequence_size, multi_targets=multi_targets, probabilistic=probabilistic, scaler=scaler) if probabilistic: output, output_std = output[0], output[1] output, output_std = output[:, :, 0], output_std[0] output_dist = torch.distributions.Normal(output, output_std) else: if probabilistic: output_dist = model(src.float()) output = output_dist.mean.detach().numpy() output_std = output_dist.stddev.detach().numpy() else: output = model(src.float()) if multi_targets == 1: labels = targ[:, :, 0] elif multi_targets &gt; 1: labels = targ[:, :, 0:multi_targets] validation_dataset = validation_loader.dataset for crit in criterion: if validation_dataset.scale: # Should this also do loss.item() stuff? if len(src.shape) == 2: src = src.unsqueeze(0) src1 = src[:, :, 0:multi_targets] loss_unscaled_full = compute_loss(labels, output, src1, crit, validation_dataset, probabilistic, output_std, m=multi_targets) unscaled_crit[crit] += loss_unscaled_full.item() * len(labels.float()) loss = compute_loss(labels, output, src, crit, False, probabilistic, output_std, m=multi_targets) scaled_crit[crit] += loss.item() * len(labels.float()) if use_wandb: if loss_unscaled_full: scaled = {k.__class__.__name__: v / (len(validation_loader.dataset) - 1) for k, v in scaled_crit.items()} newD = {k.__class__.__name__: v / (len(validation_loader.dataset) - 1) for k, v in unscaled_crit.items()} wandb.log({'epoch': epoch, val_or_test: scaled, &quot;unscaled_&quot; + val_or_test: newD}) else: scaled = {k.__class__.__name__: v / (len(validation_loader.dataset) - 1) for k, v in scaled_crit.items()} wandb.log({'epoch': epoch, val_or_test: scaled}) model.train() return list(scaled_crit.values())[0] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:13:06.300", "Id": "508975", "Score": "0", "body": "Welcome to Code Review! We need to know *what the code is intended to achieve*. To help reviewers give you better answers, please add sufficient context to your question, including a title that summarises the *purpose* of the code. We want to know **why** much more than **how**. The more you tell us about [what your code is for](//meta.codereview.stackexchange.com/q/1226), the easier it will be for reviewers to help you. The title needs an [edit] to simply [**state the task**](//meta.codereview.stackexchange.com/q/2436), rather than your concerns about the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T20:13:13.280", "Id": "508995", "Score": "0", "body": "Thank you for providing more context about the code. I [changed the title](https://codereview.stackexchange.com/revisions/257691/3) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T18:05:12.250", "Id": "257691", "Score": "1", "Tags": [ "python", "python-3.x", "machine-learning" ], "Title": "validation and test loss for a variety of PyTorch time series forecasting models" }
257691
<p>I feel like this code could be cleaned up more or it could be shorter but and more understandable. Any advice/suggestion is appreciated.</p> <pre><code>public string GetIPVersions(NetworkInterface @interface) { string ipVersions = &quot;&quot;; if (@interface.Supports(NetworkInterfaceComponent.IPv4)) ipVersions += NetworkInterfaceComponent.IPv4; if (!@interface.Supports(NetworkInterfaceComponent.IPv6)) return ipVersions; ipVersions += ipVersions.Length &gt; 0 ? $&quot; {NetworkInterfaceComponent.IPv6}&quot; : $&quot;{NetworkInterfaceComponent.IPv6}&quot;; return ipVersions; } private void UpdatePageText() { int interfacesCount = Interfaces.Count(); InterfaceCountText = interfacesCount &gt; 0 ? $&quot;{interfacesCount} interfaces found&quot; : &quot;No interfaces found&quot;; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T07:12:10.197", "Id": "509032", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T15:42:43.917", "Id": "509073", "Score": "0", "body": "Here's something I never thought I'd say: look up FizzBuzz and what solutions people find to it - it will be helpful for you to decide how to approach this." } ]
[ { "body": "<p>Switching the logic <code>@interface.Supports</code> vs <code>!@interfaceSupports</code> is confusing the code.</p>\n<p>The decision to add a space is better as a distinct statement. Blending this decision with the addition of the IPv6 text obscures the meaning of the code.</p>\n<p>With just two cases, you can be more direct:</p>\n<pre><code>public string GetIPVersions(NetworkInterface @interface) {\n boolean supportsIPv4 = ( @interface.Supports(NetworkInterfaceComponent.IPv4) );\n boolean supportsIPv6 = ( @interface.Supports(NetworkInterfaceComponent.IPv6) ); \n\n if ( supportsIPv4 ) {\n if ( supportsIPv6 ) {\n return NetworkInterfaceComponent.IPv4 + &quot; &quot; + NetworkInterfaceComponent.IPv6;\n } else {\n return NetworkInterfaceComponent.IPv4;\n }\n } else if ( supportsIPv6 ) {\n return NetworkInterfaceComponent.IPv6;\n } else {\n return &quot;&quot;;\n }\n}\n</code></pre>\n<p>Keeping the code closer to you original method:</p>\n<pre><code>public string GetIPVersions(NetworkInterface @interface) {\n string ipVersions = &quot;&quot;;\n\n if ( @interface.Supports(NetworkInterfaceComponent.IPv4) ) {\n ipVersions += NetworkInterfaceComponent.IPv4;\n }\n\n if ( @interface.Supports(NetworkInterfaceComponent.IPv6) ) {\n if ( ipVersions.Length &gt; 0 ) {\n ipVersions += &quot; &quot;;\n }\n ipVersions += NetworkInterfaceComponent.IPv6;\n }\n\n return ipVersions;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T15:40:05.673", "Id": "509072", "Score": "0", "body": "It's interesting to see how this essentially boils down to FizzBuzz." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T23:12:32.620", "Id": "257698", "ParentId": "257697", "Score": "2" } }, { "body": "<p>The Code looks neat and clean. If you want you can change this to</p>\n<pre><code>private void UpdatePageText()\n {\n InterfaceCountText = Interfaces.Count() &gt; 0 ? $&quot;{Interfaces.Count()} interfaces found&quot; : &quot;No interfaces found&quot;;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T01:36:04.837", "Id": "257703", "ParentId": "257697", "Score": "0" } }, { "body": "<p>Here is another approach although it may be a tad less understandable.<br />\nEssentially it creates an array of strings or null, filters out the nulls, and joins the remaining with a separator.<br />\nOne advantage of this approach is that it can be easily extended to support more cases.</p>\n<pre><code>public string GetIPVersions(NetworkInterface @interface)\n{\n return\n String.Join(\n &quot; &quot;,\n new string[] {\n @interface.Supports(NetworkInterfaceComponent.IPv4) ? NetworkInterfaceComponent.IPv4.ToString() : null,\n @interface.Supports(NetworkInterfaceComponent.IPv6) ? NetworkInterfaceComponent.IPv6.ToString() : null,\n }\n .Where(x =&gt; x != null));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T05:40:38.163", "Id": "257709", "ParentId": "257697", "Score": "0" } }, { "body": "<p>The first function has some convoluted logic: the if and if(!) that does an unexpected return in the middle, the extra ternary to handle the space. That's a lot to follow for what boils down to showing IPV4 and/or IPV6.</p>\n<p>For simple functions it's not a big deal, but I would try to keep the different pieces distinct, dead-simple, and top-down. <code>string.Join()</code> is perfect for space or comma-separated concatenation, let's use it.</p>\n<pre><code> public string GetIpVersions(NetworkInterface @interface) {\n var supported = new List&lt;NetworkInterfaceComponent&gt;();\n\n if (@interface.Supports(NetworkInterfaceComponent.IPv4)) supported.Add(NetworkInterfaceComponent.IPv4);\n if (@interface.Supports(NetworkInterfaceComponent.IPv6)) supported.Add(NetworkInterfaceComponent.IPv6);\n\n return string.Join(&quot; &quot;, supported);\n }\n</code></pre>\n<p><code>UpdatePageText()</code> is fine to me.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T06:42:00.083", "Id": "257711", "ParentId": "257697", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-25T22:41:02.940", "Id": "257697", "Score": "-2", "Tags": [ "c#" ], "Title": "What can I do better to clean this code up, make it smaller? Just started practicing clean code, need advice" }
257697
<p>Hello StackExchange community, I am curious if there is a better solution than mine for this exercise below:</p> <p><em>Enter a regex that matches all the items in the first column (positive examples) but none of those in the second (negative examples).</em></p> <p><strong>Positive Examples:</strong></p> <pre><code>pit spot spate slap two respite </code></pre> <p><strong>Negative Examples:</strong></p> <pre><code>pt Pot peat part </code></pre> <p><strong>My solution:</strong> <code>^[a-z](?!ar|ea)[a-z]+\s?[a-z]+</code></p> <p>You can find the exercise here:</p> <p><a href="https://regex.sketchengine.co.uk/cgi/ex1.cgi" rel="nofollow noreferrer">https://regex.sketchengine.co.uk/cgi/ex1.cgi</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T07:12:46.183", "Id": "509033", "Score": "3", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T15:39:21.620", "Id": "510417", "Score": "1", "body": "`.*?p.t.*` keep it simple :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T15:51:40.757", "Id": "510419", "Score": "0", "body": "@hjpotter92 That's what I was looking for! It felt like I was missing something or I could achieve this by a simpler solution than mine. Well I guess now it's time to learn more about lazy matches. Thanks for the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-08T05:06:49.410", "Id": "514173", "Score": "0", "body": "@SpirosGkogkas `^[^pP].*$|^pit$` works too" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T02:35:01.530", "Id": "257705", "Score": "2", "Tags": [ "strings", "regex" ], "Title": "Is there a better pattern to match those words with regex?" }
257705
<p>I have a function that creates filters for some data. The filters get added to an array and then (later) chained through the <code>reduce</code> function (the chaining part not part of my question).</p> <p>The data I receive are all strings but can actually be numbers, eg <code>{name:&quot;-45.6&quot;}</code>. If it can be a number, I want the value to be converted to a number.</p> <pre><code>formFilters = (builder) =&gt; { const filters = []; builder.forEach(b =&gt; { let {filtername, operator, value} = b; if(!value) return; if(isNumber(value)){ value = Number(value); } switch (operator) { case &quot;=&quot;: filters.push((item) =&gt; convertToNumber(item[filtername]) === value); break; case &quot;&lt;&quot;: filters.push((item) =&gt; convertToNumber(item[filtername]) &lt; value); break; case &quot;&gt;&quot;: filters.push((item) =&gt; convertToNumber(item[filtername]) &gt; value); } }); return filters; } function convertToNumber(value){ const number = Number(value); if (!Number.isNaN(number)) return number; return value; } </code></pre> <p>This works but I'm wondering if there's a cleaner way of converting the value to a number if it is a number?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T09:37:14.637", "Id": "509041", "Score": "1", "body": "To convert to a number only if value is a number use the function `const convertToNumber = value => isNaN(value) ? value : Number(value);`" } ]
[ { "body": "<p>One problem with <code>Number(value);</code> is that it casts <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Falsy\" rel=\"nofollow noreferrer\">falsy</a> values as <code>0</code> and <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Truthy\" rel=\"nofollow noreferrer\">truthy</a> values as <code>1</code>.</p>\n<p>That means that an empty string becomes <code>0</code>, which may not be what you expect.</p>\n<p>You could make a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions\" rel=\"nofollow noreferrer\">regular expression</a> test on the input to determine if it fits your expectations for a number.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>let input = document.getElementById('input');\nlet result = document.getElementById('result');\n\nfunction IsANumber() {\n let isItANumber = input.value.match(/^-?\\d*\\.?\\d+$/);\n result.innerHTML = isItANumber ? 'true' : 'false';\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;input id=\"input\" onchange=\"IsANumber()\" onkeyup=\"IsANumber()\" /&gt;&lt;br/&gt; Is a number: &lt;span id=\"result\"&gt;&lt;/span&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The example above will not fail in truthy/falsy cases, but it will determine strings like &quot;Infinity&quot; to not be numbers too.\nTherefore it may need to be modified if you have to parse these to numeric values.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T09:56:43.270", "Id": "509042", "Score": "1", "body": "The function will fail for numbers like `\"1e2\"`, `\"0x10\"`, `\"0b00\"` returning false." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T07:52:49.510", "Id": "257714", "ParentId": "257707", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T03:04:29.687", "Id": "257707", "Score": "0", "Tags": [ "javascript" ], "Title": "Write a clean convertToNumber function, if value is a number" }
257707
<p>As a side project, I'm working on a Bokeh web application to display public bikeshare data on a map. The data is updated every 2 minutes using a periodic callback. Below is the full implementation. I'm using PyBikes (<a href="https://github.com/eskerda/pybikes" rel="nofollow noreferrer">https://github.com/eskerda/pybikes</a>) to scrape the bike data. I'm interested in feedback on the use of good coding style/best practices. Also, I'm trying to learn about unit testing but I'm unsure what kind of unit tests would be appropriate here. Any other comments on how this code could be improved are welcome as well.</p> <pre><code>import json import math import pybikes from bokeh.io import curdoc from bokeh.layouts import column from bokeh.plotting import figure from bokeh.tile_providers import get_provider, Vendors from bokeh.models import GeoJSONDataSource, ColorBar, LinearColorMapper, Label from bokeh.palettes import viridis def latlon_to_mercator(lat, lon): &quot;&quot;&quot;Converts latitude/longitude coordinates from decimal degrees to web mercator format. Derived from the Java version shown here: http://wiki.openstreetmap.org/wiki/Mercator Args: lat: latitude in decimal degrees format. lon: longitude in decimal degrees format. Returns: Latitude (y) and longitude (x) as floats. &quot;&quot;&quot; radius = 6378137.0 x = math.radians(lon) * radius y = math.log(math.tan(math.radians(lat) / 2.0 + math.pi / 4.0)) * radius return y, x def color(percent_full): &quot;&quot;&quot;Returns a color from the Viridis256 palette corresponding to how full a station is. Args: percent_full: A value between 0-1 indicating percent full status of a station Returns: Color from the Viridis256 palette as a hex code string &quot;&quot;&quot; idx = int(percent_full*255) colors = viridis(256) color = colors[idx] return color def gbfs_to_geojson(stations): &quot;&quot;&quot;Converts General Bikeshare Feed Specification (GBFS) data to GeoJSON format. Args: stations: A list of GbfsStation objects. Returns: A json string containing GeoJSON-formatted data for each station &quot;&quot;&quot; geo_dict = {} geo_dict['type'] = 'FeatureCollection' geo_dict['features'] = [] for station in stations: station_dict = {} station.latitude, station.longitude = latlon_to_mercator(station.latitude, station.longitude) if station.bikes == 0 and station.free == 0: percent_full = 0 else: percent_full = float(station.bikes)/float(station.bikes + station.free) station_dict['geometry'] = {'type': 'Point', 'coordinates': [station.longitude, station.latitude]} station_dict['type'] = 'Feature' station_dict['id'] = station.extra['uid'] station_dict['properties'] = {'station name': station.name, 'bikes': station.bikes, 'free': station.free, 'color': color(percent_full), 'size': (station.free + station.bikes)*0.5} geo_dict['features'].append(station_dict) geo_json = json.dumps(geo_dict) return geo_json def get_data(): &quot;&quot;&quot;Pulls bikeshare data from the web using the Pybikes API. Returns: A json string containing GeoJSON-formatted data for each station &quot;&quot;&quot; capital = pybikes.get('capital-bikeshare') capital.update() stations = capital.stations geo_data = gbfs_to_geojson(stations) return geo_data def make_map(source): &quot;&quot;&quot;Creates a Bokeh figure displaying the source data on a map Args: source: A GeoJSONDataSource object containing bike data Returns: A Bokeh figure with a map displaying the data &quot;&quot;&quot; tile_provider = get_provider(Vendors.STAMEN_TERRAIN_RETINA) TOOLTIPS = [ ('bikes available', '@bikes'), ] p = figure(x_range=(-8596413.91, -8558195.48), y_range=(4724114.13, 4696902.60), x_axis_type=&quot;mercator&quot;, y_axis_type=&quot;mercator&quot;, width=1200, height=700, tooltips=TOOLTIPS) p.add_tile(tile_provider) p.xaxis.visible = False p.yaxis.visible = False p.circle(x='x', y='y', size='size', color='color', alpha=0.7, source=source) color_bar_palette = viridis(256) color_mapper = LinearColorMapper(palette=color_bar_palette, low=0, high=100) color_bar = ColorBar(color_mapper=color_mapper, background_fill_alpha=0.7, title='% Full', title_text_align='left', title_standoff=10) p.add_layout(color_bar) label = Label(x=820, y=665, x_units='screen', y_units='screen', text='Dot size represents total docks in station', render_mode='css', border_line_color=None, background_fill_color='white', background_fill_alpha=0.7) p.add_layout(label) return p def update(): geo_json = get_data() source.update(geojson=geo_json) source = get_data() source = GeoJSONDataSource(geojson=source) fig = make_map(source) curdoc().add_root(column(fig)) curdoc().add_periodic_callback(update, 120000) <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T03:17:39.257", "Id": "257708", "Score": "2", "Tags": [ "python", "beginner", "python-2.x", "unit-testing" ], "Title": "Interactive, real-time bikeshare web application with Bokeh" }
257708
<p>I got the C++ implementation of depth-first search (DFS) from <a href="https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/" rel="nofollow noreferrer">here</a> and made slight modifications to it. The modified code is as follows:</p> <pre><code>#include &quot;stdafx.h&quot; #include &lt;iostream&gt; #include&lt;map&gt; #include&lt;list&gt; class Graph { void DFSUtil(int v); public: std::map&lt;int, bool&gt; visited; std::map&lt;int, std::list&lt;int&gt;&gt; adj; void addEdge(int v, int w); void DFS(); }; void Graph::addEdge(int v, int w) { adj[v].push_back(w); } void Graph::DFSUtil(int v) { visited[v] = true; std::cout &lt;&lt; v &lt;&lt; &quot; &quot;; std::list&lt;int&gt;::iterator i; for (i = adj[v].begin(); i != adj[v].end(); ++i) if (!visited[*i]) DFSUtil(*i); } void Graph::DFS() { for (auto i : adj) if (visited[i.first] == false) DFSUtil(i.first); } int main() { Graph g; g.addEdge(0, 1); g.addEdge(0, 9); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(9, 3); std::cout &lt;&lt; &quot;Depth First Traversal result\n&quot;; g.DFS(); std::cin.get(); return 0; } </code></pre> <p>What further improvements can I make to this code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T16:27:15.483", "Id": "509077", "Score": "0", "body": "You need to learn the visitor pattern." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T16:32:17.597", "Id": "509078", "Score": "2", "body": "Not sure what DF search means when you apply it to a graph (what is down verses across). The term is usually applied to non-cyclic structures (like trees)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T17:05:11.277", "Id": "509084", "Score": "0", "body": "@MartinYork Thank you for the response. Where do you see \"DF\"? I only see the word \"DFS\" in my question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T17:17:08.163", "Id": "509085", "Score": "0", "body": "`DFS => DF Search => Depth First Search`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:07:18.260", "Id": "509093", "Score": "0", "body": "@MartinYork A [tree is a graph](https://en.wikipedia.org/wiki/Tree_(graph_theory))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:39:27.493", "Id": "509098", "Score": "0", "body": "@MartinYork My bad. I should have read your comment properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:42:36.760", "Id": "509100", "Score": "0", "body": "@Woodford A tree is a graph with no cycles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T11:32:24.763", "Id": "510154", "Score": "6", "body": "@MartinYork I don't know where you get the assumption that DFS is only used in the context of acyclic graphs. Just look at the cyclic examples in here: https://en.wikipedia.org/wiki/Depth-first_search \nOr look at the graph provided in the link in the question.\nBoth of them have cycles" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T10:17:44.297", "Id": "510332", "Score": "0", "body": "Depth-first search is frequently used in cyclic graphs. Determine whether an edge is a tree edge (when the DFS follows an unvisited edge to an unvisited vertex) or a back edge (when the DFS follows an unvisited edge to a visted vertex, and is part of a cycle) is often a fundamental part of algorithm in Graph Theory." } ]
[ { "body": "<blockquote>\n<p>What further improvements can I make to this code?</p>\n</blockquote>\n<p>The code is rather bad - the site you read it from tends to have lots of bad/amateur articles.</p>\n<ol>\n<li><p>The graph class:</p>\n<pre><code>std::map&lt;int, bool&gt; visited;\nstd::map&lt;int, std::list&lt;int&gt;&gt; adj;\n</code></pre>\n</li>\n</ol>\n<p>This is extremely poor and inefficient graph implementation. <code>std::map</code> creates a new memory allocation for each element. So you do it twice for both the boolean and the list. Also <code>std::list</code> allocates a piece of memory for each element as well.</p>\n<p>Overuse of memory allocation means both memory fragmentation issues as well as performance issues due lots of unmanageable RAM access and indirections. Memory loading is currently one of the slowest operations on modern processors. But compilers tend to optimize it quite well if the memory is contiguous - which is furthest from the truth in this case.</p>\n<p>To simplify the structure you'd better use <code>std::vector&lt;Node&gt;</code> where Node contains vertex's information + <code>std::vector&lt;size_t&gt;</code> of neighbors. In general, I don't believe there is a perfect solution for graph representation - instead there are numerous ways to represent and each suitable or more attuned to specific types of graphs. For instance, solutions that are good for sparse graphs are surely very poorly suited for dense graphs. Also certain additional optimizations can be made assuming that graph is fixes. The question is complex and I cannot provide an answer without knowledge of the use-case.</p>\n<ol start=\"2\">\n<li><code>DFS()</code> implementation is also pretty bad. It relies on recursion and I assure you, that for large enough connected graphs with it will blow the stack resulting in UB.</li>\n</ol>\n<p>Proper DFS/BFS implementation store states-to-be-visited in a <code>std::stack</code> or <code>std::queue</code> or something similar while the visit routine occurs in a single loop instead of recursion.</p>\n<p>Also, I presume you want some kind of output or action made on vertices from the DFS, no?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T16:10:09.647", "Id": "510354", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/122418/discussion-on-answer-by-alx23z-c-implementation-of-depth-first-search)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T14:40:28.887", "Id": "514407", "Score": "0", "body": "Look at Boost's `flat_map` to overcome the efficiency issues with the `std::map`, but still make use of map features." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T08:39:36.067", "Id": "257716", "ParentId": "257710", "Score": "16" } }, { "body": "<pre><code>std::map&lt;int, bool&gt; visited;\n</code></pre>\n<p>This is useless as a member variable.</p>\n<ul>\n<li>It means nothing before or after you call <code>DFS</code>, so it's a waste of space most of the time</li>\n<li>There's only one copy of it for a given <code>Graph</code>, which means you can't call <code>DFS</code> twice concurrently</li>\n<li>It retains its state after calling <code>DFS</code> the first time, which means you can't even call <code>DFS</code> twice in sequence.</li>\n</ul>\n<p>This variable should be local to <code>DFS</code>, created afresh at each call, and passed in to <code>DFSUtil</code> by reference, if at all (using a stack and a loop, as mentioned in ALX23z's review, does not require a helper method at all).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T11:47:48.177", "Id": "514316", "Score": "1", "body": "\"you can't even call DFS twice in sequence.\" - well you can, but it may not do what you require. Then again, there _are_ algorithms that usefully retain state for incremental operations." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T10:41:39.560", "Id": "257719", "ParentId": "257710", "Score": "5" } }, { "body": "<h2>Disagreement</h2>\n<p>I have to disagree with @ALX23z blanket statement that using <code>std::map</code> is bad idea. There is a lot more to it than that (if the graph was sparse the map is great). But you don't give enough contect to evaluate the graph implementation. All I can say it is an acceptable &quot;basic&quot; implementation.</p>\n<h2>Overall</h2>\n<p>Things that are actually bad:</p>\n<p>1: The two main structures are <strong>public</strong>.</p>\n<pre><code>class Graph {\n void DFSUtil(int v);\npublic:\n std::map&lt;int, bool&gt; visited; // public member variable\n std::map&lt;int, std::list&lt;int&gt;&gt; adj; // public member variable.\n // The user of this class can\n // damage the state of the object.\n //\n // but more importantly it locks you\n // to a specific implementation.\n // You can never remove the map without\n // fixing all the code that uses the map.\n void addEdge(int v, int w);\n void DFS();\n};\n</code></pre>\n<p>The <code>adj</code> should absolutely be private. The only method that should be public is <code>addEdge()</code>. That way if your usage of map turns out to be bad (after you measure it) then you can easily swap it out for another implementation without affecting any of the code that uses your <code>Graph</code> class.</p>\n<p>2: You have a member that tracks some external processes.</p>\n<pre><code>std::map&lt;int, bool&gt; visited;\n</code></pre>\n<p>This is not a property of the class this is a property of the traversal itself. Storing it in the class limits how the class can be used you should store this as part of the traversal processes (there is a pattern for this &quot;Visitor Pattern&quot;).</p>\n<h2>Code Review</h2>\n<p>Be consistent on your formatting:</p>\n<pre><code>#include &lt;iostream&gt;\n#include&lt;map&gt; // Why no space here\n#include&lt;list&gt;\n</code></pre>\n<hr />\n<p>Public members variables!!</p>\n<pre><code>public:\n std::map&lt;int, bool&gt; visited;\n std::map&lt;int, std::list&lt;int&gt;&gt; adj;\n</code></pre>\n<p>Member variables should always be private. If they need to be public you need to be able to articulate in a very detailed way why you are exposing the state and allowing the potability of it being mutated in a non controlled manner and thus potentially allowing the object to become invalid.</p>\n<p>Note: const (preferably static) state is ok to be public.</p>\n<hr />\n<p>This is a good interface for creating a graph.</p>\n<pre><code> void addEdge(int v, int w);\n</code></pre>\n<p>You can use this and the internal state can be nearly anything you want. If you used a PIMPL pattern you could customize the internal state depending on the type of graph.</p>\n<hr />\n<p>The problem with your code is that it only does one thing. Print out the key of the node. If you want it to do anything else you need to change the code.</p>\n<pre><code>void Graph::DFSUtil(int v)\n{\n visited[v] = true;\n std::cout &lt;&lt; v &lt;&lt; &quot; &quot;;\n\n std::list&lt;int&gt;::iterator i;\n for (i = adj[v].begin(); i != adj[v].end(); ++i)\n if (!visited[*i])\n DFSUtil(*i);\n}\n\n\nvoid Graph::DFS()\n{\n for (auto i : adj)\n if (visited[i.first] == false)\n DFSUtil(i.first);\n}\n</code></pre>\n<p>This is where you should inject your functionality (the action you want done). This is a form of &quot;Dependency Injection&quot; you pass the work action (as a function) into <code>DFS()</code> your function then gets called once for each node.</p>\n<pre><code>void Graph::DFS(std::function&lt;void(int)&gt;&amp;&amp; action);\nvoid Graph::DFSUtil(std::function&lt;void(int)&gt;&amp;&amp; action, int v);\n</code></pre>\n<p>Now the usage becomes:</p>\n<pre><code>graph.DFS([](int n){std::cout &lt;&lt; v &lt;&lt; &quot; &quot;;}); // Or you can pass any action\n // you like.\n</code></pre>\n<hr />\n<p>But your main problem is implementing the visitor pattern:</p>\n<pre><code>class GraphVisitor\n{\n std::map&lt;int, bool&gt; visited;\n virtual void doVisit(int n) = 0;\n public:\n virtual ~GraphVisitor() {}\n void visit(int n) {\n if (!visited[n]) {\n visited[n] = true;\n doVisit(n);\n }\n }\n};\nclass Graph\n{\n void accept(int i, GraphVisitor&amp; visitor)\n {\n visitor.visit(i);\n for(auto e: edges(i)) { // some way to get edges from i.\n accept(e.dst.id, visitor);\n }\n }\n public:\n void accept(GraphVisitor&amp; visitor)\n {\n for(auto i: adj) {\n accept(i, visitor);\n }\n }\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T16:33:52.550", "Id": "510358", "Score": "0", "body": "Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackexchange.com/rooms/122419/discussion-on-answer-by-martin-york-c-implementation-of-depth-first-search)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T17:16:24.160", "Id": "257741", "ParentId": "257710", "Score": "12" } }, { "body": "<p><strong>I've assumed here the OP is performing DFS on undirected graphs - if not only my second point is valid.</strong></p>\n<p>There are several other answers here suggesting better coding practices and more efficient implementations, but they're missing the biggest problem with you code: <em>it doesn't perform depth first search!</em></p>\n<p>To demonstrate this run it with the graph created by:</p>\n<pre><code>Graph g;\ng.addEdge(0, 1);\ng.addEdge(1, 3);\ng.addEdge(1, 2);\ng.addEdge(4, 3);\ng.addEdge(3, 5);\n</code></pre>\n<p>This outputs <code>0 1 3 5 2 4</code>. This is wrong. 4 is part of the 3 branch so should be explored before the program backtracks and explores 2. The bug here is in the <code>addEdge()</code> function which makes w reachable from v but does not make v reachable from w. You need to add <code>adj[w].push_back(v);</code>.</p>\n<p>The other issue with your code is that it will explore nodes which aren't attached to the rest of the graph (try adding <code>g.addEdge(20, 21);</code>. DFS shouldn't be able to get to these nodes but can anyway). The root problem here is your <code>DFS()</code> function, which starts a new depth first search every time it finds an unvisited <code>i</code>. This loop should not exist. Instead your program should have a parameter for where the depth first search should start, eg: 0, and go straight to the functionality in <code>DFSUtil()</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T13:25:57.857", "Id": "514322", "Score": "0", "body": "From the graph model I would assume that the graph is directed. Other than that, very good observations" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:12:16.513", "Id": "257744", "ParentId": "257710", "Score": "10" } }, { "body": "<p>You have received excellent feedback from others. I can only add to that in a show-and-tell fashion.</p>\n<p>What my version does is address all the issues mentioned by others:</p>\n<ul>\n<li><p>make the directed/undirected choice explicit in your graph</p>\n</li>\n<li><p>make the algorithm iterative so you don't have the stack limit</p>\n</li>\n<li><p>make your containers contiguous to reduce allocations and increase locality of reference.</p>\n<p>I opted for <code>deque</code> which, given the current access patterns still offers reference stability.</p>\n</li>\n<li><p>For the visited marks I use a local data structure. A dynamic_bitset would probably be the most pure, but I chose <code>std::vector&lt;bool&gt;</code> for simplicity.</p>\n</li>\n</ul>\n<p>Some things that haven't been mentioned:</p>\n<ul>\n<li><p>Your algorithm lacked a feedback mechanism. I added a callback argument that can be used to act on visited vertices.</p>\n</li>\n<li><p>You had DFS and the Graph model coupled. There's no reason. I made a simple interface that you could optionally define as a &quot;concept&quot; (AdjacencyGraph, if you will):</p>\n<pre><code>struct AdjacencyGraph {\n using VertexId = unsigned;\n\n size_t size() const;\n bool empty() const;\n void addEdge(VertexId, VertexId);\n range&lt;VertexId&gt; adjacent(VertexId id) const;\n };\n</code></pre>\n<p>And the DFS algorithm is a free function that operates on any such graph:</p>\n</li>\n<li><p>I added quite a few precondition checks, <code>.at(x)</code> instead of <code>[x]</code> (which does bounds checking)</p>\n</li>\n<li><p>I fixed sloppy const-correctness (most notably inside DFS, even though it's now a free function)</p>\n</li>\n<li><p>I committed the &quot;sin&quot; of premature optimization by using <code>small_vector</code> from Boost Container to optimize for &quot;expected out-degree&quot;.</p>\n<p>See here for a demonstration where this makes a big difference:</p>\n<blockquote>\n<p><em>Just for kicks, I made a little profile of the median out-degree of nodes: <a href=\"https://i.imgur.com/7zcIZ5Q.png\" rel=\"nofollow noreferrer\">i.imgur.com/7zcIZ5Q.png</a>. Since it shows the median is 40 out-edges, I replaced <code>vector&lt;OutEdge&gt;</code> with <code>small_vector&lt;OutEdge, 40&gt;</code> and behold: it runs 4x faster (10s without, 22s with heuristics)</em> . – sehe <a href=\"https://stackoverflow.com/questions/67232482/boost-fibonacci-heap-access-violation-during-pop/67238518#comment118864338_67238518\">Apr 24 at 20:51</a></p>\n</blockquote>\n</li>\n</ul>\n<p>The resulting separation of concern gives a calmer code image, IMO:</p>\n<h2>The Graph</h2>\n<pre><code>struct Graph {\n enum mode { directed, undirected };\n Graph(mode mode) : _mode(mode) {}\n\n using VertexId = unsigned;\n\n size_t size() const { return _vertices.size(); }\n bool empty() const { return _vertices.empty(); }\n\n void addEdge(VertexId v, VertexId w) {\n auto&amp; target = vertex(w); // ensure it is created\n if (_mode == undirected)\n target.adjacent.push_back(v);\n\n vertex(v).adjacent.push_back(w);\n }\n\n auto const &amp;adjacent(VertexId id) const {\n return _vertices.at(id).adjacent;\n }\n\n private:\n struct Vertex {\n small_vector&lt;VertexId, 10&gt; adjacent;\n };\n std::deque&lt;Vertex&gt; _vertices;\n mode _mode = directed;\n\n Vertex&amp; vertex(VertexId id) {\n _vertices.resize(std::max(id + 1ul, _vertices.size()));\n return _vertices.at(id);\n }\n};\n</code></pre>\n<p>Note how nice it is to be able to just flip a switch to get undirected behaviour.</p>\n<h2>The Algorithm</h2>\n<p>The algorithm can be viewed in two levels:</p>\n<pre><code>template &lt;class Graph, class V, class F&gt;\nvoid DFS(Graph const&amp; g, V start, F callback) {\n /// local state and methods\n /// ...\n /// end local definitions\n\n while (!stack.empty()) {\n for (V v : g.adjacent(pop()))\n push(v);\n }\n}\n</code></pre>\n<p>You see it is ultra-brief and clear. Of course, the devil must be in the details. However, with some good organization, we can limit the &quot;damage&quot;:</p>\n<pre><code>/// local state and methods\nusing V = typename AdjacencyGraph::VertexId;\nstd::vector&lt;bool&gt; visited(g.size());\nstd::vector&lt;V&gt; stack{start};\n\nauto push = [&amp;](V v) {\n if (visited.at(v))\n return false;\n callback(v);\n stack.push_back(v);\n visited[v] = true; // no boundscheck needed here\n return true;\n};\n\nauto pop = [&amp;] {\n auto v = stack.back();\n stack.pop_back();\n return v;\n};\n/// end local definitions\n</code></pre>\n<p>Really, this is just like a local class with two data members and two member functions. In fact, if you would have any use for re-use, you would do good to extract that type. See e.g. this answer where I do exactly that by <a href=\"https://codereview.stackexchange.com/questions/186530/read-csv-and-use-bidirectional-bfs-to-find-the-shortest-connections-between-acto/186539#:%7E:text=The%20BFS,of%20things\">extracting <code>struct BFS_State</code></a> (<a href=\"https://codereview.stackexchange.com/questions/186530/read-csv-and-use-bidirectional-bfs-to-find-the-shortest-connections-between-acto/186539#186539\">Read CSV and use bidirectional BFS to find the shortest connections between actors</a>)</p>\n<h2>Full Listing</h2>\n<p><strong><a href=\"http://coliru.stacked-crooked.com/a/604e880fce4ae67a\" rel=\"nofollow noreferrer\">Live On Coliru</a></strong></p>\n<pre><code>#include &lt;boost/container/small_vector.hpp&gt;\n#include &lt;deque&gt;\n#include &lt;vector&gt;\n#include &lt;iostream&gt;\nusing boost::container::small_vector;\n\n/*\n *struct AdjacencyGraph {\n * using VertexId = unsigned;\n *\n * size_t size() const {return {};}\n * bool empty() const {return {};}\n * void addEdge(VertexId, VertexId) { }\n * std::vector&lt;VertexId&gt; adjacent(VertexId id) const { return {}; }\n *};\n */\n\nstruct Graph {\n enum mode { directed, undirected };\n Graph(mode mode) : _mode(mode) {}\n\n using VertexId = unsigned;\n\n size_t size() const { return _vertices.size(); }\n bool empty() const { return _vertices.empty(); }\n\n void addEdge(VertexId v, VertexId w) {\n auto&amp; target = vertex(w); // ensure it is created\n if (_mode == undirected)\n target.adjacent.push_back(v);\n\n vertex(v).adjacent.push_back(w);\n }\n\n auto const &amp;adjacent(VertexId id) const {\n return _vertices.at(id).adjacent;\n }\n\n private:\n struct Vertex {\n small_vector&lt;VertexId, 10&gt; adjacent;\n };\n std::deque&lt;Vertex&gt; _vertices;\n mode _mode = directed;\n\n Vertex&amp; vertex(VertexId id) {\n _vertices.resize(std::max(id + 1ul, _vertices.size()));\n return _vertices.at(id);\n }\n};\n\ntemplate &lt;class Graph, class V, class F&gt;\nvoid DFS(Graph const&amp; g, V start, F callback)\n{\n /// local state and methods\n using VertexIndex = typename Graph::VertexId;\n std::vector&lt;bool&gt; visited(g.size());\n std::vector&lt;VertexIndex&gt; stack{start};\n\n auto push = [&amp;](VertexIndex v) {\n if (visited.at(v))\n return false;\n callback(v);\n stack.push_back(v);\n visited[v] = true; // no boundscheck needed here\n return true;\n };\n\n auto pop = [&amp;] {\n auto v = stack.back();\n stack.pop_back();\n return v;\n };\n /// end local definitions\n\n while (!stack.empty()) {\n for (VertexIndex v : g.adjacent(pop()))\n push(v);\n }\n}\n\nint main()\n{\n Graph g(Graph::directed);\n using VertexId = Graph::VertexId;\n\n for (auto [s, t] :\n {std::pair{0, 1}, {0, 1}, {0, 9}, {1, 2}, {2, 0}, {2, 3}, {9, 3}})\n {\n g.addEdge(s, t);\n }\n\n std::cout &lt;&lt; &quot;Depth First traversal\\n&quot;;\n\n VertexId start = 0;\n DFS(g, start, [](VertexId v) { std::cout &lt;&lt; &quot;Visited &quot; &lt;&lt; v &lt;&lt; &quot;\\n&quot;; });\n}\n</code></pre>\n<p>Prints</p>\n<pre><code>Depth First traversal\nVisited 1\nVisited 9\nVisited 3\nVisited 2\nVisited 0\n</code></pre>\n\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T05:37:49.847", "Id": "514383", "Score": "0", "body": "Thank you very much for promptly responding to my request :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-10T14:15:38.840", "Id": "260560", "ParentId": "257710", "Score": "2" } }, { "body": "<p>regarding</p>\n<pre><code>std::list&lt;int&gt;::iterator i;\n for (i = adj[v].begin(); i != adj[v].end(); ++i)\n if (!visited[*i])\n DFSUtil(*i);\n</code></pre>\n<p>You have the definition of <code>i</code> outside the <code>for</code> statement and not initialized; you spell out the complex and specific type rather than using <code>auto</code>, you repeatedly index <code>adj[v]</code> and you call <code>.end()</code> each time through the loop.</p>\n<p>Yet the following function shows a simple range-based <code>for</code> loop instead. So why is this one so clunky, when you do in fact know better?</p>\n<p>Also, could it have used a <code>const_iterator</code> instead?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-11T14:48:28.617", "Id": "260607", "ParentId": "257710", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T06:33:47.200", "Id": "257710", "Score": "7", "Tags": [ "c++", "c++11", "search", "depth-first-search" ], "Title": "C++ implementation of depth-first search" }
257710
<p><strong>Situation:</strong> I have implemented a factory design pattern in Python as below. There are different screens which have different configurations. One can register the screen in the factory and get the screen in case correct configuration is passed to respective factory class method.</p> <p><strong>Question:</strong> I am wondering if this is a clean solution as each screen class (<code>Screen1</code>, <code>Screen2</code>, ..) has a <code>main</code>-method which calls in a specific order the respective private class methods. Is there a better/cleaner way to handle the <code>main</code> methods in each class? Is it cleaner to implement a combination of factory and builder design pattern?</p> <p>Highly appreciate any comments and improvements!!</p> <p><strong>Code:</strong></p> <pre><code>import numpy as np import pandas as pd from abc import ABCMeta, abstractmethod df = pd.DataFrame({&quot;ident&quot;: [&quot;A1&quot;, &quot;A2&quot;, &quot;B3&quot;, &quot;B4&quot;], &quot;other_col&quot;: np.random.randint(1, 6, 4)}) class IScreens(metaclass=ABCMeta): @abstractmethod def main(self): pass class Screen1(IScreens): def __init__(self, data, config): self.data = data self.batch = config[&quot;cfg1&quot;] def __get_letter(self): self.data[&quot;campaign&quot;] = self.data[self.batch].str[:1] return self.data def __get_number(self): self.data[&quot;num&quot;] = self.data[self.batch].str[1:] return self.data def __some_other_stuff(self): self.data[&quot;other_stuff&quot;] = self.data[&quot;num&quot;].astype(int) * 100 / 2 return self.data def main(self): self.data = self.__get_letter() self.data = self.__get_number() self.data = self.__some_other_stuff() # some more processing steps follow return self.data class Screen2(IScreens): def __init__(self, data, config): self.data = data self.batch = config[&quot;cfg1&quot;] def __some_cool_stuff(self): self.data[&quot;cool_other_stuff&quot;] = self.data[self.batch] + &quot;_COOOOL&quot; return self.data def main(self): self.data = self.__some_cool_stuff() # some more processing steps follow return self.data class ScreenFactory: def __init__(self): self._screens = {} def register_screen(self, screen_name, screen_class): self._screens[screen_name] = screen_class def get_screen(self, data, config): if &quot;screen_indicator&quot; not in config: raise AssertionError(&quot;Your config file does not include 'screen_indicator' key&quot;) screen = self._screens.get(config[&quot;screen_indicator&quot;]) if not screen: raise AssertionError(&quot;screen not implemented&quot;) return screen(data=data, config=config) factory = ScreenFactory() factory.register_screen(screen_name=&quot;s1&quot;, screen_class=Screen1) config = {&quot;screen_indicator&quot;: &quot;s1&quot;, &quot;cfg1&quot;: &quot;ident&quot;} factory.get_screen(data=df, config=config).main() factory.register_screen(screen_name=&quot;s2&quot;, screen_class=Screen2) config = {&quot;screen_indicator&quot;: &quot;s2&quot;, &quot;cfg1&quot;: &quot;ident&quot;} factory.get_screen(data=df, config=config).main() <span class="math-container">```</span> </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T15:19:33.117", "Id": "509071", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<h2>IScreens is a callable</h2>\n<p>Actually, your <code>IScreens</code> class (interface) contains only one abstract method (the <code>main</code> method), so this class is a kind of callable.\nInstead of creating a specific class, you can use <code>collections.Callable</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import collections\n\nIScreens = collections.Callable\n</code></pre>\n<p>To use that class, you can do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Screen1(IScreens):\n def __init__(self, data, config):\n ...\n\n def __call__(self, *args, **kwargs): # instead of `main`\n return ...\n\ns1 = Screen1(data=..., config=...)\nresult = s1() # call the callable s1\n</code></pre>\n<h2>IScreens can contain common data</h2>\n<p>I see that the <code>data</code> and <code>config</code> variables are common to <code>Screen1</code> and <code>Screen2</code>.\nIt's a good practice to factorize this in the base class:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class IScreens(collections.Callable):\n def __init__(self, data, config):\n self.data = data\n self.batch = config[&quot;cfg1&quot;]\n</code></pre>\n<blockquote>\n<p>NOTE: Here, I don't understand why you pass a <code>config</code> dictionary, but only get the <code>batch</code> (<code>config[&quot;cfg1&quot;]</code>).</p>\n</blockquote>\n<h2>Avoid extra complexity</h2>\n<p>Private methods with double underscores, like <code>__get_letter</code>, are more difficult to debug,\nbecause their names are disguised into <code>_{className}__{attr_name}</code>.</p>\n<p>For instance:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class C:\n def __init__(self):\n self.__secret = &quot;foo&quot;\n\nobj = C()\nprint(obj._C__secret)\n# 'foo'\n</code></pre>\n<p>Very short functions like <code>__get_letter</code> should be avoided, unless reused several times.\nHere, you add complexity (and extra computation time) with them.</p>\n<h2>Getters should not mutate the instance</h2>\n<p>A getter should not change the class instance state.</p>\n<p>Here, in your <code>__get_letter</code> method, you are extracting a value (<code>self.data[self.batch].str[:1]</code>)\nand modifying the internal state (<code>self.data[&quot;campaign&quot;]</code>). Is it intentional?</p>\n<p>It is better to initialize everything in your constructor:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class Screen1(IScreens):\n def __init__(self, data, config):\n self.data = data\n self.batch = config[&quot;cfg1&quot;]\n self.data[&quot;campaign&quot;] = self.data[self.batch].str[:1]\n self.data[&quot;num&quot;] = self.data[self.batch].str[1:]\n self.data[&quot;other_stuff&quot;] = self.data[&quot;num&quot;].astype(int) * 100 / 2\n</code></pre>\n<h2>Factory registration</h2>\n<p>There are two different ways to implement factories:</p>\n<ol>\n<li>The factory (or the main function) knows all its classes and is responsible for the class registration,</li>\n<li>Each class knows the factory and it can auto-register itself, like a plugin.</li>\n</ol>\n<p>It seems that you choose the first case. You may also need to add a method to unregister.\nIn the second case, registration is usually final: its more difficult to unregister…</p>\n<p>Both are good, so.</p>\n<p>To register a class in a factory, we used to use the class name (or a class instance) instead of an arbitrary name.</p>\n<p><strong>Example using the class name:</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>class ScreenFactory:\n def __init__(self):\n self._screens = {}\n\n def register_screen(self, screen_class):\n self._screens[screen_class.__name__] = screen_class\n\n def get_screen_class(self, class_name: str):\n return self._screens[class_name]\n</code></pre>\n<p><strong>Example using the class attribute:</strong></p>\n<pre class=\"lang-py prettyprint-override\"><code>class IScreens:\n kind = &quot;unknown&quot;\n\n\nclass Screen1(IScreens):\n kind = &quot;s1&quot;\n\n\nclass ScreenFactory:\n def __init__(self):\n self._screens = {}\n\n def register_screen(self, screen_class):\n self._screens[screen_class.kind] = screen_class\n\n def get_screen_class(self, kind: str) -&gt; IScreens:\n return self._screens[kind]\n</code></pre>\n<p>The second method is interesting if you want to select an implementation (a <code>IScreens</code> class)\naccording to a tag/label extracted from textual data…</p>\n<blockquote>\n<p>NOTE: you may have noticed that I added a <code>get_screen_class</code> method.</p>\n</blockquote>\n<h2>Factory access</h2>\n<blockquote>\n<p>This is the difficult part</p>\n</blockquote>\n<p>In your <code>get_screen</code> method, you are checking if a specific configuration is valid (existence of &quot;screen_indicator&quot;)\nand if there is a suitable class which satisfy a second condition (<code>config[&quot;screen_indicator&quot;]</code> is a <em>kind</em> of <code>IScreens</code>).</p>\n<p>I am OK with that, but it can be simplified. Here is a solution with error handling:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class ScreenNotImplementedError(Exception):\n fmt = &quot;Screen not implemented for this configuration: {config}&quot;\n\n def __init__(self, *, config):\n msg = self.fmt.format(config=config)\n super(ScreenNotImplementedError, self).__init__(msg)\n\n\nclass ScreenFactory:\n ...\n\n def get_screen(self, data, config):\n try:\n kind = config[&quot;screen_indicator&quot;] # may raise KeyError\n cls = self.get_screen_class(kind) # may raise KeyError\n except KeyError:\n raise ScreenNotImplementedError(config=config)\n else:\n screen = cls(data=data, config=config)\n return screen\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-08T12:27:36.607", "Id": "511256", "Score": "0", "body": "Thanks really much for your comments! As I am writing data-pipelines using pandas (which need to be highly configurable and adaptable to say applications only with small requirement changes among them) I was moving away from procedural code and try to go with OOP. can you recommend well-written OOP code using pandas (Github repo etc) or a book/blog entry for teaching?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T13:27:23.850", "Id": "257728", "ParentId": "257713", "Score": "0" } }, { "body": "<p>It's fine for a class to include &quot;helper&quot; methods to implement more complex methods. It's just like breaking down a complex function into simpler functions. If the helper methods are not part of the class' public interface, it is a convention to use a single leading underscore in the name.</p>\n<p>I like to use <code>__init_subclass__()</code> in the base class to automatically maintain a registry of subclasses and then provide a classmethod in the base class to act as a factory function. <code>__init_subclass__()</code> gets called after the code defining a subclass is run (so, at compile time). It gets passed the new subclass, which the code below uses to register the subclass with the subclass name. <code>__init_subclass__()</code> is a classmethod even without the <code>@classmethod</code> decorator. The classmethod <code>from_config()</code> is an example factory method that instantiates an appropriate subclass based arguments passed to it. Here it is based on the subclass name, but it could be based on other factors, calculations, etc.</p>\n<pre><code>class Screen(metaclass=ABCMeta):\n registry = {}\n \n def __init_subclass__(cls):\n if cls.__name__ not in Screen.registry:\n Screen.registry[cls.__name__] = cls\n else:\n raise RuntimeError('Screen subclass &quot;{cls.__name__}&quot; already defined.')\n\n \n def __init__(self, data, config):\n self.data = data\n self.config = config\n \n \n @classmethod\n def from_config(cls, data, config):\n if &quot;screen_indicator&quot; not in config:\n raise ValueError(&quot;config missing 'screen_indicator' key&quot;)\n \n screen = Screen.registry.get(config[&quot;screen_indicator&quot;])\n if not screen:\n raise NameError(f&quot;&quot;&quot;No such screen: '{config[&quot;screen_indicator&quot;]}'&quot;&quot;&quot;)\n \n return screen(data=data, config=config)\n \n \n @abstractmethod\n def main(self):\n pass \n \n \nclass Screen1(Screen):\n \n def _do_stuff(self):\n self.data[0] *= 2\n \n def main(self):\n self._do_stuff()\n return self.data\n \n \nclass Screen2(Screen):\n \n def _do_more_stuff(self):\n self.data[0] *= 3\n \n def main(self):\n self._do_more_stuff()\n return self.data\n\n\nprint(Screen.registry)\n\ndata=[42, 'what?']\n\nconfig = {&quot;screen_indicator&quot;: &quot;Screen1&quot;, &quot;cfg1&quot;: &quot;ident&quot;}\nd1 = Screen.from_config(data=data, config=config).main()\nprint(d1)\n\nconfig = {&quot;screen_indicator&quot;: &quot;Screen2&quot;, &quot;cfg1&quot;: &quot;ident&quot;}\nd2 = Screen.from_config(data=data, config=config).main()\nprint(d2)\n\nconfig = {&quot;screen_indicator&quot;: &quot;Screen3&quot;, &quot;cfg1&quot;: &quot;ident&quot;}\nd3 = Screen.from_config(data=data, config=config).main()\nprint(d3)\n</code></pre>\n<p>Output:</p>\n<pre><code>{'Screen1': &lt;class '__main__.Screen1'&gt;, 'Screen2': &lt;class '__main__.Screen2'&gt;}\n[84, 'what?']\n[252, 'what?']\n\nNameError: No such screen: 'Screen3' ## Note: I removed the stack trace\n</code></pre>\n<p>If you need to use something other than the class name as the indicator, you can use a keyword argument in the subclass definition like so:</p>\n<pre><code>class Screen(metaclass=ABCMeta):\n registry = {}\n \n def __init_subclass__(cls, indicator=''): #### keyword gets passed in here\n if indicator:\n Screen.registry[indicator] = cls\n else:\n raise ValueError('Class subclass &quot;{cls.__name__}&quot; missing &quot;indicator&quot; argument')\n \n @classmethod\n def from_config(cls, data, config):\n if &quot;screen_indicator&quot; not in config:\n raise ValueError(&quot;config missing 'screen_indicator' key&quot;)\n \n screen = Screen.registry.get(config[&quot;screen_indicator&quot;])\n if not screen:\n raise NameError(config[&quot;screen_indicator&quot;])\n \n return screen(data=data, config=config)\n \n @abstractmethod\n def main(self):\n pass \n \n\nclass Screen1(Screen, indicator='s1'): #### set the indicator here\n \n def __init__(self, data, config):\n self.data = data\n self.config = config\n \n def _do_stuff(self):\n self.data[0] *= 2\n \n def main(self):\n self._do_stuff()\n return self.data\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T05:47:45.753", "Id": "258758", "ParentId": "257713", "Score": "0" } } ]
{ "AcceptedAnswerId": "257728", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T07:30:03.900", "Id": "257713", "Score": "0", "Tags": [ "python", "object-oriented", "design-patterns", "abstract-factory" ], "Title": "Factory / Builder Design Pattern in Python" }
257713
<p>This is a datasource for Achievements that can be toggled to be viewed within a grid or list layout. Thoughts/notes</p> <ul> <li>This code was previously duplicated in two different ViewControllers.</li> <li>Should the CollectionLayout code go in here?</li> <li>Should the SectionHeader and layout toggle button delegate go in here?</li> <li>Have I implemented the DiffableDataSource correctly?</li> </ul> <p>Any comments or advise welcome.</p> <p><a href="https://i.stack.imgur.com/YSIU7l.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YSIU7l.png" alt="Screenshot of Datasource in use" /></a></p> <pre><code>class AchievementDataSource: UICollectionViewDiffableDataSource&lt;AchievementSectionID, Achievement&gt; { var sections: [AchievementListSection] = [AchievementListSection(id: 0, name: &quot;&quot;)] lazy var currentLayout = CollectionLayoutToggleHeader.State(rawValue: userLayoutPreferenceProvider()) ?? .list { didSet { userLayoutPreferenceSetter(currentLayout.rawValue) } } var userLayoutPreferenceProvider: () -&gt; String var userLayoutPreferenceSetter: (String) -&gt; Void private let achievementPlaceholderImage = UIImage(named: &quot;placeholder_home_achievements_home_badge&quot;) init(collectionView: UICollectionView, userLayoutPreferenceProvider: @escaping () -&gt; String = { LocalUser.PreferenceSettings.groupAchievementLayout() }, userLayoutPreferenceSetter: @escaping (String) -&gt; Void = { layoutString in LocalUser.PreferenceSettings.setGroupAchievementLayout(layoutString) } ) { self.userLayoutPreferenceProvider = userLayoutPreferenceProvider self.userLayoutPreferenceSetter = userLayoutPreferenceSetter weak var weakSelf: AchievementDataSource? super.init(collectionView: collectionView) { collectionView, indexPath, achievement in return weakSelf?.configureCell(collectionView: collectionView, indexPath: indexPath, achievement: achievement) } weakSelf = self } func updateCollectionView() { var snapshot = NSDiffableDataSourceSnapshot&lt;AchievementSectionID, Achievement&gt;() snapshot.appendSections(sections.map { $0.id }) sections.forEach { section in guard !section.isCollapsed else { return } snapshot.appendItems(section.achievements, toSection: section.id) } apply(snapshot) } private func configureCell(collectionView: UICollectionView, indexPath: IndexPath, achievement: Achievement) -&gt; UICollectionViewCell? { switch currentLayout { case .list: return makeListCell(collectionView: collectionView, indexPath: indexPath, achievement: achievement) case .grid: return makeGridCell(collectionView: collectionView, indexPath: indexPath, achievement: achievement) } } private func makeListCell(collectionView: UICollectionView, indexPath: IndexPath, achievement: Achievement) -&gt; UICollectionViewCell? { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AchievementCell.reuseIdentifier, for: indexPath) as! AchievementCell cell.titleLabel.text = achievement.name cell.descriptionLabel.text = achievement.description cell.rarityIcon.image = achievement.level.icon cell.rarityIcon.tintColor = achievement.level.color cell.rarityLabel.text = achievement.level.name let imageFormatting: ImageFormatType = achievement.isLocked ? .achievementLocked : .none cell.imageView.pal_setProcessedImage(from: achievement.imageURL, placeholder: achievementPlaceholderImage, imageType: imageFormatting) cell.isLocked = achievement.isLocked cell.dateLabel.text = achievement.dateUnlocked cell.isProgressBarHidden = (achievement.type != .multi) cell.stepCompletionLabel.text = achievement.stepCompletionMessage ?? &quot;&quot; cell.progressBar.progress = achievement.completionDecimal ?? 0 cell.progressLabel.text = &quot;\(achievement.completionPercentage ?? 0)%&quot; cell.separatorView.isHidden = isLastCellInSection(cell, indexPath: indexPath) return cell } private func makeGridCell(collectionView: UICollectionView, indexPath: IndexPath, achievement: Achievement) -&gt; UICollectionViewCell? { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageSubtitleCell.reuseID, for: indexPath) as! ImageSubtitleCell cell.titleLabel.text = achievement.name cell.isLocked = achievement.isLocked let imageFormatting: ImageFormatType = achievement.isLocked ? .achievementLocked : .none cell.imageView.pal_setProcessedImage(from: achievement.imageURL, placeholder: achievementPlaceholderImage, imageType: imageFormatting) return cell } private func isLastCellInSection(_ cell: UICollectionViewCell, indexPath: IndexPath) -&gt; Bool { let currentSnapshot = snapshot() let sectionIdentifier = currentSnapshot.sectionIdentifiers[indexPath.section] let numberOfItemsInSection = currentSnapshot.numberOfItems(inSection: sectionIdentifier) return indexPath.item + 1 == numberOfItemsInSection } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T11:26:48.227", "Id": "257723", "Score": "1", "Tags": [ "swift" ], "Title": "Subclassed DiffableDataSource" }
257723
<p>I was studying resnet and wanted to program it with pytorch</p> <p>I searched for some examples(github, google) but it was hard to understand the code completely</p> <p>So I programmed resnet myself and it works.</p> <p>But I want to check just in case if I did something wrong</p> <p>Can I get some code reviews and if I had some mistakes, can someone correct me? Thank you</p> <pre><code>import torch import torch.nn as nn import torchvision import torchvision.transforms as transforms import matplotlib.pyplot as plt train_transform = transforms.Compose( [transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761))]) test_transform = transforms.Compose( [transforms.ToTensor(), transforms.Normalize((0.5071, 0.4867, 0.4408), (0.2675, 0.2565, 0.2761))]) train = torchvision.datasets.CIFAR100(root='D:/User_DATA/Desktop/파이토치 연습/CIFAR-100', train=True, transform=train_transform, download=True) test = torchvision.datasets.CIFAR100(root='D:/User_DATA/Desktop/파이토치 연습/CIFAR-100', train=False, transform=test_transform, download=True) train_loader = torch.utils.data.DataLoader(dataset=train, batch_size=100, shuffle=True) test_loader = torch.utils.data.DataLoader(dataset=test, batch_size=100, shuffle=True) cuda = torch.device('cuda') class ResNet(nn.Module): def __init__(self): super(ResNet, self).__init__() self.conv1 = nn.Conv2d(in_channels=64, out_channels=128, kernel_size=1, stride=2, padding=0) self.conv2 = nn.Conv2d(in_channels=128, out_channels=256, kernel_size=1, stride=2, padding=0) self.conv3 = nn.Conv2d(in_channels=256, out_channels=512, kernel_size=1, stride=2, padding=0) self.batch1 = nn.BatchNorm2d(128) self.batch2 = nn.BatchNorm2d(256) self.batch3 = nn.BatchNorm2d(512) # 32 32 3 self.conv1_layer = nn.Sequential( nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU() ) # 32 32 64 self.conv2_layer = nn.Sequential( nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(64) ) # 32 32 64 self.conv3_1_layer = nn.Sequential( nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(128) ) # 16 16 128 self.conv3_2_layer = nn.Sequential( nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(128), nn.ReLU(), nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(128) ) # 16 16 128 self.conv4_1_layer = nn.Sequential( nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(256) ) # 8 8 256 self.conv4_2_layer = nn.Sequential( nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(256), nn.ReLU(), nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(256) ) # 8 8 256 self.conv5_1_layer = nn.Sequential( nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(512), nn.ReLU(), nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(512) ) # 4 4 512 self.conv5_2_layer = nn.Sequential( nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(512), nn.ReLU(), nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(512) ) self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2) # 2 2 512 self.fc_layer = nn.Sequential( nn.Linear(2 * 2 * 512, 100) ) def forward(self, x): x = self.conv1_layer(x) shortcut = x x = self.conv2_layer(x) x = nn.ReLU()(x + shortcut) shortcut = x x = self.conv2_layer(x) x = nn.ReLU()(x + shortcut) shortcut = self.conv1(x) shortcut = self.batch1(shortcut) shortcut = nn.ReLU()(shortcut) x = self.conv3_1_layer(x) x = nn.ReLU()(x + shortcut) shortcut = x x = self.conv3_2_layer(x) x = nn.ReLU()(x + shortcut) shortcut = self.conv2(x) shortcut = self.batch2(shortcut) shortcut = nn.ReLU()(shortcut) x = self.conv4_1_layer(x) x = nn.ReLU()(x + shortcut) shortcut = x x = self.conv4_2_layer(x) x = nn.ReLU()(x + shortcut) shortcut = self.conv3(x) shortcut = self.batch3(shortcut) shortcut = nn.ReLU()(shortcut) x = self.conv5_1_layer(x) x = nn.ReLU()(x + shortcut) shortcut = x x = self.conv5_2_layer(x) x = nn.ReLU()(x + shortcut) x = self.maxpool(x) x = x.view(x.size(0), -1) x = self.fc_layer(x) return x model = ResNet() model = model.cuda() loss = nn.CrossEntropyLoss() optimizer = torch.optim.SGD(model.parameters(), lr=0.01, weight_decay=5e-4, momentum=0.9) scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5000, gamma=0.5) # 10 epochs cost = 0 iterations = [] train_losses = [] test_losses = [] train_acc = [] test_acc = [] for epoch in range(100): model.train() correct = 0 for X, Y in train_loader: X = X.to(cuda) Y = Y.to(cuda) optimizer.zero_grad() hypo = model(X) cost = loss(hypo, Y) cost.backward() optimizer.step() scheduler.step() prediction = hypo.data.max(1)[1] correct += prediction.eq(Y.data).sum() model.eval() correct2 = 0 for data, target in test_loader: data = data.to(cuda) target = target.to(cuda) output = model(data) cost2 = loss(output, target) prediction = output.data.max(1)[1] correct2 += prediction.eq(target.data).sum() print(&quot;Epoch : {:&gt;4} / cost : {:&gt;.9}&quot;.format(epoch + 1, cost)) iterations.append(epoch) train_losses.append(cost.tolist()) test_losses.append(cost2.tolist()) train_acc.append((100*correct/len(train_loader.dataset)).tolist()) test_acc.append((100*correct2/len(test_loader.dataset)).tolist()) # del train_loader # torch.cuda.empty_cache() model.eval() correct = 0 for data, target in test_loader: data = data.to(cuda) target = target.to(cuda) output = model(data) prediction = output.data.max(1)[1] correct += prediction.eq(target.data).sum() print('Test set: Accuracy: {:.2f}%'.format(100. * correct / len(test_loader.dataset))) plt.subplot(121) plt.plot(range(1, len(iterations)+1), train_losses, 'b--') plt.plot(range(1, len(iterations)+1), test_losses, 'r--') plt.subplot(122) plt.plot(range(1, len(iterations)+1), train_acc, 'b-') plt.plot(range(1, len(iterations)+1), test_acc, 'r-') plt.title('loss and accuracy') plt.show() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T12:55:16.127", "Id": "257727", "Score": "1", "Tags": [ "python", "pytorch" ], "Title": "resnet with pytorch" }
257727
<p>I have a <code>.txt</code> file that looks like this:</p> <pre><code>SHT1 E: T1:30.45°C H1:59.14 %RH SHT2 S: T2:29.93°C H2:67.38 %RH SHT1 E: T1:30.49°C H1:58.87 %RH SHT2 S: T2:29.94°C H2:67.22 %RH SHT1 E: T1:30.53°C H1:58.69 %RH SHT2 S: T2:29.95°C H2:67.22 %RH </code></pre> <p>I want to have a <code>DataFrame</code> that looks like this:</p> <pre><code> T1 H1 T2 H2 0 30.45 59.14 29.93 67.38 1 30.49 58.87 29.94 67.22 2 30.53 58.69 29.95 67.22 </code></pre> <p>I parse this by:</p> <ol> <li>Reading up the text file line by line</li> <li>Parsing the lines e.g. matching only the parts with <code>T1, T2, H1, and H2</code>, splitting by <code>:</code>, and removing <code>°C</code> and <code>%RH</code></li> <li>The above produces a list of lists each having <em>two</em> items</li> <li>I flatten the list of lists</li> <li>Just to chop it up into a list of four-item lists</li> <li>Dump that to a <code>df</code></li> <li>Write to an Excel file</li> </ol> <p>Here's the code:</p> <pre class="lang-py prettyprint-override"><code>import itertools import pandas as pd def read_lines(file_object) -&gt; list: return [ parse_line(line) for line in file_object.readlines() if line.strip() ] def parse_line(line: str) -&gt; list: return [ i.split(&quot;:&quot;)[-1].replace(&quot;°C&quot;, &quot;&quot;).replace(&quot;%RH&quot;, &quot;&quot;) for i in line.strip().split() if i.startswith((&quot;T1&quot;, &quot;T2&quot;, &quot;H1&quot;, &quot;H2&quot;)) ] def flatten(parsed_lines: list) -&gt; list: return list(itertools.chain.from_iterable(parsed_lines)) def cut_into_pieces(flattened_lines: list, piece_size: int = 4) -&gt; list: return [ flattened_lines[i:i + piece_size] for i in range(0, len(flattened_lines), piece_size) ] with open(&quot;your_text_data.txt&quot;) as data: df = pd.DataFrame( cut_into_pieces(flatten(read_lines(data))), columns=[&quot;T1&quot;, &quot;H1&quot;, &quot;T2&quot;, &quot;H2&quot;], ) print(df) df.to_excel(&quot;your_table.xlsx&quot;, index=False) </code></pre> <p>This works and I get what I want <em>but</em> I feel like points <code>3, 4, and 5</code> are a bit of redundant work, especially creating a list of list just to flatten it and then chop it up again.</p> <hr /> <h3>Question:</h3> <p><em>How could I simplify the whole parsing process? Or maybe most of the heavy-lifting can be done with <code>pandas</code> alone?</em></p> <p>Also, any other feedback is more than welcomed.</p>
[]
[ { "body": "<p><strong>Disclaimer:</strong> I know this is a very liberal interpretation of a code review since it suggests an entirely different approach. I still thought it might provide a useful perspective when thinking about such problems in the future and reducing coding effort.</p>\n<p>I would suggest the following approach using <a href=\"https://docs.python.org/3/library/re.html\" rel=\"nofollow noreferrer\">regex</a> to extract all the numbers that match the format &quot;12.34&quot;.</p>\n<pre><code>import re\nimport pandas as pd\n\nwith open(&quot;your_text_data.txt&quot;) as data_file:\n data_list = re.findall(r&quot;\\d\\d\\.\\d\\d&quot;, data_file.read())\n\nresult = [data_list[i:i + 4] for i in range(0, len(data_list), 4)]\n\ndf = pd.DataFrame(result, columns=[&quot;T1&quot;, &quot;H1&quot;, &quot;T2&quot;, &quot;H2&quot;])\nprint(df)\ndf.to_excel(&quot;your_table.xlsx&quot;, index=False)\n</code></pre>\n<p>This will of course only work for the current data format you provided. The code will need to be adjusted if the format of your data changes. For example: If relevant numbers may contain a varying number of digits, you might use the regex <code>&quot;\\d+\\.\\d+&quot;</code> to match all numbers that contain at least one digit on either side of the decimal point.</p>\n<p>Also please note the use of the context manager <code>with open(...) as x:</code>. Only code that accesses the object needs to and should be part of the managed context.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T20:36:17.597", "Id": "509112", "Score": "0", "body": "I absolutely don't mind that you've offered a new approach. I totally forgot about regex, I was so much into those lists of lists. This is short, simple, and does the job. Nice! Thank you for your time and insight." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T20:37:48.530", "Id": "509113", "Score": "0", "body": "PS. You've got your imports the other way round. `re` should be first and then `pandas`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T23:01:52.410", "Id": "509120", "Score": "0", "body": "You're right, I fixed the import order!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:47:29.567", "Id": "257747", "ParentId": "257729", "Score": "3" } }, { "body": "<p>You can use <code>numpy.loadtxt()</code> to read the data and <code>numpy.reshape()</code> to get the shape you want. The default is to split on whitespace and dtype of float. <code>usecols</code> are the columns we want. <code>conveters</code> is a dict mapping column nos. to functions to convert the column data; here they chop of the unwanted text. The <code>.shape()</code> converts the resulting numpy array from two columns to four columns (the -1 lets numpy calculate the number of rows).</p>\n<pre><code>src.seek(0)\ndata = np.loadtxt(src,\n usecols=(2, 3), \n converters={2:lambda s:s[3:-2], 3:lambda s:s[3:]}\n ).reshape(-1, 4)\n</code></pre>\n<p>Then just load it in a dataframe and name the columns:</p>\n<pre><code>df = pd.DataFrame(data, columns='T1 H1 T2 H2'.split())\ndf\n</code></pre>\n<p>Output:</p>\n<pre><code> T1 H1 T2 H2\n0 30.45 59.14 29.93 67.38\n1 30.49 58.87 29.94 67.22\n2 30.53 58.69 29.95 67.22\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T23:55:25.903", "Id": "257756", "ParentId": "257729", "Score": "3" } } ]
{ "AcceptedAnswerId": "257747", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T13:43:27.720", "Id": "257729", "Score": "3", "Tags": [ "python", "python-3.x", "parsing", "pandas" ], "Title": "Parsing a text file into a pandas DataFrame" }
257729
<p>I'm not that advanced in PHP or OOP concept so I'm facing some issues.</p> <p>I'm working on a project where it's using <code>AltoRouter</code> to call the functions based on the route. So I have a controller for each <code>function</code> that calls a <code>class</code> later on. For example, this is how it's done to get the list of users.</p> <pre class="lang-php prettyprint-override"><code># user.route.php $router = new AltoRouter(); $router-&gt;map('GET', 'api/users', 'UserController@get'); $match = $router-&gt;match(); if ($match === false) { // return error } else { list($controller, $action) = explode('@', $match['target']); if (is_callable(array($controller, $action))) { $result = call_user_func_array(array($controller, $action), array($match['params'])); return print_r(json_encode($result, JSON_NUMERIC_CHECK)); } else { // return error } } # user.controller.php class UserController { public static function get() { self::init(); // Check if has login // Check if has permission return User::get(); } } # app.class.php use MyApp\Log; use MyApp\Response; abstract class App { private static $init = false; protected static $log; protected static $resposta; private function __construct() { // Does not execute self::init(); } public static function init() { if (!self::$init) { self::$init = true; self::$log = new Log(); self::$response = new Response(); } } } # user.class.php use AppClass; class User extends App { public static function get() { self::init(); // Loads all users from database $users = Sql::load(&quot;SELECT ...&quot;); // ... // ... // ... self::$log-&gt;info('loaded all users'); return self::$response-&gt;success('Data loaded succefully', $users); } } </code></pre> <p>This is a basic example, but inside the <code>UserController</code> and User class I have a bunch of functions. These functions also extends and uses other functions from the <code>App</code> abstract class, for example, to insert the log into the database, to return a response on a specific format or even to share functions that are common to different controllers and classes.</p> <p>What I want inside the <code>UserController</code> and User class is to be able to call the <code>Log</code> and <code>Response</code> classes. The alternative I found is to call <code>self::init();</code> on each function inside those files (user controller and class), this way I ensure they are initialized correctly within the <code>App</code> class. But.. I need to call this init on each method on that file, otherwise it won't work. Since the <code>AltoRouter</code> calls the controller function directly, I don't know if there is other way to achieve this.</p> <p>The other problem is that with this approach I can't use this code:</p> <pre class="lang-php prettyprint-override"><code>abstract class App { protected static $log = new Log(); } </code></pre> <p>It throws the error <code>Constant expression contains invalid operations</code>. With this, I lost all the Intellisense I had on these functions.</p> <p>Before trying this approach I used to do it like this:</p> <pre class="lang-php prettyprint-override"><code># user.class.php class User { public static function get() { // Loads all users from database $users = Sql::load(&quot;SELECT ...&quot;); // ... // ... // ... Log::info('loaded all users'); return Response::success('Data loaded succefully', $users); } } </code></pre> <p>I don't know if this approach is correct or if the previous way to do was right. So let me try to explain why I'm trying these changes... I was told that the way I was doing, for example <code>Sql::load();</code> is not the proper way because it's creating a new instance of that class each time so I lose control and some benefits. Let's say for example that on the user class I have one method to add a new user.</p> <p>Instead of this:</p> <pre class="lang-php prettyprint-override"><code>class User { public static function set($post) { // Insert the main data $user_id = Sql::insert(&quot;INSERT INTO tb_user email, password...&quot;, $params); // Insert secondary info $check = Sql::insert(&quot;INSERT INTO tb_user_info firstname, lastname...&quot;, $params); // Insert user address $address_id = Sql::insert(&quot;INSERT INTO tb_address user_id, street...&quot;, $params); // Load user added $user = self::getDetail($user_id); return Response::success('User inserted', $user); } } </code></pre> <p>This would be a better approach:</p> <pre class="lang-php prettyprint-override"><code>class User { public static function set($post) { // Here it opens the connection // The idea is to inherit from extends since all methods will use this $sql = new Sql(); $response = new Response(); $user = null; try { // Insert the main data $user_id = $sql-&gt;insert(&quot;INSERT INTO tb_user email, password...&quot;, $params); // Insert secondary info $check = $sql-&gt;insert(&quot;INSERT INTO tb_user_info firstname, lastname...&quot;, $params); // Insert user address $address_id = $sql-&gt;insert(&quot;INSERT INTO tb_address user_id, street...&quot;, $params); // Loads user detail $user = self::getDetail($user_id); } catch (PDOException $erro) { $sql-&gt;rollback(); } catch (Exception $e) { echo '$e-&gt;getMessage();'; } finally { $sql-&gt;close(); } return $response-&gt;success('User inserted', $user); } } </code></pre> <p>So is there a better approach to fix thos issues and structure my code in the proper way? Again, I'm not very familiar with OOP, I'm starting to learn and I'm working on a project that is already active.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T15:19:06.733", "Id": "509070", "Score": "2", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T03:43:18.920", "Id": "510287", "Score": "0", "body": "Have a look on dependency inversion principle. Your both approaches are basically the same. They are both quite bad." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T13:48:55.023", "Id": "257730", "Score": "1", "Tags": [ "php", "object-oriented" ], "Title": "Improving php code with OOP paradigms" }
257730
<p>I've designed this game, it's my first project. It's a spin-off from &quot;The Pig Game&quot; in a JavaScript course. I tweaked the HTML and CSS templates of the Pig Game for the UI, but I did the game design and coding from scratch. You can play the game here: <a href="https://jeffparadox.000webhostapp.com/" rel="nofollow noreferrer">https://jeffparadox.000webhostapp.com/</a></p> <p>I've got some questions, if anyone cares:</p> <ol> <li><p>What do you think, do you see any problems? Can anything be clearer (especially in terms of UI) than it is now?</p> </li> <li><p>I use <code>math.random</code> for flipping images randomly. But sometimes the same image comes twice in a row, which gives more time to the players than they suppose to have. As a work around, I randomized the number twice, but that's not a complete solution. I've researched some solutions to this but they were varied and a bit complicated. It feels like there must be a simpler, more elegant solution to this problem. Any advice or direction is greatly appreciated:</p> </li> </ol> <pre><code>// Declare game engine variables let interval, imageNumber; let isSameNumber = 10; ... // Loop with time intervals interval = setInterval(function () { // Genarate image number imageNumber = Math.trunc(Math.random() * 10); if (imageNumber !== isSameNumber) { // Show image with the generated number animalEl.src = `animal-${imageNumber}.jpg`; isSameNumber = imageNumber; } else { imageNumber = Math.trunc(Math.random() * 10); animalEl.src = `animal-${imageNumber}.jpg`; isSameNumber = imageNumber; } }, 500); </code></pre> <ol start="3"> <li>Here's my complete JS code. If anyone's interested in checking it and telling me which parts I can clean-up and optimize, I'd really appreciate it. Thanks in advance:</li> </ol> <pre><code>&quot;use strict&quot;; // Selecting elements const player0El = document.querySelector(&quot;.player--0&quot;); const player1El = document.querySelector(&quot;.player--1&quot;); const tries0El = document.getElementById(&quot;tries--0&quot;); const tries1El = document.getElementById(&quot;tries--1&quot;); const current0El = document.getElementById(&quot;current--0&quot;); const current1El = document.getElementById(&quot;current--1&quot;); const animalEl = document.querySelector(&quot;.animal&quot;); const btnSpin = document.querySelector(&quot;.btn--spin&quot;); const btnReset = document.querySelector(&quot;.btn--reset&quot;); const btnRestart = document.querySelector(&quot;.btn--restart&quot;); const youWin0El = document.querySelector(&quot;#you-win--0&quot;); const youWin1El = document.querySelector(&quot;#you-win--1&quot;); const highScore0El = document.querySelector(&quot;.high-score--0&quot;); const highScore1El = document.querySelector(&quot;.high-score--1&quot;); // Declare let variables let triesLeft, playerScores, highScores, activePlayer, round, currentScore, playing; // Starting conditions const init = function () { youWin0El.classList.add(&quot;hidden&quot;); youWin1El.classList.add(&quot;hidden&quot;); youWin1El.textContent = &quot;You Win! &quot;; youWin0El.textContent = &quot;You Win! &quot;; currentScore = 0; triesLeft = [10, 10]; playerScores = [0, 0]; highScores = [0, 0]; activePlayer = 0; round = 3; playing = true; btnRestart.textContent = ` ROUND: ${round}`; tries0El.textContent = 10; tries1El.textContent = 10; current0El.textContent = 0; current1El.textContent = 0; animalEl.src = &quot;noAnimal.jpg&quot;; player0El.classList.remove(&quot;player--winner&quot;); player1El.classList.remove(&quot;player--winner&quot;); player0El.classList.add(&quot;player--active&quot;); player1El.classList.remove(&quot;player--active&quot;); }; // Initialize game init(); // ***GAME FUNCTIONS*** // Switch players const switchPlayer = function () { activePlayer = activePlayer === 0 ? 1 : 0; player0El.classList.toggle(&quot;player--active&quot;); player1El.classList.toggle(&quot;player--active&quot;); }; // Check how many rounds left const checkRound = function () { btnRestart.textContent = ` ROUND: ${round}`; if (round &lt; 1) { gameOver(); } else if (triesLeft[activePlayer] &lt; 1 &amp;&amp; round &gt; 0) { if (triesLeft[0] === 0 &amp;&amp; triesLeft[1] === 0) { triesLeft[0] = 10; triesLeft[1] = 10; tries0El.textContent = 10; tries1El.textContent = 10; } switchPlayer(); } }; // End of game const gameOver = function () { playing = false; if (playerScores[0] &gt; playerScores[1]) { youWin0El.classList.remove(&quot;hidden&quot;); } else if (playerScores[0] &lt; playerScores[1]) { youWin1El.classList.remove(&quot;hidden&quot;); } else if (playerScores[0] === playerScores[1]) { youWin1El.textContent = &quot;It's a Tie &quot;; youWin0El.textContent = &quot;It's a Tie &quot;; youWin1El.classList.remove(&quot;hidden&quot;); youWin0El.classList.remove(&quot;hidden&quot;); } }; // Check the rabbit, increase and log the score const checkRabbit = function () { if (imageNumber === 0) { currentScore = Number(document.getElementById(`current--${activePlayer}`).textContent) + 1; playerScores[activePlayer] = currentScore; document.getElementById( `current--${activePlayer}` ).textContent = currentScore; } }; // Update tries left const triesUpdate = function () { triesLeft[activePlayer] -= 1; document.getElementById(`tries--${activePlayer}`).textContent = triesLeft[activePlayer]; }; // Update high scores const registerHighScore = function () { if (playerScores[activePlayer] &gt; highScores[activePlayer]) { highScores[activePlayer] = playerScores[activePlayer]; document.getElementById( `high-score--${activePlayer}` ).textContent = `High Score: ${highScores[activePlayer]}`; } }; // ***GAME ENGINE*** // Declare game engine variables let interval, imageNumber; let isSameNumber = 10; // Spinning images btnSpin.addEventListener(&quot;click&quot;, function () { if (playing) { // Change button to Stop btnSpin.textContent = `⛔ STOP!`; // Stop the spinning (Runs only when interval is declared) if (interval) { clearInterval(interval); interval = null; btnSpin.textContent = ` SPIN!`; triesUpdate(); checkRabbit(); registerHighScore(); if (triesLeft[0] &lt; 1 &amp;&amp; triesLeft[1] &lt; 1) { round -= 1; } checkRound(); // Start the spinning (Runs only when interval is null or undefined) } else { // Loop with time intervals interval = setInterval(function () { // Genarate image number imageNumber = Math.trunc(Math.random() * 10); if (imageNumber !== isSameNumber) { // Show image with the generated number animalEl.src = `animal-${imageNumber}.jpg`; isSameNumber = imageNumber; } else { imageNumber = Math.trunc(Math.random() * 10); animalEl.src = `animal-${imageNumber}.jpg`; isSameNumber = imageNumber; } }, 500); } } }); // ***RESET GAME*** btnReset.addEventListener(&quot;click&quot;, init); </code></pre>
[]
[ { "body": "<p>First of all, great job on the game! Even though it's a simple concept it feels really well realized by you.</p>\n<p>Let's go over your questions one by one:</p>\n<h2>1. UI &amp; UX</h2>\n<p>Well done on this one! Simple, clean design, sufficient spacing on elements, consistent styling, nice visual appeal. Obviously not optimized for mobile devices, but that's a plus for the future. Just a few notes (note that these are stylistic and opinionated):</p>\n<ul>\n<li><strong>Consistent colouring</strong>: Most of the website is held in a green-ish tone, which makes the &quot;tries left&quot; counter and label stick out. This is nice for the actual counter, since it's supposed to be prominent, but the label looks a bit out of place with that much attention dragged to it. My proposal would be to give it a darkish-green colour, since it's just supposed to be recognized once, at the moment when the user wonders what the big, red &quot;10&quot; is supposed to mean.</li>\n<li><strong>Rounded containers</strong>: All the elements on the site have rounded corners, so the image of the animals should probably be rounded aswell, even if just slightly.</li>\n<li><strong>Text alignment</strong>: Since the emojis in the button texts are larger than the actual characters themself, the button text looks like it's drifting off to the bottom, while a centered alignment may look more natural.</li>\n<li><strong>Element focus</strong>: A thick, bright border drags the attention of the user on it. While the score counter surely is important, I wouldn't say that it has to be there constantly. Maybe just on the player who is currently in turn? Something that I'd like to propose is that the score counter of the player who is <em>not</em> in turn is made slightly transparent, and that once a player scores a point, their counter briefly flashes a border, to indicate success.</li>\n<li><strong>Visual feedback</strong>: As far as I can see, the button with &quot;Round 3&quot; on it does not actually do anything when I click on it? Could be that I'm mistaken. However, keep in mind that non-clickable buttons should rather not give any visual feedback (like transitions) when clicked or hovered, since the lack of action on interaction could be confusing to the user.</li>\n</ul>\n<h2>2. Randomization</h2>\n<p>Randomness is ... well, random. Or pseudo-random, atleast in the context of <code>Math.random()</code>. Every number has the same chance of being picked, even ones that you just had. To solve this, your solution is definitely a good start, but there is still a slim chance that the same number could be generated twice or thrice in a row. Here are some proposals on how to tackle the issue:</p>\n<ul>\n<li><strong>Store the last number</strong>: Fairly straightforward. Whenever you show a new image, you store the index of that image in a variable. When you generate the new image, you keep on generating random numbers <em>until</em> you reach one that doesn't match the previous one.</li>\n</ul>\n<pre><code>let lastIndex = -1;\n\n// Here, we want to set the new image.\nlet newIndex = -1;\ndo {\n newIndex = Math.trunc(Math.random() * 10);\n} while(newIndex !== lastIndex);\n\n// newIndex is now for sure different from the last one!\n</code></pre>\n<ul>\n<li><strong>Permutations</strong>: This one is slightly more advanced. Essentially, you want to ensure that out of a range of numbers (let's say 1, 2, 3, 4, 5, 6, 7, 8, 9) every number gets picked once, before any number gets picked again. <a href=\"https://stackoverflow.com/questions/18806210/generating-non-repeating-random-numbers-in-js\">There is an answer on StackOverflow</a> that describes this well, with code examples added. The way that it works is that the list of numbers shown above is shuffled (like you would shuffle a deck of cards), and then numbers are taken off one end one at a time. For a game this could be both wanted and unwanted, this is up to your design choices.</li>\n</ul>\n<h2>3. Code Review</h2>\n<ul>\n<li><strong>Data structures</strong>: Currently you are storing the data for each player (attempts, scores, ...) in two-element-arrays. You could improve clarity here by creating dedicated objects holding the data for each player. This also spares you from constantly having to index into arrays to get/set data. If you want to get really clean you could pack the UI elements into objects (or classes even!), where you can write wrapper methods that are more readable than explicitely setting classes or attributes every time.</li>\n</ul>\n<pre><code>const player1 = {\n attempts: 0,\n score: 0,\n // ...\n}\n\nlet currentPlayer = player1;\n</code></pre>\n<ul>\n<li><strong>Function definitions</strong>: In your code, you are constantly using <code>const &lt;functionname&gt; = function() { ... }</code> to create new functions. While I do not see a reason for it myself, I believe that you might have been inspired by <em>arrow-syntax</em> usages: <code>const &lt;functionname&gt; = () =&gt; { ... }</code>. The difference is out of scope for my answer, but personally I find a <code>function</code> keyword at the start of the line more readable than one nested in the middle of it.</li>\n</ul>\n<pre><code>function myFunction1() {\n console.log(&quot;It's immediately apparent that I am a function!&quot;);\n}\nconst myFunction2 = function() {\n console.log(&quot;At first glance, I might be mistaken for a variable.&quot;);\n}\n</code></pre>\n<p>It should be noted that with a game like this there are always architectural optimizations possible. You could start to (ab)use ES6 classes to more cleanly represent entities and data, you could switch to a more state-machine based game-loop, but for a project like yours what you have is good enouugh already.</p>\n<hr />\n<p>Bottom line: Really well done on the project, and I hope that my feedback does not discourage or overwhelm you. Most of the things mentioned are opinionated, and there's surely someone out there who totally disagrees with me on some. If you have any questions, don't be afraid to ask, I'd be glad to clarify!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T16:32:22.747", "Id": "510357", "Score": "0", "body": "Oh wow! Thank you so much for all this feedback and taking your time for it! I'll go over all of these word by word and clean up the project. Cheers!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T14:37:07.187", "Id": "258840", "ParentId": "257731", "Score": "2" } }, { "body": "<p>Setup:</p>\n<ol>\n<li>Create an array (or database table) of all the values.</li>\n<li>Shuffle that array.</li>\n</ol>\n<p>Then, In your loop, pick the 'next' item.</p>\n<p>And, of course, decide what to do when you run out of items. -- perhaps reshuffle and restart. Perhaps simply restart.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T01:11:05.647", "Id": "258906", "ParentId": "257731", "Score": "1" } } ]
{ "AcceptedAnswerId": "258840", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T14:11:50.847", "Id": "257731", "Score": "3", "Tags": [ "javascript", "random" ], "Title": "Catch The Rabbit Game: How to Create Non-Repeating Randomization? (JavaScript, CSS, HTML)" }
257731
<p>Below is my attempt to check if two types are the same without template instantiations.</p> <pre><code>#include &lt;cstddef&gt; template&lt;class, class&gt; struct twoTypes; template&lt;class T&gt; std::size_t isSame(twoTypes&lt;T,T&gt;*); bool isSame(void*); template&lt;class T, class U&gt; using checkIfSame = decltype(isSame(static_cast&lt;twoTypes&lt;T,U&gt;*&gt;(0))); </code></pre> <p>And to check if they're the same, checkIfSame's size will be compared to std::size_t's size:</p> <pre><code>static_assert(sizeof(checkIfSame&lt;int,int&gt;) == sizeof(std::size_t)); //They're the same static_assert(sizeof(checkIfSame&lt;const int,int&gt;) == sizeof(bool)); //Not the same </code></pre> <p>Are there any cases where my code will give the wrong result? My benchmarks show my version compiling faster than <code>std::is_same</code>, but are there any ways to make it faster?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T14:51:15.610", "Id": "509068", "Score": "2", "body": "What benchmarks? What compiler version and flags? Why do you need this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T15:15:44.283", "Id": "509069", "Score": "0", "body": "I used clang with the -ftime-trace flag. I'm mostly curious to see if my way would work." } ]
[ { "body": "<p>If you're using clang or GCC ≥10, you can use the <code>__is_same(type1, type2)</code> intrinsic.</p>\n<p>For portability:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#if !defined(__is_same) &amp;&amp; (!defined(__clang__) || !defined(__GNUC__) || __GNUC__ &lt; 10)\n#define IS_SAME(T1, T2) std::is_same_v&lt;T1, T2&gt;\n#else\n#define IS_SAME(T1, T2) __is_same(T1, T2)\n#endif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T19:26:19.780", "Id": "509104", "Score": "0", "body": "I'll look into intrinsics, though I asked my question primarily to ask for evaluation of my method of checking if two types are the same." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T19:29:38.330", "Id": "509106", "Score": "0", "body": "I think it looks okay, but intrinsics should compile even faster." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:41:29.523", "Id": "257746", "ParentId": "257733", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T14:33:54.987", "Id": "257733", "Score": "1", "Tags": [ "c++", "performance", "reinventing-the-wheel", "template" ], "Title": "Check if two types are the same without template instantiations" }
257733
<p><strong>Context (optional)</strong><br> In my job, we are interested in identifying particular events that may occur during the degradation of a physical system over its lifetime. Specifically, these are referred to as:</p> <ul> <li>Knee onset (the beginning of nonlinear degradation phase)</li> <li>Knee point (point after which accelerated degradation occurs)</li> <li>End of life (when it reaches 80% of its initial value).</li> </ul> <p>with an example shown here:<br> <a href="https://i.stack.imgur.com/2h61E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2h61E.png" alt="capacity_fade_example" /></a></p> <p>Further context and method descriptions available <a href="https://tinyurl.com/yruakajm" rel="nofollow noreferrer">here</a> and <a href="https://tinyurl.com/a6fa7vxf" rel="nofollow noreferrer">here</a>.</p> <p><strong>Code</strong><br> This is my first &quot;real&quot; OOP project, beyond the simple illustrative examples normally found in tutorials, so I would very much welcome any feedback, constructive criticism, advice etc. to help me to improve and learn. The code does currently run correctly, as far as I have tested it.</p> <p>Since this is something that will be used a lot across different projects, my intention was to gather all the required code into a class. This prevents inconsistencies due to changes being made as a result of copy and paste code. An instance can be created and all of the required logic can be executed using only 2 or 3 method calls. I have tried to make it easy to extend (e.g. adding new identification methods, or accommodating new data sources).<br></p> <p>Here is the code for creating an instance of the class and calling its methods</p> <pre><code>kf = KneeFinder(cycles, capacities, truncate=True, mode='knee') kf.set_params_using_dict(params_dict, src='severson', data_type='capacity') kf.find_onset_and_point() kf.find_eol() </code></pre> <p>Here is the code for the class</p> <pre><code>import numpy as np from sklearn.isotonic import IsotonicRegression from scipy.optimize import curve_fit from scipy.signal import medfilt import warnings import matplotlib.pyplot as plt class KneeFinder(): ''' Write docstring - Find out what it should contain for the class ''' def __init__(self, cycles, y, truncate=False, mode='knee'): self.cycles = cycles self.y = y self.truncate = truncate # whether or not to truncate using sigmoid fit self.mode = mode # knee or elbow self.point = None self.onset = None self.eol_reached = False self.eol_cycle = None # Set the fitting parameters to their default values self.reset_all_parameters() # Get a continuous array of integer cycle numbers self.x_cont = self.process_cycles_array(self.cycles) # Methods # Set up the models - should these 4 be staticmethods? def _asym_sigmoidal(self, x, a, b, c, d, m): ''' Formula for asymmetric sigmoidal function ''' # Ignore the warnings about overflow in power warnings.filterwarnings( action='ignore', message='overflow encountered in power', module=r'.*new_knee_finder') return d + ((a - d) / (1 + (x / c) ** b) ** m) def _bw_func(self, x, b0, b1, b2, cp): ''' Formula for the single Bacon-Watts model''' return b0 + b1*(x-cp) + b2*(x-cp)*np.tanh((x-cp)/1e-8) def _bw2_func(self, x, b0, b1, b2, b3, cp, co): ''' Formula for the double Bacon-Watts model''' return b0 + b1*(x-cp) + b2*(x-cp)*np.tanh((x-cp)/1e-8) + b3*(x-co)*np.tanh((x-co)/1e-8) def _exponential(self, x, a, b, c, d, theta): ''' Formula for the line plus exponential model''' # Ignore the warnings about overflow in power warnings.filterwarnings( action='ignore', message='overflow encountered in multiply', module=r'.*new_knee_finder') return d*np.exp(a*x - b) + c + theta*x def find_onset_and_point(self): ''' Write docstring ''' # Get the monotonic fit to the experimental data self.mon_data = self.fit_monotonic(x_cont=self.x_cont, x_data=self.cycles, y_data=self.y) # Fit asym_sigmoid to the monotonic data if self.truncate==True if self.truncate: # Try to fit the sigmoid, but this may fail with a RuntimeError # telling us that the optimal parameters were not found. try: self.sig_fit = self.fit_sigmoid(x_data=self.x_cont, y_data=self.mon_data) self.indices = self.get_truncated_indices(data=self.sig_fit) except RuntimeError as err: error_msg = str(err) print(error_msg) # Check for the specific error message about fitting if 'Optimal parameters not found' in error_msg: print(&quot;Can't fit sigmoid for truncation. Skipping&quot;) # Since we can't fit the asym_sigmoid for truncation, # set self.indices as if self.truncate==False self.indices = np.arange(len(self.mon_data)) else: self.indices = np.arange(len(self.mon_data)) # Fit line_exponential to the (normal/truncated) monotonic self.exp_fit = self.fit_line_exp(x_data=self.x_cont, y_data=self.mon_data, indices=self.indices) # Fit BW and double BW to exp_fit self.point, self.bw_fit = self.fit_bacon_watts(x_cont=self.x_cont, indices=self.indices, y_data=self.exp_fit) self.onset, self.bw2_fit = self.fit_double_bacon_watts(x_cont=self.x_cont, indices=self.indices, y_data=self.exp_fit) # Find the indices of the values in x_cont that are closest to the # cycle numbers for onset and point, as computed using BW and double BW onset_idx = np.argmin(np.abs(self.x_cont - int(self.onset))) point_idx = np.argmin(np.abs(self.x_cont - int(self.point))) # Get the y value (capacity/IR) corresponding to onset and point, # using mon_data self.onset_y = self.mon_data[onset_idx] self.point_y = self.mon_data[point_idx] # Include a return statement so you can use line-profiler to assess running time return def find_eol(self): ''' Determine whether or not end of life (EOL) is reached, and if so, at which cycle. Use the monotonic fit to check for EOL. This is because: 1. The values are within the range of experimental values. This is not the case if you were to extend the line_exp fit past the truncation point. It decreases very rapidly, so you are almost sure to find an EOL, even though it doesn't occur in the actual experimental data. 2. Putting (1) aside, if you find an EOL using the truncated or un-truncated line_exp fit, there is often a mismatch between the cycle number at which line_exp reaches 80% and the cycle number at which the monotonic fit reaches 80%. The monotonic fit, being essentially linear interpolation between points, much more closely fits the experimental data, so the EOL cycle number identified using monotonic fit is more reliable. 3. If you use the truncated line_exp fit, you are potentially ignoring a large percentage of the data (past the truncation). You could then easily miss EOL occurrences from past the cycle at which the line_exp fit is truncated. Note, simply extending the line_exp fit past the truncation point is covered in (1). ''' # Begin by assuming EOL is not reached self.eol_reached = False # Get the monotonic fit self.mon_data = self.fit_monotonic(x_cont=self.x_cont, x_data=self.cycles, y_data=self.y) # Use the monotonic fit to check for EOL, because it is guaranteed # to be there for the whole curve and it's essentially linear interp # meaning that it will be closer to the data than line_exp or sig fits # Find the initial (experimental) value and compute the EOL value init_val = self.y[0] if self.mode.lower() == 'knee': self.eol_val = 0.8 * init_val self.post_eol_indices = np.where(self.mon_data &lt; self.eol_val)[0] elif self.mode.lower() == 'elbow': self.eol_val = 2.0 * init_val self.post_eol_indices = np.where(self.mon_data &gt; self.eol_val)[0] # If it finds indices past the EOL index, set eol_reached to true and # find the first cycle number in x_cont after the EOL value is reached if len(self.post_eol_indices) &gt; 0: self.eol_reached = True self.eol_idx = self.post_eol_indices[0] self.eol_cycle = self.x_cont[self.eol_idx] return # Define a method to show the results on a plot def plot_results(self, line_exp=False, mon=False, data_style='-'): ''' Write docstring ''' fig, ax = plt.subplots() ax.plot(self.cycles, self.y, data_style, label='Experimental') if mon: ax.plot(self.x_cont, self.mon_data, label='Monotonic', color='green') if line_exp: ax.plot(self.x_cont[self.indices], self.exp_fit, label='Line_exp fit', color='purple') ax.axvline(self.onset, label=f'{self.mode.capitalize()} onset', color='orange') ax.axvline(self.point, label=f'{self.mode.capitalize()} point', color='red') ax.axhline(self.onset_y, color='orange') ax.axhline(self.point_y, color='red') if self.eol_cycle != None: ax.axvline(self.eol_cycle, label='End of life', color='black') ax.grid(alpha=0.4) ax.legend() plt.show() # Define the helper methods def process_cycles_array(self, cycles): ''' Write docstring ''' # Identify the first and last cycle numbers in the cycles array. # In the case of non-integer cycle values, round up to the next # integer for the first cycle and remove any fractional part of # the last cycle number. Avoids issues with NaNs in the monotonic fit. first_cycle = int(np.ceil(cycles[0])) last_cycle = int(cycles[-1]) # Create an array of integers from first to last cycle numbers. x_cont = np.arange(first_cycle, last_cycle+1) return x_cont def fit_monotonic(self, x_cont, x_data, y_data): ''' x_cont (type: array) Array of continuous integer values for which the fitted IsotonicRegression result should be used to generate the monotonic fit. x_data (type: array) Experimental x data e.g. cycle number y_data (type: array) Experimental y data e.g. capacity or internal resistance ''' # Create an IsotonicRegression instance if self.mode.lower() == 'knee': ir = IsotonicRegression(increasing=False) elif self.mode.lower() == 'elbow': ir = IsotonicRegression(increasing=True) # Fit the monotonic curve to the experimental data ir.fit(x_data, y_data) # Get a value for every cycle based on the fit mon_data = ir.predict(x_cont) return mon_data def fit_sigmoid(self, x_data, y_data): ''' Write docstring ''' sig_popt, _ = curve_fit(self._asym_sigmoidal, x_data, y_data, p0=self.sig_p0, bounds=self.sig_bounds) sig_fit = self._asym_sigmoidal(x_data, *sig_popt) return sig_fit def compute_second_derivative(self, data): ''' Write docstring ''' # Using np.gradient gives us a result of the same shape dy_dx = np.gradient(data) d2y_dx2 = np.gradient(dy_dx) # Set a threshold, below which, the value is set to zero d2y_dx2[np.where(np.abs(d2y_dx2) &lt; 1e-10)] = 0.0 # Replace the last 2 values with the value at index [-3] to avoid # the sharp change that happens at the end of the d2y_dx2 array d2y_dx2[-2] = d2y_dx2[-3] d2y_dx2[-1] = d2y_dx2[-3] return d2y_dx2 def get_truncated_indices(self, data): ''' Write docstring ''' # Compute the second derivative of data, # which will be the asymmetric sigmoid fit self.d2 = self.compute_second_derivative(data) # Filter d2 self.d2 = medfilt(self.d2, 5) # Get an array of the sign of d2 to find changes self.d2_sign = np.sign(self.d2) # Use mode to determine which new sign value to look for to find changes if self.mode == 'knee': new_sign_val = 1 elif self.mode == 'elbow': new_sign_val == -1 # Find out if there are any places where the sign changes change_indices = np.where(self.d2_sign == new_sign_val)[0] # If there are no sign changes, return the full array of indices if len(change_indices) == 0: indices = np.arange(0, len(data)) return indices else: # Find the first index at which the sign changes from -ve to +ve self.first_change_idx = change_indices[0] # Look ahead a few cycles to make sure it is not a local erroneous fluctuation # Note this is incomplete, because there's nothing to handle AssertionErrors lookahead = np.min((20, len(self.d2_sign) - self.first_change_idx)) assert(np.all(self.d2_sign[self.first_change_idx + lookahead] == new_sign_val)) indices = np.arange(0, self.first_change_idx) return indices def fit_line_exp(self, x_data, y_data, indices): ''' Write docstring ''' # Use the indices array to select subsets of the other input arrays # if truncation has been deemed necessary. If no truncation is needed, # the indices array will contain the indices for every cycle x_data = x_data[indices] y_data = y_data[indices] # Fit the line plus exponential model to the monotonic data # Get the optimal parameters for _exponential exp_popt, _ = curve_fit(self._exponential, x_data, y_data, p0=self.line_exp_p0, bounds=self.line_exp_bounds) # Apply the optimal parameters to the continuous cycle array exp_fit = self._exponential(x_data, *exp_popt) return exp_fit def fit_bacon_watts(self, x_cont, indices, y_data): ''' Write docstring. Pass the line_exponential fit to this method, to use the Bacon-Watts method to compute the cycle number at which the knee point occurs. ''' # Use the indices array to select subsets of the other input arrays x_cont = x_cont[indices] y_data = y_data[indices] # Set some p0 and bounds values based on the cycle numbers # of the data being considered by the KneeFinder instance self.bw_p0[3] = x_cont[-1]/1.5 # Set the upper bound to be the final cycle self.bw_bounds[1][3] = x_cont[-1] # Fit the Bacon Watts model to the line_exponential input popt_bw, _ = curve_fit(self._bw_func, x_cont, y_data, p0=self.bw_p0, bounds=self.bw_bounds) # Apply the optimal parameters to the continuous cycle array # to get the Bacon-Watts fit bw_fit = self._bw_func(x_cont, *popt_bw) return popt_bw[3], bw_fit def fit_double_bacon_watts(self, x_cont, indices, y_data): ''' Write docstring ''' # Use the indices array to select subsets of the other input arrays x_cont = x_cont[indices] y_data = y_data[indices] # Set some p0 and bounds values based on the cycle numbers # of the data being considered by the KneeFinder instance. # These p0 values give the onset and point a starting location # somewhere in the second half of the curve. self.bw2_p0[4] = x_cont[-1]/2.0 self.bw2_p0[5] = x_cont[-1]/1.5 # Set the upper bound to be the final cycle self.bw2_bounds[1][4] = x_cont[-1] self.bw2_bounds[1][5] = x_cont[-1] # Apply the optimal parameters to the continuous cycle array # to get the double Bacon-Watts fit popt_bw2, _ = curve_fit(self._bw2_func, x_cont, y_data, p0=self.bw2_p0, bounds=self.bw2_bounds) bw2_fit = self._bw2_func(x_cont, *popt_bw2) return popt_bw2[4], bw2_fit # Methods for setting and resetting parameters. All of these methods are very similar def reset_all_parameters(self): try: # Set the parameters to their default values self.line_exp_p0 = [1, 1, 1, 1, 1] self.line_exp_bounds = [0, 0, 0, 0, 0], [1, 1, 1, 1, 1] self.sig_p0 = [1, 1, 1, 1, 1] self.sig_bounds = [0, 0, 0, 0, 0], [1, 1, 1, 1, 1] self.bw_p0 = [1, 1, 1, 1] self.bw_bounds = ([-np.inf, -np.inf, -np.inf, 0],[np.inf, np.inf, np.inf, np.inf]) self.bw2_p0 = [1, 1, 1, 1, 1, 1] self.bw2_bounds = ([-np.inf, -np.inf, -np.inf, -np.inf, 0, 0], [np.inf, np.inf, np.inf, np.inf, np.inf, np.inf]) except Exception as e: print(f&quot;Error: {e}&quot;) def set_params_using_dict(self, params_dict, src, data_type): try: # Assign the parameter values for the fitting functions, # for this particular instance. self.set_sigmoid_params(params_dict[src][data_type]['sig']['p0']) self.set_sigmoid_bounds(params_dict[src][data_type]['sig']['bounds']) self.set_line_exp_params(params_dict[src][data_type]['line_exp']['p0']) self.set_line_exp_bounds(params_dict[src][data_type]['line_exp']['bounds']) except Exception as e: print(f&quot;Error: {e}&quot;) def set_line_exp_params(self, p0=None): # Input validation - check for the correct lengths. # Could also check that they obey the relevant bounds, # but could maybe leave that to common sense or leave the # curve_fit method to raise the exception. try: assert(len(p0)==5) self.line_exp_p0 = p0 except AssertionError: print(&quot;Argument p0 must have length of 5 for line exponential.&quot;) print(p0) return None except Exception as e: print(f&quot;Error: {e}&quot;) def set_line_exp_bounds(self, bounds=None): # Input validation - check for the correct lengths try: assert(len(bounds)==2) assert(len(bounds[0])==5) assert(len(bounds[1])==5) self.line_exp_bounds = bounds except AssertionError: print(&quot;bounds must have length of 5 for line exponential.&quot;) print(bounds) return None except Exception as e: print(f&quot;Error: {e}&quot;) def reset_line_exp_params(self): try: self.line_exp_p0 = [1, 1, 1, 1, 1] self.line_exp_bounds = [0, 0, 0, 0, 0], [1, 1, 1, 1, 1] print(&quot;Parameters for line_exp reset&quot;) except Exception as e: print(f&quot;Error: {e}&quot;) def set_sigmoid_params(self, p0=None): # Input validation - check for the correct lengths try: assert(len(p0)==5) self.sig_p0 = p0 except AssertionError: print(&quot;Argument p0 must have length of 5 for asym_sigmoid.&quot;) print(p0) return None except Exception as e: print(f&quot;Error: {e}&quot;) def set_sigmoid_bounds(self, bounds=None): # Input validation - check for the correct lengths try: assert(len(bounds)==2) assert(len(bounds[0])==5) assert(len(bounds[1])==5) self.sig_bounds = bounds except AssertionError: print(&quot;bounds must have length of 5 for asym_sigmoid.&quot;) print(bounds) return None except Exception as e: print(f&quot;Error: {e}&quot;) def reset_sigmoid_params(self): try: self.sig_p0 = [1, 1, 1, 1, 1] self.sig_bounds = [0, 0, 0, 0, 0], [1, 1, 1, 1, 1] print(&quot;Parameters for asym_sigmoid reset&quot;) except Exception as e: print(e) def set_bw_params(self, p0=None): # Input validation - check for the correct lengths try: assert(len(p0)==4) self.bw_p0 = p0 except AssertionError: print(&quot;Argument p0 must have length of 4 for Bacon Watts.&quot;) print(p0) except Exception as e: print(f&quot;Error: {e}&quot;) def set_bw_bounds(self, bounds=None): # Input validation - check for the correct lengths try: assert(len(bounds)==2) assert(len(bounds[0])==4) assert(len(bounds[1])==4) self.bw_bounds = bounds except AssertionError: print(&quot;bounds must have length of 4 for Bacon Watts.&quot;) print(bounds) return None except Exception as e: print(f&quot;Error: {e}&quot;) def reset_bw_params(self): try: # Reset the Bacon-Watts initial parameters and bounds to # some default values self.bw_p0 = [1, 1, 1, 1] self.bw_bounds = ([-np.inf, -np.inf, -np.inf, 0], [np.inf, np.inf, np.inf, np.inf]) print(&quot;Parameters for Bacon Watts reset&quot;) except Exception as e: print(f&quot;Error: {e}&quot;) def set_bw2_params(self, p0=None): # Input validation - check for the correct lengths try: assert(len(p0)==6) self.bw2_p0 = p0 except AssertionError: print(&quot;Arguments p0 and bounds must have length of 6 for double Bacon Watts.&quot;) print(p0) except Exception as e: print(f&quot;Error: {e}&quot;) def set_bw2_bounds(self, bounds=None): # Input validation - check for the correct lengths try: assert(len(bounds)==2) assert(len(bounds[0])==6) assert(len(bounds[1])==6) self.bw2_bounds = bounds except AssertionError: print(&quot;bounds must have length of 6 for double Bacon Watts.&quot;) print(bounds) except Exception as e: print(f&quot;Error: {e}&quot;) def reset_bw2_params(self): try: # Reset the double Bacon-Watts initial parameters and bounds to # some default values self.bw2_p0 = [1, 1, 1, 1, 1, 1] self.bw2_bounds = ([-np.inf, -np.inf, -np.inf, -np.inf, 0, 0], [np.inf, np.inf, np.inf, np.inf, np.inf, np.inf]) print(&quot;Parameters for double Bacon Watts reset&quot;) except Exception as e: print(f&quot;Error: {e}&quot;) </code></pre> <p>For a minimum working example, the class is saved in a file called new_knee_finder.py. The data used in the example is taken from <a href="https://data.mendeley.com/datasets/c35zbmn7j8/1" rel="nofollow noreferrer">here</a>. The parameter dictionary would normally be stored and maintained somewhere else, but is explicitly constructed here for the purpose of MWE.</p> <pre><code># A MWE for Code Review from new_knee_finder import KneeFinder import numpy as np # Create some data cycles = np.arange(0, 700, 50) capacities = np.array([3.27795, 3.19774, 3.1372, 3.10605, 3.07494, 3.0869, 3.00876, 3.00872, 2.98472, 2.93986, 2.92171, 2.89218, 2.66845, 2.154]) # Make a dict for the initial curve fitting parameters params_dict_diao = {'diao': {'capacity': {'sig': {'p0': None, 'bounds': None}, 'line_exp': {'p0': None, 'bounds': None}}}} params_dict_diao['diao']['capacity']['sig']['p0'] = np.array([4.619, 4.671, 1530.0, 0.870, 1701.0]) params_dict_diao['diao']['capacity']['sig']['bounds'] = [0, 0, 1e-8, 0, -1],[10, 50, 5000, 10, 5000] params_dict_diao['diao']['capacity']['line_exp']['p0'] = np.array([1.89e-3, 0.77, 1.88, -0.11, 0]) params_dict_diao['diao']['capacity']['line_exp']['bounds'] = [0, 0, 0, -np.inf, -np.inf],[np.inf, np.inf, np.inf, 0, 0] kf = KneeFinder(cycles, capacities, truncate=True, mode='knee') kf.set_params_using_dict(params_dict_diao, src='diao', data_type='capacity') kf.find_onset_and_point() kf.find_eol() kf.plot_results(mon=True, line_exp=False, data_style='-o') </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T16:36:44.160", "Id": "509080", "Score": "1", "body": "Welcome to Code Review. Do you have a usage example with your class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T17:27:23.093", "Id": "509087", "Score": "3", "body": "Thanks @Mast. I have added some code for a minimum working example at the end of my question." } ]
[ { "body": "<p>Here are a few comments and observation about the code:</p>\n<h3>Write docstring</h3>\n<p>In many IDEs or REPLs getting help on an object returns the object's doctring. For example, in Jupyter or IDLE typing <code>help(KneeFinder)</code> would display the doctring for the <code>KneeFinder</code> class. So, generally use docstrings to show information about how someone would use the module/class/method/function/object.</p>\n<p>In contrast, comments are seen by someone looking at the source code. Perhaps to adapt/debug/enhance/modify it. So comments should be written for that audience.</p>\n<h3>warnings.filterwarnings</h3>\n<p><code>warnings</code> maintains a global list of warning filters. <code>warnings.filterwarnings()</code> add a new filter to the front of that list of filters. So it looks like <code>filterwarnings()</code> adds the same filter to the list on each call <code>_asym_sigmoidal()</code>. Same for <code>_exponential()</code>. Put the calls to <code>filterwarnings()</code> somewhere else, such as <code>__init__()</code>, or use the <code>warnings.catch_warnings()</code> context manager in a <code>with-statement</code> to temporarily change the warning filters.</p>\n<h3>instance variables as method arguments</h3>\n<p>The calls to the various <code>fit_</code> methods, such as <code>fit_monotonic()</code> and <code>fit_sigmoid()</code>, pass instance variables (e.g., self.whatever) as arguments. Unless you expect to call the methods with other arguments, just reference the instance variables in the methods and drop the arguments. As it is, some instance variables are passed as arguments and some are referenced directly, e.g., <code>fit_monotonic</code> takes <code>self.x_cont</code>, <code>self.cycles</code>, and <code>self.yreferences</code> as arguments, but directly references <code>self.mode</code> and <code>fit_sigmoid</code>.</p>\n<h3>Enums</h3>\n<p>Consider using an <code>enum.Enum</code> for <code>self.mode</code>. Although, for this small case I would probably stick with strings. Use <code>self.mode = mode.lower()</code> in <code>__init__()</code> so you don't have to do it for every test (or forget to do in like in <code>get_truncated_indices()</code>).</p>\n<h3>DRY principle</h3>\n<p>Don't repeat yourself. The <code>reset_all_parameters</code> method directly resets various instance variables, but there are other methods, e.g., <code>reset_line_exp_params</code> that reset some parameters. <code>reset_all_parameters</code> should call the other methods rather than reset the variables itself.</p>\n<h3><code>set_params_using_dict(self, params_dict, src, data_type)</code></h3>\n<p>It seems odd to call the method like this:</p>\n<pre><code>kf.set_params_using_dict(params_dict_diao, src='diao', data_type='capacity')\n</code></pre>\n<p>and then in method to:</p>\n<pre><code>self.set_sigmoid_params(params_dict[src][data_type]['sig']['p0'])\n... same for other parameters\n</code></pre>\n<p>Why not just call the method with the correct dict like this:</p>\n<pre><code>kf.set_params_using_dict(params_dict_diao['diao']['capacity'])\n</code></pre>\n<h3><code>except Exception as e:</code></h3>\n<p>Catching all exceptions this way is generally frowned upon. You should catch specific exceptions that you expect could happen and that you can do something about and/or safely ignore. For example, if there is an exception during <code>set_params_using_dict()</code>, does it make sense to ignore it and continue?</p>\n<h3><code>assert</code> statement</h3>\n<p>An <code>assert</code> statement is a debugging tool. If end user invokes the Python interpreter with the -O flag (optimize), <code>assert</code> statements are effectively removed. So don't use <code>assert</code> for input validation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-14T15:03:59.600", "Id": "514618", "Score": "0", "body": "Thanks a lot for your detailed answer. There are things in there that I hadn't noticed/considered, and they will help me to improve this code and also my code in the future." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-05-07T07:03:28.457", "Id": "260446", "ParentId": "257734", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T15:26:24.230", "Id": "257734", "Score": "5", "Tags": [ "python", "object-oriented" ], "Title": "Python OOP code for identifying knees in data" }
257734
<p>My C++ solution for <a href="https://www.hackerrank.com/challenges/making-candies/problem" rel="nofollow noreferrer">HackerRank's &quot;Making Candies&quot; problem</a>, reproduced below, is as optimized as I can make it and appears similar to what others say are optimal solutions. However, six of the test cases still fail due to timing out. I would be interested to know if there are any significant opportunities to optimize my code that I missed.</p> <p>I'm guessing that I'm either missing some way to simplify the computation (perhaps part of it can be precomputed and stored in a lookup table?), or there's some way to compute the answer without using a loop.</p> <pre class="lang-cpp prettyprint-override"><code>std::ios::sync_with_stdio(false); long m, w, p, n; std::cin &gt;&gt; m &gt;&gt; w &gt;&gt; p &gt;&gt; n; for (long candies = 0, passes = 0, total = LONG_MAX; ; ++passes) { const auto production = __int128{m} * w; const long goal = n - candies; const long passes_needed = goal/production + !!(goal%production); const long subtotal = passes + passes_needed; if (passes_needed &lt;= 2) { std::cout &lt;&lt; subtotal; return 0; } if (total &lt; subtotal) { std::cout &lt;&lt; total; return 0; } total = subtotal; candies += production; if (candies &gt;= p) { const auto d = std::div(candies, p); long budget = d.quot; candies = d.rem; const long diff = w - m; if (diff &lt; 0) { const long w_hired = std::min(budget, -diff); budget -= w_hired; w += w_hired; } else if (diff &gt; 0) { const long m_purchased = std::min(budget, diff); budget -= m_purchased; m += m_purchased; } const long half = budget &gt;&gt; 1; m += half + (budget &amp; 1); w += half; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:15:42.873", "Id": "509096", "Score": "3", "body": "Links can rot over time. Please improve the question by including a synopsis of the problem your code is solving." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T22:56:49.827", "Id": "509118", "Score": "0", "body": "Have you looked at how your algorithm behaves on the 6 tests that fail? Offhand, there's some smell where you used the `__int128` compiler intrinsic to do a multiplication, but then added the result to a long. What actually happens when your algorithm fails on those 6 test?s" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T22:57:28.887", "Id": "509119", "Score": "0", "body": "Also, you may find your life is easier if you write either an Algorithm Description Document, or comment the reasons why you are doing the operations you are doing. That will help isolate algorithmic issues from coding errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T23:58:22.697", "Id": "509124", "Score": "0", "body": "@CortAmmon It gets the correct answer, it just takes too long. There's no issue with adding `production` to `candies`, because if `production` is too large to fit in a `long` then it must be the case that `passes_needed <= 2`." } ]
[ { "body": "<h1>Unlearn bad behavior taught by competitive coding sites</h1>\n<p>Competitive coding sites unfortunately teach some bad coding habits. You did not include your whole program, the <code>#include</code>s are missing for example. If you did <code>#include &lt;bits/stdc++.h&gt;</code>, <a href=\"https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h\">don't</a>.</p>\n<p>The call to <code>std::ios::sync_with_stdio()</code> is only useful if your program is I/O bound, and it won't make a difference if you are just writing the final result to <code>std::cout</code>.</p>\n<h1>Use of integer types</h1>\n<p><code>__int128</code> is not a standard C++ type, and I don't think it is necessary at all to use it. The problem states that <code>n</code> is limited to <span class=\"math-container\">\\$10^{12}\\$</span>, so you only need 64-bit variables and <a href=\"https://stackoverflow.com/questions/1815367/catch-and-compute-overflow-during-multiplication-of-two-large-integers\">some care to avoid values wrapping around</a>.</p>\n<p>A <code>long</code> is only guaranteed to be at least 32-bits in size. So reading in the initial values is already broken since they might be larger than that. Also, none of the values should ever become negative, so the appropriate type to use here is <a href=\"https://en.cppreference.com/w/cpp/types/integer\" rel=\"nofollow noreferrer\"><code>std::uint64_t</code></a>.</p>\n<h1>Speeding up the algorithm</h1>\n<p>Yes, you can optimize your solution further. Consider the case where the desired number of candies <code>n = 1000000000000</code>, the cost is so high you can never buy/hire (<code>p = n</code>), and you start with <code>m = 1</code> and <code>w = 1</code>. Then your loop will just do <code>n</code> iterations, adding <code>1</code> to <code>candies</code> each time.</p>\n<p>What you should do is calculate how many iterations it would take to get enough money to buy/hire something new, and then advance that many iterations in one step. So:</p>\n<pre><code>const auto passes_needed_to_buy = candies &lt; p ? (p - candies) / production : 0;\n</code></pre>\n<p>Of course, if this value is more than <code>passes_needed</code>, then you know you will never be able to buy anything before you produced enough candy.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T18:33:02.013", "Id": "510197", "Score": "0", "body": "1) I included `algorithm`, `climits`, `cmath` and `iostream`. I did not include `bits/stdc++.h`. The `sync_with_stdio(false)` is in there to make clear that the test cases aren't failing due to the program being I/O-bound.\n\n2) The use of `__int128` is because `m` and `w` can be up to 10^12 (≈2^40), and the result of the multiplication indeed overflows an (unsigned) 64-bit integer in several of the test cases. I used `long` because that's what the question said to use; I'm aware it's not portable (to Windows).\n\n3) Good idea, but it doesn't speed it up enough to pass the failing test cases." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T18:42:31.693", "Id": "510199", "Score": "0", "body": "Ah, the question tells you that the values are passed as `long` *parameters* to a function named `minimumPasses()`, but you are reading them from `std::cin`. So you are already not following the instructions to the letter. About `m` and `w`: please follow the link where the answer shows you to detect if the multiplication overflowed. If it did, you know you have more production than you ever need. So there is no need to store anything in a `__int128`. What are the test cases that are failing exactly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T19:00:24.423", "Id": "510203", "Score": "0", "body": "The values are read from `cin` because that's how the test cases are set up. I did follow the link and it looks like about 20 lines of code to detect overflow, which is clearly less optimal than just doing a 128-bit multiplication. I'm not asking how to make this code more portable, I'm asking how it can be optimized. Test cases 4, 7, 9, 14, 16 and 19 are failing due to timeout." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T23:42:00.577", "Id": "510212", "Score": "0", "body": "Please read the answers in the question about overflow handling again. The top one mentions this one-liner: `if (a != 0 && x / a != b) { // overflow handling }`. As for the failing test cases: please provide us with the actual values for `m`, `w`, `p` and `n`. And while you might not care about portability, other people will read your question as well and have different priorities, so in our answers will point out all the issues we find." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T23:55:58.957", "Id": "510394", "Score": "0", "body": "So I tried using that method of detecting overflow, but it caused several test cases to fail. I think there must be some edge cases it doesn't catch, or else the fact that signed integer overflow is UB is screwing things up. So I'm going to stick with using 128-bit ints for now, although I may try your method with unsigned ints later. I did however manage after some trial and error to get the failing test cases working (see my answer above), with some help from your optimization suggestion. And you are right, portability is important. Apologies if I came across as aggressive." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T13:13:46.617", "Id": "258766", "ParentId": "257739", "Score": "1" } }, { "body": "<p>I figured out how to get the failing test cases passing, with a little help from G. Sliepen's answer. It turns out I needed to calculate the number of passes needed to buy another machine or worker, and return early, as G. Sliepen suggested, if that number equaled or exceeded the number of passes needed to complete the order without any purchases.</p>\n<p>But, in addition to returning early, I <em>also</em> could leverage that calculation to advance the algorithm forward to the point where we buy something. This addition is what ultimately allowed the program to pass all the test cases.</p>\n<p>The relevant snippet:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>const std::int64_t passes_needed_to_buy =\n candies &lt; p ? (p - candies) / production : 0;\n\nif (passes_needed_to_buy &gt;= passes_needed - 1) {\n // We won't buy anything, so return early\n std::cout &lt;&lt; total;\n return 0;\n}\n// Skip forward to when we buy something\npasses += passes_needed_to_buy;\ncandies += production * passes_needed_to_buy;\n</code></pre>\n<p>The full program:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;algorithm&gt;\n#include &lt;cassert&gt;\n#include &lt;cmath&gt;\n#include &lt;cstdint&gt;\n#include &lt;iostream&gt;\n\n#ifdef __SIZEOF_INT128__\n\nusing Int128 = __int128;\n\n#else\n\n#include &lt;boost/multiprecision/cpp_int.hpp&gt;\n\nusing Int128 = boost::multiprecision::int128_t;\n\n#endif\n\nint main() {\n std::ios::sync_with_stdio(false);\n\n std::int64_t m, w, p, n;\n\n std::cin &gt;&gt; m &gt;&gt; w &gt;&gt; p &gt;&gt; n;\n\n assert(m &gt; 0 &amp;&amp; m &lt;= 1'000'000'000'000);\n assert(w &gt; 0 &amp;&amp; w &lt;= 1'000'000'000'000);\n assert(p &gt; 0 &amp;&amp; p &lt;= 1'000'000'000'000);\n assert(n &gt; 0 &amp;&amp; n &lt;= 1'000'000'000'000);\n\n for (std::int64_t candies = 0, passes = 0, total = INT64_MAX; ; ++passes) {\n const auto production = Int128{m} * w;\n\n const auto goal = n - candies;\n\n const std::int64_t passes_needed =\n goal/production + !!(goal%production);\n\n const auto subtotal = passes + passes_needed;\n\n if (passes_needed &lt;= 2) {\n std::cout &lt;&lt; subtotal;\n return 0;\n }\n\n if (total &lt; subtotal) {\n std::cout &lt;&lt; total;\n return 0;\n }\n\n total = subtotal;\n\n candies += production;\n\n const std::int64_t passes_needed_to_buy =\n candies &lt; p ? (p - candies) / production : 0;\n\n if (passes_needed_to_buy &gt;= passes_needed - 1) {\n std::cout &lt;&lt; total;\n return 0;\n }\n\n passes += passes_needed_to_buy;\n candies += production * passes_needed_to_buy;\n\n const auto d = std::div(candies, p);\n\n auto budget = d.quot; candies = d.rem;\n\n const auto diff = w - m;\n\n if (diff &lt; 0) {\n const auto w_hired = std::min(budget, -diff);\n\n budget -= w_hired;\n w += w_hired;\n } else if (diff &gt; 0) {\n const auto m_purchased = std::min(budget, diff);\n\n budget -= m_purchased;\n m += m_purchased;\n }\n\n const auto half = budget &gt;&gt; 1;\n\n m += half + (budget &amp; 1);\n w += half;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T23:45:04.630", "Id": "258859", "ParentId": "257739", "Score": "0" } } ]
{ "AcceptedAnswerId": "258859", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T16:45:50.317", "Id": "257739", "Score": "2", "Tags": [ "c++", "performance", "time-limit-exceeded", "mathematics", "complexity" ], "Title": "Can I further optimize this solution for HackerRank's “Making Candies”?" }
257739
<p>I have cleanly separated functionality of a message bus - namely the diagnostics (optional), sending, decoding and the bus driver, I need to now bind this together and have done so with a <code>MessageBus</code> class.</p> <p>It feels anemic though, with a lot of pass through methods.</p> <p>On the flip side it is necessary for coordinating <code>StartAsync()</code> which links dependencies on the <code>driver</code> and <code>receiver</code> (binding them so they can call back) - I saw no other way of achieving this if I registered all individual interfaces via an inversion of control container as it would get out of sync (how to bind the driver to the decoder for instance).</p> <p>If this is the wrong place for comments on code please let me know and I will remove straight away. Any pointers much appreciated.</p> <pre><code>public class MessageBus : IDisposable { private readonly MessageBusReceiver receiver; private readonly MessageBusPublisher publisher; private readonly IMessageBusDriver driver; private int isRunning; private readonly MessageBusDiagnostics diagnostics = null; public MessageBus(IMessageBusDriver driver, SerializerRegistry serializerRegistry, ITypeIdentifier typeIdentifier, ILoggerFactory loggerFactory, bool isDebug = false) { this.driver = driver; this.publisher = new MessageBusPublisher(serializerRegistry, driver, typeIdentifier); this.receiver = new MessageBusReceiver(serializerRegistry, typeIdentifier, loggerFactory.CreateLogger&lt;MessageBusReceiver&gt;()); if (isDebug) diagnostics = new MessageBusDiagnostics(driver, loggerFactory.CreateLogger&lt;MessageBusDiagnostics&gt;()); } void AssertIsRunning() { if (this.isRunning == 0) throw new InvalidOperationException($&quot;{nameof(StartAsync)} must be called before calling other methods.&quot;); } public async Task SubscribeAsync(string topic, QualityOfService qos, CancellationToken cancellationToken = default) { AssertIsRunning(); await this.driver.SubscribeAsync(topic, qos, null, null, null, cancellationToken); } public async Task UnsubscribeAsync(string topic, CancellationToken cancellationToken = default) { AssertIsRunning(); await this.driver.UnsubscribeAsync(topic, cancellationToken); } public async Task StartAsync(Func&lt;object, Task&gt; receiveApplicationMessage) { if (Interlocked.CompareExchange(ref this.isRunning, 1, 0) == 1) throw new InvalidOperationException(&quot;Already running.&quot;); this.receiver.OnMessageDecoded = receiveApplicationMessage; await this.driver.StartAsync(this.receiver.ReceiveMessageFromMessageBusDriver); } public async Task StopAsync() { if (Interlocked.CompareExchange(ref this.isRunning, 0, 1) == 0) throw new InvalidOperationException(&quot;Not running.&quot;); await this.driver.StopAsync(); } public async Task PublishAsync(object notification, string busPath, QualityOfService qos = QualityOfService.AtMostOnce, CancellationToken cancellationToken = default) { AssertIsRunning(); await this.publisher.PublishAsync(notification, busPath, qos, cancellationToken); } public async Task PublishAsync(object notification, Dictionary&lt;string, string[]&gt; pathTokens = null, QualityOfService qos = QualityOfService.AtMostOnce, CancellationToken cancellationToken = default) { AssertIsRunning(); await this.publisher.PublishAsync(notification, pathTokens, qos, cancellationToken); } public void Dispose() { this.driver.Dispose(); this.diagnostics?.Dispose(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T23:10:17.560", "Id": "509121", "Score": "1", "body": "A fast tip: you can optimize out all `async` State Machines here as you have only one `await` and no code after it and it's not inside `using` or `try-catch` statement. For example `public Task UnsubscribeAsync(...) { AssertIsRunning(); return this.driver.UnsubscribeAsync(...); }`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T11:53:33.007", "Id": "510246", "Score": "0", "body": "@aepot thank you, indeed you are right just a couple of pointers - been burnt in the past with https://stackoverflow.com/questions/63584024/simple-injector-instance-is-requested-outside-the-context-of-an-active-async-s and also `ConfigureAwait` I believe would be best practice (in some cases) https://medium.com/bynder-tech/c-why-you-should-use-configureawait-false-in-your-library-code-d7837dce3d7f" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T11:56:24.450", "Id": "510247", "Score": "0", "body": "`ConfigureAwait(false)` doesn't affect the above tip." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T12:01:40.313", "Id": "510334", "Score": "0", "body": "David Fowler (ASP.NET Architect) [suggests](https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#prefer-asyncawait-over-directly-returning-task) to prefer `await` over `return Task`. Please read the all reasoning and then decide which approach you choose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T12:06:15.137", "Id": "510335", "Score": "2", "body": "Why do you have a single class which can handle everything? Why don't you introduce separate interfaces for publisher and consumer clients?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T13:07:55.567", "Id": "510342", "Score": "0", "body": "Peter thats what i wanted, however i need to chain the interfaces in `public async Task StartAsync(Func<object, Task> receiveApplicationMessage)` this is causing me to bind it all together (and pass through method calls - my exact dislike)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T13:14:21.077", "Id": "510343", "Score": "0", "body": "It would be possible to separate interfaces, but i need away to start (publisher cannot be used until receiver is started)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T13:43:03.503", "Id": "510346", "Score": "0", "body": "@morleyc Why can't you start publisher without consumer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T20:43:37.297", "Id": "510377", "Score": "1", "body": "I have realized my specific use of MQTT.net lib is driving the upstream pattern (other libs, such as NetMQ and Azure Service Bus do not have to be \"started\" and if it is doing background work then it is likely initialized/started in the constructor and stopped in dispose), I will have a go at changing this and using a fluent configuration to \"build\" the message bus which will do the binding for me. This will then allow proper and neat separation of concerns. I will post up as an answer once done." } ]
[ { "body": "<p>I think what i was missing was a &quot;builder&quot; class that could take care of the construction, and allow the interfaces to be returned.</p>\n<p>Not all transport types needed to be &quot;started&quot;, so i left that concern to the builder of the specific bus (i.e. MQTT transport would have different requirements to Kafka for instance).</p>\n<p>Any &quot;stopping&quot; can be done on dispose - any one not wanting to receive messages before then can unsubscribe via the <code>ISubscriber</code> interface.</p>\n<p>So we build the base <code>MessageBusBuilderBase</code> class:</p>\n<pre><code>public abstract class MessageBusBuilderBase\n{\n private MessageBusDiagnostics messageBusDiagnostics;\n public bool IsDebugEnabled =&gt; messageBusDiagnostics != null;\n\n protected abstract Task&lt;ITransport&gt; NewTransportAsync(ILoggerFactory loggerFactory, Func&lt;TransportMessage, Task&gt; receiveMessage);\n\n public async Task&lt;BuiltInterfaces&gt; CreateAsync(IMessageSerializer[] serializers, ITypeIdentifier typeIdentifier, ILoggerFactory loggerFactory, bool isDebug = false)\n {\n var serializerRegistry = new SerializerRegistry(serializers);\n var receiver = new MessageDeserializer(serializerRegistry, typeIdentifier, loggerFactory.CreateLogger&lt;MessageDeserializer&gt;());\n var transport = await NewTransportAsync(loggerFactory, receiver.ReceiveMessageFromTransport);\n var publisher = new MessagePublisher(serializerRegistry, transport, typeIdentifier);\n var subscriber = new MessageSubscriber(transport);\n\n // chain up event handler functions\n receiver.OnMessageDecoded = subscriber.ReceiveMessageFromDeserializer;\n\n if (isDebug)\n this.messageBusDiagnostics = new MessageBusDiagnostics(transport, loggerFactory.CreateLogger&lt;MessageBusDiagnostics&gt;());\n\n return new BuiltInterfaces(publisher, subscriber);\n }\n}\n</code></pre>\n<p>And the specific derived class for <code>MqttMessageBusBuilder</code>:</p>\n<pre><code>public class MqttMessageBusBuilder : MessageBusBuilderBase\n{\n private readonly MqttSettings settings;\n public MqttMessageBusBuilder(MqttSettings settings)\n {\n this.settings = settings;\n }\n\n protected override async Task&lt;ITransport&gt; NewTransportAsync(ILoggerFactory loggerFactory, Func&lt;TransportMessage, Task&gt; receiveMessage)\n {\n var logger = loggerFactory.CreateLogger&lt;MqttMessageBusBuilder&gt;();\n logger.LogDebug($&quot;{nameof(MqttMessageBusBuilder)} is creating a new {nameof(MqttConnection)} and will connect to {this.settings.Server}:{this.settings.Port}.&quot;);\n \n var connection = new MqttConnection(this.settings, receiveMessage, loggerFactory.CreateLogger&lt;MqttConnection&gt;());\n\n await connection.StartAsync();\n logger.LogDebug($&quot;{nameof(MqttConnection)} has been started via {nameof(MqttConnection.StartAsync)}&quot;);\n\n return connection;\n }\n}\n</code></pre>\n<p>With the above, we now have the interfaces chained correctly, and can register the instances with a inversion of control container clearly separating the concerns of publishing and subscribing:</p>\n<pre><code>var mqttBusBuilder = new MqttMessageBusBuilder(settings);\nvar serializers = new [] { MessagePackSerializer };\nvar idStrategy = new IdentifyUsingTransportHeaders();\nmqttBusBuilder\n .Create(serializers, idStrategy, loggerFactory, var out publisher, var out subscriber);\n\ncontainer.RegisterSingleton(publisher);\ncontainer.RegisterSingleton(subscriber);\n</code></pre>\n<p>With regards to &quot;stopping&quot; the bus, I could create a <code>BusManager</code> class to manage a list of created busses and call <code>StopAsync</code> on call - alternatively will just perform this transparently by <em>stopping</em> in <code>Dispose()</code> and let that be a concern of the bus itself as i see other busses do not have <code>Start</code> or <code>Stop</code> functions so I shouldn't let that be the driver of my interface design.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T12:51:47.867", "Id": "510830", "Score": "1", "body": "`Task.Run(async () => await connection.StartAsync());` returns `Task` which is not awaited in the code. That's bad practice in `async` programming. Also running awaitable method on a separate thread has no sense. You can optimize out thread and keep the same \"not awaited\" mistake with `_ = connection.StartAsync()` but I suggest to fix it e.g. simple `await connection.StartAsync()`, probably not in this method but outside in a caller's code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-04T14:49:17.660", "Id": "510886", "Score": "1", "body": "Valid point - thought was some form of background long running task (which it is not in this case) will get this fixed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T18:35:36.793", "Id": "258932", "ParentId": "257740", "Score": "2" } } ]
{ "AcceptedAnswerId": "258932", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T17:05:54.367", "Id": "257740", "Score": "5", "Tags": [ "c#", "design-patterns" ], "Title": "Anemic class that binds functionality" }
257740
<p>This code succeeds in downloading log text files from multiple URLs. Can this be made more efficient?</p> <pre><code>let private downloadLogs toDirectory = let createFileDirectories (url : string) = let directory = $@&quot;{toDirectory}\{url.Substring(13, 3)}&quot; try if not (Directory.Exists(directory)) then Directory.CreateDirectory(directory) |&gt; ignore with | ex -&gt; failwith ex.Message let year = DateTime.Now.Year let month = DateTime.Now.Month.ToString(&quot;d2&quot;) let day = DateTime.Now.Day let d01LogUrlWithDate = d01LogPartialUrl + $&quot;{year}-{month}-{day}&quot; let d02LogUrlWithDate = d02LogPartialUrl + $&quot;{year}-{month}-{day}&quot; let s01LogUrlWithDate = s01LogPartialUrl + $&quot;{year}-{month}-{day}&quot; let s02LogUrlWithDate = s02LogPartialUrl + $&quot;{year}-{month}-{day}&quot; let urlWithDateList = [d01LogUrlWithDate; d02LogUrlWithDate; s01LogUrlWithDate; s02LogUrlWithDate] // create folder for each url file urlWithDateList |&gt; List.iter createFileDirectories let buildFinalUrlAndRequest number url = try let finalUrl = if number = 0 then $&quot;%s{url}-1.log&quot; else $&quot;%s{url}-{number}.log&quot; printfn $&quot;Searching for URL: {finalUrl}&quot; let response = Http.AsyncRequestStream(finalUrl) |&gt; Async.RunSynchronously if response.StatusCode &gt;= 200 &amp;&amp; response.StatusCode &lt;= 299 then printfn $&quot;URL Ready For Download: {url}&quot; Ok response else // this is never triggered printfn $&quot;Error. Status Code: {response.StatusCode}&quot; Error $&quot;Status Code: {response.StatusCode}&quot; with | ex -&gt; Error $&quot;Request Error: {ex.Message}&quot; let buildRequestList (state : seq&lt;Result&lt;HttpResponseWithStream, string&gt;&gt;) t = let range = seq{0..11} let responseSeq = seq{ for num in range do let numberUpdated = num + 1 let response = buildFinalUrlAndRequest numberUpdated t response } responseSeq |&gt; Seq.filter (fun x -&gt; x |&gt; function | Ok _ -&gt; true | Error _ -&gt; false) |&gt; Seq.append state let getResponse urls = urls |&gt; Seq.fold buildRequestList Seq.empty |&gt; Seq.choose (fun x -&gt; x |&gt; function | Ok response -&gt; Some (async{ try let fileName = Path.GetFileName(response.ResponseUrl.Replace(@&quot;/&quot;, @&quot;\&quot;)) let subDir = response.ResponseUrl.Substring(13,3) let pathName = $&quot;&quot;&quot;{toDirectory}\{subDir}\{fileName}&quot;&quot;&quot; use outputFile = new FileStream(pathName, FileMode.Create) do! response.ResponseStream.CopyToAsync(outputFile) |&gt; Async.AwaitTask printfn $&quot;File Downloaded: {pathName}&quot; return pathName with | ex -&gt; printfn $&quot;Download error {ex.Message}&quot; return &quot;&quot; }) | _ -&gt; None ) urlWithDateList |&gt; getResponse |&gt; Async.Parallel |&gt; Async.RunSynchronously |&gt; Array.toList </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T06:28:41.910", "Id": "510300", "Score": "2", "body": "In what way? Execution speed? Memory Usage? Code Verbosity? Idomaticism?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T12:44:45.647", "Id": "510340", "Score": "1", "body": "@Maslow Provide the best code review you can given the code. Optimize anything that you can see needs optimization and explain the trade offs." } ]
[ { "body": "<p>There appears to be more options for parallelization and async here, and I think the fold overcomplicated what you were trying to do.</p>\n<pre class=\"lang-fs prettyprint-override\"><code>#if false\n#r $&quot;FSharp.Data&quot;\n#endif\nopen System.Net\nopen System.IO\nopen FSharp.Data\n\nlet d01LogUrlWithDate, d02LogUrlWithDate, s01LogUrlWithDate, s02LogUrlWithDate = $&quot;&quot;,&quot;&quot;,&quot;&quot;,&quot;&quot;\n\nmodule Async =\n let map f x =\n async {\n let! x' = x\n return f x'\n }\n let bind f x =\n async{\n let! x' = x\n return! f x'\n }\n \nlet private downloadLogs toDirectory =\n\n let createFileDirectories (url : string) =\n let directory = @&quot;{toDirectory}\\{url.Substring(13, 3)}&quot;\n \n // if it is going to blow up, let it blow up keeping the entire stack trace\n if not &lt;| Directory.Exists directory\n // I prefer strongly typed ignore, less prone to refactoring issues\n then Directory.CreateDirectory directory |&gt; ignore&lt;DirectoryInfo&gt;\n\n let urlWithDateList = // less clutter in scope\n let year = DateTime.Now.Year\n let month = DateTime.Now.Month.ToString(&quot;d2&quot;)\n let day = DateTime.Now.Day\n [\n d01LogUrlWithDate\n d02LogUrlWithDate\n s01LogUrlWithDate\n s02LogUrlWithDate\n ] |&gt; List.map (fun x -&gt; x + $&quot;{year}-{month}-{day}&quot;)\n\n // create folder for each url file\n urlWithDateList |&gt; List.iter createFileDirectories\n\n let buildFinalUrlAndRequest number url =\n async {\n \n try // this area wasn't as complex, so I left the try alone\n // I'd think this should be $&quot;%s{url}-{number+1}.log&quot; or else 1 would stop on zero's output\n let finalUrl = if number = 0 then $&quot;%s{url}-1.log&quot; else $&quot;%s{url}-{number}.log&quot;\n printfn $&quot;Searching for URL: {finalUrl}&quot;\n let! response = FSharp.Data.Http.AsyncRequestStream finalUrl\n if response.StatusCode &gt;= 200 &amp;&amp; response.StatusCode &lt;= 299\n then \n printfn $&quot;URL Ready For Download: {url}&quot;\n return Ok response \n else // this is never triggered\n printfn $&quot;Error. Status Code: {response.StatusCode}&quot;\n return Error $&quot;Status Code: {response.StatusCode}&quot;\n with \n | ex -&gt; return Error $&quot;Request Error: {ex.Message}&quot;\n }\n\n // if you are just throwing away the Result.Error options, then you don't need to use Results\n let buildRequestList t : seq&lt;Async&lt;Result&lt;HttpResponseWithStream,string&gt;&gt;&gt; =\n seq{0..11}\n |&gt; Seq.map(fun i -&gt;\n async {\n let numberUpdated = i + 1\n let! response = buildFinalUrlAndRequest numberUpdated t\n return response\n }\n )\n\n let getResponse urls =\n urls\n |&gt; Seq.collect buildRequestList\n |&gt; Async.Parallel\n // these two Async.map calls could be composed together\n |&gt; Async.map(Seq.choose(function | Ok x -&gt; Some x | _ -&gt; None))\n |&gt; Async.map (Seq.map (fun response -&gt;\n async{\n let fileName = Path.GetFileName(response.ResponseUrl.Replace(@&quot;/&quot;, &quot;\\&quot;&quot;)) // fix syntax highlighting here on stack\n let subDir = response.ResponseUrl.Substring(13,3)\n let pathName = $@&quot;{toDirectory}\\{subDir}\\{fileName}&quot; // fix syntax highlighting here on Stack\n use outputFile = new FileStream(pathName, FileMode.Create)\n do! response.ResponseStream.CopyToAsync(outputFile) |&gt; Async.AwaitTask\n printfn $&quot;File Downloaded: {pathName}&quot;\n return pathName\n }\n |&gt; Async.Catch // this way, no try needed above\n |&gt; Async.map( // map the catch to option, and log the errors\n function\n | Choice1Of2 x -&gt; Some x\n | Choice2Of2 ex -&gt; printfn $&quot;Download error {ex.Message}&quot;; None\n )\n ))\n |&gt; Async.bind Async.Parallel\n\n urlWithDateList\n |&gt; getResponse\n |&gt; Async.RunSynchronously\n |&gt; Seq.choose id // discard empty values\n |&gt; Seq.toList\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T19:36:28.510", "Id": "510370", "Score": "0", "body": "Excellent! I want to learn all that I can in regards to writing idiomatic and efficient F# code. Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T15:05:59.340", "Id": "258842", "ParentId": "257742", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T17:38:22.213", "Id": "257742", "Score": "0", "Tags": [ ".net", "f#", ".net-core" ], "Title": "Downloading multiple log files" }
257742
<p>Hello fellow programmers, I am currently implementing a function and wanted to know if there was anything I could change to simplify the code, make it more readable, or to optimize the running time and memory usage. My current implementation works as expected, without any bugs.</p> <p>The function I am implementing is called <code>FilterConnectionSet()</code> and filters a given set of connections based on some criteria, and returns a list containing only the connections that satisfy those criteria.</p> <p>Each connection is linked to what we call a <code>container</code>, which is basically an external tool that can be attached to our software. Each containers has a given type (A, B, C, etc.). When a container is changed/updated, there is a variable named <code>modifiedContainers</code> of type <code>ContainerDictionary</code> that is automatically updated to include the modified container. Note that this variable is passed as a parameter to my function. I cannot change the code that updates the list of modified containers. All I can say is that <code>ContainerDictionary</code> is basically a custom class that wraps a <code>Dictionary&lt;&gt;</code>.</p> <p>Before performing any container related operation in our software, we perform a &quot;refresh&quot; by importing all the latest data from all the attached containers. However, for performance purposes, we do not want to import data from containers that were not updated since the last refresh. Additionally, even if we do not support that feature yet, multiple containers of a specific type (let's call it <code>TypeA</code>) type can be attached to our software at the same time. In that case, we want to group those containers based on some other properties, and only import the data of a single container per group, and display a warning message to the user that the data of the other containers of the same group were discarded.</p> <p>Please note that I can only change the function that filters the connections. I cannot make any changes to the functions that takes care of updating the <code>modifiedContainers</code> list, or the actual import of data, or anything else not shown in this questions.</p> <p>Here's how my <code>FilterConnectionSet</code> function works:</p> <ol> <li>The function takes <code>connectionSet</code> (the list of connections to be filtered) and <code>modifiedContainers</code> (a list of containers that have been recently updated) as parameters.</li> <li>It then loops through all the connections and and separates all the connections to containers of <code>TypeA</code>. All remaining connections are automatically added to the list of filtered connections.</li> <li>Using LinQ, the connections of <code>TypeA</code> are then split in different groups based on the other properties.</li> <li>The function loops through each groups and does the following: <ul> <li>Define a <code>connectionToAdd</code> variable, and initialize to last connection in the group.</li> <li>Loop through all the connection in the group <ul> <li>IF the connection is not linked to a container in the <code>modifiedContainers</code> list, THEN go to the next connection in the group.</li> <li>ELSE, update the <code>connectionToAdd</code> variable.</li> </ul> </li> <li>IF there was more than one connection in the group, THEN display the message stating the only one container data will be imported.</li> <li>Add the connection stored inside the <code>connectionToAdd</code> variable to the list of filtered connections.</li> <li>Go to the next group of connection and repeat</li> </ul> </li> <li>Return the list of filtered connections</li> </ol> <p>Here is my current implementation:</p> <pre><code> private static List&lt;Connection&gt; FilterConnectionSet(List&lt;Connection&gt; connectionSet, ContainerDictionary modifiedContainers) { var filteredConnectionSet = new List&lt;Connection&gt;(); var typeAConnections = new List&lt;Connection&gt;(); foreach (var connection in connectionSet) { // Check connection Type. If TypeA, add to list of TypeA connections, else add to filtered set. if (connection.Type == &quot;TypeA&quot;) { typeAConnections.Add(connection); } else { filteredConnectionSet.Add(connection); } } // Group the connections of TypeA based on other properties var groupedTypeAConnections = typeAConnections.GroupBy(c =&gt; new {c.property1, c.property2}); foreach (var connectionGroup in groupedTypeAConnections) { var connectionToAdd = connectionGroup.Last(); foreach (var connection in connectionGroup) { // Please note here the the ContainerInModifiedList function is a helper function that cannot be changed. if (!ContainerInModifiedList(connection, modifiedContainers)) { continue; } connectionToAdd = connection; } // If there is more than one connection in the group, display warning message. Please not that the helper function for displaying messages cannot be changed. if (connectionGroup.Count() &gt; 1) { var warningMessage = string.Format(&quot;Multiple containers with property1 = {0} and property2 = {1} were detected. Only the container {2} will be imported!&quot;, connectionToAdd.property1, connectionToAdd.property2, connectionToAdd.Container.Name); ErrorHelper.PublishWarningMessage(warningMessage); } filteredConnectionSet.Add(connectionToAdd); } return filteredConnectionSet; } </code></pre> <p>I hope I provided enough details.</p> <p>I am open to any comments and suggestion!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T20:39:46.653", "Id": "510446", "Score": "1", "body": "@aepot Anonymous types have structural comparison by default." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:30:22.570", "Id": "257745", "Score": "1", "Tags": [ "c#", "performance", "linq" ], "Title": "Optimizations on a function that fIlters a list of connections" }
257745
<p>I've recently started programming in C and as my first serious program I thought I'd create a simple calculator. To make it a bit more complex I decided not to use the functions included in math.h (like pow) but to create these functions by myself. Let me know if there is something I can do to improve this code.</p> <pre><code>#include&lt;stdio.h&gt; double power(double x, double y, double r) // This function calculates the power and takes numer1, number2 and the results { r = 1; // We need to initialize the results otherwise we can't store the partial result on line 11 int c; for (c = y; c &gt; 0; c--) // putting c equal to y we can decrement c and obtain the precise number of operations needed to complete the power { int pow = y; // that's a bit tricky: we can't apply the modulus operand in line 12 because y is a double, so we must convert y in an int r *= x; // this way result = 1 * number1, then number1 * number1, then number1 * number1 * number1 and so on if ((x &lt; 0) &amp;&amp; (pow % 2 == 1)) /* If the first number is negative, and we calculate the power of this number to 2 or multiples, the number resulting will be negative                                                                 to obtain the correct result (positive) we must multiply the result to -1, if the previous conditions are met */ { x *= -1; } } printf(&quot;%0.1lf&quot;, r); } double root(double x, double y, double r) { int c; if (x &lt; 0) { puts(&quot;is impossible to calcultate the root of a negative number&quot;); } for (c = 1; c &lt; x; c++) { int partRes = x; partRes /= c; if (partRes * partRes == x) { printf(&quot;The root of %0.1lf is: %0.1d\n&quot;, x, partRes); break; } } } int main() { double num1, num2, res; char op; puts(&quot;Input number, operator and number&quot;); puts(&quot;operands permitted: + (addition), - (subtraction), * (multiplication), / (division), ^ (power), $ (square root)&quot;); scanf(&quot;%lf %c %lf&quot;, &amp;num1, &amp;op, &amp;num2); if (op == '+') { res = num1 + num2; printf(&quot;%0.1lf&quot;, res); } else if (op == '-') { res = num1 - num2; printf(&quot;%0.1lf&quot;, res); } else if (op == '*') { res = num1 * num2; printf(&quot;%0.1lf&quot;, res); } else if (op == '/') { res = num1 / num2; printf(&quot;%0.1lf&quot;, res); } else if (op == '^') { power(num1, num2, res); } else if (op == '$') { root(num1, num2, res); } else printf(&quot;error, use a valid operand&quot;); } </code></pre>
[]
[ { "body": "<p><strong><code>power()</code> problems</strong></p>\n<p><code>double power()</code> does not return a value.</p>\n<p>Incorrect result when <code>y</code> is not a value in the <code>int</code> range.</p>\n<p>Code attempts a linear power calculation: O(y). Research <a href=\"https://en.wikipedia.org/wiki/Exponentiation_by_squaring\" rel=\"nofollow noreferrer\">Exponentiation by squaring</a>. It is faster and less precision loss.</p>\n<p><code>double r</code> parameter serves no purpose. Instead make a local <code>double r</code> variable.</p>\n<p>A floating point power function is one of the most changeling functions to code well. Rough cut below.</p>\n<hr />\n<p><strong><code>root()</code> problems</strong></p>\n<p><code>double root()</code> does not return a value.</p>\n<p>Other problems like <code>power()</code>.</p>\n<hr />\n<p><strong>It floating point, not fixed point</strong></p>\n<p>More informative to use exponential notation for large and small value than a fix-point format.</p>\n<pre><code>// printf(&quot;%0.1lf&quot;, res);\nprintf(&quot;%g&quot;, res);\n</code></pre>\n<hr />\n<p>Sample improved <code>my_power()</code> - unchecked</p>\n<pre><code>// Very rough code\ndouble my_power(double x, double y) {\n double whole;\n double fraction = modf(y, &amp;whole);\n if (fraction == 0.0) {\n double r = 1.0;\n double p = fabs(whole);\n while (p &gt; 0) {\n if (fmod(p, 2.0)) {\n r *= x;\n }\n x *= x;\n p /= 2.0;\n }\n if (whole &lt; 0) {\n r = 1.0 / r;\n }\n return r;\n }\n if (x == 0.0) {\n return 0.0;\n }\n if (x &lt; 0.0) {\n return NAN;\n }\n return exp(log(x) * y);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T19:46:13.483", "Id": "257752", "ParentId": "257749", "Score": "2" } } ]
{ "AcceptedAnswerId": "257752", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:53:43.563", "Id": "257749", "Score": "5", "Tags": [ "beginner", "c", "calculator" ], "Title": "My first program in C. A simple command-line calculator" }
257749
<p>I'm writing my own library, that is for asynchronous network communication. and then, wanna write my own HTTP proxy server for load-balancing connections to backend servers with it.</p> <p>when I'm using <code>docker</code> at my work in company, I thought that &quot;if the <code>apache</code> have REST API for adding/removing proxies, it may be modified dynamically in runtime without reloading/restarting daemon.&quot; (It may be a little stupid idea...)</p> <p>Anyway, I planned to create it, more stupid idea came.</p> <p>&quot;If I can generalize that handles some data flow, i.e. stream.&quot;</p> <p>I searched for various things. And I discovered that it was called 'ReactiveX', but there was a part that I didn't like a little. so I am decided to write the whole thing similar to it myself. In my idea, the intrinsic view of data as a stream is the same as that of RX. But the important differences are the direction that data stream is heading and, its processor. And the encapsulation of the processing flow.</p> <p><strong>1. Generalization of <code>Iterator</code> and <code>Iteratable</code>.</strong></p> <p>What was needed to handle certain data in a unified way is <code>source</code> that supplies that data. and almost things can be <code>iterator</code>. e.g. <code>socket</code>'s <code>accept()</code> function. And it was most important to be compatible with the C++ standard. Then, many things can be integrated without myself implementing them or fitting into any framework.</p> <pre><code>/** * struct last_iterator_t. * Represents the end of iteration. * e.g. iterator == end_of_iterator */ struct last_iterator_t { }; constexpr last_iterator_t end_of_iterator = {}; namespace _ { /** * struct iteratable_t&lt;_iteratable&gt; * Generalize an iteratable to one interface. * All of `iteratable_t&lt;type&gt;` will copy source container. * To prevent copy, use with `std::move` or wrap it as `std::shard_ptr`. */ template&lt;typename _iteratable&gt; struct iteratable_t { static_assert( traits::is_iteratable&lt;_iteratable&gt;, &quot;iteratable_t&lt;type&gt; can work with only iteratable containers!&quot; ); using trait = traits::iterator_of&lt;_iteratable&gt;; using state_t = iteratable_state_t&lt;typename trait::value_t, trait&gt;; using iterator_t = state_iterator_t&lt;typename trait::value_t, state_t&gt;; /* source container or source sequence something: */ instrusive&lt;_iteratable&gt; source; /* constructor of this iteratable.*/ iteratable_t() { } iteratable_t(_iteratable source) : source(std::move(source)) { } iteratable_t(const iteratable_t&amp; other) : source(other.source) { } iteratable_t(iteratable_t&amp;&amp; other) : source(std::move(other.source)) { } /* assignment operators. */ inline iteratable_t&amp; operator =(const iteratable_t&amp; other) { source = other.source; return *this; } inline iteratable_t&amp; operator =(iteratable_t&amp;&amp; other) { source = std::move(other); return *this; } /* get begining of iteratable. */ inline iterator_t begin() const { SEQ_INIT_ASSERT((bool) source, &quot;tried to access uninitialized iteratable&lt;type&gt;!&quot;); /* : non default initializable. */ return iterator_t(state_t(trait::begin_of(*source), trait::end_of(*source))); } /* get ending of iteratable. */ inline last_iterator_t end() const { return end_of_iterator; } }; } /** * using iteratable_t&lt;iteratable&gt;. * Facade declaration for using _::iteratable_t&lt;iteratable&gt; class. */ template&lt;typename _iteratable&gt; using iteratable_t = typename traits::anti_recursive&lt;_::iteratable_t&lt;typename std::decay&lt;_iteratable&gt;::type&gt;&gt;::type; </code></pre> <p>But, as everyone knows, there is nothing <code>Asynchronous</code> in <code>Iterator</code>. Not suitable for asynchronous. So I tried to provide a bit of a non-standard methods. And, by static polymorphism, they are unified into async state.</p> <pre><code>/** * struct state_iterator_t&lt;value_type, state_type&gt; * Adapts state-type to iterator. */ template&lt;typename value_type, typename state_type&gt; struct state_iterator_t { mutable instrusive&lt;state_type&gt; state; static_assert( traits::state_iterators::has_end_of&lt;state_type&gt;, &quot;state_type must implement `bool is_end_of()` method!&quot; ); static_assert( traits::state_iterators::has_forward&lt;state_type&gt;, &quot;state_type must implement `bool forward()` method!&quot; ); static_assert( traits::state_iterators::has_value&lt;state_type&gt;, &quot;state_type must implement `value_type value()` method!&quot; ); /** * delegated functor for invoking eligible polymorphic methods. * @note Polys marked with ^ must be implemented. * * 1. ensure: initiate if the state isn't initiated. -&gt; calls `init` method once in entire iteration. * 2. end_of ^: determines end of the state. * 3. forward ^: shift the input to forward. * 4. value ^: acquire the current value of input. * 5. pending: test the input is available without blocking. * 6. wait: wait if the input is unavailable yet. * * the life-cycle(flow) of state_type is: * * 1. instantiating prototype of state_type by iteratable. * 2. then, integrated into manipulatables or operatables. * 3. cloning state_type from prototype when `begin` of iteratable method called. * 4. --- then, moved to manipulator, loop or worker (consumer) --- * 5. the consumer checks end of iterator first and runs iterator. * * This flow is slightly different depending on the subject * that operates the Iterator, but the big frame is as follows. * * --&gt; state_type::init() once, * while (it != seq::end_of_iterator) { * --&gt; state_type::is_end_of() &lt;-- RETRY * --&gt; state_type::pending() * =&gt; on true: returns immediately. * --&gt; state_type::wait(-1) * =&gt; on true: returns immediately. * --&gt; goto RETRY. * * value_type value = *it; * --&gt; state_type::value(). * * ... (external code) ... * * ++it; * --&gt; state_type::forward(). * } * * @note in debug mode binaries, the is_end_of method is called every * time the iterator move forward to the next sequence or accessing current value, * checking pending values, waiting incoming values. */ polys::state_iterator_poly_ensure&lt;state_type&gt; _ensure; polys::state_iterator_poly_end_of&lt;state_type&gt; _end_of; polys::state_iterator_poly_forward&lt;state_type&gt; _forward; polys::state_iterator_poly_value&lt;state_type&gt; _value; polys::state_iterator_poly_pending&lt;state_type&gt; _pending; polys::state_iterator_poly_wait&lt;state_type&gt; _wait; /* constructors */ state_iterator_t() { } state_iterator_t(const state_type&amp; o) : state(o) { } state_iterator_t(state_type&amp;&amp; o) : state(std::move(o)) { } /* cloning/shifting constructors */ state_iterator_t(const state_iterator_t&amp; o) : state(o.state), _ensure(o._ensure), _end_of(o._end_of), _forward(o._forward), _value(o._value), _pending(o._pending), _wait(o._wait) { } state_iterator_t(state_iterator_t&amp;&amp; o) : state(std::move(o.state)), _ensure(std::move(o._ensure)), _end_of(std::move(o._end_of)), _forward(std::move(o._forward)), _value(std::move(o._value)), _pending(std::move(o._pending)), _wait(std::move(o._wait)) { } /* assignment operators */ inline state_iterator_t&amp; operator =(const state_iterator_t&amp; o) { state = o.state; _ensure = o._ensure; _end_of = o._end_of; _forward = o._forward; _value = o._value; _pending = o._pending; _wait = o._wait; return *this; } inline state_iterator_t&amp; operator =(state_iterator_t&amp;&amp; o) { state = std::move(o.state); _ensure = std::move(o._ensure); _end_of = std::move(o._end_of); _forward = std::move(o._forward); _value = std::move(o._value); _pending = std::move(o._pending); _wait = std::move(o._wait); return *this; } /* called if iterated by standard-way. */ inline bool __end_of() const { _ensure(state); if (!_end_of(state)) { if (_pending(state)) return false; while (!_end_of(state)) { if (_wait(state, -1)) return _end_of(state); } } return true; } /* redirect methods to compile-time polymorphic methods */ inline void init() { return _ensure(state); } inline bool end_of() const { return _end_of(state); } inline value_type value() const { return _value(state); } inline bool forward() { return _forward(state); } inline bool pending() const { return _pending(state); } inline bool wait(int timeout) const { return _wait(state, timeout); } /* checking end of iteration or not. */ inline bool operator ==(const last_iterator_t&amp;) const { return __end_of(); } inline bool operator !=(const last_iterator_t&amp;) const { return !__end_of(); } /* iterate forward to. */ inline state_iterator_t&amp; operator ++() { _ensure(state); _forward(state); return *this; } inline state_iterator_t operator ++(int) { _ensure(state); state_iterator_t clone(*this); _forward(state); return clone; } /* get value of current iteration. */ inline value_type operator *() const { _ensure(state); return _value(state); } }; </code></pre> <p>And this <code>Iteratable</code> should always be <code>Replay</code> enabled. Therefore, it is internally wrapped with the original data in a <code>iterable_t&lt;...&gt;</code> class, implements the <code>anti_recursive</code>, and blocks recursive wrapping. below is example which generates numeric sequence.</p> <pre><code>namespace iteratables { /** * struct numeric_range_t&lt;number_type, step_type&gt;. * generates numeric sequence. */ template&lt;typename number_type, typename step_type&gt; struct numeric_range_t { static_assert( std::is_integral&lt;number_type&gt;::value || std::is_floating_point&lt;number_type&gt;::value || std::is_pointer&lt;number_type&gt;::value || traits::can_offset_incremental&lt;number_type&gt;, &quot;numeric_range_t&lt;num_type, ?&gt; requires numeric offset type!&quot; ); static_assert( std::is_integral&lt;step_type&gt;::value || (!std::is_pointer&lt;number_type&gt;::value &amp;&amp; !traits::can_offset_incremental&lt;number_type&gt; &amp;&amp; std::is_floating_point&lt;step_type&gt;::value) , &quot;numeric_range_t&lt;?, step_type&gt; requires numeric stepping offset type!&quot; ); SEQ_DECLARE_ITERATABLE(state_t, _init); struct state_t { number_type next, last; step_type step; bool revert; state_t(number_type&amp;&amp; next, number_type&amp;&amp; last, step_type&amp;&amp; step) : next(std::move(next)), last(std::move(last)), step(std::move(step)), revert(step &lt; 0) { SEQ_RANGE_ASSERT(step != 0, &quot;step amount for numeric_range_t&lt;type&gt; never be zero!&quot;); } inline bool is_end_of() const { return revert ? next &lt;= last : next &gt;= last; } inline bool forward() { if (!is_end_of()) { next += step; return true; } return false; } inline number_type value() const { return next; } } _init; numeric_range_t(number_type&amp;&amp; next, number_type&amp;&amp; last, step_type&amp;&amp; step) : _init(std::move(next), std::move(last), std::move(step)) { } }; } /** * range ( start, end [, increasement ] ) * generates numeric sequence in given range. */ template&lt;typename number_type,typename step_type = int&gt; inline auto range(number_type from, number_type to, step_type step = 1) { return iteratable_t&lt;iteratables::numeric_range_t&lt;number_type, step_type&gt;&gt;( iteratables::numeric_range_t&lt;number_type, step_type&gt;(std::move(from), std::move(to), std::move(step))); } /** * infinite( start [, increasement ] ) * generates numeric sequence until overflow. */ template&lt;typename number_type, typename step_type = int&gt; inline auto infinite(number_type from, step_type step = 1) { static_assert( std::is_integral&lt;number_type&gt;::value || std::is_floating_point&lt;number_type&gt;::value, &quot;infinite range (until overflow) can accept only integer types and floating points!&quot; ); number_type to = step &lt; 0 ? std::numeric_limits&lt;number_type&gt;::min() - step : std::numeric_limits&lt;number_type&gt;::max() - step; return iteratable_t&lt;iteratables::numeric_range_t&lt;number_type, step_type&gt;&gt;( iteratables::numeric_range_t&lt;number_type, step_type&gt;(std::move(from), std::move(to), std::move(step))); } </code></pre> <p>And this code can be used like:</p> <pre><code>for (int i: range(0, 100)) { std::cout &lt;&lt; i &lt;&lt; &quot;\n&quot;; } </code></pre> <p><strong>2. Generalization of <code>Operator</code>s which manipulates the data sequence.</strong></p> <p>After generalizing the <code>iterator</code> and <code>iteratable</code>, I needed to generalize more then beyond for writing manipulators. The process must never be complicated or difficult, and type no much code. So, defined the rule more. And what must be implemented as a core is to be able to recognize and combine each other without passing by template arguments. But it shouldn't be with <code>virtual table</code> for <code>performance</code>.</p> <pre><code>namespace _ { /** * struct operatable_t&lt;operator&gt;. * Operator takes iteratables and handles them, and then, * internally creates progressive or bypass action which met its purpose. */ template&lt;typename operatable = void&gt; struct operatable_t { instrusive&lt;operatable&gt; source; /** * take iteratable and decide returnning action by its purpose. */ template&lt;typename iteratable&gt; inline auto take(iteratable&amp;&amp; input) -&gt; iteratable_t&lt;typename traits::action_of&lt;operatable, iteratable&gt;::action_type&gt; { static_assert( traits::is_iteratable&lt;iteratable&gt;, &quot;take(iteratable) can only take iteratable!&quot; ); SEQ_INIT_ASSERT((bool) source, &quot;tried to interact with uninitialized operator!&quot;); return iteratable_t&lt;typename traits::action_of&lt;operatable, iteratable&gt;::action_type&gt;((*source).take(std::move(input))); } /* constructor of this operatable_t. */ operatable_t() { } operatable_t(operatable source) : source(std::move(source)) { } operatable_t(const operatable_t&amp; o) : source(o.source) { } operatable_t(operatable_t&amp; o) : source(std::move(o.source)) { } /* assignment operators. */ inline operatable_t&amp; operator =(const operatable_t&amp; other) { source = other.source; return *this; } inline operatable_t&amp; operator =(operatable_t&amp;&amp; other) { source = std::move(other); return *this; } }; } template&lt;typename operatable&gt; using operatable_t = typename traits::anti_recursive&lt;_::operatable_t&lt;typename std::decay&lt;operatable&gt;::type&gt;&gt;::type; /** * Pipe operator. * This operator is for putting the iteratable into operatable. */ template&lt;typename iteratable, typename operatable&gt; inline auto operator &gt;&gt; (_::iteratable_t&lt;iteratable&gt; source, _::operatable_t&lt;operatable&gt; dest) -&gt; decltype(std::declval&lt;operatable_t&lt;operatable&gt;&gt;().take(std::declval&lt;iteratable_t&lt;iteratable&gt;&amp;&amp;&gt;())) { return dest.take(iteratable_t&lt;iteratable&gt;(std::move(source))); } </code></pre> <p><code>bypass</code> passes <code>iteratable</code> itself to <code>executor</code>, which is an implementation. <code>progressive</code> passes individual data by enumerating its <code>iteratable</code>. That doesn't mean that <code>progressive</code> will immediately <code>iterate</code> all the data in advance. Only when trying to get data from the <code>progressive</code> result <code>iteratable</code>, it processes one by one and provides the result.</p> <pre><code>/** * struct exec_progressive_action_t&lt;executor_type, iteratable&gt; * Handle input and return its result progressively. */ template&lt;typename executor_type, typename iteratable&gt; struct exec_progressive_action_t { using trait = traits::iterator_of&lt;iteratable&gt;; using return_type = traits::executor::progressive_return_of&lt;executor_type, typename trait::value_t&gt;; using decayed_return_type = typename std::decay&lt;return_type&gt;::type; using decayed_iteratable = typename std::decay&lt;iteratable&gt;::type; SEQ_DECLARE_ITERATABLE(state_t, _init); struct state_t { executor_type executor; decayed_iteratable input; instrusive&lt;typename trait::begin_t, true&gt; next; instrusive&lt;typename trait::end_t, true&gt; last; instrusive&lt;decayed_return_type, true&gt; buffer; state_t(executor_type&amp; executor, decayed_iteratable&amp;&amp; input) : executor(executor), input(std::move(input)) { } inline void init() { next = input.begin(); last = input.end(); (*next).init(); } inline bool is_end_of() { return (*next).end_of(); } inline bool pending() { return (*next).pending(); } inline bool wait(int timeout) { return (*next).wait(timeout); } inline decayed_return_type&amp; value() { if (!buffer) { auto _value = (*next).value(); buffer = executor.handle(std::move(_value)); } return *buffer; } inline bool forward() { if ((*next).forward()) { buffer.unset(); return true; } return false; } }; state_t _init; exec_progressive_action_t(executor_type&amp; executor, decayed_iteratable&amp;&amp; input) : _init(executor, std::move(input)) { } }; </code></pre> <p>Below code is a example of <code>operatable</code>.</p> <pre><code>namespace operatables { /** * struct flat_map&lt;handler_type&gt;. * maps the input interatable to given functor. */ template&lt;typename handler_type&gt; struct flat_map { using functor_is = traits::action_functor_of&lt;handler_type&gt;; using return_type = typename functor_is::return_type; using decayed_type = typename std::decay&lt;return_type&gt;::type; static_assert( !functor_is::is_bypass || traits::is_iteratable&lt;typename functor_is::return_type&gt;, &quot;`bypass` action should return iteratable type!&quot; ); struct executor_t { handler_type handler; instrusive&lt;decayed_type, false&gt; buffer; executor_t(handler_type&amp;&amp; handler) : handler(std::move(handler)) { } template&lt;typename iteratable&gt; inline decayed_type&amp;&amp; bypass(iteratable&amp;&amp; input) { return std::move(*(buffer = handler(input))); } template&lt;typename input_type&gt; inline decayed_type&amp;&amp; handle(input_type&amp;&amp; input) { return std::move(*(buffer = handler(input))); } }; SEQ_DECLARE_TAKE_BOTHWAY(executor_t, _init, functor_is::is_bypass); executor_t _init; flat_map(handler_type&amp;&amp; handler) : _init(std::move(handler)) { } }; } /** * flat_map( handler functor ). * maps the input iteratable to given functor. * 1. progressive mode: []( data-type ...) { return processed-data. }; * 2. bypass mode: []( dynamic_iterator&lt;data-type&gt; ... ) { return iteratable; }; */ template&lt;typename handler_type&gt; inline auto flat_map(handler_type&amp;&amp; handler) -&gt; operatable_t&lt;operatables::flat_map&lt;handler_type&gt;&gt; { return operatable_t&lt;operatables::flat_map&lt;handler_type&gt;&gt;( operatables::flat_map&lt;handler_type&gt;(std::move(handler))); } </code></pre> <p>And then, its usage:</p> <pre><code>auto zero_to_one = range(0, 5) &gt;&gt; flat_map([](int v) { return v / 2.0; }) &gt;&gt; flat_map([](dynamic_iteratable&lt;double&gt; values) { std::vector&lt;int&gt; s; for(auto k : values) { s.push_back(k); for (int v : range(0, (int)k + 5)) { s.push_back(v); } } return values; }); for (auto i : zero_to_one) { std::cout &lt;&lt; i &lt;&lt; &quot;\n&quot;; } </code></pre> <p>The argument of second <code>flat_map</code> call, the reason of <code>dynamic_iteratable&lt;type&gt;</code> is, <code>iteratable_t&lt;...&gt;</code> template will be transformed to human unreadable and can't be typed by hand to too-long. e.g. <code>iteratable_t&lt;operatables::flat_map&lt;lambda [] -&gt;124ab...&gt;::iteratable&lt;iteratables::numeric_range_t&lt;int, int, int&gt;&gt;..............&gt;</code>.</p> <p>So, it should be wrapped into shorter type.</p> <pre><code> /** * struct dynamic_iteratable&lt;data_type&gt;. * Wraps compile-time generated iteratable to dynamic instance. */ template&lt;typename data_type&gt; struct dynamic_iteratable { struct state_t; struct iteratable_trans; struct iterator_trans; using iteratable_ptr = trans_ptr&lt;iteratable_trans&gt;; using iterator_ptr = trans_ptr&lt;iterator_trans&gt;; struct iterator_trans { instrusive&lt;data_type, true&gt; temp; void* _object; /* * Delegates to: * * inline void init() { return _ensure(state); } * inline bool is_end_of() const { return _end_of(state); } * inline value_type value() const { return _value(state); } * inline bool forward() { return _forward(state); } * inline bool pending() const { return _pending(state); } * inline bool wait(int timeout) const { return _wait(state, timeout); } */ iterator_ptr (*_clone)(const iterator_ptr&amp;); void (*_init)(const iterator_ptr&amp;); bool (*_end_of)(const iterator_ptr&amp;); data_type&amp; (*_value)(const iterator_ptr&amp;); bool (*_forward)(const iterator_ptr&amp;); bool (*_pending)(const iterator_ptr&amp;); bool (*_wait)(const iterator_ptr&amp;, int); }; struct iteratable_trans { void* _object; iterator_ptr (*begin)(const iteratable_ptr&amp;); }; SEQ_DECLARE_ITERATABLE(state_t, _init); /* transparent pointers to original iteratable. */ struct state_t { mutable iteratable_ptr transparent; mutable iterator_ptr iterator; inline void init() { SEQ_INIT_ASSERT(transparent, &quot;tryied to iterate uninitialized dynamic iterator!&quot;); iterator = transparent-&gt;begin(transparent); iterator-&gt;_init(iterator); } inline bool is_end_of() const { return iterator-&gt;_end_of(iterator); } inline data_type&amp; value() const { return iterator-&gt;_value(iterator); } inline bool forward() { return iterator-&gt;_forward(iterator); } inline bool pending() const { return iterator-&gt;_pending(iterator); } inline bool wait(int timeout) const { return iterator-&gt;_wait(iterator, timeout); } }; template&lt;typename iteratable&gt; dynamic_iteratable(iteratable&amp;&amp; _iteratable) { using qualified_iteratable = iteratable_t&lt;iteratable&gt;; using begin_type = typename traits::iterator_of&lt;qualified_iteratable&gt;::begin_t; static_assert( traits::is_iteratable&lt;iteratable&gt;, &quot;not iteratables can't be wrapped to dynamic iteratable!&quot; ); struct func_proxy { static iterator_ptr clone(const iterator_ptr&amp; p) { iterator_trans* newbie = new iterator_trans(*p.get()); newbie-&gt;_object = new begin_type(*((begin_type*)p-&gt;_object)); return iterator_ptr(newbie, [](iterator_trans* p) { delete ((begin_type*)(p-&gt;_object)); }); } static void init(const iterator_ptr&amp; p) { ((begin_type*)(p-&gt;_object))-&gt;init(); }; static bool end_of(const iterator_ptr&amp; p) { return ((begin_type*)(p-&gt;_object))-&gt;end_of(); }; static data_type&amp; value(const iterator_ptr&amp; p) { return *(p-&gt;temp = ((begin_type*)(p-&gt;_object))-&gt;value()); } static bool forward(const iterator_ptr&amp; p) { return ((begin_type*)(p-&gt;_object))-&gt;forward(); }; static bool pending(const iterator_ptr&amp; p) { return ((begin_type*)(p-&gt;_object))-&gt;pending(); }; static bool wait(const iterator_ptr&amp; p, int v) { return ((begin_type*)(p-&gt;_object))-&gt;wait(v); }; }; iteratable_trans* data = new iteratable_trans(); data-&gt;_object = new qualified_iteratable(std::move(_iteratable)); data-&gt;begin = [](const iteratable_ptr&amp; ptr) { auto* _iteratable = ((qualified_iteratable*)ptr-&gt;_object); iterator_trans* iter = new iterator_trans(); iterator_ptr shareable(iter, [](iterator_trans* p) { delete ((begin_type*)(p-&gt;_object)); }); iter-&gt;_object = new begin_type(_iteratable-&gt;begin()); iter-&gt;_clone = func_proxy::clone; iter-&gt;_init = func_proxy::init; iter-&gt;_end_of = func_proxy::end_of; iter-&gt;_value = func_proxy::value; iter-&gt;_forward = func_proxy::forward; iter-&gt;_pending = func_proxy::pending; iter-&gt;_wait = func_proxy::wait; return shareable; }; _init.transparent = iteratable_ptr(data, [](iteratable_trans* p) { delete ((qualified_iteratable*)(p-&gt;_object)); }); } state_t _init; }; </code></pre> <p><strong>3. Ideas for minimizing <code>waiting</code> and <code>polling</code>.</strong></p> <p>As you may have noticed if you look at some of the code I've shown in the sample above, they don't have any awaitable <code>handles</code> provided by the <code>kernel</code>.</p> <p>So I devised an idea. I'm not in the process of implementing it yet. The reason I'm writing this long article is to get advice about the idea and, wanna get reviews about above generalizations.</p> <p>The idea I'm thinking of is:</p> <ol> <li>Only one waitable <code>handle</code> is allocated per thread. It maybe accessible by <code>TLS</code>. (not decided)</li> <li>The <code>handle</code> exits its state whenever it is signaled that any <code>async</code> request from that thread has been completed.</li> <li>And the <code>iteratable</code> who generated the <code>async request</code> is issued <code>async token</code>, and when it is completed, the token is returned.</li> <li>When all the <code>asynchronous tokens</code> issued for the thread are returned, the waiting <code>handles</code> are returned to the <code>concurrent queue</code>.</li> </ol> <p>However, all this process is based on the premise that the response to the <code>asynchronous request</code> must be <code>iteratable</code>.</p> <p>Can I get any advice on this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T12:45:40.477", "Id": "510158", "Score": "0", "body": "The code you implemented so far looks a lot like what C++20's [ranges library](https://en.cppreference.com/w/cpp/ranges#Example) provides." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T13:27:34.160", "Id": "510165", "Score": "0", "body": "@G.Sliepen wow! I knew the first time today. :) I haven't seen 20 standards yet" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T18:59:05.797", "Id": "257750", "Score": "0", "Tags": [ "c++", "asynchronous", "async-await" ], "Title": "Idea for writing asynchronous data processing chains easier (similar to `ReactiveX`) and its implementation" }
257750
<ol> <li>I want to generate a random date of birth [mm/dd/yyyy]which will represent an age equal to less than 18years old</li> <li>My requirement is to dynamically generate test data [date of birth] to negatively test a system which needs a date of birth (age) to be always greater than 18 years old</li> <li>The system which I am trying to test compares the user's input D.O.B. with the current date and calculates the age, if the age is less than 18 years old then throws an error</li> <li>I have tried to create the below python snippet to generate a date of birth [for age less than 18 years old] and kindly need expert opinions to know if this is indeed the correct/best approach?</li> </ol> <pre><code>start_date = date.today() - relativedelta(years=18) end_date = date.today() time_between_dates = end_date - start_date days_between_dates = time_between_dates.days random_number_of_days = random.randrange(days_between_dates) random_date = start_date + datetime.timedelta(days=random_number_of_days) month = random_date.month day = random_date.day year = random_date.year # Once I have the the day, month, year then I can convert it in ISO date format as per my needs </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T09:28:53.830", "Id": "510150", "Score": "0", "body": "Do you really need *random* dates for testing? Usually, good tests focus on the boundary conditions, so you'd want to use dates including exactly 18 years, the same ±1day, and at the other extreme, today and tomorrow. A really good test will allow the \"today\" date to be passed into the code under test, so we can check the right behaviour when the birthday or the present day is 29 February." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T13:43:24.170", "Id": "510168", "Score": "1", "body": "@TobySpeight what you say is true for a generic unit test. For a fuzzer you actually do need random input. It's not clear that the OP appreciates this distinction mind you." } ]
[ { "body": "<p><code>datetime.date</code> has a <code>.replace()</code> method that returns a copy with some values changed. This can be used to get the date 18 years ago.</p>\n<pre><code>end_date = date.today()\nstart_date = end_date.replace(year=end_date.year - 18)\n</code></pre>\n<p><code>datetime.date.toordinal</code> returns an integer corresponding to the date. The ordinals for the start and stop date can be used in <code>random.randint()</code> to pick a random ordinal, which can then be converted back into a date with <code>date.fromordinal()</code>.</p>\n<pre><code>random_date = date.fromordinal(random.randint(start_date.toordinal(), end_date.toordinal()))\n</code></pre>\n<p><code>date.isoformat()</code> returns a date a as YYYY-MM-DD. Or use <code>date.strftime()</code> for more control over the date format. In an f-string, a date is converted to ISO format, or a format string can be used: <code>f&quot;{random_date:%a, %b %d, %Y}&quot;</code> -&gt; <code>'Sat, Dec 14, 2013'</code>.</p>\n<p>If you want to generate a list of dates in the range, use <code>random.sample()</code> with a <code>range</code> object.</p>\n<pre><code>NUMBER_OF_DATES = 10\n\ndate_range = range(start_date.toordinal(), end_date.toordinal())\nrandom_dates = [date.fromordinal(o) for o in random.sample(date_range, NUMBER_OF_DATES)]\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T01:05:07.060", "Id": "257758", "ParentId": "257753", "Score": "6" } } ]
{ "AcceptedAnswerId": "257758", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T21:09:30.250", "Id": "257753", "Score": "0", "Tags": [ "python", "datetime" ], "Title": "Code to generate a random date of birth which will always represent an age less than 18 years from current date" }
257753
<p>I have a some code in which eslint thrown an error of the type: <code>import/no-cycle</code>, but I don't understand where this cyclic dependency comes from.</p> <p>The exact error thrown is: <code>ESLint: Dependency cycle via ../types:7=&gt;./Jobs:1(import/no-cycle)</code>.</p> <h3>File 1. jobs/Jobs</h3> <pre class="lang-js prettyprint-override"><code>import { AuthJobs } from './Auth'; export interface IJobs { auth: AuthJobs; // ... more types } </code></pre> <h3>File 2. jobs/types</h3> <pre class="lang-js prettyprint-override"><code>import { IJobs } from './Jobs'; // This class doesn't use IJobs export interface JobRunResponse&lt;D, F = undefined&gt; { data?: any; dataError?: JobErrorResponse&lt;D&gt;; } </code></pre> <h3>File 3. jobs/Auth/AuthJobs</h3> <pre class="lang-js prettyprint-override"><code>// Remember that in File 2, `JobRunResponse` doesn't use `IJobs` // which at the same time is the one that uses `AuthJobs` import { JobRunResponse } from '../types'; export class AuthJobs { // Class properties and methods } </code></pre> <h3>File 4. jobs/Auth/index</h3> <pre class="lang-js prettyprint-override"><code>// Here is where eslint thown the error export { AuthJobs } from './AuthJobs'; </code></pre> <h3>Folder structure</h3> <pre><code>jobs ├── Auth │   ├── AuthJobs.ts │   └── index.ts ├── Jobs.ts └── types.ts </code></pre> <p>Trying to understand where cyclical dependency comes from, I can think that when <code>JobRunResponse</code> from <code>../types</code> it's imported in <strong>File 3</strong>(jobs/Auth/AuthJobs), implicitly import <code>IJobs</code> that use <code>AuthJobs</code>, but this doesn't make sense, I can't find any other explanation.</p> <pre><code>jobs/Jobs -&gt; jobs/Auth/AuthJobs -&gt; jobs/Auth/index -&gt; jobs/Jobs </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T23:56:09.453", "Id": "509123", "Score": "2", "body": "All code in an imported module is executed irrespective of what reference you are importing. If you dont give the references to import eg`import {} from \"./Jobs\"` `import {} from \"./Auth\"` and `import {} from \"../types\"` the cyclic import will still exist." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-26T22:39:58.953", "Id": "257754", "Score": "0", "Tags": [ "javascript", "typescript" ], "Title": "Understanding import/no-cycle problem in eslint" }
257754
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with std::invocable concept in C++</a> and <a href="https://codereview.stackexchange.com/q/254096/231235">A recursive_transform Template Function Implementation with recursive_invoke_result_t and std::ranges::transform in C++</a>. Besides the version using <code>std::invocable</code>, I am attempting to implement another type <code>recursive_transform</code> function with the unwrap level parameter so that the usage like <code>recursive_transform&lt;1&gt;(Ranges, Lambda)</code> is available.</p> <p><strong>The experimental implementation</strong></p> <p>The experimental implementation of <code>recursive_transform</code> function with the unwrap level parameter is as follows.</p> <pre><code>// recursive_invoke_result_t implementation template&lt;typename, typename&gt; struct recursive_invoke_result { }; template&lt;typename T, std::invocable&lt;T&gt; F&gt; struct recursive_invoke_result&lt;F, T&gt; { using type = std::invoke_result_t&lt;F, T&gt;; }; template&lt;typename F, template&lt;typename...&gt; typename Container, typename... Ts&gt; requires ( !std::invocable&lt;F, Container&lt;Ts...&gt;&gt;&amp;&amp; std::ranges::input_range&lt;Container&lt;Ts...&gt;&gt;&amp;&amp; requires { typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type; }) struct recursive_invoke_result&lt;F, Container&lt;Ts...&gt;&gt; { using type = Container&lt;typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type&gt;; }; template&lt;typename F, typename T&gt; using recursive_invoke_result_t = typename recursive_invoke_result&lt;F, T&gt;::type; // recursive_transform implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, class T, class F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { if constexpr (unwrap_level &gt; 0) { recursive_invoke_result_t&lt;F, T&gt; output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element) { return recursive_transform&lt;unwrap_level - 1&gt;(element, f); } ); return output; } else { return f(input); } } </code></pre> <p><strong>Test cases</strong></p> <pre><code>// non-nested input test, lambda function applied on input directly int test_number = 3; std::cout &lt;&lt; recursive_transform&lt;0&gt;(test_number, [](auto&amp;&amp; element) { return element + 1; }) &lt;&lt; std::endl; // nested input test, lambda function applied on input directly std::vector&lt;int&gt; test_vector = { 1, 2, 3 }; std::cout &lt;&lt; recursive_transform&lt;0&gt;(test_vector, [](auto element) { element.push_back(4); element.push_back(5); return element; }).size() &lt;&lt; std::endl; // std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt; auto recursive_transform_result = recursive_transform&lt;1&gt;( test_vector, [](int x)-&gt;std::string { return std::to_string(x); } ); // For testing std::cout &lt;&lt; &quot;std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt;: &quot; + recursive_transform_result.at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0) is a std::string // std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt; std::cout &lt;&lt; &quot;std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt;: &quot; &lt;&lt; recursive_transform&lt;1&gt;( recursive_transform_result, [](std::string x) { return std::atoi(x.c_str()); }).at(0) + 1 &lt;&lt; std::endl; // std::string element to int // std::vector&lt;std::vector&lt;int&gt;&gt; -&gt; std::vector&lt;std::vector&lt;std::string&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2 = { test_vector, test_vector, test_vector }; auto recursive_transform_result2 = recursive_transform&lt;2&gt;( test_vector2, [](int x)-&gt;std::string { return std::to_string(x); } ); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result2.at(0).at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0).at(0) is also a std::string // std::deque&lt;int&gt; -&gt; std::deque&lt;std::string&gt; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(1); test_deque.push_back(1); auto recursive_transform_result3 = recursive_transform&lt;1&gt;( test_deque, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result3.at(0) &lt;&lt; std::endl; // std::deque&lt;std::deque&lt;int&gt;&gt; -&gt; std::deque&lt;std::deque&lt;std::string&gt;&gt; std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); auto recursive_transform_result4 = recursive_transform&lt;2&gt;( test_deque2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result4.at(0).at(0) &lt;&lt; std::endl; // std::list&lt;int&gt; -&gt; std::list&lt;std::string&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4 }; auto recursive_transform_result5 = recursive_transform&lt;1&gt;( test_list, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result5.front() &lt;&lt; std::endl; // std::list&lt;std::list&lt;int&gt;&gt; -&gt; std::list&lt;std::list&lt;std::string&gt;&gt; std::list&lt;std::list&lt;int&gt;&gt; test_list2 = { test_list, test_list, test_list, test_list }; auto recursive_transform_result6 = recursive_transform&lt;2&gt;( test_list2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result6.front().front() &lt;&lt; std::endl; </code></pre> <p>The output of the test code above:</p> <pre><code>4 5 std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt;: 1 std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt;: 2 string: 1 string: 1 string: 1 string: 1 string: 1 </code></pre> <p></p> <b>Full Testing Code</b> <p> <p>The full testing code:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;array&gt; #include &lt;cassert&gt; #include &lt;chrono&gt; #include &lt;complex&gt; #include &lt;concepts&gt; #include &lt;deque&gt; #include &lt;execution&gt; #include &lt;exception&gt; #include &lt;functional&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; #include &lt;list&gt; #include &lt;map&gt; #include &lt;mutex&gt; #include &lt;numeric&gt; #include &lt;optional&gt; #include &lt;ranges&gt; #include &lt;stdexcept&gt; #include &lt;string&gt; #include &lt;tuple&gt; #include &lt;type_traits&gt; #include &lt;utility&gt; #include &lt;variant&gt; #include &lt;vector&gt; // recursive_invoke_result_t implementation template&lt;typename, typename&gt; struct recursive_invoke_result { }; template&lt;typename T, std::invocable&lt;T&gt; F&gt; struct recursive_invoke_result&lt;F, T&gt; { using type = std::invoke_result_t&lt;F, T&gt;; }; template&lt;typename F, template&lt;typename...&gt; typename Container, typename... Ts&gt; requires ( !std::invocable&lt;F, Container&lt;Ts...&gt;&gt;&amp;&amp; std::ranges::input_range&lt;Container&lt;Ts...&gt;&gt;&amp;&amp; requires { typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type; }) struct recursive_invoke_result&lt;F, Container&lt;Ts...&gt;&gt; { using type = Container&lt;typename recursive_invoke_result&lt;F, std::ranges::range_value_t&lt;Container&lt;Ts...&gt;&gt;&gt;::type&gt;; }; template&lt;typename F, typename T&gt; using recursive_invoke_result_t = typename recursive_invoke_result&lt;F, T&gt;::type; // recursive_transform implementation (the version with unwrap_level) template&lt;std::size_t unwrap_level = 1, class T, class F&gt; constexpr auto recursive_transform(const T&amp; input, const F&amp; f) { if constexpr (unwrap_level &gt; 0) { recursive_invoke_result_t&lt;F, T&gt; output{}; std::ranges::transform( std::ranges::cbegin(input), std::ranges::cend(input), std::inserter(output, std::ranges::end(output)), [&amp;f](auto&amp;&amp; element) { return recursive_transform&lt;unwrap_level - 1&gt;(element, f); } ); return output; } else { return f(input); } } int main() { // non-nested input test, lambda function applied on input directly int test_number = 3; std::cout &lt;&lt; recursive_transform&lt;0&gt;(test_number, [](auto&amp;&amp; element) { return element + 1; }) &lt;&lt; std::endl; // nested input test, lambda function applied on input directly std::vector&lt;int&gt; test_vector = { 1, 2, 3 }; std::cout &lt;&lt; recursive_transform&lt;0&gt;(test_vector, [](auto element) { element.push_back(4); element.push_back(5); return element; }).size() &lt;&lt; std::endl; // std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt; auto recursive_transform_result = recursive_transform&lt;1&gt;( test_vector, [](int x)-&gt;std::string { return std::to_string(x); } ); // For testing std::cout &lt;&lt; &quot;std::vector&lt;int&gt; -&gt; std::vector&lt;std::string&gt;: &quot; + recursive_transform_result.at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0) is a std::string // std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt; std::cout &lt;&lt; &quot;std::vector&lt;string&gt; -&gt; std::vector&lt;int&gt;: &quot; &lt;&lt; recursive_transform&lt;1&gt;( recursive_transform_result, [](std::string x) { return std::atoi(x.c_str()); }).at(0) + 1 &lt;&lt; std::endl; // std::string element to int // std::vector&lt;std::vector&lt;int&gt;&gt; -&gt; std::vector&lt;std::vector&lt;std::string&gt;&gt; std::vector&lt;decltype(test_vector)&gt; test_vector2 = { test_vector, test_vector, test_vector }; auto recursive_transform_result2 = recursive_transform&lt;2&gt;( test_vector2, [](int x)-&gt;std::string { return std::to_string(x); } ); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result2.at(0).at(0) &lt;&lt; std::endl; // recursive_transform_result.at(0).at(0) is also a std::string // std::deque&lt;int&gt; -&gt; std::deque&lt;std::string&gt; std::deque&lt;int&gt; test_deque; test_deque.push_back(1); test_deque.push_back(1); test_deque.push_back(1); auto recursive_transform_result3 = recursive_transform&lt;1&gt;( test_deque, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result3.at(0) &lt;&lt; std::endl; // std::deque&lt;std::deque&lt;int&gt;&gt; -&gt; std::deque&lt;std::deque&lt;std::string&gt;&gt; std::deque&lt;decltype(test_deque)&gt; test_deque2; test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); test_deque2.push_back(test_deque); auto recursive_transform_result4 = recursive_transform&lt;2&gt;( test_deque2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result4.at(0).at(0) &lt;&lt; std::endl; // std::list&lt;int&gt; -&gt; std::list&lt;std::string&gt; std::list&lt;int&gt; test_list = { 1, 2, 3, 4 }; auto recursive_transform_result5 = recursive_transform&lt;1&gt;( test_list, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result5.front() &lt;&lt; std::endl; // std::list&lt;std::list&lt;int&gt;&gt; -&gt; std::list&lt;std::list&lt;std::string&gt;&gt; std::list&lt;std::list&lt;int&gt;&gt; test_list2 = { test_list, test_list, test_list, test_list }; auto recursive_transform_result6 = recursive_transform&lt;2&gt;( test_list2, [](int x)-&gt;std::string { return std::to_string(x); }); // For testing std::cout &lt;&lt; &quot;string: &quot; + recursive_transform_result6.front().front() &lt;&lt; std::endl; return 0; } </code></pre> </p> <p><a href="https://godbolt.org/z/bYvdKnfex" rel="nofollow noreferrer">A Godbolt link is here.</a></p> <p>All suggestions are welcome.</p> <p>The summary information:</p> <ul> <li><p>Which question it is a follow-up to?</p> <p><a href="https://codereview.stackexchange.com/q/253556/231235">A recursive_transform Template Function Implementation with std::invocable concept in C++</a> and</p> <p><a href="https://codereview.stackexchange.com/q/254096/231235">A recursive_transform Template Function Implementation with recursive_invoke_result_t and std::ranges::transform in C++</a></p> </li> <li><p>What changes has been made in the code since last question?</p> <p>The type <code>recursive_transform</code> function with the unwrap level parameter is the main idea here.</p> </li> <li><p>Why a new review is being asked for?</p> <p>If there is any possible improvement, please let me know.</p> </li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T00:00:13.790", "Id": "257757", "Score": "3", "Tags": [ "c++", "recursion", "template", "lambda", "c++20" ], "Title": "A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++" }
257757
<p>I've been interested in making fully repeatable, reproducible game states. This led me into the world of DDD, and specifically, the concept of Aggregates + Event Sourcing (although that's not necessarily a DDD concept). In this context, the state of the Aggregate is reconstituted from a sequence of Domain Events, each Event representing some change to the Aggregate. This gave me one portion of reproducibility, returning to an exact state based on a sequence of Events.</p> <pre><code>new state = old state + event </code></pre> <p>Another piece of wisdom I read from the DDD books (Domain-Driven Design, and Implementing Domain-Driven Design), is that Value Objects should probably be used more often than initially realized; leaving Entities to be more focused as Value Object containers. Additionally, Value Objects can be maintained as Immutable. This means though that when a change needs to happen to one of these Value Objects, the object is replaced in the container, rather than being changed in place. So I needed a way of getting, or generating these Events. The IDDD book mentions in the Event Sourcing in Functional Languages section that Aggregate methods can be transformed into stateless functions that take the Command, any Domain Services, and returns a list of Events.</p> <pre><code>events = state + command </code></pre> <p>This kind of notation in both places led me to overloading the plus operator.</p> <p>With both of these pieces, I'm able to model changing any Value Object or Entity in a more functional, stateless way, using only Commands or Events.</p> <p>In the following code, we have three categories of objects. We have the Brazier objects, which react to Brazier Commands, by responding with Brazier Events. Braziers can be reconstituted from Brazier Events, to bring a Brazier to a given state. Brazier Events are the result of a given state, plus a Command.</p> <h2>What I'm looking for</h2> <ul> <li>I'm worried that perhaps I'm misusing, or abusing the plus operator convention. When I think about other examples I've seen, they have been closed over the type that implemented the operator. For instance, Int + Int = Int, Double + Double = Double, Money + Money = Money. This though is Brazier + Command = Events. I don't think anything I've read says that the operator should, or must be closed over a single type, so maybe it's just something that I don't need to worry about.</li> <li>In my previous iteration (not on code review), the Brazier class had an <code>isLit: Boolean</code> property. Since there were only two options, true or false, I made them objects in a sealed class hierarchy. In other contexts, they could still be part of a sealed hierarchy like this, maybe being objects, maybe being classes, depending on if some other state is required. Since these specific classes, like Brazier, will only react to, or respond with, specific Commands and Events, there's kind of naturally a finite number of possible combinations, which seems like it might fit well with a sealed hierarchy like this, but I'm also wondering if this isn't a great use of the sealed hierarchies. It does seem to nicely simplify the handling methods though, given that all cases are mentioned in the when.</li> <li>This pattern seems like it would work well for an Aggregate. But there's this awkward feeling with regards to using it with Value Objects that I can't quite explain. Sure, the result is Immutable, and the ways the Value Object can change are clearly defined, but it feels more like Value Object operations should be closed over the type, but again, maybe this is just an uncomfortable feeling that shouldn't weigh very much.</li> </ul> <pre class="lang-kotlin prettyprint-override"><code>sealed class BrazierCommand object LightBrazier : BrazierCommand() object ExtinguishBrazier : BrazierCommand() sealed class BrazierEvent object BrazierLit : BrazierEvent() object BrazierExtinguished : BrazierEvent() sealed class Brazier { companion object { fun fromEvents( events: Iterable&lt;BrazierEvent&gt;, initial: Brazier = UnlitBrazier, ): Brazier = events.fold(initial, Brazier::plus) } operator fun plus(command: BrazierCommand): Iterable&lt;BrazierEvent&gt; = when (command) { is LightBrazier -&gt; listOf(BrazierLit) is ExtinguishBrazier -&gt; listOf(BrazierExtinguished) } operator fun plus(event: BrazierEvent): Brazier = when (event) { is BrazierLit -&gt; LitBrazier is BrazierExtinguished -&gt; UnlitBrazier } } object LitBrazier : Brazier() object UnlitBrazier : Brazier() </code></pre> <p>Some tests that illustrate usage:</p> <pre class="lang-kotlin prettyprint-override"><code>import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class BrazierTests { @Test fun `UnlitBrazier plus LightBrazier equals BrazierLit`() { val brazierEvents = UnlitBrazier + LightBrazier assertEquals(BrazierLit, brazierEvents.single()) } @Test fun `LitBrazier plus ExtinguishBrazier equals BrazierExtinguished`() { val brazierEvents = LitBrazier + ExtinguishBrazier assertEquals(BrazierExtinguished, brazierEvents.single()) } @Test fun `UnlitBrazier plus BrazierLit equals LitBrazier`() { val brazier = UnlitBrazier + BrazierLit assertEquals(LitBrazier, brazier) } @Test fun `LitBrazier plus BrazierExtinguished equals UnlitBrazier`() { val brazier = LitBrazier + BrazierExtinguished assertEquals(UnlitBrazier, brazier) } @Test fun `reconstitute LitBrazier from events`() { val events = listOf( BrazierLit, ) val brazier = Brazier.fromEvents(events) assertEquals(LitBrazier, brazier) } } </code></pre>
[]
[ { "body": "<p>Very interesting question! Makes me want to read more about the DDD topic, which I should :-)</p>\n<p>For now at least to answer one of your questions:</p>\n<p>Not sure for <code>plus</code>, but <code>times/div</code> operator is definitely okay to use for different types. It's typical for multiplication or division with scalar. Imagine for example 2D Vector multiplied by scalar value. Then signature would be something like:</p>\n<pre><code>operator fun Vector.times(ratio: Float): Vector {\n return Vector(x = x * ratio, y = y * ratio)\n}\n</code></pre>\n<p>I am not sure though, if plus as an operator is the correct way to go. Can't think of real-world example, where you are adding 2 completely different types returning 3rd. Is there a better name for the operation? Is that really &quot;adding&quot;? Maybe so, maybe not.</p>\n<p>Definitely consider infix notation as alternative too:\n<a href=\"https://kotlinlang.org/docs/functions.html#infix-notation\" rel=\"nofollow noreferrer\">https://kotlinlang.org/docs/functions.html#infix-notation</a></p>\n<p>Edit:</p>\n<p>I don't like implementations of your plus and minus function - this branching using when. The whole point of classing is that you can get result without having to decide based on instance.\nMaybe <code>BrazierEvent</code> class should have a field, that is supposed to be returned to basically do mapping you have there, ex. <code>BrazierLit -&gt; LitBrazier</code> and <code>BrazierExtinguished -&gt; UnlitBrazier</code>. Same goes for minus and that functionality. It should be inside of <code>BrazierCommand</code> class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-07T17:25:17.537", "Id": "511189", "Score": "0", "body": "Yeah, previously I had a different naming pattern. `applyEvent`, and then separate command methods, `light` or `extinguish`, which I changed to an `applyCommand` method. At this point, I started using the infix notation, like `newState = oldState applyEvent event`. Then, while I was writing some notes about the structure, I started using the plus notation mentioned in the OP. That's what lead me to think about it in terms of the plus operator. But yeah, it's not quite adding. Thanks again for the feedback!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-12T21:55:38.417", "Id": "511698", "Score": "0", "body": "No worries, looking back at it again, I added edit to comment on one more code smell." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-18T02:19:14.253", "Id": "512241", "Score": "0", "body": "Thanks for the edit. My usage of the Sealed Class + When (is) was partially inspired by this section from the Kotlin documentation (https://kotlinlang.org/docs/sealed-classes.html#sealed-classes-and-when-expression) where it says \"The key benefit of using sealed classes comes into play when you use them in a when expression.\"" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-06T19:39:37.087", "Id": "259176", "ParentId": "258757", "Score": "1" } } ]
{ "AcceptedAnswerId": "259176", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T03:29:10.673", "Id": "258757", "Score": "2", "Tags": [ "functional-programming", "kotlin", "ddd" ], "Title": "A Stateless Immutable Event-Driven DDD Pattern in Kotlin" }
258757
<p>My code currently:</p> <pre><code>import os import pandas as pd from selenium import webdriver from tabulate import tabulate from datetime import datetime import time from bs4 import BeautifulSoup as bs start = datetime.now() browser = webdriver.Chrome() class GameData: def __init__(self): self.date = [] self.time = [] self.game = [] self.score = [] self.home_odds = [] self.draw_odds = [] self.away_odds = [] def parse_data(url): browser.get(url) df = pd.read_html(browser.page_source, header=0)[0] time.sleep(3) html = browser.page_source soup = bs(html,&quot;lxml&quot;) cont = soup.find('div', {'id':'wrap'}) conti = cont.find('div', {'id':'col-content'}) content = conti.find('table', {'class':'table-main'}, {'id':'tournamentTable'}) main = content.find('th', {'class':'first2 tl'}) count = main.findAll('a') country = count[1].text league = count[2].text game_data = GameData() game_date = None for row in df.itertuples(): if not isinstance(row[1], str): continue elif ':' not in row[1]: game_date = row[1].split('-')[0] continue game_data.date.append(game_date) game_data.time.append(row[1]) game_data.game.append(row[2]) game_data.score.append(row[3]) game_data.home_odds.append(row[4]) game_data.draw_odds.append(row[5]) game_data.away_odds.append(row[6]) browser.quit() return game_data, country, league # You can input as many URLs you want urls = { &quot;https://www.oddsportal.com/soccer/europe/champions-league/results/&quot; } if __name__ == '__main__': results = None for url in urls: game_data, country, competition = parse_data(url) result = pd.DataFrame(game_data.__dict__) result['country'] = country result['competition'] = competition if results is None: results = result else: results = results.append(result, ignore_index=True) results | | date | time | game | score | home_odds | draw_odds | away_odds | country | competition | |----|-------------|--------|--------------------------------------|---------|-------------|-------------|-------------|-----------|------------------| | 0 | 17 Mar 2021 | 20:00 | Bayern Munich - Lazio | 2:1 | 1.35 | 6.02 | 7.53 | Europe | Champions League | | 1 | 17 Mar 2021 | 20:00 | Chelsea - Atl. Madrid | 2:0 | 2.33 | 3.1 | 3.49 | Europe | Champions League | | 2 | 16 Mar 2021 | 20:00 | Manchester City - B. Monchengladbach | 2:0 | 1.28 | 6.25 | 10.17 | Europe | Champions League | | 3 | 16 Mar 2021 | 20:00 | Real Madrid - Atalanta | 3:1 | 2.26 | 3.6 | 3.16 | Europe | Champions League | | 4 | 10 Mar 2021 | 20:00 | Liverpool - RB Leipzig | 2:0 | 2.37 | 3.8 | 2.85 | Europe | Champions League | </code></pre> <p>How can I make this code better for readability?</p> <p>Also, since CR is asking to explain further, (mods can delete this)</p>
[]
[ { "body": "<p>Some quick comments. Since your request is about readability, you can do three things at least:</p>\n<ul>\n<li>get rid of unused variables eg: <code>start = datetime.now()</code></li>\n<li>improve the naming conventions for your variables: variables like <code>cont</code> or <code>conti are</code> quite similar (risk of typos/confusion) but the names are not intuitive and do not accurately describe the data you are manipulating. <code>count</code> is also too generic to be meaningful. Note that game_date looks confusingly similar to game_data and you even have a line: <code>game_data.date.append(game_date)</code>. I think the risk of typo bugs is not negligible here.</li>\n<li>add some line spacing here and there, plus a few comments. You can afford it as the code is less than 100 lines of code, so the implementation is reasonable and not bloated.</li>\n</ul>\n<p>I don't think the class <code>GameData</code> is really useful the way it is implemented. To get the final printable result you could stick with a dataframe, you already have one, so see if it can be transformed further or transposed to another.</p>\n<p>You have <code>time.sleep</code> after <code>pd.read_html</code>, but it does not guarantee that the page will be fully loaded. There are several functions in Selenium that you can use to wait for the presence of a given element. But probably you could use the requests module instead. On sites that use JS/Ajax, you may have no other choice but to use Selenium, but it takes more effort to do it right.</p>\n<p>It would be good to add some <strong>validation</strong> to make sure that the result of your scraping is not void. Otherwise the processing will be wrong and return garbage. The BS <code>find</code> function will return None if the element is not found. So all you have to do is something like:</p>\n<pre><code>if None in (cont, conti, content, main):\n</code></pre>\n<p>or you can use the <code>any</code> function for this purpose.\nHowever, <code>findAll</code> has a different behavior and will return an empty list if there is no matching element found.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T00:23:11.377", "Id": "510282", "Score": "0", "body": "Thanks. Very useful.\n\n`I don't think the class GameData is really useful the way it is implemented. To get the final printable result you could stick with a dataframe, you already have one, so see if it can be transformed further or transposed to another`\n\nCan you help me with this bit?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T21:19:19.503", "Id": "258785", "ParentId": "258761", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T11:17:57.500", "Id": "258761", "Score": "2", "Tags": [ "python" ], "Title": "Scraping game data from web" }
258761
<p>This program tokenizes an arithmetic expression specified in infix notation. It is one of my personal projects and I would love to receive expert advice.</p> <p>After compiling, you can run the program with one command-line argument:</p> <pre class="lang-sh prettyprint-override"><code>$ tokenize &lt;arith_expr&gt; </code></pre> <p>This is an example of running the program:</p> <pre class="lang-sh prettyprint-override"><code>$ tokenize &quot;3^2 + 4.5 * (-2 - 1)&quot; </code></pre> <p>The tokenizer currently supports these operators <code>+ - * / ^</code>.</p> <pre><code>#include &lt;ctype.h&gt; #include &lt;stdbool.h&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; /* Can store an operator or an operand */ struct token { char operator; float operand; }; /* Check if given token is an operator */ bool is_operator(char token) { if (token == '+' || token == '-' || token == '*' || token == '/' || token == '^') return true; else return false; } /* Remove all spaces from string */ void rmspaces(char *str) { const char *dup = str; do { while (isspace(*dup)) ++dup; } while (*str++ = *dup++); } /* Return first token of given arithmetic expression */ struct token *tokenize(char **expr) { static bool op_allowed = false; struct token *token = malloc(sizeof *token); if (!token) { printf(&quot;Error: memory allocation failed&quot;); exit(EXIT_FAILURE); } if (op_allowed &amp;&amp; is_operator(*expr[0])) { token-&gt;operator = *expr[0]; ++(*expr); op_allowed = false; } else if (!op_allowed &amp;&amp; *expr[0] == '(') { token-&gt;operator = *expr[0]; ++(*expr); } else if (op_allowed &amp;&amp; *expr[0] == ')') { token-&gt;operator = *expr[0]; ++(*expr); } else { char *rest; token-&gt;operand = strtof(*expr, &amp;rest); token-&gt;operator = '\0'; if (*expr == rest) { printf(&quot;Invalid expression\n&quot;); exit(EXIT_FAILURE); } strcpy(*expr, rest); op_allowed = true; } return token; } /* Handle command line arguments */ int main(int argc, char *argv[]) { if (argc != 2) { printf(&quot;Usage: %s &lt;arith_expr&gt;\n&quot; &quot;Example: %s \&quot;5 2 3 * +\&quot;\n&quot;, argv[0], argv[0]); exit(EXIT_FAILURE); } char *expr = argv[1]; rmspaces(expr); struct token *token; while (expr[0] != '\0') { token = tokenize(&amp;expr); if (token-&gt;operator == '\0') // token is operand printf(&quot;%f\n&quot;, token-&gt;operand); else printf(&quot;%c\n&quot;, token-&gt;operator); } return EXIT_SUCCESS; } </code></pre>
[]
[ { "body": "<p>Your <code>is_operator</code> function can be rewritten as</p>\n<pre><code>return token == '+' || token == '-' || token == '*' || token == '/' || token == '^';\n</code></pre>\n<p>Much cleaner, in my opinion.</p>\n<hr />\n<p>The program has a memory leak. Your <code>tokenize</code> function allocates a <code>struct token</code> on the heap, but the object is never freed.</p>\n<p>Better yet, instead of returning a <code>struct token*</code>, just return a <code>struct token</code>. The struct certainly isn't large enough to warrant an allocation on the heap.</p>\n<hr />\n<p>Instead of checking whether <code>token</code> is an operand by comparing <code>operator</code> to <code>0</code>, use an enum.</p>\n<pre><code>typedef enum { \n TokenType_Operator, \n TokenType_Operand \n} token_type;\n</code></pre>\n<p>Then your <code>token</code> struct can consist of the <code>token_type</code> enum, and an union.</p>\n<pre><code>struct token\n{\n token_type type;\n union {\n char operator;\n float operand;\n } data;\n};\n</code></pre>\n<p>If you're using C11, you don't even need to name the union anything.</p>\n<hr />\n<p>As a next step, try to implement a tokenizer that tokenizes in one pass. Right now, your tokenizer 1) removes whitespace (which involves a linear pass) and 2) copies of the rest of the string after the tokenizing an operand into the original buffer. If you have a large buffer, this could become a bottleneck.</p>\n<p>A common way to implement a tokenizer is using a DFA (deterministic finite automata). In fact, a DFA is a starting point for most handwritten lexers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T15:02:26.507", "Id": "510173", "Score": "0", "body": "The tokenizer is part of [a calculator I programmed](https://codereview.stackexchange.com/questions/257409) and the points you mentioned are very helpful, thanks!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T14:26:37.690", "Id": "258768", "ParentId": "258763", "Score": "4" } }, { "body": "<pre><code>while (isspace(*dup))\n</code></pre>\n<p>has a common mistake, but it is <em>wrong</em>. For example Linux manuals have this in their notes:</p>\n<blockquote>\n<p>NOTES\nThe standards require that the argument c for these functions is either EOF or a value that is representable in the type unsigned\nchar. If the argument c\nis of type char, it must be cast to unsigned char, as in the following example:</p>\n<pre><code>char c;\n...\nres = toupper((unsigned char) c);\n</code></pre>\n<p>This is necessary because char may be the equivalent of signed char, in which case a byte where the top bit is set would be sign\nextended when converting to\nint, yielding a value that is outside the range of unsigned char.</p>\n</blockquote>\n<hr />\n<p>For <code>isoperator</code> I would use</p>\n<pre><code>return token &amp;&amp; strchr(&quot;+-*/^&quot;, token);\n</code></pre>\n<p><code>strchr</code> returns the pointer to the first occurrence of the given character in the string, and NULL pointer if not found. The <code>token &amp;&amp;</code> part is to make sure that <code>token</code> is not the NUL character, because <code>strchr</code> does return a pointer to the terminator if 2nd argument is the NUL character.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T12:59:30.950", "Id": "510949", "Score": "0", "body": "Thanks! I will take your suggestions into consideration." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-05T12:56:03.540", "Id": "259118", "ParentId": "258763", "Score": "2" } } ]
{ "AcceptedAnswerId": "258768", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T11:37:06.390", "Id": "258763", "Score": "5", "Tags": [ "algorithm", "c", "calculator", "lexer" ], "Title": "Tokenize arithmetic expression in C" }
258763
<p>This is an algorithm regarding the <a href="https://en.wikipedia.org/wiki/Runge%E2%80%93Kutta%E2%80%93Fehlberg_method" rel="nofollow noreferrer">RKF method</a>:</p> <pre><code>import numpy as np class rkf(): def __init__(self,f, a, b, x0, atol, rtol, hmax, hmin): self.f=f self.a=a self.b=b self.x0=x0 self.atol=atol self.rtol=rtol self.hmax=hmax self.hmin=hmin def solve(self): a2 = 2.500000000000000e-01 # 1/4 a3 = 3.750000000000000e-01 # 3/8 a4 = 9.230769230769231e-01 # 12/13 a5 = 1.000000000000000e+00 # 1 a6 = 5.000000000000000e-01 # 1/2 b21 = 2.500000000000000e-01 # 1/4 b31 = 9.375000000000000e-02 # 3/32 b32 = 2.812500000000000e-01 # 9/32 b41 = 8.793809740555303e-01 # 1932/2197 b42 = -3.277196176604461e+00 # -7200/2197 b43 = 3.320892125625853e+00 # 7296/2197 b51 = 2.032407407407407e+00 # 439/216 b52 = -8.000000000000000e+00 # -8 b53 = 7.173489278752436e+00 # 3680/513 b54 = -2.058966861598441e-01 # -845/4104 b61 = -2.962962962962963e-01 # -8/27 b62 = 2.000000000000000e+00 # 2 b63 = -1.381676413255361e+00 # -3544/2565 b64 = 4.529727095516569e-01 # 1859/4104 b65 = -2.750000000000000e-01 # -11/40 r1 = 2.777777777777778e-03 # 1/360 r3 = -2.994152046783626e-02 # -128/4275 r4 = -2.919989367357789e-02 # -2197/75240 r5 = 2.000000000000000e-02 # 1/50 r6 = 3.636363636363636e-02 # 2/55 c1 = 1.157407407407407e-01 # 25/216 c3 = 5.489278752436647e-01 # 1408/2565 c4 = 5.353313840155945e-01 # 2197/4104 c5 = -2.000000000000000e-01 # -1/5 t = self.a x = np.array(self.x0) h = self.hmax T = np.array( [t] ) X = np.array( [x] ) while t &lt; self.b: if t + h &gt; self.b: h = self.b - t k1 = h * self.f(t, x) k2 = h * self.f(t + a2 * h, x + b21 * k1 ) k3 = h * self.f(t + a3 * h, x + b31 * k1 + b32 * k2) k4 = h * self.f(t + a4 * h, x + b41 * k1 + b42 * k2 + b43 * k3) k5 = h * self.f(t + a5 * h, x + b51 * k1 + b52 * k2 + b53 * k3 + b54 * k4) k6 = h * self.f(t + a6 * h, x + b61 * k1 + b62 * k2 + b63 * k3 + b64 * k4 + b65 * k5) r = abs( r1 * k1 + r3 * k3 + r4 * k4 + r5 * k5 + r6 * k6 ) / h r = r / (self.atol+self.rtol*(abs(x)+abs(k1))) if len( np.shape( r ) ) &gt; 0: r = max( r ) if r &lt;= 1: t = t + h x = x + c1 * k1 + c3 * k3 + c4 * k4 + c5 * k5 T = np.append( T, t ) X = np.append( X, [x], 0 ) h = h * min( max( 0.94 * ( 1 / r )**0.25, 0.1 ), 4.0 ) if h &gt; self.hmax: h = self.hmax elif h &lt; self.hmin or t==t-h: raise RuntimeError(&quot;Error: Could not converge to the required tolerance.&quot;) break return (T,X) </code></pre> <p>Which works just fine, but I was wondering if is it possible to make this even faster and more efficient?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T13:32:06.243", "Id": "510166", "Score": "1", "body": "This looks like an excerpt of a class method. Please show all of your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T16:05:39.343", "Id": "510176", "Score": "0", "body": "@Reinderien As you requested, I just did." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T16:32:49.000", "Id": "510180", "Score": "2", "body": "It's generally a good idea to include [type hints](https://www.python.org/dev/peps/pep-0484/) to increase the readability of and document your program. Also take a look at Python [naming conventions](https://realpython.com/python-pep8/#naming-conventions) for classes (CamelCase) and variables (lowercase only). Lastly, you don't need the empty brackets in `class rkf():` --> `class RKF:`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T16:52:21.517", "Id": "510181", "Score": "2", "body": "@riskypenguin That feedback belongs in an answer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T17:00:31.367", "Id": "510183", "Score": "1", "body": "Also, I'm not sure you implemented the algorithm correctly. After a quick look at the Wikipedia article, there seems to be a few notable differences between your implementation and the one described on Wikipedia, but since I don't know much about your code or what it's supposed to accomplish, I can't tell if those are intended or not." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T18:43:53.180", "Id": "510200", "Score": "0", "body": "@cliesnes The main difference between my implementation and the one in Wikipedia, is that Wikipedia only defines \"Tolerance\" and hence, cannot efficiently tackle a system of ODEs (specially when the ODEs have different order of magnitudes) . But I used the absolute Tolerance and relative tolerance to tackle that problem. Besides that, the main algorithm is the same as Wiki's." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T18:47:30.040", "Id": "510201", "Score": "0", "body": "@riskypenguin Thanks for your feedback, I'll try my best to name everything better next time :)) but I was hoping that you would have any thoughts on how to increase the efficiency of this code... somehow(?) Since I think the main algorithm is straightforward (?)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T07:30:11.010", "Id": "510316", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." } ]
[ { "body": "<p>All these lines are really weird:</p>\n<pre><code>a4 = 9.230769230769231e-01 # 12/13\n</code></pre>\n<p>Unless you have a good reason (which I'd then state in the code as a comment) to do that, just write <code>a4 = 12/13</code> instead.</p>\n<p>Gonna be the same anyway:</p>\n<pre><code>&gt;&gt;&gt; import dis\n&gt;&gt;&gt; dis.dis('a4 = 12/13')\n 1 0 LOAD_CONST 0 (0.9230769230769231)\n 2 STORE_NAME 0 (a4)\n 4 LOAD_CONST 1 (None)\n 6 RETURN_VALUE\n&gt;&gt;&gt; dis.dis('a4 = 9.230769230769231e-01')\n 1 0 LOAD_CONST 0 (0.9230769230769231)\n 2 STORE_NAME 0 (a4)\n 4 LOAD_CONST 1 (None)\n 6 RETURN_VALUE\n</code></pre>\n<p>This line for example is not right:</p>\n<pre><code>b51 = 2.032407407407407e+00 # 439/216\n</code></pre>\n<p>The values differ slightly, your value being less accurate:</p>\n<pre><code>&gt;&gt;&gt; 2.032407407407407e+00\n2.032407407407407\n&gt;&gt;&gt; 439/216\n2.0324074074074074\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T22:05:22.920", "Id": "510211", "Score": "0", "body": "I'm not sure your if suggestion would make the code more efficient. Do you have any thoughts on the main algorithm? (By main algorithm, I mean what happens in the while loop)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T00:29:50.347", "Id": "510217", "Score": "1", "body": "Since I showed that it's gonna be the same (except for the minor value differences), you should be sure that it does *not* make it more efficient :-). No other thoughts, looks too complicated for me right now and I'm a newb at numpy." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T20:07:36.653", "Id": "258779", "ParentId": "258764", "Score": "2" } }, { "body": "<p>A significant improvement is to use lists and Python's built in append and convert the final list to array, instead of using np.append. I've run a test to demonstrate the performance enhancement:</p>\n<pre><code>def lorenz(t,u):\n s=10\n r=24\n b=8/3\n x,y,z=u\n vx=s*y-s*x\n vy=r*x-x*z-y\n vz=x*y-b*z\n return np.array([vx,vy,vz])\n\nx0=[2,2,2]\n\nt, u = rkf( f=lorenz, a=0, b=1e+3, x0=x0, atol=1e-8, rtol=1e-6 , hmax=1e-1, hmin=1e-40,show_info=True).solve()\n</code></pre>\n<p>Now, when using numpy arrays and np.append I get:</p>\n<pre><code>Execution time: 56.7198397 seconds\nNumber of data points: 120732\n</code></pre>\n<p>Using list and Python's append:</p>\n<pre><code>Execution time: 8.3110496 seconds\nNumber of data points: 120732\n</code></pre>\n<p>Which is a huge difference on the performance. Also another slight improvement is to use sqrt(sqrt()) instead of **0.25 :</p>\n<pre><code>h = h * min( max( 0.94 * sqrt(sqrt( 1 / r )), 0.1 ), 4.0 ) \n</code></pre>\n<p>Feel free to add your thoughts and suggestions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T13:54:34.370", "Id": "510347", "Score": "1", "body": "I suspect that the performance boost of using the built-in isn't due to stock Python being faster, but rather misuse of numpy. Rather than appends, having a fixed-size array and doing slice assignments to it should help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T18:42:16.140", "Id": "258812", "ParentId": "258764", "Score": "2" } }, { "body": "<ul>\n<li><p>If you're already using Numpy and you find that you are motivated to do loop unrolling in an attempt to make things fast, it's time to switch to C and use lower-level vectorized libraries</p>\n</li>\n<li><p>Your class does not deserve to be a class, and should just be a function</p>\n</li>\n<li><p>You should add type hints</p>\n</li>\n<li><p>There is really no reason to pre-compute your fractions as you have. This makes so marginal a speed difference, at a cost of so worse a legibility and maintainability, that it isn't worth it compared to other efforts like switching language</p>\n</li>\n<li><p><code>k</code>, <code>A</code>, <code>R</code> and <code>C</code> are obviously vectors, and <code>B</code> is obviously a triangular matrix. Best to actually represent them as such.</p>\n</li>\n<li><p>Since <code>T</code> and <code>X</code> are being frequently reallocated, there's no advantage to using numpy - just use Python lists</p>\n</li>\n<li><p>Your calculation for <code>k</code> is actually a series of dot-products, and so it's best to just call into <code>np.dot</code></p>\n</li>\n<li><p>You're not using in-place operators where you should, i.e. <code>t = t + h</code> should just be <code>t += h</code></p>\n</li>\n<li><p>This condition:</p>\n<pre><code> if t + h &gt; self.b:\n h = self.b - t\n</code></pre>\n</li>\n</ul>\n<p>is more legible as</p>\n<pre><code> if h &gt; b - t:\n h = b - t\n</code></pre>\n<p>When doing all of the above, I experience a marginal slowdown of 4.2 us in exchange for greater legibility and maintainability, and centralized constants.</p>\n<h2>Alternate implementation</h2>\n<pre><code>from functools import partial\nfrom timeit import timeit\nfrom typing import Callable, Tuple, Sequence\n\nimport numpy as np\n\n\nclass rkf_old():\n\n def __init__(self, f, a, b, x0, atol, rtol, hmax, hmin):\n self.f = f\n self.a = a\n self.b = b\n self.x0 = x0\n self.atol = atol\n self.rtol = rtol\n self.hmax = hmax\n self.hmin = hmin\n\n def solve(self):\n\n a2 = 2.500000000000000e-01 # 1/4\n a3 = 3.750000000000000e-01 # 3/8\n a4 = 9.230769230769231e-01 # 12/13\n a5 = 1.000000000000000e+00 # 1\n a6 = 5.000000000000000e-01 # 1/2\n\n b21 = 2.500000000000000e-01 # 1/4\n b31 = 9.375000000000000e-02 # 3/32\n b32 = 2.812500000000000e-01 # 9/32\n b41 = 8.793809740555303e-01 # 1932/2197\n b42 = -3.277196176604461e+00 # -7200/2197\n b43 = 3.320892125625853e+00 # 7296/2197\n b51 = 2.032407407407407e+00 # 439/216\n b52 = -8.000000000000000e+00 # -8\n b53 = 7.173489278752436e+00 # 3680/513\n b54 = -2.058966861598441e-01 # -845/4104\n b61 = -2.962962962962963e-01 # -8/27\n b62 = 2.000000000000000e+00 # 2\n b63 = -1.381676413255361e+00 # -3544/2565\n b64 = 4.529727095516569e-01 # 1859/4104\n b65 = -2.750000000000000e-01 # -11/40\n\n r1 = 2.777777777777778e-03 # 1/360\n r3 = -2.994152046783626e-02 # -128/4275\n r4 = -2.919989367357789e-02 # -2197/75240\n r5 = 2.000000000000000e-02 # 1/50\n r6 = 3.636363636363636e-02 # 2/55\n\n c1 = 1.157407407407407e-01 # 25/216\n c3 = 5.489278752436647e-01 # 1408/2565\n c4 = 5.353313840155945e-01 # 2197/4104\n c5 = -2.000000000000000e-01 # -1/5\n\n t = self.a\n x = np.array(self.x0)\n h = self.hmax\n\n T = np.array([t])\n X = np.array([x])\n\n while t &lt; self.b:\n\n if t + h &gt; self.b:\n h = self.b - t\n\n k1 = h * self.f(t, x)\n k2 = h * self.f(t + a2 * h, x + b21 * k1)\n k3 = h * self.f(t + a3 * h, x + b31 * k1 + b32 * k2)\n k4 = h * self.f(t + a4 * h, x + b41 * k1 + b42 * k2 + b43 * k3)\n k5 = h * self.f(t + a5 * h, x + b51 * k1 + b52 * k2 + b53 * k3 + b54 * k4)\n k6 = h * self.f(t + a6 * h, x + b61 * k1 + b62 * k2 + b63 * k3 + b64 * k4 + b65 * k5)\n\n r = abs(r1 * k1 + r3 * k3 + r4 * k4 + r5 * k5 + r6 * k6) / h\n r = r / (self.atol + self.rtol * (abs(x) + abs(k1)))\n if len(np.shape(r)) &gt; 0:\n r = max(r)\n if r &lt;= 1:\n t = t + h\n x = x + c1 * k1 + c3 * k3 + c4 * k4 + c5 * k5\n T = np.append(T, t)\n X = np.append(X, [x], 0)\n h = h * min(max(0.94 * (1 / r) ** 0.25, 0.1), 4.0)\n if h &gt; self.hmax:\n h = self.hmax\n elif h &lt; self.hmin or t == t - h:\n raise RuntimeError(&quot;Error: Could not converge to the required tolerance.&quot;)\n break\n\n return (T, X)\n\n\ndef rkf(\n f: Callable[[float, float], float],\n a: float, b: float, x0: float,\n atol: float, rtol: float,\n hmax: float, hmin: float,\n) -&gt; Tuple[\n Sequence[float], Sequence[float],\n]:\n A = np.array((0, 1/4, 3/8, 12/13, 1, 1/2))\n B = np.array((\n ( 0, 0, 0, 0, 0, 0),\n ( 1/4, 0, 0, 0, 0, 0),\n ( 3/32, 9/32, 0, 0, 0, 0),\n (1932/2197, -7200/2197, 7296/2197, 0, 0, 0),\n ( 439/216, -8, 3680/513, -845/4104, 0, 0),\n ( -8/27, 2, -3544/2565, 1859/4104, -11/40, 0),\n ))\n R = np.array((1/360, 0, -128/4275, -2197/75240, 1/50, 2/55))\n C = np.array((25/216, 0, 1408/2565, 2197/4104, -1/5))\n\n k = np.empty((6,))\n t = a\n x = x0\n h = hmax\n\n T = [t]\n X = [x0]\n\n while t &lt; b:\n if h &gt; b - t:\n h = b - t\n\n Ta = A*h + t\n\n for i, ta in enumerate(Ta):\n k[i] = h * f(ta, x + np.dot(\n B[i, :i],\n k[:i],\n ))\n\n r = np.abs(np.dot(R, k)) / h\n r /= atol + rtol * (np.abs(x) + np.abs(k[0]))\n if len(np.shape(r)) &gt; 0:\n r = max(r)\n if r &lt;= 1:\n t += h\n x += np.dot(C, k[:5])\n T.append(t)\n X.append(x)\n h *= min(max(0.94 * (1 / r) ** 0.25, 0.1), 4.0)\n if h &gt; hmax:\n h = hmax\n elif h &lt; hmin or t == t - h:\n raise ValueError(&quot;Error: Could not converge to the required tolerance.&quot;)\n\n return T, X\n\n\ndef test_fun(t: float, k: float) -&gt; float:\n return 3*t - 2*k + 1/(t**2 + k**2)\n\n\ndef main():\n args = dict(f=test_fun, a=-3, b=11, x0=-1, atol=1e-3, rtol=-3, hmax=100, hmin=-100)\n\n old = rkf_old(**args).solve\n new = partial(rkf, **args)\n\n for method in (old, new):\n t, x = method()\n print(t)\n print(x)\n\n N = 20_000\n print(f'{timeit(method, number=N)/N*1e6:.1f} us')\n\n\n\nmain()\n</code></pre>\n<p>This outputs</p>\n<pre><code>[-3 11]\n[-1.00000000e+00 -6.00218231e+05]\n53.9 us\n\n[-3, 11]\n[-1, -600218.2310934969]\n58.1 us\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T01:50:18.110", "Id": "510395", "Score": "1", "body": "I did suspect those coefficients to be vectors and matrix, but I was stumbling on how to implement it, and your answer is exactly what I was looking for. Many thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T00:39:15.103", "Id": "258860", "ParentId": "258764", "Score": "1" } } ]
{ "AcceptedAnswerId": "258860", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T12:19:32.753", "Id": "258764", "Score": "5", "Tags": [ "python", "python-3.x", "numpy", "numerical-methods" ], "Title": "Optimizing an implementation of the RKF method" }
258764
<p>I am working on a small side-project since a couple of weeks, I am using Flask but trying to use as few libraries as possible and no ORMs (for learning purposes.</p> <p>I am currently working on the User service on my application and currently stuck in the registration email confirmation part regarding my design.</p> <p>Since I am not using any ORM, I wrote those classes:</p> <ul> <li><code>UserRepository</code>: interact with the user table in the database (add, get, delete user and save)</li> <li><code>UserService</code>: actions on a User (registration, deactivate user, update stats)</li> <li><code>User</code>: representation of a User entity, no methods, methods are in the UserService (most of them take a User as a parameter expect the one to create a new User)</li> </ul> <p><strong>Current issue:</strong></p> <p>When a new user register, I send a registration email with a URL link to activate the account. I am using <code>URLSafeTimedSerializer</code> to do that and dump the <code>user.email</code> to generate the account confirmation URL. The email is sent and when the user click on the link, I am able to decrypt the <code>user.email</code> using <code>URLSafeTimedSerializer.loads()</code>. But with my current design, I am not quite confident how I am going to retrieve the <code>user.email</code>. Maybe the <code>UserService</code> class should take the <code>UserRepository</code> as an argument?</p> <p><strong>user/views.py</strong></p> <pre><code>user = Blueprint('user', __name__, template_folder='templates') # ---------- # STUCK HERE # ---------- @user.route('/activate/&lt;activation_token&gt;', methods=[&quot;GET&quot;]) def activate(activation_token): private_key = current_app.config['SECRET_KEY'] s = URLSafeTimedSerializer(private_key) user_email = s.loads(activation_token) # now I need to check if that user is already confirmed, if not I have to change current User confirmed value from from False to True # I should probably create a new UserService instance and create a method get_user_by_email(email) ? def generate_registration_token(email): private_key = current_app.config['SECRET_KEY'] s = URLSafeTimedSerializer(private_key) u = s.dumps(email) return u def send_registration_email(email): from prepsmarter.blueprints.user.tasks import deliver_contact_email token = generate_registration_token(email) host = current_app.config['HOST'] activation_url = f&quot;{host}/activate/{token}&quot; try: deliver_contact_email(email, activation_url) return &quot;ok&quot; except Exception as e: return str(e) @user.route('/register') def login(): return render_template('register.html') @user.route('/new-user',methods = ['POST']) def register_user(): form_email = request.form.get('email') form_password = request.form.get('psw') form_password_repeat = request.form.get('psw-repeat') registration_form = RegistrationForm(form_email, form_password, form_password_repeat).validate_registration() if registration_form: new_user = UserService().register_user(form_email, form_password) user_repository = UserRepository(conn, 'users') user_repository.add_user(new_user) user_repository.save() send_registration_email(new_user.email) return &quot;new user created&quot; #will probably change return statements later on return &quot;new uer not created&quot; #will probably change return statements later on </code></pre> <p><strong>user/models.py (User class)</strong></p> <pre><code>class User(): def __init__(self, email, password, registration_date, active, sign_in_count, current_sign_in_on, last_sign_in_on): self.email = email self.password = password self.registration_date = registration_date self.active = active self.confirmed = False </code></pre> <p><strong>user/services.py (UserRepository)</strong></p> <pre><code>class UserRepository(): def __init__(self, conn, table): self.conn = conn self.table = table #select exists(select 1 from users where email='pamousset75@gmail.com') def add_user(self, user): sql = &quot;INSERT INTO users (email, password, is_active, sign_in_count, current_sign_in_on, last_sign_in_on) VALUES (%s, %s, %s, %s, %s, %s)&quot; cursor = self.conn.cursor() # the is_active column in the DB is a tinyint(1). True = 1 and False = 0 if user.active == True: is_active = 1 is_active = 0 cursor.execute(sql, ( user.email, user.password, is_active, user.sign_in_count, user.current_sign_in_on, user.last_sign_in_on)) resp = cursor.fetchall() return resp def delete_user(self): return &quot;&quot; def get_user(self): return &quot;&quot; def save(self): self.conn.commit() </code></pre> <p><strong>user/services.py (UserService)</strong></p> <pre class="lang-py prettyprint-override"><code>class UserService(): def register_user(self, email, password): sign_in_count = 1 today_date = datetime.today().strftime('%Y-%m-%d') active = True new_user = User(email, password, today_date, active, sign_in_count, today_date, today_date) return new_user def desactivate_user(self, User): if User.active == False: print(f&quot;User {User.email} is already inactive&quot;) User.active = False def reactive_user(self, User): if User.active == True: print(f&quot;User {User.email} is already active&quot;) User.active = True def is_active(self, User): return User.is_active </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T23:39:10.723", "Id": "510572", "Score": "0", "body": "Your formatting seems off - as written Python would fail to interpret this. Please double-check your indentation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T00:29:24.493", "Id": "510577", "Score": "0", "body": "@Peilonrayz I suspect that `generate_registration_token` is still off" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T00:32:52.753", "Id": "510578", "Score": "1", "body": "@Reinderien Right you are! Pierre you're going to have to double check `generate_registration_token`'s indentation. Unfortunately we aren't allowed to edit the indentation, like I did for `UserService`." } ]
[ { "body": "<p>It's unstated, so I have to assume that you're using <code>itsdangerous</code> and its implementation of <a href=\"https://itsdangerous.palletsprojects.com/en/1.1.x/url_safe/?highlight=urlsafetimedserializer\" rel=\"nofollow noreferrer\">URLSafeTimedSerializer</a> .</p>\n<p>You ask:</p>\n<blockquote>\n<p>with my current design, I am not quite confident how I am going to retrieve the <code>user.email</code></p>\n</blockquote>\n<p>I'm not sure where the confusion lies. You say you already <em>have</em> the email, from this call:</p>\n<pre><code>user_email = s.loads(activation_token)\n</code></pre>\n<p>So maybe you're actually looking for a way to query the database by user email. Given your current patterns this would be done via your <code>UserRepository</code> class, possibly <code>get_user</code> - which currently looks to be an unimplemented stub.</p>\n<p>Your repository class, at least in theory, should be fine; though your <code>self.table</code> is unused and I don't see a use for it even if all of your stubs were implemented.</p>\n<p><code>add_user</code> doesn't make sense. You send an <code>INSERT</code>, don't include a <code>RETURNING</code> clause, and then run a <code>fetchall()</code>. What do you expect this to return? You haven't indicated what your database is, nor even what your <code>conn</code> is, but I doubt that this is going to work.</p>\n<p><code>UserService</code> seems like a lot of boilerplate that can go away entirely. <code>register_user</code> can move those defaults to column-level default declarations right in the database. Even if you were to keep your default values in the application code, you should not be calling <code>strftime</code> when assigning a value to <code>User.registration_date</code>; leave it as a real date object.</p>\n<p>I'd also be surprised if your database interaction library (that you haven't specified) isn't able to deal with booleans directly, and similarly for the database below it. Specifically, modern database like PostgreSQL do not require conversion to a 0/1 nor representation as a <code>smallint</code>, and <a href=\"https://www.postgresql.org/docs/current/datatype-boolean.html\" rel=\"nofollow noreferrer\">can use <code>true</code>, <code>false</code> and <code>boolean</code></a>. The difference seems minor but better communicates your intent.</p>\n<p>Everything else in the service class is trivial and doesn't offer any value over doing the boolean operations in place. The <code>print</code>s should be replaced with logging calls, and/or converted to meaningful HTTP response messages. <code>desactivate</code> is spelled <code>deactivate</code>.</p>\n<p>I don't see any evidence that the password is getting hashed or salted when it goes to the database. Please ensure that this is the case.</p>\n<pre><code>from prepsmarter.blueprints.user.tasks import deliver_contact_email\n</code></pre>\n<p>deserves to be at the top of your file and not in a method.</p>\n<p>The return value from <code>send_registration_email</code> is problematic. Returning an &quot;ok&quot; string or a string-ified exception goes counter to proper Python exception handling. It's less surprising to simply return <code>None</code> (i.e. not return at all), and if an exception happens, the caller needs to handle it. As written, the <code>except</code> type you've shown is too broad.</p>\n<p><code>new uer</code> is likely a typo.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-01T00:25:10.983", "Id": "258946", "ParentId": "258765", "Score": "2" } } ]
{ "AcceptedAnswerId": "258946", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T12:28:41.403", "Id": "258765", "Score": "2", "Tags": [ "python", "object-oriented", "design-patterns", "flask" ], "Title": "Python: separation of concern User Model and User DB" }
258765
<p>I wrote below piece of code generating dummy data loaded to MongoDB.</p> <p><strong>2 issues :</strong></p> <p>1.customer class has subscriber class so it nested with one level customer--&gt; subsciber. I think i'm not doing right:</p> <pre><code>self.subscriber = Subscriber().returnJson() </code></pre> <p>it does working , but what if need to add another class under subscriber? it will become messy.</p> <p>2.Peroformance - very bad:</p> <p>10 documents:</p> <pre><code> real 0m20.371s user 0m2.691s sys 0m0.736s </code></pre> <p>for 1000 documents - very bad:</p> <pre><code>real 5m8.299s user 1m40.819s sys 0m44.380s </code></pre> <p>The generating of documents is the bottleneck - not the actual load.</p> <p>Surely multiprocessing didn't work well , as performance is really bad. second ,I collect all document in a list (see mongo_doc[]) and at the end use insert_many i think it right , but it doesn't show meaningful improvement compare to insert_one.</p> <p>Would appreciate any help</p> <pre><code>from faker import Faker import json from multiprocessing.pool import ThreadPool as Pool import concurrent.futures import random from motor.motor_asyncio import AsyncIOMotorClient from config.config import DB, CONF,trace_request,redis_client pool_size = 10 mongo_docs = [] customer_type_options = ['Individual', 'Organization'] customer_status_options = ['Active', 'Cancelled','Suspened','Collection'] class Subscriber(): def __init__(self): fake = Faker() self.subscriber_no= random.randint(10000000, 99999999) def returnJson(self): return dict (subscriber_no= self.subscriber_no) class Customer(): def __init__(self): fake = Faker() self.customer_no = random.randint(10000000, 99999999) self.customer_type = random.choice(customer_type_options) self.customer_status = random.choice(customer_status_options) self.address = fake.address() self.subscriber = Subscriber().returnJson() def returnJson(self): return {'customer_no': self.customer_no, 'customer_type': self.customer_type, 'customer_status': self.customer_status, 'address': self.address, 'subscriber': self.subscriber } class ComplexEncoder(json.JSONEncoder): def default(self, obj): if hasattr(obj,'returnJson'): return obj.returnJson() else: return json.JSONEncoder.default(self, obj) def LoadOToMongo(Customer): mongo_docs.append(Customer.returnJson()) if __name__ == &quot;__main__&quot;: no_of_input = 2 pool = Pool(pool_size) jobs =[] for i in range(0, no_of_input): customer = Customer() pool.apply_async(LoadOToMongo, (customer,)) pool.close() pool.join() #bulk insert DB.customer.insert_many(mongo_docs) <span class="math-container">```</span> </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T15:32:48.847", "Id": "258770", "Score": "1", "Tags": [ "python", "mongodb", "multiprocessing" ], "Title": "Python/Mongo - Generating dummy data" }
258770
<p>What do you think of the following function to offer an alternative to fgets, looking for insights about portability, safety, readability and performance:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;errno.h&gt; int sc_gets(char *buf, int n) { int count = 0; char c; if (__glibc_unlikely(n &lt;= 0)) return -1; while (--n &amp;&amp; (c = fgetc(stdin)) != '\n') buf[count++] = c; buf[count] = '\0'; return (count != 0 || errno != EAGAIN) ? count : -1; } #define BUFF_SIZE 10 int main (void) { char buff[BUFF_SIZE]; sc_gets(buff, sizeof(buff)); // how to use printf (&quot;%s\n&quot;, buff); return 0; } </code></pre> <p><em>NB: I have already read <a href="https://codereview.stackexchange.com/questions/179201/fgets-alternative">fgets() alternative</a> which was interesting but my code is different.</em></p> <hr /> <p>Second version thanks to the comments and vnp's insight:</p> <pre class="lang-c prettyprint-override"><code> #include &lt;stdio.h&gt; #include &lt;errno.h&gt; long sc_gets(char *buf, long n) { long count = 0; char c; while (--n &amp;&amp; (c = fgetc(stdin)) != '\n') { if (c == EOF) break; buf[count++] = c; } buf[count] = '\0'; return (count != 0 || errno != EAGAIN) ? count : -1; } #define BUFF_SIZE 1024 int main (void) { char buff[BUFF_SIZE]; sc_gets(buff, sizeof(buff)); printf (&quot;%s\n&quot;, buff); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T17:50:48.957", "Id": "510191", "Score": "0", "body": "If you are going to use implementation specific API `__glibc_unlikely()` it is probably best to wrap them in a macro to provide alternatives for implementations that don't have them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T17:54:03.007", "Id": "510192", "Score": "0", "body": "I already checked about them, there is no need to replace them as \"the platforms that don't support them just define them to expand to empty strings. \" https://stackoverflow.com/questions/109710/how-do-the-likely-unlikely-macros-in-the-linux-kernel-work-and-what-is-their-ben" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T17:58:57.020", "Id": "510194", "Score": "1", "body": "I think you misunderstand that. This is systems that know about `likely`/`unlikely` but don't implement it will expand to white space. Implementations that don't understand it don't automatically do something special to support it. I could be wrong (does the language standard say something special)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T18:07:47.650", "Id": "510195", "Score": "1", "body": "It looks good to me, but @MartinYork is right, portability is not guaranteed, I ran it in a Windows environment both with gcc version 9.2.0 (tdm64-1) POSIX adapted version, and with MSVC and the compilation fails for both with `undefined reference to __glibc_unlikely'` and `unresolved external symbol __glibc_unlikely` respectively." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T18:55:29.180", "Id": "510202", "Score": "0", "body": "The unlikely is likely (pun intended) a premature optimization. `fgetc` will do locking io and kill performance. POSIX and Windows both have unlocked stdio, but they do it differently. `int` as the size type matches `fgets`, but I'd still have gone foe `size_t`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T19:00:46.993", "Id": "510204", "Score": "0", "body": "Is there an error too: doesn't eat `\\n` if the line has n-1 characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T00:45:29.127", "Id": "510218", "Score": "0", "body": "@Antti love the pun! How comes pthread has such optimizations if it is not portable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T06:00:32.750", "Id": "510225", "Score": "1", "body": "long is not size_t. long on wibdows has exact same representation as int." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T06:09:27.343", "Id": "510226", "Score": "0", "body": "Excellent point, forgot about this. What would you suggest then?" } ]
[ { "body": "<ul>\n<li><p>The function does not handle end-of-file correctly. <code>stdin</code> is just a stream, and could be closed like any other stream. For example, type <code>Ctrl-D</code>. Or</p>\n<pre><code> echo -n a | ./a.out\n a????????\n</code></pre>\n<p>Keep in mind that reading beyond end-of-file doesn't set <code>errno</code>.</p>\n</li>\n<li><p>There is no reason to special-case <code>count == 0</code>.</p>\n<p>An IO error doesn't break the loop. If it happened, all the subsequent invocations of <code>fgets</code> would return <code>EOF</code>, and upon the loop termination the <code>count</code> will be <code>n</code>.</p>\n</li>\n<li><p>Pass the buffer size as <code>size_t</code>. This is what <code>sizeof</code> yields, and the buffers could be large enough for their size to overflow an integer.</p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T01:13:42.347", "Id": "510220", "Score": "0", "body": "Thanks a lot for your insight, please have a look at version 2 :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T21:57:29.673", "Id": "258786", "ParentId": "258772", "Score": "3" } } ]
{ "AcceptedAnswerId": "258786", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T17:01:43.410", "Id": "258772", "Score": "3", "Tags": [ "c" ], "Title": "fgets without the line return" }
258772
<p>I made myself a function to check if a string is a path or an URL:</p> <pre class="lang-py prettyprint-override"><code>import os def isPath(s): &quot;&quot;&quot; @param s string containing a path or url @return True if it's a path, False if it's an url' &quot;&quot;&quot; if os.path.exists(s): # if a file with name s exists, we don't check any further and just return True return True elif s.startswith(&quot;/&quot;): # clearly a path, urls never start with a slash return True elif &quot;://&quot; in s.split(&quot;.&quot;)[0]: # if a protocol is present, it's an url return False elif &quot;localhost&quot; in s: # special case for localhost domain name where splits on . would fail return False elif len(s.split(&quot;/&quot;)[0].split(&quot;.&quot;)) &gt; 1: # dots before the first slash, normally separating TLD and domain name return False elif len(s.split(&quot;/&quot;)[0].split(&quot;:&quot;)) &gt; 1: # if colons are present, either it's a IPv6 adress or there is a port number return False else: # all possible cases of an url checked, so it must be a path return True </code></pre> <p>Did I miss any cases of an url / path, and can the function be improved in some way ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T21:22:09.657", "Id": "510210", "Score": "0", "body": "`file:///path/to/file` is perfectly valid path, as is `.dir/file`" } ]
[ { "body": "<p>Some high level comments:</p>\n<ul>\n<li>Checking if a string is a url (or a path) is usually done using regular expressions that can be found online. Not sure what's the scope of this function, but it can be seen as reinventing the wheel and might miss some uncommon cases</li>\n<li>The method name gives the impression that returning True means it's a path, and False means that it's not, where in fact False has the meaning of being a URL. I would split this function into two: <code>isPath</code> where False just means that the given string is not a Path, and <code>isUrl</code> where False means it's not a URL. Or at the very least renaming it to <code>isPathOrUrl</code></li>\n<li>It's a personal preference but I'd change <code>elif</code> to be <code>if</code> as all the conditional bodies are returning something so no need to use <code>else</code></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T20:28:41.090", "Id": "258780", "ParentId": "258773", "Score": "2" } }, { "body": "<p>Seems to me that the approach can be simplified, <em>maybe</em>. You could check if the string begins with http:// or https:// (+ ftp:// and more if you so wish).</p>\n<p>FYI the startswith function can also accept a tuple of values, which can be useful for testing multiple possibilities in one pass. So I would start by checking this condition (protocol presence).</p>\n<p>However my impression is that you also want to handle URLS that are not prefixed by a protocol eg: <a href=\"http://www.somesite.com\" rel=\"nofollow noreferrer\">www.somesite.com</a>. But this could perfectly be a directory or a file, you never know. Tools like wget or httrack will even create subdirectories named after the host names being crawled. Sqlmap too.</p>\n<p>You could check with os.path.exists whether <a href=\"http://www.somesite.com\" rel=\"nofollow noreferrer\">www.somesite.com</a> actually exists on your system, but this would be against a relative path. What is it going to be ? The current working directory ?</p>\n<p>Some of your assumptions are not safe, for example:</p>\n<blockquote>\n<p>if colons are present, either it's a IPv6 adress or there is a port number</p>\n</blockquote>\n<p>In Linux at least, file names can perfectly have colons. In Windows, it could be that this character is invalid in file names, I'm not sure and can't test right now. But there are differences between operating systems in this regard, and even between file systems.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-03T11:05:52.770", "Id": "510822", "Score": "0", "body": "\"Some of your assumptions are not safe, for example: if colons are present, either it's a IPv6 adress or there is a port number\" - It _is_ safe, because i check in my code before that if a file with name `s` exists, in which case my code immediately says true (is a path)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T20:52:29.413", "Id": "258782", "ParentId": "258773", "Score": "2" } } ]
{ "AcceptedAnswerId": "258782", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T17:21:22.950", "Id": "258773", "Score": "3", "Tags": [ "python", "python-3.x", "url" ], "Title": "Function for checking if a string is a path or an URL be improved" }
258773
<p><strong>Problem</strong></p> <p>Output a receipt of purchased items. Inputs:</p> <ul> <li>products_text_path: Products are found in a text file in <code>&lt;barcode&gt;:&lt;name&gt;:&lt;price&gt;</code> line format.</li> <li>purchased_items_set: The purchased items are given as a list of integer barcodes. Same item be found several times.</li> <li>discount_rules_text_path: There are discount rules in a text file in <code>&lt;barcode&gt;:&lt;min_quantity&gt;:&lt;discount&gt;</code> format which mean that buying more than <code>min_quantity</code> of the <code>barcode</code> item will give you a <code>discount</code> (given as the discount percentage /1)</li> </ul> <p><strong>Goal</strong></p> <p>Readable code that handles very large amount of input</p> <p><strong>Example</strong></p> <pre><code>Products: - 123:banana:0.5 - 789:apple:0.4 Discounts: - 123:2:0.2 # Meaning buying 2 bananas will add a 20% discount Purchases: - [123,123] # Bought 2 bananas Output: - [('banana', 2, 0.8)] </code></pre> <p><strong>Potential issues in the code below</strong></p> <ul> <li>I'm holding all the information in memory.</li> <li>I might be using too many classes to represent the difference pieces of information?</li> </ul> <p><strong>Code</strong></p> <p>Code is best understood when read starting from the <code>start_process</code> function</p> <pre><code>class Product: def __init__(self, barcode: int, name: str, price: float): self.bardcode = barcode self.name = name self.price = price @classmethod def parse_product(cls, product_line: str): name, barcode_str, price_str = product_line.split(':') price = float(price_str) barcode = int(barcode_str) return cls(barcode, name, price) class Products: def __init__(self): self.products = {} # Type: Dict&lt;int, Product&gt; def add_product(self, product: Product): self.products[product.bardcode] = product def get_product(self, product_barcode): return self.products[product_barcode] @classmethod def parse_products(products_cls, products_path: str): products = products_cls() with open(products_path) as products_lines: for product_line in products_lines: product = Product.parse_product(product_line) products.add_product(product) return products class ProductPurchase: def __init__(self, barcode: int, quantity = 1, discount = 0.0): self.barcode = barcode self.quantity = quantity self.discount = discount class DiscountRule: def __init__(self, product_barcode: int, min_quantity: int, discount_amount: float): self.product_barcode = product_barcode self.min_quantity = min_quantity self.discount_amount = discount_amount @classmethod def parse(cls, discount_rule: str): barcode_str, min_quantity_str, discount_amount_str = discount_rule.split(':') return cls(int(barcode_str), int(min_quantity_str), float(discount_amount_str)) class DiscountRules: def __init__(self): self.dicounts = {} # Type: Dict&lt;int, DiscountRule&gt; def add_discount(self, discount: DiscountRule): self.dicounts[discount.product_barcode] = discount def apply_discount(self, purchase: ProductPurchase): if purchase.barcode not in self.dicounts: return discount = self.dicounts[purchase.barcode] if purchase.quantity &lt; discount.min_quantity: return purchase.discount = discount.discount_amount @classmethod def parse_discount_rules(cls, rules_path: str): rules = cls() with open(rules_path) as rules_lines: for rule_line in rules_lines: rule = DiscountRule.parse(rule_line) rules.add_discount(rule) return rules class Purchases: def __init__(self): self.purchases = {} # Type: Dict&lt;int, ProductPurchase&gt; def add_purchase(self, purchased_barcode: int): if purchased_barcode in self.purchases: self.purchases[purchased_barcode].quantity += 1 else: self.purchases[purchased_barcode] = ProductPurchase(purchased_barcode) def get_purchases(self): for purchase in self.purchases.values(): yield purchase class Checkout: def __init__(self, purchases: Purchases, products: Products, discount_rules: DiscountRules): self.purchases = purchases self.products = products self.discount_rules = discount_rules def check_out(self): result = [] for purchase in self.purchases.get_purchases(): self.discount_rules.apply_discount(purchase) product = self.products.get_product(purchase.barcode) price = _calculate_price(product.price, purchase.quantity, purchase.discount) result.append((product.name, purchase.quantity, price)) return result def _calculate_price(price, quantity, discount): return str(round(price * quantity * (1.0 - discount), 2)) def start_process(products_paths: str, discounts_path: str, scanner_input): purchases = Purchases() for purchased_barcode in scanner_input: purchases.add_purchase(purchased_barcode) products = Products.parse_products(products_paths) discount_rules = DiscountRules.parse_discount_rules(discounts_path) checkout = Checkout(purchases, products, discount_rules) return checkout.check_out() </code></pre>
[]
[ { "body": "<ul>\n<li>Indentation is not a multiple of 4, while PEP8 establishes that it should.</li>\n<li>No entry-point to your script (if __ name __ == '__ main __'...).</li>\n<li>Parse_product was getting the name before the barcode, while the question establishes the order is the opposite one.</li>\n<li>Class products is basically a dictionary. It does not make sense to me to have a whole class to just cover a dictionary (not actually exposing all of the useful interface form it) just for the parse_products class method. I see 4 options: inherit from dict, this way at least its a proper dict, have ProductUtils and just have the utility function parse_products, or have a function parse_products, have the parse_products utility inside the Product class, no need to have Product and Products (if products its basically a dict). All of them seem better to me.</li>\n<li>Calculate price makes no sense to have it as a utility function. If it computes the discounted price of a purchase, why not have it in the Purchase class?</li>\n<li>Do you have some background working with DBs? The ProductPurchase structure makes sense in the context of a database. But in this OOP design, why not just having ProductCart? Also, instead of storing barcodes, store the actual products (we don't loose much space for a single object reference we already have, and it will be much more useful than just having the key to it)!</li>\n<li>Similarly, purchases is just a dict, so why not inherit from it to get its full utility and just override what we need to be different. Also, add_purchase is misleading, since you add a product/barcode, not a purchase (since the purchase is generated within the method).</li>\n<li>The DiscountRules class seems to me un-necessary. Why not store the discounts in the Product class itself?</li>\n<li>In general, no docstrings in any of the methods nor comments anywhere.</li>\n<li>The check_out method basically only needs to go through the purchases. Essentially, it does nothing and thus it is not needed.</li>\n<li>Other comments in the code</li>\n</ul>\n<p>This is the final version I suggest:</p>\n<pre><code>from typing import Iterable, Dict\n\n\nclass Product:\n def __init__(self, barcode: int, name: str, price: float):\n self.barcode = barcode\n self.name = name\n self.price = price\n self.discounts = []\n\n @classmethod\n def parse_product(cls, product_line: str):\n barcode, name, price = product_line.split(':')\n return cls(int(barcode), name, float(price))\n\n def add_discount(self, discount: 'DiscountRule'):\n self.discounts.append(discount)\n\n\nclass Products(dict):\n def __init__(self, *args, **kwargs):\n super(Products, self).__init__(*args, **kwargs)\n\n def add_product(self, product: Product):\n self[product.barcode] = product\n\n @classmethod\n def parse_products(cls, products_path: str, discount_rules: 'Dict[int, DiscountRule]'):\n products = cls()\n with open(products_path) as products_lines:\n for product_line in products_lines:\n product = Product.parse_product(product_line)\n\n if product.barcode in discount_rules:\n product.add_discount(discount_rules[product.barcode])\n\n products.add_product(product)\n return products\n\n\nclass ProductPurchase:\n def __init__(self, product: Product, quantity: int = 1):\n self.product = product\n self.quantity = quantity\n\n @property\n def discount(self):\n total_discount = None\n for discount in self.product.discounts:\n if self.quantity &gt;= discount.min_quantity:\n if total_discount is None:\n total_discount = 0\n total_discount += discount.discount_amount\n return total_discount\n\n def purchase(self, quantity: int = 1):\n self.quantity += quantity\n\n @property\n def discounted_price(self):\n return round(self.product.price * self.quantity * (1.0 - self.discount), 2)\n\n\nclass DiscountRule:\n def __init__(self, product_barcode: int, min_quantity: int, discount_amount: float):\n self.product_barcode = product_barcode\n self.min_quantity = min_quantity\n self.discount_amount = discount_amount\n\n @classmethod\n def parse(cls, discount_rule: str):\n barcode_str, min_quantity_str, discount_amount_str = discount_rule.split(':')\n return cls(int(barcode_str), int(min_quantity_str), float(discount_amount_str))\n\n @classmethod\n def parse_discount_rules(cls, rules_path: str) -&gt; 'Iterable[int, DiscountRule]':\n with open(rules_path) as rules_lines:\n for rule_line in rules_lines:\n discount_rule = DiscountRule.parse(rule_line)\n yield discount_rule.product_barcode, discount_rule\n\n\nclass Purchases(dict):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def purchase(self, product: Product):\n if product.barcode in self:\n self[product.barcode].purchase()\n else:\n self[product.barcode] = ProductPurchase(product)\n\n\nclass ShoppingCart:\n def __init__(self, purchases: Purchases, products: Products):\n self.purchases = purchases\n self.products = products\n\n @classmethod\n def init_from_files(cls, products_path: str, discounts_path: str, scanner_input: list):\n discount_rules = DiscountRule.parse_discount_rules(discounts_path)\n\n products = Products.parse_products(products_path, dict(discount_rules))\n\n purchases = Purchases()\n for purchased_barcode in scanner_input:\n purchases.purchase(products[purchased_barcode])\n\n return cls(purchases, products)\n\n\nif __name__ == &quot;__main__&quot;:\n cart = ShoppingCart.init_from_files(&quot;products.txt&quot;, &quot;discounts.txt&quot;, [123, 123])\n\n print(&quot;TICKET&quot;)\n for purchase in cart.purchases.values():\n print(&quot;%s x %s | %s€&quot; % (purchase.quantity, purchase.product.name, purchase.discounted_price))\n print(&quot;------&quot;)\n</code></pre>\n<p>And code with comments on it:</p>\n<pre><code>from typing import Iterable, List\n\n\nclass Product:\n def __init__(self, barcode: int, name: str, price: float):\n self.barcode = barcode # bardcode seems a typo for barcode\n self.name = name\n self.price = price\n self.discounts = []\n\n @classmethod\n def parse_product(cls, product_line: str):\n barcode, name, price = product_line.split(':')\n &quot;&quot;&quot;price = float(price_str)\n barcode = int(barcode_str) &gt;&gt;&gt; un-needed in two steps &quot;&quot;&quot;\n return cls(int(barcode), name, float(price))\n\n def add_discount(self, discount: 'DiscountRule'):\n self.discounts.append(discount)\n\n\nclass Products(dict):\n def __init__(self, *args, **kwargs):\n super(Products, self).__init__(*args, **kwargs)\n\n def add_product(self, product: Product):\n self[product.barcode] = product\n\n &quot;&quot;&quot;def get_product(self, product_barcode):\n return self[product_barcode]\n \n &gt;&gt;&gt; no need for this method, the dict already implements a get\n &quot;&quot;&quot;\n\n @classmethod\n def parse_products(cls, products_path: str):\n &quot;&quot;&quot;stick to the cls naming convention\n since it is a class method from the Products class, it is trivial that it is a product_cls\n &quot;&quot;&quot;\n products = cls()\n with open(products_path) as products_lines:\n for product_line in products_lines:\n product = Product.parse_product(product_line)\n products.add_product(product)\n return products\n\n\nclass ProductPurchase:\n def __init__(self, product: Product, quantity: int = 1): # &gt;&gt;&gt; type hinting missing\n self.product = product\n self.quantity = quantity\n # self.discount = discount\n &quot;&quot;&quot;\n &gt;&gt;&gt; instead of storing a hard copy of the discount, which might get corrupted\n if the discount or quantity change, use a property and compute it live\n &quot;&quot;&quot;\n\n @property\n def discount(self):\n &quot;&quot;&quot; computes the discount, accepts multiple discounts per product now &quot;&quot;&quot;\n total_discount = None\n for discount in self.product.discounts:\n if self.quantity &gt;= discount.min_quantity:\n if total_discount is None:\n total_discount = 0\n total_discount += discount.discount_amount\n return total_discount\n\n def purchase(self, quantity: int = 1):\n &quot;&quot;&quot; provide a nice interface for modifying the quantity &quot;&quot;&quot;\n self.quantity += quantity\n\n @property\n def discounted_price(self):\n return round(self.product.price * self.quantity * (1.0 - self.discount), 2)\n\n\nclass DiscountRule:\n def __init__(self, product_barcode: int, min_quantity: int, discount_amount: float):\n self.product_barcode = product_barcode\n self.min_quantity = min_quantity\n self.discount_amount = discount_amount\n\n @classmethod\n def parse(cls, discount_rule: str):\n barcode_str, min_quantity_str, discount_amount_str = discount_rule.split(':')\n return cls(int(barcode_str), int(min_quantity_str), float(discount_amount_str))\n\n @classmethod\n def parse_discount_rules(cls, rules_path: str) -&gt; 'Iterable[DiscountRule]':\n with open(rules_path) as rules_lines:\n for rule_line in rules_lines:\n yield DiscountRule.parse(rule_line)\n\n @classmethod\n def add_discounts_to_products(cls, discounts: 'Iterable[DiscountRule]', products: Products):\n for discount in discounts:\n if discount.product_barcode in products:\n products[discount.product_barcode].add_discount(discount)\n\n\nclass Purchases(dict):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def purchase(self, product: Product): # work with objects! not with keys which refer to objects\n if product.barcode in self:\n self[product.barcode].purchase()\n else:\n self[product.barcode] = ProductPurchase(product)\n\n &quot;&quot;&quot;def get_purchases(self):\n for purchase in self.values():\n yield purchase\n &gt;&gt;&gt; not needed since now the interface is the actual dict\n &quot;&quot;&quot;\n\n\nclass ShoppingCart: # a more meaningful name to the object, check_out is an action/method\n def __init__(self, purchases: Purchases, products: Products):\n self.purchases = purchases\n self.products = products\n # self.discount_rules = discount_rules &gt;&gt;&gt; not needed anymore\n\n def check_out(self) -&gt; Iterable:\n &quot;&quot;&quot; return an iterable instead of a list, the caller can then do whatever xhe wants &quot;&quot;&quot;\n for purchase in self.purchases.values():\n yield purchase.product.name, purchase.quantity, purchase.discounted_price\n\n @classmethod\n def init_from_files(cls, products_path: str, discounts_path: str, scanner_input: list):\n # get products from products_path\n products = Products.parse_products(products_path)\n\n # get discount_rules from discount_path\n discount_rules = DiscountRule.parse_discount_rules(discounts_path)\n DiscountRule.add_discounts_to_products(discount_rules, products)\n\n purchases = Purchases()\n for purchased_barcode in scanner_input:\n purchases.purchase(products[purchased_barcode])\n\n return cls(purchases, products)\n\n\n\n\n&quot;&quot;&quot;def get_checkout(products_paths: str, discounts_path: str, scanner_input):\n \n &gt;&gt;&gt; if all the code is using objects, why have a random function and not use those objects?\n&quot;&quot;&quot;\n\nif __name__ == &quot;__main__&quot;:\n cart = ShoppingCart.init_from_files(&quot;products.txt&quot;, &quot;discounts.txt&quot;, [123, 123])\n print(list(cart.check_out()))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T00:21:00.653", "Id": "510216", "Score": "2", "body": "Elaborate review, suggesting valid design issues One prime strategy/directive in both software-development and writing (text, not code) is _divide and conquer_ or [modularisation](https://en.m.wikipedia.org/wiki/Divide_and_rule). This would ease reading/understanding/maintaining of both your answer and the code under review. What about __headings__ and separate __code-blocks__ (modules) to improve structure" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T21:03:05.217", "Id": "258783", "ParentId": "258775", "Score": "3" } }, { "body": "<ul>\n<li>Use <a href=\"https://docs.python.org/3/library/dataclasses.html\" rel=\"nofollow noreferrer\">dataclasses</a> so you don't have to write boilerplate for your data containers.</li>\n<li>You don't really need <code>Products</code>, <code>DiscountRules</code>, and <code>Purchases</code> when you could just have <code>dict[int, Product]</code>, <code>dict[int, DiscountRule]</code>, and <code>dict[int, ProductPurchase]</code> respectively. The existence of these classes makes the code harder to read.</li>\n<li><code>Checkout</code> doesn't need to be a class. You can just declare the method <code>check_out</code>. <a href=\"https://pyvideo.org/pycon-us-2012/stop-writing-classes.html\" rel=\"nofollow noreferrer\">If you find yourself writing a class that only has two methods, one of which is <code>__init__</code>, you probably don't need a class</a>.</li>\n<li><a href=\"https://blog.agentrisk.com/you-better-work-in-cents-not-dollars-2edb52cdf308\" rel=\"nofollow noreferrer\">Don't store currency as floats</a>. Use a currency's smallest unit so you can store it as an integer. The main idea is to avoid rounding errors that come up in floating point arithmetic. For example, if <code>Product</code>'s <code>price</code> is the price in US currency, it should be an integer representing the price in cents, not dollars.</li>\n<li>You can use <a href=\"https://docs.python.org/3/library/collections.html#collections.Counter\" rel=\"nofollow noreferrer\"><code>collections.Counter</code></a> to count the scanned barcodes, which gives you something like a <code>dict[int, int]</code> (barcode -&gt; quantity). Then you can use this to create a collection of <code>ProductPurchase</code>s later.</li>\n<li>I see type hints being used, but not consistently. Type hints should be added for method return types as well.</li>\n<li>This is personal preference, but for the methods that parse a string into a data container type like <code>Product</code>, instead of the names <code>parse_product</code>, <code>parse</code>, etc. I would name it <code>from_string</code> so the usage is more self-documenting, e.g. <code>Product.from_string(s)</code>.</li>\n</ul>\n<h2>Refactored version</h2>\n<pre class=\"lang-python prettyprint-override\"><code>from __future__ import annotations\n\nfrom collections import Counter\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Product:\n barcode: int\n name: str\n price: int # in the currency's smallest unit, e.g. cents for US currency\n\n @staticmethod\n def from_string(product: str) -&gt; Product:\n barcode, name, price = product.split(&quot;:&quot;)\n return Product(int(barcode), name, int(price))\n\n\n@dataclass\nclass DiscountRule:\n barcode: int\n min_quantity: int\n discount_amount: int # percentage, e.g. 20 =&gt; 20% discount\n\n @staticmethod\n def from_string(discount_rule: str) -&gt; DiscountRule:\n barcode, min_quantity, discount_amount = discount_rule.split(&quot;:&quot;)\n return DiscountRule(\n int(barcode), int(min_quantity), int(discount_amount)\n )\n\n\n@dataclass\nclass ProductPurchase:\n product: Product\n quantity: int\n discount: int # percentage, e.g. 20 =&gt; 20% discount\n\n @property\n def cost(self) -&gt; float:\n return self.product.price * self.quantity * (100 - self.discount) / 100\n\n def __str__(self) -&gt; str:\n discount_text = (\n f&quot; (with {self.discount}% discount)&quot; if self.discount &gt; 0 else &quot;&quot;\n )\n return f&quot;{self.quantity}x {self.product.name}{discount_text} {self.cost / 100:.2f}&quot;\n\n\ndef calculate_product_purchase(\n products: dict[int, Product],\n discounts: dict[int, DiscountRule],\n barcode: int,\n quantity: int,\n) -&gt; ProductPurchase:\n product = products[barcode]\n discount_pct = (\n discount.discount_amount\n if (discount := discounts.get(barcode, None))\n and quantity &gt;= discount.min_quantity\n else 0\n )\n return ProductPurchase(product, quantity, discount_pct)\n\n\ndef print_receipt(\n products_path: str, discounts_path: str, purchases: list[int]\n) -&gt; None:\n with open(products_path) as p_file, open(discounts_path) as d_file:\n products = {\n p.barcode: p for line in p_file if (p := Product.from_string(line))\n }\n discounts = {\n d.barcode: d\n for line in d_file\n if (d := DiscountRule.from_string(line))\n }\n\n for barcode, quantity in Counter(purchases).items():\n product_purchase = calculate_product_purchase(\n products, discounts, barcode, quantity\n )\n print(product_purchase)\n\n\nif __name__ == &quot;__main__&quot;:\n print_receipt(\n &quot;products.txt&quot;, &quot;discounts.txt&quot;, [123, 123, 123, 123, 789, 789]\n )\n</code></pre>\n<h3>products.txt</h3>\n<pre class=\"lang-none prettyprint-override\"><code>123:banana:50\n789:apple:40\n</code></pre>\n<h3>discounts.txt</h3>\n<pre class=\"lang-none prettyprint-override\"><code>123:2:20\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T08:47:59.617", "Id": "510233", "Score": "0", "body": "great comments! why not having calculate product_purchase as a class method? also, why do you store references to classes using barcodes and not the class itself? also, I see multiple discounts stored by value and in +1 place, can't this be a problem if such discount needs to be changed during run time?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T09:34:59.563", "Id": "510235", "Score": "1", "body": "@miquelvir `calculate_product_purchase` _could_ be a class method, yes, but I personally didn't like the call pattern of `ProductPurchase.calculate_product_purchase(...)`. Personal preference, really." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T09:35:49.863", "Id": "510237", "Score": "0", "body": "@miquelvir Re `also, why do you store references to classes using barcodes and not the class itself?`: I'm not sure I quite follow you here. Are you asking why I didn't model `Product` to contain a list of `DiscountRule`s? If so, I didn't feel like that was really necessary and would introduce unwanted coupling. When I think of a `Product` in this problem, it clearly needs an id (barcode), a name, and a unit price. But I don't think it should hold a `DiscountRule` or a `list[DiscountRule]`, i.e. I think its model should exist independently of `DiscountRule`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T09:36:40.413", "Id": "510238", "Score": "0", "body": "(continuing from the previous comment) For example, what if in the future there is a new kind of `DiscountRule` that offers a discount if you purchase everything in a list of distinct `Product`s (e.g. buy one apple and one banana for 10% off)? Then that coupling might need to be refactored out in that case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T09:37:58.320", "Id": "510239", "Score": "0", "body": "Re the part about discounts stored by value and discounts changing at runtime: If the discounts change, then all one needs to do is recalculate all the product purchases using the updated discounts. In other words, simply re-running the program with the changed discounts file, since the flow we have here is `load data & input -> perform calculations -> print report -> exit program`. The data flow is unidirectional, and I don't think there's anything in the problem statement that would suggest that we need to worry about discounts being modified while the program is running." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T09:39:54.897", "Id": "510240", "Score": "0", "body": "your logic makes sense @Setris, I was however asking about why you store barcode in DiscountRule, and not a Product. If discount rule refers to a product, is not it more useful to store the product itself, and not a barcode we can use to get it from somewhere?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T09:49:15.370", "Id": "510241", "Score": "0", "body": "@miquelvir Ah, I see what you mean. Yeah, so for `DiscountRule`, I could definitely see storing `Product` there if we wanted to for example print each `DiscountRule` in a human-friendly format, e.g. `Buy at least 2x Apple, save 20%`. In this case there wasn't really a need to do that, so I kept the model that's closer to what @Omar had in the original code. Note that for `ProductPurchase` I am keeping a reference to `Product` instead of just the `barcode` because it's needed for the pretty-print `__str__`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T09:58:25.983", "Id": "510242", "Score": "0", "body": "makes sense, I still think its cleaner to hold the product however" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T00:26:05.260", "Id": "258790", "ParentId": "258775", "Score": "3" } }, { "body": "<p>Since you are handling <strong>CSV</strong> data, and if you have a well-structured file, there is no need to reinvent the wheel and do the parsing yourself. Python already has a library for this purpose: <a href=\"https://docs.python.org/3/library/csv.html\" rel=\"nofollow noreferrer\">csv — CSV File Reading and Writing</a>. Of course it is not impossible that a personal and minimalist implementation could perform better than an established and time-proven module, but this is doubtful. But you can test for yourself.</p>\n<p>Another more obvious alternative would be using <a href=\"https://pandas.pydata.org/docs/reference/api/pandas.read_csv.html\" rel=\"nofollow noreferrer\">Pandas</a>. Import the data to a dataframe, that can be further manipulated with the result of your calculations.</p>\n<p>And you have yet one more option: a <strong>database</strong>. You could use the <strong>sqlite</strong> module and import the files to tables. I think this option is well suited for your purpose. You can get the job done with a few joins and possibly some subselects depending on the need. But here this is just a very basic join of 3 tables that you need.</p>\n<p>SQLite can import CSV files in bulk but you'll need to invoke the shell for this. See for example: <a href=\"https://wizardforcel.gitbooks.io/sqlite-doc-en/content/30.html\" rel=\"nofollow noreferrer\">https://wizardforcel.gitbooks.io/sqlite-doc-en/content/30.html</a></p>\n<p>NB: the database file does not even have to be stored on disk, you can create an in-memory DB that is disposed after your program has executed. But if you have large datasets and you are worried about memory consumption, then use a DB file. If you are on Linux you can use a temporary file on /tmp, which is normally tmpfs (= fast data access).</p>\n<p>Either way, it is going to be easier to perform your calculations (rebates) in bulk, when all the data has been imported. You can create views, temporary tables etc. If your needs become more complex, then you can use a mix of Python and SQlite, or choose a database that supports stored procedures to handle more sophisticated computations.</p>\n<p>I don't think the approach you've chosen is optimal. At the very least I would recommend that you separate these two concerns in your coding: the import of data, and the transformation of data. My suggestion is to reconsider the tools available for the job. It seems to me that you can ditch those classes and simplify the job a lot if you choose the DB approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T14:50:14.037", "Id": "258804", "ParentId": "258775", "Score": "2" } } ]
{ "AcceptedAnswerId": "258790", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T19:01:39.120", "Id": "258775", "Score": "8", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Print receipt from cash register in Python" }
258775
<p>This is meant to be a drop in replacement for getline as it's not crossplatform. I am trying to do as minimal work as possible in here including only calling strlen once at the very end to calculate the size of the final block.</p> <p>returns -1 for error, 0 for EOF, 1 for success</p> <p>The way it works it by setting the last two bytes in the array as <code>[0, 1]</code> and if the buffer is filled it will look like <code>[X,0]</code>, <code>X</code> being either <code>LF</code> where we are done, or something else meaning we need to realloc and loop again unless we are at eof.</p> <pre class="lang-c prettyprint-override"><code>int fgets_line(char **line, size_t *capacity, size_t *length, FILE *stream) { if (!*line &amp;&amp; !(*line = malloc(*capacity = 64))) return *capacity = 0, -1; (*line)[0] = 0; if (length) *length = 0; char *position = *line; while (1) { (*line)[*capacity - 1] = 1; (*line)[*capacity - 2] = 0; if (fgets(position, *line + *capacity - position, stream)) { if ((*line)[*capacity - 1] == 0 &amp;&amp; (*line)[*capacity - 2] != '\n') { size_t new_capacity = *capacity * 2; char *tmp = realloc(*line, new_capacity); if (tmp) { position = tmp + *capacity - 1; *line = tmp; *capacity = new_capacity; } else return -1; } else goto success; } else if (position != *line) { if (feof(stream)) goto success; return -1; } else return 0; } success: if (length) *length = position - *line + strlen(position); return 1; } </code></pre> <p>usage is similar to getline</p> <pre class="lang-c prettyprint-override"><code>int main() { char *line = NULL; size_t capacity = 0, length = 0; int result = 0; while ((result = fgets_line(&amp;line, &amp;capacity, &amp;length, stdin))) printf(&quot;---Capacity: %-8zuLength: %-8zu---\n%s------\n&quot;, capacity, length, line); } </code></pre>
[]
[ { "body": "<ul>\n<li><p>Do not put the sentinel characters in every iteration. Set them before the loop, and after a successful reallocation.</p>\n<p>Also, <code>(*line)[*capacity - 2] = 0;</code> is redundant. Indeed, if <code>(*line)[*capacity - 1]</code> remains <code>1</code> we don't care, and if it turns to <code>0</code> then <code>(*line)[*capacity - 2]</code> has been overwritten anyway.</p>\n</li>\n<li><p><code>goto</code> is totally unwarranted. <code>break</code> works very well.</p>\n</li>\n<li><p>Do not handle <code>fgets</code> failures inside the loop. Break immediately.</p>\n</li>\n<li><p>Using <code>position</code> as an index, rather than the pointer, seems cleaner. Consider</p>\n<pre><code> fgets(*line + position, *capacity - position, stream)\n</code></pre>\n<p>etc.</p>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T22:50:38.187", "Id": "258788", "ParentId": "258778", "Score": "3" } }, { "body": "<p><strong>Error: Mishandles input errors</strong></p>\n<p>When <code>fgets()</code> returns <code>NULL</code> due to an input error, this function might return 0 (for end-of-file).</p>\n<p><strong>Lack of in code documentation</strong></p>\n<p>A <em>declaration</em> like <code>int fgets_line(char **line, size_t *capacity, size_t *length, FILE *stream);</code> deserves documentation describing the goals and function limitations. (e.g. a .h file.) Do not assume users want to dissect the function source code to learn basic functionality.</p>\n<p><strong>Minimum work</strong></p>\n<p>&quot;minimal work as possible&quot; --&gt; User I/O is a sink-hole of time. A linear extra call to <code>strlen()</code> will not be noticed.</p>\n<p><strong>Pedantic: Reliance on not reading a <em>null character</em></strong></p>\n<p>Code performs incorrectly with <code>*length = position - *line + strlen(position);</code> should <code>fgets()</code> read a <em>null character</em>.</p>\n<p>Either adjust code to detect reading a <em>null character</em> (not easy) or consider dropping the <code>length</code> parameter. Calling code can use <code>strlen()</code> if desired.</p>\n<p><strong>Pedantic: <code>*capacity</code> not validated</strong></p>\n<p>If <code>fgets_line()</code> is called with a wee <code>*capacity</code> (like 0 or 1), <code>(*line)[various]</code> risks accessing the array out of bounds. Take care in assuming how the caller set up the buffer pointer and size. It may have been <em>right-sized</em> after a prior read.</p>\n<p><strong>Pedantic: Out of <code>int</code> range</strong></p>\n<p><code>fgets()</code> uses an <code>int</code> for the size, so <code>*line + *capacity - position</code> risks out-of-range conversion.</p>\n<hr />\n<p><strong>Design</strong></p>\n<p>I am not a fan of giving the user the ability to overwhelm memory resources and prefer a sane upper bound to allocation size.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T19:00:52.137", "Id": "510440", "Score": "0", "body": "Thanks for pointing out that fgets skips over NULL bytes, that hadn't even occurred to me. This function is supposed to return 0 for EOF, but I guess a valid point could be made that 0 should be success, -1 for EOF, and 1 for error. I did notice the out of int range problem when compiling with MSVC, and planned to solve it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T19:04:39.677", "Id": "510441", "Score": "0", "body": "@Anotra `fgets()` does not skip over _null characters_. It reads and saves them like any other non-`'\\n'` character. The trouble is that it is hard to detect them for the caller." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T19:05:34.030", "Id": "510442", "Score": "0", "body": "right, my wording was bad. That's what I mean" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T02:56:27.337", "Id": "258861", "ParentId": "258778", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T20:00:29.800", "Id": "258778", "Score": "2", "Tags": [ "c" ], "Title": "C fgets_line of arbitrary length" }
258778
<p>I am coding a JS Mandelbrot Set viewer and am looking for suggestions on how to improve my code. I already did some cleanup and got the execution time from 7s to about 160ms on my computer.</p> <p>Some info about my Code:</p> <ul> <li>Complex numbers are stored as an array where the first number is the real part and the second one is the imaginary part.</li> <li>the <code>isInBulb</code> checks if the coordinate is inside one of the 2 bigger white areas and instantly returns <code>maxIterations</code></li> </ul> <p>If you have any further questions feel free to ask :)</p> <p>I haven't implemented any optimizations based on symmetry, I plan on adding the ability to zoom in once I am happy with the performance and any optimizations based on that wouldn't have much impact zoomed in.</p> <p>I am mainly looking for suggestions increasing the speed or making the code more elegant while not making it any slower.</p> <p>Thank you :)</p> <p><a href="https://codepen.io/Teiem/pen/YzNWXeR" rel="nofollow noreferrer">https://codepen.io/Teiem/pen/YzNWXeR</a></p> <p><code>Main.js:</code></p> <pre><code>const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const width = 1600; const height = 1200; const scale = 0.4 * Math.min(width, height); const offsetX = width / 2; const offsetY = height / 2; const maxIterations = 512; canvas.width = width; canvas.height = height; const workers = []; const createWorkers = () =&gt; { for (let i = 0; i &lt; navigator.hardwareConcurrency; i++) { const worker = new Worker(&quot;./script/worker/worker.js&quot;); workers.push(worker); worker.onmessage = renderDone; } }; let tW; const manageRender = () =&gt; { const sab = new SharedArrayBuffer(width * height * 4); perHeight = height / workers.length; rowsDone = 0; workers.forEach((worker, i) =&gt; worker.postMessage([ sab, width, height, offsetX, offsetY, scale, maxIterations, Math.floor(perHeight * i), Math.floor(perHeight * (i + 1)), ])) tW = performance.now(); }; let doneWorkers = 0; const renderDone = ({data}) =&gt; { // console.log(rowsDone, performance.now() - tW, &quot;ms&quot;); if (++rowsDone !== workers.length) return; ctx.putImageData(new ImageData(new Uint8ClampedArray(data).slice(), width, height), 0, 0); // const t1 = performance.now(); // console.log(t1 - t0 + ' ms'); }; createWorkers(); const t0 = performance.now(); manageRender(); </code></pre> <p><code>Worker.js:</code></p> <pre><code>let width, height, offsetX, offsetY, scale, maxIterations; const addComplex = (a, b) =&gt; { a[0] += b[0]; a[1] += b[1]; return a; }; const squareComplex = (a) =&gt; { const oldReal = a[0]; a[0] = a[0] ** 2 - a[1] ** 2; a[1] = 2 * oldReal * a[1]; return a; }; const a = [0, 0, 0]; const b = [0.59, 0.55, 0.75]; const c = [0.1, 0.2, 0.3]; const d = [0.75, 0.75, 0.75]; const generateColor = step =&gt; [0, 1, 2].map(i =&gt; (a[i] + b[i] * Math.cos(6.28318 * (c[i] * step + d[i]))) * 255); // const period = 20; const testIfEscapes = c =&gt; { let z = [0, 0]; // let xOld = 0; // let yOld = 0; for (let i = 0; i &lt; maxIterations; i++) { z = squareComplex(addComplex(z, c)); const absZ = z[0] ** 2 + z[1]**2; if (absZ &gt; 4) return i; // if (z[0] === xOld &amp;&amp; z[1] === yOld) return maxIterations; // if (i % period === 0) { // xOld = z[0]; // yOld = z[1]; // } } return maxIterations; }; const isInBulb = c =&gt; { const x = c[0]; const y = c[1]; const q = (x - 0.25) ** 2 + y ** 2; return (q * (q + (x - 0.25))) &lt;= (0.25 * y ** 2) || ((x + 1) ** 2 + y ** 2) &lt;= (0.0625) ? maxIterations : testIfEscapes(c); }; const getColorAtPosition = (x, y) =&gt; { const escapesIn = isInBulb([(x - offsetX) / scale, (y - offsetY) / scale]); if (escapesIn === maxIterations) return [230, 247, 255]; if (escapesIn === 0) return [0, 0, 0]; return generateColor(escapesIn / 512); }; let once = true; const render = (uint8ClampedArray, fromY, toY) =&gt; { for (let x = 0; x &lt; width; x++) { for (let y = fromY; y &lt; toY; y++) { const [r, g, b] = getColorAtPosition(x, y); const off = (y * width + x) * 4; uint8ClampedArray[off] = r; uint8ClampedArray[off + 1] = g; uint8ClampedArray[off + 2] = b; uint8ClampedArray[off + 3] = 255; } } }; onmessage = ({data: [buffer, _width, _height, _offsetX, _offsetY, _scale, _maxIterations, fromY, toY]}) =&gt; { width = _width; height = _height; offsetX = _offsetX; offsetY = _offsetY; scale = _scale; maxIterations = _maxIterations; // uint8ClampedArray = buffer ?? new Uint8ClampedArray(buffer); // const t0 = performance.now(); render(new Uint8ClampedArray(buffer), fromY, toY); // const t1 = performance.now(); // console.log(t1 - t0 + ' ms', fromY, toY); postMessage(buffer); } </code></pre>
[]
[ { "body": "<h2>Review</h2>\n<p>Some bad habits and inappropriate data structures used.</p>\n<ul>\n<li><p>It is a very bad habit to leave commented code in your source.</p>\n</li>\n<li><p>Only use arrays when all the items represent the same thing.</p>\n<p>Using arrays to hold structured data makes code very hard to read and sensitive to changes like item order, number of properties, etc. You use arrays for the data passed to the workers, defining the color channel modulation frequencies, and to hold complex numbers.</p>\n<p>The rewrite uses Objects with named properties rather than arrays.</p>\n</li>\n<li><p>Do not use <code>let</code> in global scope as they become globals (not scoped to the script but to the page) and can cause your code or 3rd party code to throw errors because either attempt to redefine the variable or access the variable while it is in dead space.</p>\n<p>Note it is safe to use <code>let</code> in modules and workers (local) scope</p>\n</li>\n<li><p>You have some undeclared variables. (<code>perHeight</code> and <code>rowsDone</code>) You should use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Strict mode\">Strict_mode</a> to prevent common bad practices from becoming bad habits. Also strict mode code runs faster.</p>\n</li>\n</ul>\n<h2>Workers</h2>\n<p>Good to see you are aware of <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/NavigatorConcurrentHardware/hardwareConcurrency\" rel=\"nofollow noreferrer\" title=\"MDN Web API's navigator hardwareConcurrency\">navigator.hardwareConcurrency</a> and use it to get the number of hardware cores to use.</p>\n<p>Some further points when using workers.</p>\n<ul>\n<li><p>When creating workers it is best to use only available hardware cores.</p>\n<p>Rather than create <code>navigator.hardwareConcurrency</code> workers, use one less, leaving a core free to handle the main thread.</p>\n</li>\n<li><p>When you no longer need a worker you should remove it.</p>\n<p>Even when worker threads are idle they still exist an as such have a resource foot print. Call the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/worker/terminate\" rel=\"nofollow noreferrer\" title=\"MDN Web API's worker terminate\">worker.terminate</a> terminate function to remove the worker.</p>\n</li>\n<li><p>When you first use a worker there is a considerable overhead as the page needs to setup a context for the workers. As such timing performance outside the worker will give an inaccurate representation of the time taken to do the work.</p>\n<p>See rewrite. Moves the timing measurement into the worker which passes the time back to the main thread. This will give you a far more accurate time to render pixels.</p>\n</li>\n<li><p>The shared array buffer reference does not need to be passed back to the main thread. You do so as you need to communicate the buffer reference to the function handling the workers incoming message.</p>\n<p>The rewrite handles the outgoing and incoming messages in the same scope thus the shared buffer reference does not need to be passed back from the worker. The incoming message only has the time.</p>\n<p>Also there is no need to create a view of the shared buffer when sending the reference to the worker.</p>\n</li>\n<li><p>Always use <code>addEventListener</code> to add listeners rather than directly assign a listener to a <code>on</code> property. This ensures that the listener is not overwritten or overwriting others that directly assign listeners.</p>\n</li>\n</ul>\n<h2>Pixels</h2>\n<p>The example uses <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Uint32Array\">Uint32Array</a> view of the shard pixel data. This allows fast writes to the pixel data as you can set a pixel in a single expression rather than 4 (when done per RGBA channel)</p>\n<p>Note that RGBA32 has channels from highest to lowest bytes Alpha <code>0xFF000000</code>, Blue <code>0x00FF0000</code>, Green <code>0x0000FF00</code>, Red <code>0x000000FF</code> (numbers are bit masks for each channel)</p>\n<h2>Rewrite</h2>\n<p>The example creates a worker from a function as CR snippets do not allow linking scripts. The worker functions is marked with string directives <code>&quot;##START##&quot;</code> and <code>&quot;##END##'</code> to simplify trimming the function string. These are arbitrary directives and not required if creating workers from a file reference.</p>\n<p>I have also modified the behavior to render the canvas sized to fit the page rather than set to a fixed size.</p>\n<p>Note the rewrite was not written with performance in mind. Rather it was was written to improve data handling, and worker management.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ctx = canvas.getContext('2d');\nconst width = canvas.width = innerWidth;\nconst height = canvas.height = innerHeight;\nconst scale = 0.4 * Math.min(width, height);\nconst offsetX = width / 2;\nconst offsetY = height / 2;\nconst maxIterations = 512;\nconst workers = [];\ncreateWorkers(MBRenderWorker);\nmanageRender(renderDone);\n\nfunction createWorkers(workerFunction) {\n const functionStr = workerFunction.toString().replace(/.*?##START##\";|\"##END##\";.*/g, \"\");\n var i = Math.max(1, (navigator.hardwareConcurrency ?? 2) - 1);\n while (i--) {\n workers.push(new Worker(URL.createObjectURL(new Blob([functionStr], {type : 'application/javascript'}))));\n }\n}\nfunction manageRender(done){\n const sab = new SharedArrayBuffer(width * height * 4);\n const perHeight = height / workers.length;\n var workerCount = workers.length, totalTime = 0;\n const jobsDone = workerCount;\n workers.forEach((worker, i) =&gt; {\n worker.postMessage({\n pixels: sab, \n width, height, offsetX, offsetY,\n scale, maxIterations,\n fromY: Math.floor(perHeight * i),\n toY: Math.floor(perHeight * (i + 1)),\n });\n worker.addEventListener(\"message\", message =&gt; {\n worker.terminate();\n totalTime += message.data.time;\n if (!--workerCount) { \n done(sab);\n info.textContent = \"Time to render \" + totalTime.toFixed(2) + \"ms using \" + jobsDone + \" threads\";\n }\n });\n });\n}\nfunction renderDone(array) {\n ctx.putImageData(new ImageData(new Uint8ClampedArray(array).slice(), width, height), 0, 0);\n}\n\n\n\n\n\n\nfunction MBRenderWorker() {\"##START##\";\"use strict\";\n const RGB = (r, g, b) =&gt; ({r, g, b});\n const a = RGB(0, 0, 0);\n const b = RGB(0.59, 0.55, 0.75);\n const c = RGB(0.1, 0.2, 0.3);\n const d = RGB(0.75, 0.75, 0.75);\n const generateColor = step =&gt; 0xFF000000 +\n (((a.r + b.r * Math.cos(6.28318 * (c.r * (step / 512) + d.r))) * 255) &amp; 0xFF) +\n (((a.g + b.g * Math.cos(6.28318 * (c.g * (step / 512) + d.g))) * 0xFF00) &amp; 0xFF00) +\n (((a.b + b.b * Math.cos(6.28318 * (c.b * (step / 512) + d.b))) * 0xFF0000) &amp; 0xFF0000);\n const ComplexNum = (a = 0, i = 0) =&gt; ({a, i});\n const add = (a, b) =&gt; {\n a.a += b.a;\n a.i += b.i;\n return a;\n }\n const square = cplx =&gt; {\n [cplx.a, cplx.i] = [cplx.a ** 2 - cplx.i ** 2, 2 * cplx.a * cplx.i];\n return cplx;\n }\n const distSqr = cplx =&gt; cplx.a * cplx.a + cplx.i * cplx.i;\n const testIfEscapes = (c, maxIterations) =&gt; {\n var i = 0;\n const z = ComplexNum();\n while (i++ &lt;= maxIterations) { if (distSqr(square(add(z, c))) &gt; 4) { break } }\n return --i;\n }\n const isInBulb = pos =&gt; {\n const q = (pos.a - 0.25) ** 2 + pos.i ** 2;\n return (q * (q + (pos.a - 0.25))) &lt;= (0.25 * pos.i ** 2) || ((pos.a + 1) ** 2 + pos.i ** 2) &lt;= (0.0625);\n }\n const getColorAtPosition = (data, x, y) =&gt; {\n const pos = ComplexNum((x - data.offsetX) / data.scale, (y - data.offsetY) / data.scale);\n const inBulb = isInBulb(pos);\n if (inBulb) { return 0xFFFFF8E0 }\n const iterations = testIfEscapes(pos, data.maxIterations);\n return !iterations ? 0xFF000000 : generateColor(iterations);\n }\n const render = (data) =&gt; {\n const pixels = new Uint32Array(data.pixels);\n var x, y;\n for (x = 0; x &lt; data.width; x++) {\n for (y = data.fromY; y &lt; data.toY; y++) { \n pixels[y * data.width + x] = getColorAtPosition(data, x, y);\n }\n }\n }\n addEventListener(\"message\", message =&gt; {\n const start = performance.now();\n render(message.data);\n postMessage({time: performance.now() - start});\n });\n\"##END##\";}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas {\n position: absolute;\n top: 0px;\n left: 0px;\n}\ndiv {\n position: absolute;\n top: 10px;\n left: 10px;\n color: white;\n font-family: arial;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;canvas id=\"canvas\"&gt;&lt;/canvas&gt;\n&lt;div id=\"info\"&gt;fghfh&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T23:26:15.340", "Id": "258858", "ParentId": "258781", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T20:42:09.263", "Id": "258781", "Score": "2", "Tags": [ "javascript", "performance" ], "Title": "JS Mandelbort Set Viewer" }
258781
<p>I've just taken the leap over to RTK instead of 'vanilla' redux and am blown away by how much less code I need to write. I'm not entirely sure how to structure my slices, however, and figured I'd ask for a small code review so I do not accidentally start breaking conventions from the start. This is how one of my slices is currently looking:</p> <pre><code>import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'; import bundle from '../../bundler'; import {BundleStartAction, BundleCompleteAction, BundlesState } from './bundleSliceInterface.ts' export const createBundle = createAsyncThunk( 'bundle', async (data: { cellId: string; input: string }, thunkAPI) =&gt; { const { cellId, input } = data; thunkAPI.dispatch(bundleStart({ cellId })); const result = await bundle(input); thunkAPI.dispatch( bundleComplete({ cellId, bundle: { code: result.code, err: result.err } }) ); } ); const initialState: BundlesState = {}; const bundleSlice = createSlice({ name: 'bundle', initialState, reducers: { bundleStart: (state, action: PayloadAction&lt;BundleStartAction&gt;) =&gt; { state[action.payload.cellId] = { loading: true, code: '', err: '' }; }, bundleComplete: (state, action: PayloadAction&lt;BundleCompleteAction&gt;) =&gt; { state[action.payload.cellId] = { loading: false, code: action.payload.bundle.code, err: action.payload.bundle.err, }; }, }, extraReducers: {}, }); export const { bundleStart, bundleComplete } = bundleSlice.actions; export default bundleSlice.reducer; </code></pre> <p>Any feedback or tips on how to structure slices properly is greatly appreciated.</p> <p>Thanks in advance!</p>
[]
[ { "body": "<blockquote>\n<p>I am blown away by how much less code I need to write</p>\n</blockquote>\n<p>I'm going to blow your mind even more because you actually do not need to <code>dispatch</code> any actions inside <code>createAsyncThunk</code>. It does that for you!</p>\n<p>The &quot;pending&quot; action doesn't have a <code>payload</code> so getting the <code>cellId</code> is a little bit tricky. You can <a href=\"https://redux-toolkit.js.org/api/createAsyncThunk#promise-lifecycle-actions\" rel=\"nofollow noreferrer\">see the types of the dispatched actions in the docs</a>. The property that you want is <code>action.meta.arg.cellId</code>.</p>\n<p>You get better TypeScript support on your reducer by using the <a href=\"https://redux-toolkit.js.org/api/createReducer#usage-with-the-builder-callback-notation\" rel=\"nofollow noreferrer\">builder callback notation</a>. It already knows the types of your thunk actions!</p>\n<p>The part that I am unclear on is what your <code>bundle</code> function does as it seems like it catches errors on its own? That's fine but you can also throw errors in the inner function of <code>createAsyncThunk</code> and handle them in the reducer with the <code>createBundle.rejected</code> action. You can also use the <a href=\"https://redux-toolkit.js.org/api/createAsyncThunk#handling-thunk-errors\" rel=\"nofollow noreferrer\"><code>rejectWithValue</code> helper</a> to customize the error <code>payload</code>.</p>\n<pre><code>export const createBundle = createAsyncThunk(\n &quot;bundle/create&quot;,\n async (data: { cellId: string; input: string }) =&gt; {\n const { cellId, input } = data;\n const result = await bundle(input);\n // this is the payload\n return {\n cellId,\n bundle: result\n };\n }\n);\n\nconst initialState: BundlesState = {};\nconst bundleSlice = createSlice({\n name: &quot;bundle&quot;,\n initialState,\n reducers: {},\n extraReducers: (builder) =&gt;\n builder\n .addCase(createBundle.pending, (state, action) =&gt; {\n const { cellId } = action.meta.arg;\n state[cellId] = { loading: true, code: &quot;&quot;, err: &quot;&quot; };\n })\n .addCase(createBundle.rejected, (state, action) =&gt; {\n //??\n })\n .addCase(createBundle.fulfilled, (state, action) =&gt; {\n const { bundle, cellId } = action.payload;\n state[cellId] = {\n loading: false,\n code: bundle.code,\n err: bundle.err\n };\n })\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-23T02:15:24.607", "Id": "259888", "ParentId": "258784", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T21:09:57.270", "Id": "258784", "Score": "5", "Tags": [ "react.js", "redux" ], "Title": "Redux Toolkit Structure with TS" }
258784
<p>So i've been working on Tetris in python. The code is not finished but it does run some basic tests. I have showed several people my code on Disocrd and one person had a a lot to say about my code. He was confused as to why i have two classes for Tetris pieces. He didn't understand my wall-kick data structure. Also he didn't get why I have two ids for a Tetris piece id and rid.</p> <p>First of all let me explain some of my code that might be confusing. I have a TetrominoCore class. It stores data about a tetris piece like for instance what a Z piece looks like and its rotations. It does not store the location of the piece. For that i have a Tetromino class. He was confused and said why dont i just use inheritance instead of id references. I have two ids for my pieces id and rid. Id indexes the teromino array to get the right data for a speicefic piece while rid indexes the states of a tetronmino core basically the rotations. Im sorry if this is really confusing.</p> <p>If you didnt get any of that i hope you can still provide some input on my code and how i can improve it thank you.</p> <p><a href="https://github.com/MonkeyToiletLadder/Tetris" rel="nofollow noreferrer">https://github.com/MonkeyToiletLadder/Tetris</a></p> <pre><code>&quot;&quot;&quot; tetromino.py Author: Vaxeral Tetris version 0.1.0 March 25 2021 &quot;&quot;&quot; import numpy from enum import IntEnum from typing import NewType from typing import List from typing import Dict from typing import Tuple from weight import TetrisWeight as Weight from field import TetrisField as Field from time import time class WallkickTests: def __init__( self, stor: List[Tuple[int, int]], rtos: List[Tuple[int, int]], rtot: List[Tuple[int, int]], ttor: List[Tuple[int, int]], ttol: List[Tuple[int, int]], ltot: List[Tuple[int, int]], ltos: List[Tuple[int, int]], stol: List[Tuple[int, int]] ): self.tests = [ [numpy.array(t) for t in stor], [numpy.array(t) for t in rtos], [numpy.array(t) for t in rtot], [numpy.array(t) for t in ttor], [numpy.array(t) for t in ttol], [numpy.array(t) for t in ltot], [numpy.array(t) for t in ltos], [numpy.array(t) for t in stol] ] def __getitem__( self, key: int ) -&gt; List[Tuple[int, int]]: return self.tests[key] class TetrominoState: def __init__(self, shape, left, right, bottom): self.bottom = bottom self.left = left # Used to detect collisions with the left wall. self.right = right # Used to detect collisions with the right wall. self.shape = shape # The shape of the particular state/rotation. def get_left_bound( self, field: Field ) -&gt; int: return 0 - self.left def get_right_bound( self, field: Field ) -&gt; int: return field.width - (self.right + 1) def get_bottom_bound( self, field: Field ) -&gt; int: return field.height - (self.bottom + 1) TetrominoShape = NewType('TetrominoShape', numpy.array) class TShape(IntEnum): I = 0 J = 1 L = 2 O = 3 S = 4 T = 5 Z = 6 class TetrominoCore: # Flyweight pattern def __init__( self, shape: TetrominoShape ): self.states: List[TetrominoState] = [] # The states/rotations of the shape shapes = TetrominoCore.generate_rotations(shape) for shape in shapes: self.states.append(TetrominoCore.to_state(shape)) def get_state( self, rid: int ): return self.states[rid] @staticmethod def generate_rotations( shape: TetrominoShape ) -&gt; List[TetrominoShape]: shapes = [] array = numpy.array(shape) shapes.append( array ) shapes.append( numpy.rot90(array, 1) ) shapes.append( numpy.rot90(array, 2) ) shapes.append( numpy.rot90(array, 3) ) return shapes @staticmethod def to_state( shape: TetrominoShape ) -&gt; TetrominoState: left = len(shape[0]) right = 0 bottom = 0 for j in range(len(shape)): for i in range(len(shape[0])): block = shape[j][i] if block: if i &lt; left: left = i if i &gt; right: right = i if j &gt; bottom: bottom = j return TetrominoState(shape, left, right, bottom) tetrominoes = [ TetrominoCore([ # I [0,0,0,0], [1,1,1,1], [0,0,0,0], [0,0,0,0], ]), TetrominoCore([ # J [1,0,0], [1,1,1], [0,0,0] ]), TetrominoCore([ # L [0,0,1], [1,1,1], [0,0,0] ]), TetrominoCore([ # O [0,0,0,0], [0,1,1,0], [0,1,1,0], [0,0,0,0] ]), TetrominoCore([ # S [0,1,1], [1,1,0], [0,0,0] ]), TetrominoCore([ # T [0,1,0], [1,1,1], [0,0,0] ]), TetrominoCore([ # Z [1,1,0], [0,1,1], [0,0,0] ]) ] wallkicks = [ WallkickTests( [( 0, 0),(-1, 0),(-1, 1),( 0,-2),(-1,-2)], [( 0, 0),( 1, 0),( 1,-1),( 0, 2),( 1, 2)], [( 0, 0),( 1, 0),( 1,-1),( 0, 2),( 1, 2)], [( 0, 0),(-1, 0),(-1, 1),( 0,-2),(-1,-2)], [( 0, 0),( 1, 0),( 1, 1),( 0,-2),( 1,-2)], [( 0, 0),(-1, 0),(-1,-1),( 0, 2),(-1, 2)], [( 0, 0),(-1, 0),(-1,-1),( 0, 2),(-1, 2)], [( 0, 0),( 1, 0),( 1, 1),( 0,-2),( 1,-2)] ), WallkickTests( [( 0, 0),(-2, 0),( 1, 0),(-2,-1),( 1, 2)], [( 0, 0),( 2, 0),(-1, 0),( 2, 1),(-1,-2)], [( 0, 0),(-1, 0),( 2, 0),(-1, 2),( 2,-1)], [( 0, 0),( 1, 0),(-2, 0),( 1,-2),(-2, 1)], [( 0, 0),( 2, 0),(-1, 0),( 2, 1),(-1,-2)], [( 0, 0),(-2, 0),( 1, 0),(-2,-1),( 1, 2)], [( 0, 0),( 1, 0),(-2, 0),( 1,-2),(-2, 1)], [( 0, 0),(-1, 0),( 2, 0),(-1, 2),( 2,-1)] ) ] class Tetromino(Weight): def __init__( self, id: int, position: Tuple[int, int], speed: float, field: Field ): Weight.__init__(self, position, speed, field) self.id = id + 1 self.rid = 0 # The state/rotation id. Indexes the list of states in tetromino core self.is_touching = False self.timer = 0 def __str__(self): # I couldnt get pretty print to work so there is this. shape = self.get_state().shape string = &quot;[\n&quot; for j in range(len(shape)): string += '\t' for i in range(len(shape[0])): string += f&quot;{shape[j][i]}, &quot; string += '\n' string += ']\n' return string def get_core(self): return tetrominoes[self.id - 1] def get_state( self, rid = None ) -&gt; TetrominoState: if not rid: rid = self.rid return self.get_core().get_state(rid) def get_next_state( self, direction: str ) -&gt; TetrominoState: rid = self.rid if direction == 'left': rid += 1 elif direction == 'right': rid -= 1 if rid &lt; 0: rid = 3 if rid &gt; 3: rid = 0 return self.get_core().get_state(rid) def set_next_state( self, direction: str ): if direction == 'left': self.rid += 1 elif direction == 'right': self.rid -= 1 if self.rid &lt; 0: self.rid = 3 if self.rid &gt; 3: self.rid = 0 def get_wallkick_tests( self, dir: str ) -&gt; int: next_rid = None if dir == 'left': next_rid = self.rid + 1 elif dir == 'right': next_rid = self.rid - 1 if next_rid &lt; 0: next_rid = 3 elif next_rid &gt; 3: next_rid = 0 tests = None if self.rid == 0 and next_rid == 3: tests = 0 elif self.rid == 3 and next_rid == 0: tests = 1 elif self.rid == 3 and next_rid == 2: tests = 2 elif self.rid == 2 and next_rid == 3: tests = 3 elif self.rid == 2 and next_rid == 1: tests = 4 elif self.rid == 1 and next_rid == 2: tests = 5 elif self.rid == 1 and next_rid == 0: tests = 6 elif self.rid == 0 and next_rid == 1: tests = 7 id = self.id - 1 if id != TShape.O or id != TShape.I: return wallkicks[0][tests] if id == TShape.I: return wallkicks[1][tests] return -1 def move_left( self ): state = self.get_state() # Check if the tetromino is against the left wall if self.position[0] &lt;= state.get_left_bound(self.field): print(&quot;Cant move left.&quot;) return # Try to move left. If there is overlap then exit, cant move left. x = int(self.position[0] - 1) y = int(self.position[1]) for j in range(len(state.shape)): for i in range(len(state.shape[0])): l = y k = x if state.shape[j][i] and self.field[l + j][k + x]: print(&quot;Cant move left&quot;) return self.position[0] -= 1 def move_right( self ): state = self.get_state() # Check if the tetromino is against the left wall if self.position[0] &gt;= state.get_right_bound(self.field): print(&quot;Cant move right.&quot;) return # Try to move left. If there is overlap then exit, cant move left. x = int(self.position[0] + 1) y = int(self.position[1]) for j in range(len(state.shape)): for i in range(len(state.shape[0])): l = y k = x if state.shape[j][i] and self.field[l + j][k + i]: print(&quot;Cant move right&quot;) return self.position[0] += 1 def fall( self ): state = self.get_state() if self.position[1] &gt;= state.get_bottom_bound(self.field): if not self.is_touching: self.timer = time() self.is_touching = True return x = int(self.position[0]) y = int(self.position[1] + 1) for j in range(len(state.shape)): for i in range(len(state.shape[0])): l = y k = x if state.shape[j][i] and self.field[l + j][k + i]: if not self.is_touching: self.timer = time() self.is_touching = True return self.is_touching = False self.position[1] += self.speed def rotate( self, dir: str ): tests = self.get_wallkick_tests(dir) state = self.get_next_state(dir) x = None y = None for test in tests: overlap = False x = test[0] y = test[1] if x &lt;= state.get_left_bound(self.field): continue if x &gt;= state.get_right_bound(self.field): continue if y &gt;= state.get_bottom_bound(self.field): continue for j in range(len(state.shape)): for i in range(len(state.shape[0])): l = y k = x if state.shape[j][i] and self.field[l + j][k + i]: overlap = True if overlap: continue self.set_next_state(dir) self.position[0] = x self.position[1] = y break def stamp( self ): state = self.get_state() x = int(self.position[0]) y = int(self.position[1]) for j in range(len(state.shape)): for i in range(len(state.shape[0])): l = y k = x if state.shape[j][i]: self.field[l + j][k + i] = self.id </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T05:47:31.323", "Id": "510224", "Score": "0", "body": "`from typing import Dict, List, Tuple, NewType` is a common practice, instead of writing multiple import statements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T06:43:44.540", "Id": "510232", "Score": "0", "body": "Thanks i will adopt this into my code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T22:16:38.890", "Id": "258787", "Score": "0", "Tags": [ "python", "tetris" ], "Title": "Tetris in python" }
258787
<p>I'm trying to practice some functional techniques. I haven't worked much in Haskell, so any language-specific tips would be very appreciated, but what I care for even more are general tips towards my approach that I can carry between functional languages. Performance is not a big concern of mine right now.</p> <p>I implemented the winner-checking algorithm for the connect-four game. Basically, given a 6x7 grid, I need to be able to determine if a player has successfully placed four consecutive tiles down (horizontally, vertically, or diagonally). If so, I need to return which player it was.</p> <p>Here is my implementation:</p> <pre class="lang-hs prettyprint-override"><code>module Logic (Player(..), Board, getWinner) where import qualified Control.Monad as Monad data Player = Player1 | Player2 type BoardEntry = Maybe Player type Board = [[BoardEntry]] type Coord a = (a, a) instance Eq Player where Player1 == Player1 = True Player2 == Player2 = True x == y = False map2dList :: (a -&gt; b) -&gt; [[a]] -&gt; [[b]] map2dList fn = map (map fn) getElementAt :: [a] -&gt; Int -&gt; Maybe a getElementAt (el:_) 0 = Just el getElementAt (_:rest) n = getElementAt rest (n - 1) getElementAt [] _ = Nothing getBoardEntryAt :: Board -&gt; Coord Int -&gt; Maybe BoardEntry getBoardEntryAt board (x, y) = getElementAt board y &gt;&gt;= flip getElementAt x getBoardDimensions :: Board -&gt; (Int, Int) getBoardDimensions board = ((length . head) board, length board) addCoords :: Coord Int -&gt; Coord Int -&gt; Coord Int addCoords (x1, y1) (x2, y2) = (x1 + x2, y1 + y2) isCoordInRegion :: (Int, Int) -&gt; Coord Int -&gt; Bool isCoordInRegion (width, height) (x, y) = x &gt;= 0 &amp;&amp; x &lt; width &amp;&amp; y &gt;= 0 &amp;&amp; y &lt; height getAllCoordsInRegion :: (Int, Int) -&gt; [Coord Int] getAllCoordsInRegion (width, height) = [(x,y) | x &lt;- [0..width-1], y &lt;- [0..height-1]] getWinner :: Board -&gt; Maybe Player getWinner board = let fourInRowsFromOrigin = [ [(0, 0), (1, 0), (2, 0), (3, 0)], [(0, 0), (1, 1), (2, 2), (3, 3)], [(0, 0), (0, 1), (0, 2), (0, 3)], [(0, 0), (-1, 1), (-2, 2), (-3, 3)] ] playerPieceAt = Monad.join . getBoardEntryAt board results = concat $ do coord &lt;- (getAllCoordsInRegion . getBoardDimensions) board fourInRow &lt;- map2dList (addCoords coord) fourInRowsFromOrigin player &lt;- [Player1, Player2] return [player | all ((== Just player) . playerPieceAt) fourInRow] in case results of [winner] -&gt; Just winner [] -&gt; Nothing _ -&gt; undefined </code></pre> <p>And here is a sample driver, to help see that it works:</p> <pre class="lang-hs prettyprint-override"><code>import Logic (Player(Player1, Player2), Board, getWinner) getWinnerAsString :: Maybe Player -&gt; [Char] getWinnerAsString Nothing = &quot;No one has won&quot; getWinnerAsString (Just Player1) = &quot;Player 1&quot; getWinnerAsString (Just Player2) = &quot;Player 2&quot; printWinner :: Board -&gt; IO () printWinner = putStrLn . getWinnerAsString . getWinner exampleBoard :: Board exampleBoard = let __ = Nothing p1 = Just Player1 p2 = Just Player2 in [ [__, __, __, __, __, __, __], [__, __, __, __, __, __, __], [__, __, p2, p1, __, __, __], [__, __, p1, p2, __, __, __], [__, p1, p1, p2, p1, __, __], [p1, p2, p2, p2, p1, __, __] ] main :: IO () main = printWinner exampleBoard </code></pre>
[]
[ { "body": "<p>All the indexing can be deleted. You only need the transpose function plus a custom function that grabs the diagonals of a matrix (list of lists, all of the same length).</p>\n<pre><code>import Data.List (transpose)\n\n-- | The 'diagonals' function returns the diagonals of a matrix\ndiagonals :: [[a]] -&gt; [[a]]\ndiagonals matrix = lowerDiags matrix ++ upperDiags matrix\n where lowerDiags = reverse . transpose . zipWith drop [1..]\n upperDiags = transpose . zipWith drop [0..] . transpose\n</code></pre>\n<p>You can invoke it as shown below. If any of the vectors has four in a row, you have a winner.</p>\n<pre><code>board = ...\nvectors = board ++ transpose board ++ diagonals board ++ diagonals (reverse board)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T01:47:24.497", "Id": "258792", "ParentId": "258789", "Score": "3" } }, { "body": "<p>This is very good! The other answer addresses the non-obvious algorithmic improvement, so I'll try to tackle matters of style and hopefully point you toward more FP intuition.</p>\n<p>Since your <code>Player</code> type isn't fancy, just let the compiler derive your instances.</p>\n<pre><code>data Player = Player1 | Player2 deriving Eq\n</code></pre>\n<p>You will probably also benefit from compiling with warnings (add <code>-Wall</code> to your flags, in a cabal file it's <code>ghc-options: -Wall</code> in your <code>executable</code> or <code>library</code> sections). In this case the compiler would have warned you about “unused matches” for <code>x</code> and <code>y</code>. This can help you find definitions where you maybe mistakenly used the wrong variable somewhere. You can tell the compiler “no really, I meant not to use this” by prefixing declarations with an underscore (<code>_x</code> and <code>_y</code>). That will also help tell whoever's reading your code not to expect to see that value used in the definition.</p>\n<p><code>map2dList</code> is equivalently written as <code>map . map</code>. If the reason why isn't immediately obvious, try to work it out from your knowledge of precedence, you'll see weirder and more terse things as you explore higher order functions.</p>\n<p><code>getElementAt</code> is <a href=\"https://hackage.haskell.org/package/safe-0.3.19/docs/Safe.html#v:atMay\" rel=\"nofollow noreferrer\"><code>&quot;safe&quot;.Safe.atMay :: \\[a\\] -&gt; Int -&gt; Maybe a</code></a>. <code>atMay</code> also short circuits on negative numbers, which is a nice convenience feature and also allows you to accept infinite lists. Not relevant to your code now, but you never know what the future holds and how else your functions might be used or by whom.</p>\n<p><code>getBoardEntryAt</code> is clever, there's nothing wrong with it, but I find this version more readable. I'm easily confused whenever I see <code>flip</code> though.</p>\n<pre><code>getBoardEntryAt board (x, y) = join . fmap (`atMay` x) . (`atMay` y) $ board\n</code></pre>\n<p><code>getBoardDimensions</code> is a partial function (from the use of <code>head</code>), you could use <code>headMay</code> from safe or even annotate your function with <code>Safe.Partial.Partial</code> like <code>getBoardDimensions :: Partial =&gt; ...</code>.</p>\n<p><code>isCoordInRegion</code> is dead code, but I'd also write it like—</p>\n<pre><code>isCoordOnBoard :: Board -&gt; Coord Int -&gt; Bool\nisCoordOnBoard board (x, y) =\n let\n (xDim, yDim) = getBoardDimensions board\n between lo v hi = lo &lt;= v &amp;&amp; v &lt; hi\n in\n between 0 x xDim &amp;&amp; between 0 y yDim\n</code></pre>\n<p>Since you're assuming the region begins at <span class=\"math-container\">\\$(0, 0)\\$</span>, I think it makes more sense to make this a function on <code>Board</code>s, not maximum bounds. If you were passing a lower and upper bound that would make the difference for me. I also find it convenient to define a small helper function with a name whenever I see repetition in a function like that, naming things makes the number of concepts you have to juggle in your head drop. Again, valuable for whoever comes to read your code later.</p>\n<p>This function also exists as <a href=\"https://hackage.haskell.org/package/base-4.14.1.0/docs/Data-Ix.html#v:inRange\" rel=\"nofollow noreferrer\"><code>&quot;base&quot;.Data.Ix.inRange :: (Ix a) =&gt; (a, a) -&gt; a -&gt; Bool</code></a>. Pairs are instances of <code>Ix</code>, so you'd use it like <code>inRange ((0, 0), (xDim, yDim)) (x, y)</code>. <code>getAllCoordsInRegion</code> is also in <code>Ix</code> as <code>range</code>. For that matter, you might also want to check out the <a href=\"https://hackage.haskell.org/package/array\" rel=\"nofollow noreferrer\">array</a> package, which isn't in <code>base</code> but is a part of Haskell2010 which means it's basically batteries-included into all modern Haskell compilers (uh... GHC).</p>\n<p><code>getWinner</code> I think benefits primarily from <em>Rainer P.</em>'s answer, I don't have anything else to add since that's overriding. I will note that it's partial in using <code>undefined</code>.</p>\n<p>The only other thing I'd note is how <code>getWinnersAsString</code> returns <code>[Char]</code> instead of <code>String</code>. Unless I'm planning to actually fold over the characters in a <code>String</code> or otherwise look at it letter-wise, use <code>String</code> for non-parseable strings.</p>\n<p>But a lot of the above is me being a huge tyrannical pedant, your code is very good as-is and I'd probably just wave it through an actual code review!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T06:31:16.057", "Id": "510230", "Score": "0", "body": "Thanks so much for the tips - those are very helpful! I am a bit confused with your version of getBoardEntryAt - does it actually work? I had used the \">>=\" operator to flatten the maybe types, you're using \"<$>\", which it seems doesn't do that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T15:36:33.287", "Id": "510257", "Score": "1", "body": "Oops! Sorry, I was testing in the REPL and didn't copy over my final version." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T04:11:37.457", "Id": "258794", "ParentId": "258789", "Score": "3" } } ]
{ "AcceptedAnswerId": "258794", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-27T23:49:27.037", "Id": "258789", "Score": "4", "Tags": [ "haskell", "functional-programming" ], "Title": "Connect-Four winner-checking algorithm" }
258789
<p>I want to solve the following task --- I am given a vector of integers. I want to 'compress' this list, where the elements will be replaced with numbers <code>0</code> through <code>n - 1</code>, where <code>n</code> is the number of unique elements in the vector, such that the relative ordering among the elements is preserved, i.e., if previously <code>vector[index1] &lt; vector[index2]</code>, then that is still true after the compression. In other words, each element is replaced with its ranking among the source vector.</p> <p>For example, given the vector <code>{1, 3, 10, 6, 3, 12}</code>, the elements will be replaced with <code>0</code> through <code>4</code> since there are 5 unique value. To preserve ordering, it will be transformed into <code>{0, 1, 3, 2, 1, 4}</code>.</p> <p>Right now, to complete this, I use the following algorithm:</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt; #include &lt;map&gt; #include &lt;set&gt; #include &lt;vector&gt; using namespace std; int compress_vector(vector&lt;int&gt;&amp; vec) { // function compresses the vector passed in by reference // and returns the total number of unique elements map&lt;int, int&gt; m; set&lt;int&gt; s; for (auto i : vec) s.insert(i); int counter = 0; for (auto i : s) { m[i] = counter; counter++; } for (auto&amp; i : vec) i = m[i]; return s.size(); } int main() { vector&lt;int&gt; vec = { 1, 3, 10, 6, 3, 12 }; // int size = compress_vector(vec); // Should output &quot;0 1 3 2 1 4&quot;, then a newline, then a &quot;5&quot; for (auto i : vec) cout &lt;&lt; i &lt;&lt; &quot; &quot;; cout &lt;&lt; endl; cout &lt;&lt; size; return 0; } </code></pre> <p>However, I feel this function is quite messy --- it uses maps, sets, and counters. While this is functional, is there a <em>faster</em> or <em>cleaner</em> way to do this?</p> <p>Thanks</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T02:47:49.170", "Id": "510222", "Score": "0", "body": "Your example (and expected output) is confusing and difficult to understand." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T04:05:27.177", "Id": "510223", "Score": "0", "body": "@Casey I guess what is meant here is to apply a bijection from the data to `[0, n - 1]` that preserves order, or, in other words, replace each value with its rank among the source array." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T06:22:06.037", "Id": "510227", "Score": "0", "body": "@L.F.: yes, I think this is what I mean. I have been taught that this is called \"list compression,\" but if you have another term/description that would better explain it, please edit it in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T06:28:15.713", "Id": "510228", "Score": "0", "body": "@MikeSmith I think your description is mostly fine. I've edited the question hopefully clarify it; please take a look and refine it as appropriate." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T06:29:09.173", "Id": "510229", "Score": "0", "body": "It's great! Now I just need my original question answered ;)" } ]
[ { "body": "<h1>Algorithm improvements</h1>\n<p>I really don’t understand what this algorithm is supposed to be doing. Your description of it is incomplete and vague (for example, you say <code>vector[index1] &lt; vector[index2]</code>… but what is <code>index1</code> and <code>index2</code>?), and the single example is not illuminating. It <em>looks</em> like you’re just trying to get the sorted position of each element in the vector. So it’s very possible that there is a <em>much</em> better algorithm that can solve this; there’s no way for me to know when what you’re trying to do makes no sense to me.</p>\n<p>However, I <em>can</em> look at what your existing implementation is doing and at least improve on that a bit.</p>\n<p>You use a set to get all the unique elements in the vector, and then you use a map to get… I dunno, something something count (the sorted index?). I can’t help you with the second part. But I <em>can</em> help you with the first part, because you don’t need the set. You can use the map to get the unique values, like so:</p>\n<pre><code>auto compress_vector(std::vector&lt;int&gt;&amp; vec)\n{\n auto m = std::map&lt;int, int&gt;{};\n\n // You don't need the set. You can use the map's keys to get the unique\n // values.\n for (auto i : vec)\n m[i] = 0;\n\n // And then you can recover the &quot;set&quot; of unique values by just iterating\n // on the map's keys.\n auto counter = 0;\n for (auto [i, _] : m)\n m[i] = counter++;\n\n // The above loop may be optimized by avoiding the duplicate lookup:\n // for (auto&amp; p : m)\n // p-&gt;second = counter++;\n\n for (auto&amp; i : vec)\n i = m[i];\n\n return m.size();\n}\n</code></pre>\n<p>You could also go the other way, and keep the set but ditch the map:</p>\n<pre><code>auto compress_vector(std::vector&lt;int&gt;&amp; vec)\n{\n auto s = std::set&lt;int&gt;{};\n\n for (auto i : vec)\n s.insert(i);\n\n // The values of the map are just the indices of the set.\n for (auto&amp; i : vec)\n i = std::distance(s.begin(), s.find(i));\n\n return s.size();\n}\n</code></pre>\n<p>Depending on a lot of factors, it <em>might</em> be more efficient to ditch the set and use a sorted vector instead:</p>\n<pre><code>auto compress_vector(std::vector&lt;int&gt;&amp; vec) {\n // Take care of the degenerate case of an empty input vector first.\n //\n // Not strictly necessary, but will save a lot of work.\n if (vec.empty())\n return 0;\n\n // You could also do this:\n // if (vec.size() == 1)\n // {\n // vec[0] = 0;\n // return 1;\n // }\n\n // A second container, either a map, set, or second vector, is probably\n // unavoidable, because we need to keep track of the original values while\n // also changing the vector's contents, in order to know the sorted\n // indices.\n //\n // Note that this is the lazy way of building the sorted vector. If there\n // are a lot of duplicate values, it *might* be faster to:\n // 1) reserve vec.size()\n // 2) for each element in vec, do a lower_bound() search, to find if\n // it's already in sorted, and if not, then you have the insert\n // position\n auto sorted = vec;\n std::sort(sorted.begin(), sorted.end());\n sorted.erase(std::unique(sorted.begin(), sorted.end()), sorted.end());\n\n // Transform each element in the input vector into the index of the\n // element in the sorted vector.\n std::transform(vec.begin(), vec.end(), vec.begin(),\n [&amp;sorted](auto i)\n {\n // Instead of std::find(), you could also use a binary search,\n // like std::lower_bound().\n return static_cast&lt;int&gt;(\n std::distance(\n sorted.begin(),\n std::find(sorted.begin(), sorted.end(), i)\n )\n );\n }\n );\n\n return sorted.size();\n}\n</code></pre>\n<h1>Code review</h1>\n<pre><code>using namespace std;\n</code></pre>\n<p>This is always a bad idea. You can probably get away with it in simple, toy programs, but you should never do it in real code.</p>\n<pre><code>int compress_vector(vector&lt;int&gt;&amp; vec)\n</code></pre>\n<p>“Out” parameters (function parameters taken by non-<code>const</code> reference, and then modified with the “return” value) are generally not a great idea. They usually make functions harder to use, because they put the onus on the user to set up space for the return. What if I want the original vector <em>and</em> the “compressed” vector? Now I have to deal with the pain of setting up the result manually, rather than just writing <code>auto result = compress_vector(input);</code>. And if the vector I want to “compress” is already <code>const</code> (which is often the case), it’s on me to make a copy again.</p>\n<p>I know there is an argument that out parameters can be more efficient, but that doesn’t really apply here, because you’re creating whole maps, sets, and/or copies of the vector in the function anyway.</p>\n<p>An even better design would be to take an output iterator argument.</p>\n<pre><code>for (auto i : vec) s.insert(i);\n</code></pre>\n<p>Don’t do this. Saving a single line in the function just isn’t worth the risk of missing the hard-to-spot loop body and introducing bugs. If your function is so long that you actually need to save a line or two in order to fit it on screen, your function is too long in any case, and should be broken up.</p>\n<pre><code>for (auto i : vec) s.insert(i);\nint counter = 0;\nfor (auto i : s) {\n m[i] = counter;\n counter++;\n}\nfor (auto&amp; i : vec) i = m[i];\n</code></pre>\n<p>Space out the code. There are <em>THREE</em> loops here, jammed all together. That is three entirely separate logical sections of the function. Each section should be separated from the others by a blank line, to make it clear where the function’s “paragraphs” are. (And, of course, both the first and last loops should not be single lines.)</p>\n<p>You should also consider using algorithms instead of naked loops, for two reasons. First, they make your code clearer: a naked loop could be doing <em>ANYTHING</em>… but an algorithm spells out exactly what is happening. Also, algorithms are <em>much</em> easier to optimize.</p>\n<p>So the big glob of code above could be:</p>\n<pre><code>std::for_each(vec.begin(), vec.end(), [&amp;s](auto i) { s.insert(i); });\n\nauto counter = 0;\nstd::for_each(s.begin(), s.end(), [&amp;m, &amp;counter](auto i) { m[i] = counter++; });\n\nstd::for_each(vec.begin(), vec.end(), [&amp;m](auto&amp; i) { i = m[i]; });\n</code></pre>\n<p>Of course, all three algorithms are <code>for_each()</code> here, because I don’t really understand what the loops are supposed to be doing. <code>for_each()</code> is what you use when nothing else makes more sense. You’ll note that in the modified algorithm I wrote above, I used more specific algorithms, like <code>transform()</code>, <code>unique()</code>, and <code>find()</code> because I understood what was going on.</p>\n<pre><code>return s.size();\n</code></pre>\n<p>You have a bug here. <code>s.size()</code> gives an unsigned type, which is problematic enough, but the real issue is that the type may be (and often is) larger than an <code>int</code>. But you are forcing it to be crammed into an <code>int</code>, which may cause truncation, or other weirdness. If you’re absolutely sure you want <code>compress_vector()</code> to return <code>int</code>, then you should at least assert that the size of the vector is smaller than the maximum value of <code>int</code>. Or, on the other hand, maybe you don’t really want <code>compress_vector()</code> to return <code>int</code>? I don’t understand what you want from this function, so I can’t guess which is the right answer.</p>\n<p>In <code>main()</code>:</p>\n<pre><code>for (auto i : vec) cout &lt;&lt; i &lt;&lt; &quot; &quot;;\n</code></pre>\n<p>Once again, this should not be on a single line. Also, you probably don’t want a whole string constant for just a space; you probably mean <code>' '</code>, not <code>&quot; &quot;</code>.</p>\n<pre><code>cout &lt;&lt; endl;\n</code></pre>\n<p><code>std::endl</code> really makes no sense here. If you want a newline, use a newline: <code>std::cout &lt;&lt; '\\n';</code>.</p>\n<pre><code>return 0;\n</code></pre>\n<p>You don’t need this in <code>main()</code>.</p>\n<h1>Summary</h1>\n<p>Because your description of the problem is so vague and incomplete, and your examples of the intended usage are so limited and unrevealing, it’s impossible to give good recommendations. There is just so much about this function that is unexplained, and so many unanswered questions: Does it really need to modify the input vector; could it not simply return a new vector instead? Why does it return the number of unique elements; is that really important information? Why does it return that value as an <code>int</code>, rather than <code>std::size_t</code> or <code>std::vector::size_type</code>? And so on and so forth.</p>\n<p>The best I can do is offer base-level suggestions going by the literal operations in the given code; in other words, I can only give suggestions for tuning the existing algorithm… I can’t suggest <em>better</em> algorithms, if there are any.</p>\n<p>That said, there are certainly some corners you could cut, and some inefficiencies you could remove. You don’t need a set <em>and</em> a map… that’s just overkill in just about any situation. You might even get away with a sorted vector, which should be <em>way</em> more efficient than either a map or a set… especially if you do a binary search.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T06:35:32.510", "Id": "510231", "Score": "0", "body": "Sorry, I do not have much experience in all of this --- I just made this function on the fly, and the number of unique elements was important to me at the time I made this function. Yes, you could also return a new vector, and from what I have been told, I think that is the better idea. At this point, I am still trying to learn programming paradigms and the \"best\" way to do things. If you want to suggest new code to do it, I am completely fine with that. I believe some of the comments may have cleared up a bit of confusion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T13:30:14.233", "Id": "510250", "Score": "1", "body": "Oh, there’s nothing to apologize for: there’s nothing *wrong* with what you wrote. It’s a fine effort. It’s just that to review code properly, just having the code itself isn’t enough; you need information about the *context*: how that code is going to be used. Programming is engineering; there is no “right” answer, only “this is best for *this* situation”… so the more one knows about the situation, the more useful one’s review comments can be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T13:30:18.323", "Id": "510251", "Score": "0", "body": "For example, I think it’s *possible* to do this “compression” with no extra map, set, or even extra vector—to do it all in place with no extra allocation. But that is going to be a *really* complicated and possibly inefficient algorithm for large data sets. So *if* it *is* really important to use an “out” parameter… *and* your data sets won’t be huge… *and* you really want to avoid the cost of extra allocations… then *maybe* that would be the way to go. It all depends on the context." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T17:54:42.083", "Id": "510259", "Score": "0", "body": "Oh, ok! I get it now. I failed to provide the context. I will do so next time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T12:27:15.927", "Id": "510412", "Score": "0", "body": "I don't know. Creating maps and sets is unpleasantly slow due to lots of allocations but the algo you propose is `O(n^2)` instead of `O(n log n)` which is rather bad. And I don't see how `for_each` is better than a naked range-based for loop. The latter is much more preferred as it is less verbose and thus more clear." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T06:30:05.450", "Id": "258796", "ParentId": "258791", "Score": "4" } }, { "body": "<p>It feels to me that it is a bit too much to create both <code>std::map</code> and <code>std::set</code> for such a simple purpose. You just need to generate sorted order of vec and then to adjust it a little bit so elements with same value are mapped to the same index.</p>\n<pre><code>size_t compress_vector(vector&lt;int&gt;&amp; vec)\n{\n if(vec.empty())\n {\n return 0;\n }\n // plan is to make vector ord of indices so that vec[ord[i]] is sorted\n vector&lt;size_t&gt; ord;\n size_t siz = vec.size();\n ord.reserve(siz);\n\n for(size_t i = 0; i&lt;siz; i++)\n {\n ord.push_back(i);\n }\n\n std::sort(ord.begin(), ord.end(), [&amp;vec](size_t l, size_t r){return vec[l] &lt; vec[r];});\n\n // now with sorted indices one can simply iteratively figure out which mapped value do you have\n // you iterate over elements of ord and keep track of the previous element's value to see if a change in values occurred.\n int prevValue = vec.front();\n size_t count = 0;\n for(size_t i : ord)\n {\n if(prevValue != vec[i])\n {\n prevValue = vec[i];\n count++;\n }\n vec[i] = (int)count;\n }\n\n return count+1;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T17:57:18.850", "Id": "510429", "Score": "0", "body": "I think there might be a solution by using a `std::vector<std::pair<int, int>>` and sorting it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T18:03:42.810", "Id": "510434", "Score": "0", "body": "@MikeSmith yeah instead of sorting `ord` according to some lambda you can create pair where first element is value while second is original index. Then continue with equivalent logical procedure." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T12:18:17.690", "Id": "258869", "ParentId": "258791", "Score": "0" } } ]
{ "AcceptedAnswerId": "258796", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T00:39:51.817", "Id": "258791", "Score": "5", "Tags": [ "c++", "algorithm", "vectors" ], "Title": "Compressing a vector into a specific range" }
258791
<p>I am on my second iteration of the famous &quot;Number Of Islands&quot; graph problem on Leetcode.</p> <p><a href="https://leetcode.com/problems/number-of-islands/" rel="nofollow noreferrer">https://leetcode.com/problems/number-of-islands/</a></p> <pre><code>Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. Example 1: Input: grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;] ] Output: 1 Example 2: Input: grid = [ [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;1&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;0&quot;,&quot;0&quot;], [&quot;0&quot;,&quot;0&quot;,&quot;0&quot;,&quot;1&quot;,&quot;1&quot;] ] Output: 3 </code></pre> <p>My approach is to iterate through each cell in the grid, incrementing a counter when the value == 1. Then, do a breadth-first search of the cell's neighbors, adding them to the queue if their value == 1. Once the queue is empty, keep iterating through all the cells.</p> <p>To avoid infinite loops, I first used a <code>set()</code> to keep track of a list of tuple coordinates. This seemed to jack up my memory usage, so I then improved the algorithm by removing the set and simply setting the value of visited cells to 0.</p> <p>I passed all the test cases but still can't figure out how to get a better runtime. I'm currently slower than ~90% of python submissions.</p> <p>I would appreciate if anyone can help speed this thing up!</p> <pre class="lang-py prettyprint-override"><code> class Solution: def numIslands(self, grid: List[List[str]]) -&gt; int: &quot;&quot;&quot; Gets the neighbors of a coordinate in a grid. Returns a list of tuples. &quot;&quot;&quot; m = len(grid) n = len(grid[0]) def get_neighbors(coord: Tuple[int, int]) -&gt; List[Tuple]: delta_row = [0, 1, 0, -1] delta_column = [1, 0, -1, 0] neighbors = [] for i in range(len(delta_row)): new_x = coord[0] + delta_row[i] new_y = coord[1] + delta_column[i] if -1 &lt; new_x &lt; m and -1 &lt; new_y &lt; n: neighbors.append((new_x, new_y)) return neighbors # loop through the entire grid and set coords to 0 as we visit them # if val == 1, do a breadth-first search for neighbors and increment islands # if val == 0, continue to next coordinate. islands = 0 for i in range(len(grid)): for j in range(len(grid[0])): coord = (i, j) if grid[coord[0]][coord[1]] == &quot;1&quot;: islands += 1 # breadth-first search q = deque([coord]) while len(q) &gt; 0: c = q.popleft() grid[c[0]][c[1]] = &quot;0&quot; for neighbor in get_neighbors(c): if grid[neighbor[0]][neighbor[1]] == &quot;1&quot;: q.append(neighbor) grid[neighbor[0]][neighbor[1]] = &quot;0&quot; return islands </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T08:57:22.007", "Id": "510234", "Score": "0", "body": "Hi! Refer to https://codereview.stackexchange.com/help/how-to-ask for good titling. Edit suggested!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T18:42:57.293", "Id": "510263", "Score": "1", "body": "Thanks for the suggestion and the edit :)" } ]
[ { "body": "<p>My suggestions:</p>\n<ul>\n<li><p>The variables <code>m</code> and <code>n</code> are initialized but never used</p>\n</li>\n<li><p>The function <code>get_neighbors</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_neighbors(coord: Tuple[int, int]) -&gt; List[Tuple]:\n delta_row = [0, 1, 0, -1]\n delta_column = [1, 0, -1, 0]\n\n neighbors = []\n for i in range(len(delta_row)):\n new_x = coord[0] + delta_row[i]\n new_y = coord[1] + delta_column[i]\n\n if -1 &lt; new_x &lt; m and -1 &lt; new_y &lt; n:\n neighbors.append((new_x, new_y))\n\n return neighbors\n</code></pre>\n<p>Can be simplified to:</p>\n<pre><code>def get_neighbors(r: int, c: int) -&gt; List[Tuple]:\n neighbors = (r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)\n return [(r, c) for r, c in neighbors if -1 &lt; r &lt; m and -1 &lt; c &lt; n]\n</code></pre>\n<p>Instead of unpacking <code>coord</code> you can pass the row <code>r</code> and column <code>c</code> directly. This also improves the runtime by roughly 30%.</p>\n</li>\n</ul>\n<h2>Alternative approach</h2>\n<p>An alternative and faster approach is to use recursion:</p>\n<pre><code>def recursive(grid: List[List[str]]) -&gt; int:\n islands = 0\n m, n = len(grid), len(grid[0])\n\n def sink_neighbors(row, col):\n grid[row][col] = '0'\n if row &gt; 0 and grid[row - 1][col] == '1':\n sink_neighbors(row - 1, col)\n if row &lt; m - 1 and grid[row + 1][col] == '1':\n sink_neighbors(row + 1, col)\n if col &gt; 0 and grid[row][col - 1] == '1':\n sink_neighbors(row, col - 1)\n if col &lt; n - 1 and grid[row][col + 1] == '1':\n sink_neighbors(row, col + 1)\n\n for r in range(m):\n for c in range(n):\n if grid[r][c] == '1':\n islands += 1\n sink_neighbors(r, c)\n return islands\n</code></pre>\n<p>Running the recursive solution on LeetCode:</p>\n<pre><code>Runtime: 120 ms, faster than 98.12% of Python3 online submissions for Number of Islands\n</code></pre>\n<p>This is the running time of the original, improved, and recursive solutions on a random grid of 1 million elements:</p>\n<pre><code>Runtime original: 2.345 s\nRuntime improved: 1.544 s\nRuntime improved2: 1.097 s\nRuntime recursive: 0.696 s\n</code></pre>\n<h2>Full code</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from collections import deque\nfrom typing import List, Tuple\nimport random\nfrom time import perf_counter as pc\n\n\ndef original(grid: List[List[str]]) -&gt; int:\n m = len(grid)\n n = len(grid[0])\n\n def get_neighbors(coord: Tuple[int, int]) -&gt; List[Tuple]:\n delta_row = [0, 1, 0, -1]\n delta_column = [1, 0, -1, 0]\n\n neighbors = []\n for i in range(len(delta_row)):\n new_x = coord[0] + delta_row[i]\n new_y = coord[1] + delta_column[i]\n\n if -1 &lt; new_x &lt; m and -1 &lt; new_y &lt; n:\n neighbors.append((new_x, new_y))\n\n return neighbors\n\n islands = 0\n\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n coord = (i, j)\n if grid[coord[0]][coord[1]] == &quot;1&quot;:\n islands += 1\n q = deque([coord])\n while len(q) &gt; 0:\n c = q.popleft()\n grid[c[0]][c[1]] = &quot;0&quot;\n for neighbor in get_neighbors(c):\n if grid[neighbor[0]][neighbor[1]] == &quot;1&quot;:\n q.append(neighbor)\n grid[neighbor[0]][neighbor[1]] = &quot;0&quot;\n\n return islands\n\n\ndef improved(grid: List[List[str]]) -&gt; int:\n m, n = len(grid), len(grid[0])\n\n def get_neighbors(r: int, c: int) -&gt; List[Tuple]:\n neighbors = (r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)\n return [(r, c) for r, c in neighbors if -1 &lt; r &lt; m and -1 &lt; c &lt; n]\n\n islands = 0\n\n for row in range(m):\n for col in range(n):\n if grid[row][col] == &quot;1&quot;:\n islands += 1\n q = deque([(row, col)])\n while len(q) &gt; 0:\n r, c = q.popleft()\n grid[r][c] = &quot;0&quot;\n for r, c in get_neighbors(r, c):\n if grid[r][c] == &quot;1&quot;:\n q.append((r, c))\n grid[r][c] = &quot;0&quot;\n\n return islands\n\n\ndef improved2(grid: List[List[str]]) -&gt; int:\n m, n = len(grid), len(grid[0])\n islands = 0\n for row in range(m):\n for col in range(n):\n if grid[row][col] == '1':\n islands += 1\n grid[row][col] = '0'\n q = [(row, col)]\n while q:\n r, c = q.pop(0)\n for r, c in (r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1):\n if 0 &lt;= r &lt; m and 0 &lt;= c &lt; n and grid[r][c] == '1':\n grid[r][c] = '0'\n q.append((r, c))\n return islands\n\n\ndef recursive(grid: List[List[str]]) -&gt; int:\n islands = 0\n m, n = len(grid), len(grid[0])\n\n def sink_neighbors(row, col):\n grid[row][col] = '0'\n if row &gt; 0 and grid[row - 1][col] == '1':\n sink_neighbors(row - 1, col)\n if row &lt; m - 1 and grid[row + 1][col] == '1':\n sink_neighbors(row + 1, col)\n if col &gt; 0 and grid[row][col - 1] == '1':\n sink_neighbors(row, col - 1)\n if col &lt; n - 1 and grid[row][col + 1] == '1':\n sink_neighbors(row, col + 1)\n\n for r in range(m):\n for c in range(n):\n if grid[r][c] == '1':\n islands += 1\n sink_neighbors(r, c)\n return islands\n\n\nif __name__ == &quot;__main__&quot;:\n N = 1000\n random_grid = [[str(random.randint(0, 1)) for _ in range(N)] for _ in range(N)]\n res = []\n\n # Benchmark\n for f in original, improved, improved2, recursive:\n random_grid_copy = [row[:] for row in random_grid]\n t0 = pc()\n res.append(f(random_grid_copy))\n t1 = pc()\n print(f'Runtime {f.__name__}: {round(t1 - t0, 3)} s')\n\n # Correctness\n assert all(x == res[0] for x in res)\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T16:09:02.743", "Id": "510258", "Score": "0", "body": "It may be worth noting that the recursive flood fill breaks if an island is too large. A 32x32 grid filled with `\"1\"`s (i.e. one big island) is sufficient to hit python's default maximum recursion depth of 1000. I really wonder why they didn't include this trivial test case. The OP's iterative flood fill, while a bit slower, is more robust in that regard." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T18:57:25.557", "Id": "510266", "Score": "0", "body": "Great answer, thank you. To sum up, the biggest performance improvement comes from passing coordinates as integers directly to `get_neighbors()` as opposed to using/unpacking a tuple? Crazy to me that one fix cuts runtime by 30%. Also, the recursive function's base condition is \"no neighbors that equal 1\", which is an interesting case I'd never considered. This is a very helpful answer, thanks again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T02:54:23.723", "Id": "510285", "Score": "0", "body": "@qotsa42 I am glad I could help. Less unpacking helps but using list comprehension and doing fewer operations in `get_neighbors()` also help to get to the 30% improvement. You can try to add changes to the `original` and run the benchmark to see the difference." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T22:56:03.417", "Id": "510393", "Score": "0", "body": "@qotsa42 FYI I added `improved2` that improves the original runtime a bit more" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T12:12:14.120", "Id": "258801", "ParentId": "258793", "Score": "3" } }, { "body": "<p>As performance improvements have already been provided, I want to add some points regarding readability and &quot;pythonic&quot; code.</p>\n<p><strong>Variable naming:</strong></p>\n<pre><code>m = len(grid)\nn = len(grid[0])\n...\nfor i in range(len(grid)):\n for j in range(len(grid[0])):\n</code></pre>\n<p>These variable names are not descriptive at all. The following is way more readable:</p>\n<pre><code>height = len(grid)\nwidth = len(grid[0])\n...\nfor row in range(height):\n for column in range(width):\n</code></pre>\n<p>Please also note that we do not need to recalculate these values for our for-loops.</p>\n<hr />\n<p><strong>Pythonic while-loop:</strong></p>\n<p><code>while len(q) &gt; 0:</code> is equivalent to <code>while q:</code>.</p>\n<hr />\n<p><strong>get_neighbors:</strong></p>\n<pre><code>delta_row = [0, 1, 0, -1]\ndelta_column = [1, 0, -1, 0]\n...\nfor i in range(len(delta_row)):\n new_x = coord[0] + delta_row[i]\n new_y = coord[1] + delta_column[i]\n</code></pre>\n<p>In Python you should basically never have to iterate over an index and access list elements by that index.\nA quick fix is the following:</p>\n<pre><code>delta_rows = [0, 1, 0, -1]\ndelta_columns = [1, 0, -1, 0]\n...\nfor delta_row, delta_column in zip(delta_rows, delta_columns):\n new_x = coord[0] + delta_row\n new_y = coord[1] + delta_column\n</code></pre>\n<p>Please also note that this is where variable naming is very important to make it easier to read the code and identify mistakes. In <code>get_neighbors</code> you mix three different ways to name your variables (<code>m, n</code> - <code>row, column</code> - <code>x, y</code>) that have to be interpreted by the reader before understanding (and maybe debugging) the code. At first glance it's not obvious to the reader whether <code>new_x</code> should actually be the new row (I'd say the other way round is more intuitive: y = row and x = column) and whether it's correct to compare it to <code>m</code> instead of <code>n</code>.</p>\n<hr />\n<p><strong>Conditions:</strong></p>\n<pre><code>if -1 &lt; new_x &lt; m and -1 &lt; new_y &lt; n:\n</code></pre>\n<p>can also be written as</p>\n<pre><code>if new_x in range(m) and new_y in range(n):\n</code></pre>\n<p>or even better as</p>\n<pre><code>if new_row in range(height) and new_column in range(width):\n</code></pre>\n<p>I would argue this further increases readability in this case, although it's up to a bit of personal preference.</p>\n<hr />\n<p><strong>Passing around coordinates:</strong></p>\n<p>I often find it useful to use <a href=\"https://pymotw.com/2/collections/namedtuple.html\" rel=\"nofollow noreferrer\">collections.namedtuples</a> as &quot;mini-classes&quot; if a certain structure is used often. As you have to pass around and access coordinates quite frequently, this might be applicable here.</p>\n<p>By using something like</p>\n<pre><code>Coordinate = namedtuple(&quot;Coordinate&quot;, &quot;row column&quot;)\n</code></pre>\n<p>you are then able to create and access coordinates in a more readable way. Example usage:</p>\n<pre><code>coordinate = Coordinate(row=row, column=column)\n \nrow, column = coordinate\nrow = coordinate.row\ncolumn = coordinate.column\n\ngrid[coordinate.row][coordinate.column] = &quot;0&quot;\n</code></pre>\n<p>This also applies to type hints in method headers. For example in <code>get_neighbors</code>:</p>\n<pre><code>def get_neighbors(coord: Tuple[int, int]) -&gt; List[Tuple]:\n</code></pre>\n<p>becomes</p>\n<pre><code>def get_neighbors(coord: Coordinate) -&gt; List[Coordinate]:\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:35:16.783", "Id": "510269", "Score": "0", "body": "These are great tips -- never really seen a use case in the wild for `namedtuples`, so thanks for pointing that out. So with `zip()`. Your naming conventions also make much more sense. I appreciate the hints towards being more pythonic. Interestingly, iterating through `range(height)` and `range(width)` in `get_neighbors()` slows down the runtime on larger grids. On the leetcode testcases, using `range()` takes about 25% longer than doing `-1 < x < height`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T12:52:10.013", "Id": "510341", "Score": "0", "body": "`m` and `n` are standard names used exactly like that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T12:57:00.070", "Id": "258803", "ParentId": "258793", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T04:06:35.710", "Id": "258793", "Score": "4", "Tags": [ "python", "graph" ], "Title": "Leetcode: number of islands" }
258793
<p>I'm working on a project of mine which required multiple calls to <code>strncat()</code>, and it came to me that it'd have been much easier if C also had something like <code>&quot;file://&quot; + getenv(&quot;HOME&quot;) + filename</code> for string generation. So I built a function that works in a similar fashion, it is a variadic function, the arguments are <code>NULL</code> terminated.</p> <p>Usage: <code>char *str = mutant_string (&quot;file://&quot;, getenv (&quot;HOME&quot;), filename, NULL);</code></p> <p><em><strong>It's obviously up to the user to free the memory <code>str</code> allocated.</strong></em></p> <p>The code:-</p> <pre class="lang-c prettyprint-override"><code>char *mutant_string (const char *s, ...) { va_list argv; va_start (argv, s); char *return_string = strdup (s); size_t realsize, nmemb; realsize = strlen (return_string); // Or initial size char *c, *ptr; while ((c = va_arg(argv, char*))) { nmemb = strlen (c); realsize += nmemb; ptr = realloc (return_string, sizeof(char) * (realsize + 1)); if (!ptr) { perror (&quot;realloc&quot;); free (return_string); va_end (argv); return NULL; } return_string = ptr; strncat (return_string, c, nmemb); } return_string[realsize] = 0; va_end (argv); return return_string; } </code></pre> <p>I welcome any kind of observations or opinions. Let me know if there's an external library or function that does exactly this and something that I can read.</p> <p>Thank you.</p>
[]
[ { "body": "<p>It looks like this code needs a couple of headers to be included before it will compile:</p>\n<pre><code>#include &lt;stdarg.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n</code></pre>\n<p>It also only works on platforms that have <code>strdup()</code>. It would be easy to make it more portable.</p>\n<p>If <code>s</code> is a null pointer, then we have undefined behaviour, but we haven't indicated that we don't allow a null for the first argument.</p>\n<p>Why are we not testing whether <code>strdup()</code> returns a null pointer?</p>\n<p>Well done for avoiding the common hazard with <code>realloc()</code>. Too many C programmers fail to deal properly with allocation failure. The scope of <code>ptr</code> could be reduced so that we declare and initialise together, and we don't need to multiply by <code>sizeof (char)</code> (which must be 1, by definition):</p>\n<pre><code>char *ptr = realloc(return_string, realsize + 1);\n</code></pre>\n<p>The use of <code>strncat()</code> in a loop is wasteful, since it starts from the beginning every time. Since we know where the string ends, it's better to start from that position.</p>\n<p>The algorithm could be much more efficient. Instead of many <code>realloc()</code> calls, we could make two passes over the arguments: one to measure the total size, and one to copy the characters across.</p>\n<p>Compare this extract from a Valgrind run of the code:</p>\n<pre class=\"lang-none prettyprint-override\"><code>==25527== HEAP SUMMARY:\n==25527== in use at exit: 0 bytes in 0 blocks\n==25527== total heap usage: 5 allocs, 5 frees, 1,063 bytes allocated\n</code></pre>\n<p>against the two-pass version that doesn't need to realloc:</p>\n<pre class=\"lang-none prettyprint-override\"><code>==24899== HEAP SUMMARY:\n==24899== in use at exit: 0 bytes in 0 blocks\n==24899== total heap usage: 2 allocs, 2 frees, 1,037 bytes allocated\n</code></pre>\n<p>That's fewer than half the allocations for a very simple &quot;Hello World&quot; test program:</p>\n<pre><code>char *mutant_string (const char *s, ...);\n\n#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n\nint main(void)\n{\n char *s = mutant_string(&quot;Hello&quot;, &quot; &quot;, &quot;World&quot;, &quot;!&quot;, NULL);\n if (!s) {\n return 1;\n }\n puts(s);\n free(s);\n}\n</code></pre>\n<p>Here's what the two-pass version looks like:</p>\n<pre><code>#include &lt;stdarg.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n\nchar *mutant_string(const char *s, ...)\n{\n if (!s) {\n return NULL;\n /* alternatively - return a new, empty string */\n }\n\n va_list argv;\n\n /* First pass - measure the total length */\n size_t total_len = strlen(s);\n va_start(argv, s);\n const char *c;\n while ((c = va_arg(argv, const char*))) {\n total_len += strlen(c);\n }\n va_end(argv);\n\n char *buf = malloc(total_len + 1);\n if (!buf) {\n return buf;\n }\n\n /* Second pass - copy the string data */\n char *p = buf;\n {\n /* first argument */\n size_t len = strlen(s);\n memcpy(p, s, len);\n p += len;\n }\n\n /* other arguments */\n va_start(argv, s);\n while ((c = va_arg(argv, const char*))) {\n size_t len = strlen(c);\n memcpy(p, c, len);\n p += len;\n }\n va_end(argv);\n *p = '\\0';\n\n return buf;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T04:39:55.937", "Id": "510291", "Score": "0", "body": "Wow .. this was so much helpful! Thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T10:08:02.380", "Id": "258800", "ParentId": "258795", "Score": "4" } }, { "body": "<p>The main issue with this is that variadic functions have non-existent type safety. It is better to avoid them - it's one of those old things in C that's simply broken.</p>\n<p>I would suggest to instead write a function like:</p>\n<pre><code>char* strcat_alloc (size_t n, const char* list[n])\n</code></pre>\n<p>Okay, so that takes an array as parameter which may be cumbersome. To make it easier to use, we can combine it with a variadic wrapper macro and compound literals:</p>\n<pre><code>#define cat(...) strcat_alloc( sizeof (const char*[]){ __VA_ARGS__ } / sizeof(const char*), \\\n (const char*[]){ __VA_ARGS__ } )\n</code></pre>\n<p>Now isn't that as bad as a variadic function? Not at all, because in this case we force every parameter passed to be a pointer part of an initializer list. C has somewhat strict rules then, particularly if you use a conforming compiler. Then it's neither allowed to pass pointers of wrong type, not integers etc.</p>\n<p>Complete example together with a naive implementation of the function follows. It can be optimized a lot, but the main point I wished to make is the function interface.</p>\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n\n#define cat(...) strcat_alloc(sizeof (const char*[]){ __VA_ARGS__ } / sizeof(const char*), \\\n (const char*[]){ __VA_ARGS__ } )\n\nchar* strcat_alloc (size_t n, const char* list[n])\n{\n size_t size = 0;\n for(size_t i=0; i&lt;n; i++)\n {\n size += strlen(list[i]);\n }\n size++; // null term\n \n char* result = malloc(size);\n if(result == NULL)\n {\n return result;\n }\n \n *result = '\\0';\n for(size_t i=0; i&lt;n; i++)\n {\n strcat(result, list[i]);\n }\n return result;\n}\n\nint main (void)\n{\n char STR1[] = &quot;hello&quot;;\n char STR2[] = &quot;world&quot;;\n char* str = cat(STR1, &quot; &quot;, &quot;meow&quot;, &quot; &quot;, STR2, &quot; &quot;, &quot;meow&quot;);\n puts(str);\n free(str);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T13:55:15.407", "Id": "510348", "Score": "0", "body": "Thanks for this answer. I actually didn't know you could cast `__VA_ARGS__` like that (or is it even called casting?). Can you please provide me with any reading material on this? Really appreciate the help." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T13:59:00.160", "Id": "510349", "Score": "2", "body": "@debdutdeb It's not a cast, it's a _compound literal_, like I wrote. A temporary anonymous variable if you will. Basically `(type){ initializers }` and it gets the same scope as the one it was declared in. In this case `__VA_ARGS__` forms the initializer list of a temporary array, and initializer lists of pointers have rather strict typing rules." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T13:26:51.543", "Id": "510414", "Score": "0", "body": "`for(size_t i=0; i<n; i++) { strcat(result, list[i]); }` uses the a [slow algorithm](https://wiki.c2.com/?ShlemielThePainter), but code is, as you say, \"can be optimized a lot\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T13:49:52.003", "Id": "510415", "Score": "0", "body": "@chux-ReinstateMonica Yes, this is just a naive placeholder code. For real quality code I would probably just speculatively allocate 256 bytes or so, then fill those bytes up at the same time as I iterate through the string arrays. And if it goes beyond 256 bytes, realloc size*2 and so on." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T06:55:40.170", "Id": "258830", "ParentId": "258795", "Score": "2" } }, { "body": "<blockquote>\n<p>Usage: <code>char *str = mutant_string (&quot;file://&quot;, getenv (&quot;HOME&quot;), filename, NULL);</code></p>\n</blockquote>\n<p><code>mutant_string(&quot;Hello&quot;, &quot; &quot;, &quot;World&quot;, &quot;!&quot;, NULL);</code> contains a weakness.</p>\n<p><code>NULL</code>, a <em>null pointer constant</em> is not certainly a <code>char *</code>, a <em>null pointer</em>. It could be an <code>int</code> 0 for example and cause grief with <code>va_arg(argv, char*)</code> with <em>undefined behavior</em> (UB).</p>\n<p>When an integer, passing a <code>NULL</code> to a <code>...</code> function does not convert the <code>NULL</code> to a pointer.</p>\n<p>When <code>NULL</code> is an integer, it is often typed to be the same size of a <code>char*</code>, such as <code>0L</code> perhaps - reducing bad UB. Yet that is not required nor are <code>int</code> and <code>char *</code> certainly passed the same way. Robust uses a <em>pointer</em> to terminate the list.</p>\n<p>Consider alternatives</p>\n<pre><code>mutant_string(&quot;file://&quot;, getenv (&quot;HOME&quot;), filename, (char*)NULL); \nmutant_string(&quot;file://&quot;, getenv (&quot;HOME&quot;), filename, (char*)0);\n</code></pre>\n<hr />\n<blockquote>\n<p>the arguments are NULL terminated.</p>\n</blockquote>\n<p>Fails a corner case of <code>mutant_string(NULL)</code> as code attempts <code>strdup(NULL)</code> and likely <code>strlen(NULL)</code>. Easy to fix with a test.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T17:31:47.707", "Id": "510423", "Score": "1", "body": "Oh yes, I'd forgotten the gotcha with `NULL` and varargs! Good catch." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T13:31:37.747", "Id": "258872", "ParentId": "258795", "Score": "3" } } ]
{ "AcceptedAnswerId": "258800", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T04:50:14.787", "Id": "258795", "Score": "5", "Tags": [ "c", "strings", "variadic" ], "Title": "C function that emulates string concatenation operator '+' in Python or Go" }
258795
<p>I tried to make a Pong game in Java. It's my first game I have ever programmed, and I would be very pleased if you would take the time to advise me on what I could do better next time. Thank you so much :) .</p> <p>Here is my code:</p> <p>Start.java:</p> <pre><code>import java.awt.EventQueue; public class Start { public static void main(String[] args) { Runnable runner = new Runnable() { public void run() { GameFrame gameFrame = new GameFrame(); } }; EventQueue.invokeLater(runner); } } </code></pre> <p>GameFrame.java:</p> <pre><code>import javax.swing.JFrame; public class GameFrame extends JFrame{ public GameFrame() { initFrame(); } private void initFrame() { add(new GameBoard()); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle(&quot;PongGame&quot;); setResizable(false); pack(); setLocationRelativeTo(null); setVisible(true); } } </code></pre> <p>GameBoard.java:</p> <pre><code>import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import javax.swing.JPanel; public class GameBoard extends JPanel implements Runnable{ public static final int WIDTH = 900 ; public static final int HEIGHT = 2 * WIDTH / 3; private final int DELAY = 10; private int scoreL = 0; private int scoreR = 0; private boolean inGame = false; private Paddle rightPaddle, leftPaddle; private Ball ball; private Thread game; public GameBoard() { initGameBoard(); } private void initGameBoard() { setBackground(Color.black); setPreferredSize(new Dimension(WIDTH, HEIGHT)); setFocusable(true); addKeyListener(new KAdapter()); ball = new Ball(); rightPaddle = new Paddle(&quot;right&quot;); leftPaddle = new Paddle(&quot;left&quot;); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setStroke(new BasicStroke(5.0f)); g2d.drawLine(WIDTH/2, 0, WIDTH/2, HEIGHT); drawBall(g2d); drawPaddle(g2d); drawScore(g2d); if(!inGame) { drawPressSpace(g2d); } Toolkit.getDefaultToolkit().sync(); } public void addNotify() { super.addNotify(); game = new Thread(this); game.start(); } private void drawPaddle(Graphics2D g2d) { g2d.drawImage(rightPaddle.getImage(), rightPaddle.getX(), rightPaddle.getY(), this); g2d.drawImage(leftPaddle.getImage(), leftPaddle.getX(), leftPaddle.getY(), this); } private void drawPressSpace(Graphics2D g2d) { String press = &quot;Press space to begin&quot;; Font font = new Font(&quot;Verdana&quot;, Font.BOLD , 20); FontMetrics fm = getFontMetrics(font); g2d.setFont(font); g2d.setColor(Color.red); g2d.drawString(press, (WIDTH - fm.stringWidth(press)) / 2, (HEIGHT - fm.getHeight()) / 2); } private void drawScore(Graphics2D g2d) { Font font = new Font(&quot;Verdana&quot;, Font.PLAIN , 50); FontMetrics fm = getFontMetrics(font); g2d.setColor(Color.gray); g2d.setFont(font); g2d.drawString(&quot;&quot;+scoreL, 50, fm.stringWidth(&quot;&quot;+scoreL) + 40); g2d.drawString(&quot;&quot;+scoreR, WIDTH - fm.stringWidth(&quot;&quot;+scoreR) - 50, fm.stringWidth(&quot;&quot;+scoreR) + 40); } private void drawBall(Graphics2D g2d) { g2d.drawImage(ball.getImage(), ball.getX(), ball.getY(), this); } public void run() { long beforeT, timeDiff, sleep; beforeT = System.currentTimeMillis(); while (true) { updatePaddles(); if(inGame) { updateBall(); } else { rightPaddle.resetPos(); leftPaddle.resetPos(); } repaint(); timeDiff = System.currentTimeMillis() - beforeT; sleep = DELAY - timeDiff; if (sleep &lt; 2) { sleep = 2; } try { Thread.sleep(sleep); }catch(Exception e) { e.getStackTrace(); } beforeT = System.currentTimeMillis(); } } private void updatePaddles() { rightPaddle.move(); leftPaddle.move(); } private void updateBall() { boolean b = checkCollision(); int i = ball.move(b); if(i != 0) { switch(i) { case 1: scoreR++; break; case 2: scoreL++; break; } inGame = false; } } private boolean checkCollision() { Rectangle rb = ball.getBounds(); Rectangle rp = rightPaddle.getBounds(); if(rb.intersects(rp)) { return true; } rp = leftPaddle.getBounds(); if(rb.intersects(rp)) { return true; } return false; } private class KAdapter extends KeyAdapter{ public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if(!inGame &amp;&amp; keyCode == KeyEvent.VK_SPACE) { inGame = true; ball.start(); return; } if(inGame) { if(rightPaddle.isKey(keyCode)) { rightPaddle.keyPressed(keyCode); } else if(leftPaddle.isKey(keyCode)) { leftPaddle.keyPressed(keyCode); } } } public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if(rightPaddle.isKey(keyCode)) { rightPaddle.keyReleased(keyCode); } else if(leftPaddle.isKey(keyCode)) { leftPaddle.keyReleased(keyCode); } } } } </code></pre> <p>Sprite.java:</p> <pre><code>import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.image.BufferedImage; public class Sprite { protected int x; protected int y; private int width; private int height; protected BufferedImage image; public Sprite(int width, int height) { this.width = width; this.height = height; updateImage(); } private void updateImage() { image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = (Graphics2D) image.getGraphics(); g2d.setColor(Color.white); g2d.fillRect(0, 0, width, height); } public BufferedImage getImage() { return this.image; } public int getX() { return this.x; } public int getY() { return this.y; } public Rectangle getBounds() { return new Rectangle(x, y, width, height); } } </code></pre> <p>Paddle.java:</p> <pre><code>import java.awt.event.KeyEvent; public class Paddle extends Sprite{ public final static int WIDTH = 20; public final static int HEIGHT = GameBoard.HEIGHT / 5; private final int SPEED = 8; private String side; private int up; private int down; private int dy; public Paddle(String side) { super(WIDTH, HEIGHT); this.side = side; setSide(); resetPos(); } private void setSide() { if(side.equals(&quot;right&quot;)) { up = KeyEvent.VK_UP; down = KeyEvent.VK_DOWN; x = GameBoard.WIDTH - WIDTH; } else if(side.equals(&quot;left&quot;)) { up = KeyEvent.VK_W; down = KeyEvent.VK_S; x = 0; } else { System.out.println(&quot;tato strana neexistuje!&quot;); } } public boolean isKey(int keyCode) { return up == keyCode || down == keyCode; } public void move() { if(checkHeightCol()) { dy = 0; } y+=dy; } private boolean checkHeightCol() { return dy + y &lt; 0 || dy + y &gt; GameBoard.HEIGHT - HEIGHT; } public void resetPos() { y = (GameBoard.HEIGHT - HEIGHT) / 2; } public void keyPressed(int keyCode) { if(keyCode == up) { dy = -SPEED; } if (keyCode == down) { dy = SPEED; } } public void keyReleased(int keyCode) { if(keyCode == up) { dy = 0; } if (keyCode == down) { dy = 0; } } } </code></pre> <p>Ball.java:</p> <pre><code>import java.util.Random; public class Ball extends Sprite{ public static final int SIZE = 20; private int xSpeed; private int ySpeed; private final int MIN_SPEED = 8; private final int MAX_SPEED = 25; public Ball() { super(SIZE, SIZE); restart(); } public void start() { generateRandomDirection(); } private void generateRandomDirection() { Random r = new Random(); double randomY = 0.1 + (0.8 - 0.1) * r.nextDouble(); ySpeed = (int) Math.round(randomY * MIN_SPEED); double randomX = Math.sqrt(MIN_SPEED * MIN_SPEED - ySpeed * ySpeed); xSpeed = (int) Math.round(randomX); ySpeed *= (r.nextInt() % 2 == 0) ? 1 : -1; xSpeed *= (r.nextInt() % 2 == 0) ? 1 : -1; } public void restart() { xSpeed = 0; ySpeed = 0; x = (GameBoard.WIDTH - SIZE) / 2; y = (GameBoard.HEIGHT - SIZE) / 2; } public int move(boolean paddleCollision) { int state = 0; if(x + xSpeed &lt; 0) { restart(); state = 1; } else if(x + xSpeed &gt; GameBoard.WIDTH - SIZE ) { restart(); state = 2; }else if(checkHeightCollision()) { ySpeed *= -1; } else if(paddleCollision) { xSpeed *= -1; } x+=xSpeed; y+=ySpeed; return state; } private boolean checkHeightCollision() { return y + ySpeed &lt; 0 || y + ySpeed &gt; GameBoard.HEIGHT - SIZE; } } </code></pre>
[]
[ { "body": "<p>Code looks clean, some variables should maybe have a little bit better name, some comments would be nice, overall very good for your first game.</p>\n<p>Some points:</p>\n<ul>\n<li><p>You should use a <em>package</em>, this makes it also easier to create a <em>jar</em>, and <em>jars</em> are good for distributing programs/games.</p>\n</li>\n<li><p>I would combine <em>Start.java</em>, <em>GameFrame.java</em> and <em>GameBoard.java:</em> and make class <em>GameBoard</em> final.</p>\n</li>\n<li><p>Anyway, regarding <em>GameFrame.java</em>, I would include private method <em>initFrame()</em> within constructor.</p>\n</li>\n<li><p>Read about <em>GraphicsConfiguration</em> -&gt; <a href=\"https://docs.oracle.com/javase/9/docs/api/java/awt/GraphicsConfiguration.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/9/docs/api/java/awt/GraphicsConfiguration.html</a></p>\n</li>\n<li><p>Using an <em>interface</em> for inputs makes it easier to create a multiplayer (hot-seat or later tcp/ip) version. <a href=\"https://docs.oracle.com/javase/tutorial/java/concepts/interface.html\" rel=\"nofollow noreferrer\">https://docs.oracle.com/javase/tutorial/java/concepts/interface.html</a></p>\n</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T16:20:28.197", "Id": "510761", "Score": "0", "body": "Thank you so much for your advice. I will definitely use your tips :) . Have a nice day." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T11:01:51.597", "Id": "258867", "ParentId": "258805", "Score": "1" } } ]
{ "AcceptedAnswerId": "258867", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T16:27:01.033", "Id": "258805", "Score": "5", "Tags": [ "java", "beginner", "game", "pong" ], "Title": "Pong Game project" }
258805
<p>This is my first post on this forum. I have read the guidelines and will try to adhere to them, but I apologize if I miss something. The code I am posting is intended to duplicate the output of &quot;date -u&quot; in the XV6 OS. It does this, with the exception of dates before the 1700s (This wasn't relevant to the task, and the math is a little different, from what I read). My goal with this post is to seek advice on improving the code in terms of safety and performance, with an emphasis on best practices that I can generalize to future C code (I realize this may not be as doable for something intended to run in XV6). Advice on both my code and better techniques for posting here is appreciated!</p> <pre><code>#include &quot;types.h&quot; #include &quot;stat.h&quot; #include &quot;user.h&quot; #include &quot;date.h&quot; int check_leap(int year); void print_day(int year, int month, int day); void print_month(int month); int month_key(int month); int main(void) { struct rtcdate current_date; if(date(&amp;current_date) != 0) exit(); print_day(current_date.year, current_date.month, current_date.day); print_month(current_date.month); printf(1, &quot; %d&quot;,current_date.day); printf(1,&quot; %d:%d:%d&quot;, current_date.hour, current_date.minute, current_date.second); printf(1,&quot; %d&quot;, current_date.year); printf(1,&quot; UTC\n&quot;); exit(); } int check_leap(int year) { if(year % 4 == 0) { if(year % 100 == 0) { if(year % 400 == 0) return 1; //Leap year } } return 0; } int month_key(int month) { int key; switch (month) { case 1: key = 1; break; case 2: key = 4; break; case 3: key = 4; break; case 4: key = 0; break; case 5: key = 2; break; case 6: key = 5; break; case 7: key = 0; break; case 8: key = 3; break; case 9: key = 6; break; case 10: key = 1; break; case 11: key = 4; break; case 12: key = 6; break; default: key = -1; break; } return key; } void print_day(int year, int month, int day) { int week_day; int decade = year % 100; int century = year / 100; int leap = check_leap(year); int key = month_key(month); if(key &lt; 0) { printf(1, &quot;%s&quot;, &quot;Invalid value for month!\n&quot;); exit(); } week_day = decade / 4; week_day += day; week_day += key; if((leap) &amp;&amp; ((month == 1) || (month == 2))) { week_day -= 1; } switch (century) { case 17: week_day += 4; break; case 18: week_day += 2; break; case 19: break; case 20: week_day += 6; break; default: printf(1, &quot;%s&quot;, &quot;Centuries before 1700 or after 2000 not yet supported. \n&quot;); break; } week_day += decade; week_day = (week_day % 7) - 1; if(week_day &lt; 0 || week_day &gt; 6) { printf(1, &quot;Invalid Day error!&quot;); //TS code- to be removed } switch(week_day) { case 0: printf(1, &quot;Sun &quot;); break; case 1: printf(1, &quot;Mon &quot;); break; case 2: printf(1, &quot;Tue &quot;); break; case 3: printf(1, &quot;Wed &quot;); break; case 4: printf(1, &quot;Thu &quot;); break; case 5: printf(1, &quot;Fri &quot;); break; case 6: printf(1, &quot;Sat &quot;); break; default: printf(1, &quot;Unknown day!&quot;); break; } return; } void print_month(int month) { switch (month) { case 1: printf(1, &quot;Jan&quot;); break; case 2: printf(1, &quot;Feb&quot;); break; case 3: printf(1, &quot;Mar&quot;); break; case 4: printf(1, &quot;Apr&quot;); break; case 5: printf(1, &quot;May&quot;); break; case 6: printf(1, &quot;Jun&quot;); break; case 7: printf(1, &quot;Jul&quot;); break; case 8: printf(1, &quot;Aug&quot;); break; case 9: printf(1, &quot;Sep&quot;); break; case 10: printf(1, &quot;Oct&quot;); break; case 11: printf(1, &quot;Nov&quot;); break; case 12: printf(1, &quot;Dec&quot;); break; default: printf(1, &quot;Month Error&quot;); break; } return; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T21:05:44.067", "Id": "510557", "Score": "1", "body": "@Toby Speight OP here has incorrect code for either set of rules for `check_leap()`. The change from Juliann to Gregorian calendar and it leap year rules only begin in 1582. The new rule were only accepted by the majority of the planet in the 19xx, well past 1700s. The old rules continue is use today in select venues." } ]
[ { "body": "<h2>XV6 bizarreness</h2>\n<p>XV6 has made at least one ill-advised decision in forcing a non-standard signature of <code>printf</code> that requires a file descriptor be passed in. Maybe they should have omitted <code>printf</code> entirely and made you use <code>fprintf</code> instead, but anyway: at the least, you should make a <code>stdout</code> constant equal to 1 and use this instead of the numeric literal.</p>\n<p>You could actually make <code>#define</code> shims in a header file that centralize the XV6-to-C99 translation, including a definition for <code>fprintf</code> that you can call as you would the standard version, but in fact calls the XV6 <code>printf</code> internally. If you're in a course that forces non-standard C but you still want to learn standard C this would be a sane option.</p>\n<p>Also, does returning from <code>main</code> not work? If it does, <code>return</code> instead of <code>exit()</code>.</p>\n<h2>month_key</h2>\n<p>Re-express this long, continuous <code>switch</code> as a <code>static const</code> lookup array that you index into, after having performed a bounds check. The same is possible for your <code>switch (week_day)</code> and <code>switch (month)</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T19:25:27.993", "Id": "258891", "ParentId": "258806", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T16:47:36.927", "Id": "258806", "Score": "3", "Tags": [ "beginner", "c", "reinventing-the-wheel", "homework" ], "Title": "Date program for xv6- improvement and testing" }
258806
<p>It's been a while I have been on here and I hope I still understand the rules. I have recently started learning PHP and WordPress for a Whatsapp Chatbot integration. I have created a webhook on my WordPress site that returns a JSON, which is consumed by Google Dialogflow(Chatbot engine).</p> <p>For example, my webhook returns something like this</p> <pre><code>{ &quot;fulfillmentMessages&quot;: [ { &quot;text&quot;: { &quot;text&quot;: [ &quot;Text response from webhook&quot; ] } } ] } </code></pre> <p>To achieve this structure, I have written used this nested associative array</p> <pre><code>$innerarr= array(); $innerarr[0] = &quot;Text response from webhook&quot;; $newarr = array(); $newarr[&quot;fulfillmentMessages&quot;]= array(); $newarr[&quot;fulfillmentMessages&quot;][0] = array(&quot;text&quot;=&gt;array(&quot;text&quot;=&gt;$innerarr)); echo json_encode($newarr); </code></pre> <p>It works but I'm also thinking, should I</p> <ol> <li>Use a class definition instead that manages the above?</li> <li>Use the \stdClass object to dynamically create this structure?</li> <li>Is there a neater way to do this as the dynamic properties will grow depending on the request from the chatbot</li> <li>Am I overthinking?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T00:08:12.387", "Id": "510281", "Score": "0", "body": "This question may be closed for asking for \"general best practices\"." } ]
[ { "body": "<p>Do you can use a converter tool to help you understand the conversion structure, ex.: <a href=\"https://wtools.io/convert-json-to-php-array\" rel=\"nofollow noreferrer\">wtools.io</a>.\nIn this case, the PHP array structure for your json is similar that it:</p>\n<pre><code>$innerarr = array (\n 'fulfillmentMessages' =&gt; \n array (\n 0 =&gt; \n array (\n 'text' =&gt; \n array (\n 'text' =&gt; \n array (\n 0 =&gt; 'Text response from webhook',\n ),\n ),\n ),\n ),\n);\n\necho json_encode($innerarr);\n</code></pre>\n<p>or, using sort arrays:</p>\n<pre><code>$innerarr = [\n 'fulfillmentMessages' =&gt; [\n 0 =&gt; [\n 'text' =&gt; [\n 'text' =&gt; [\n 0 =&gt; 'Text response from webhook',\n ],\n ],\n ],\n ],\n];\n\necho json_encode($innerarr);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T00:06:23.433", "Id": "510280", "Score": "3", "body": "You have provided two alternative approaches, but I am not sure that you have provided a _review_. Why is `$innerarr` a good variable name for the entire set of data?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:20:12.337", "Id": "258815", "ParentId": "258811", "Score": "0" } }, { "body": "<p>Your vague sample indicates that you are only pushing one text message into the structure.</p>\n<ul>\n<li>I see no compelling reason to declare the variables in your sample script.</li>\n<li>There is also no benefit in creating objects, because <code>json_encode()</code> is going to be using the same syntax when the data is converted to a json string.</li>\n</ul>\n<p>I recommend that you do away with the single-use variables and write the necessary structure directly into the <code>json_encode()</code> call.</p>\n<p>Code: (<a href=\"https://3v4l.org/ZOBNI\" rel=\"nofollow noreferrer\">Demo with <code>JSON_PRETTY_PRINT</code> for readabilty</a>)</p>\n<pre><code>echo json_encode(\n [\n 'fulfillmentMessages' =&gt; [\n [\n 'text' =&gt; [\n 'text' =&gt; [\n 'Text response from webhook',\n ]\n ]\n ]\n ]\n ]\n );\n</code></pre>\n<p>I am unable to advise on &quot;<em>the dynamic properties will grow depending on the request from the chatbot</em>&quot; because you have not been clear about what this data will look like. Asking for &quot;General Best Practices&quot; is off-topic on CodeReview.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T03:26:32.060", "Id": "510286", "Score": "2", "body": "Just for completeness, No difference if using assoc arrays or objects. Well there is one exception - empty array vs. empty object. One is encoded as array and the other as object. Unless JSON_FORCE_OBJECT is used...." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T00:05:29.957", "Id": "258823", "ParentId": "258811", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T18:08:30.690", "Id": "258811", "Score": "-1", "Tags": [ "php", "json" ], "Title": "Best Practice: creating a nested associative array JSON in PHP" }
258811
<p>I wanted to have a function called timeit which can measure the time of execution of n iterations of any other function. I still learning C++ but I come up with that : Any thought ?</p> <pre><code>#include&lt;chrono&gt; using namespace std; template&lt;typename output, typename ...ArgsT, typename ...Input&gt; double timeit(output (*function)(Input...), int n, ArgsT ...args) { auto start = chrono::high_resolution_clock::now(); for(int k = 0; k &lt; n; ++k) { function(args...); } auto end = chrono::high_resolution_clock::now(); chrono::duration&lt;double&gt; elapsed = (end-start); return elapsed.count(); } </code></pre>
[]
[ { "body": "<p>The big thing you're missing here is perfect forwarding. When you receive the argument pack, it may contain one or more rvalue references. But when you pass <code>args...</code> to the function you're timing, you've given a name to the pack, so even though what you received were rvalue references, what you end up passing to the timed function won't be an rvalue reference any more.</p>\n<p>To fix this, you'd use <code>std::forward</code>:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>function(std::forward&lt;ArgsT&gt;(args)...);\n</code></pre>\n<p>The other obvious addition I'd consider would be gathering and returning the return values from the calls you make. One possibility would be to return something like a <code>pair&lt;double, std::vector&lt;output&gt;&gt;</code>, to hold the time and the return values.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:33:27.223", "Id": "510268", "Score": "0", "body": "Thank you for your answer, I will look into ``std::forward``. It was me first time using argument pack so i did not think about passing by references." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:39:40.103", "Id": "510270", "Score": "0", "body": "@ThomasL: For a first attempt at something, I'd say you did admirably well (quite a lot better than my first attempt, anyway)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:42:40.873", "Id": "510271", "Score": "0", "body": "Thank you I am sure you do well too." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:44:34.253", "Id": "510272", "Score": "0", "body": "@ThomasL: I've done better since, but my first attempt was pretty ugly. :-)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:24:24.040", "Id": "258816", "ParentId": "258814", "Score": "2" } } ]
{ "AcceptedAnswerId": "258816", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T20:10:42.387", "Id": "258814", "Score": "1", "Tags": [ "c++" ], "Title": "Function measuring time of another function" }
258814
<p>I am writing a simple wrapper around <code>fetch</code>.</p> <pre class="lang-js prettyprint-override"><code>async function apiCall( endpoint: string, { data, headers: customHeaders, ...customConfig }: { data?: Object; headers?: Object } = {} ) { const config = { method: data ? 'POST' : 'GET', body: data ? JSON.stringify(data) : undefined, headers: { 'content-type': data ? 'application/json' : undefined, ...customHeaders, }, ...customConfig, } return fetch(endpoint, config as any).then(async (response) =&gt; { if (response.ok) { const json = await response.json() // return json } else { // what if `response` contains error messages in json format? return Promise.reject(new Error('Unknown Error')) } }) } </code></pre> <p>It works fine. The problem is with this snippet:</p> <pre class="lang-js prettyprint-override"><code> return fetch(endpoint, config as any).then(async (response) =&gt; { if (response.ok) { const json = await response.json() return json } else { // what if `response` contains error messages in json format? return Promise.reject(new Error('Unknown Error')) } }) </code></pre> <p>If <code>response</code> is not ok, it rejects with a generic <code>Error</code>. This is because by default, <code>window.fetch</code> will only reject a promise if the actual network request failed. But the issue is that, even if <code>response</code> is not ok, it might still be able to have error messages in <code>json</code> format. This depends on the backend implementation details but sometimes you are able to get the error messages in the response body by <code>response.json()</code>. Now this use case is not covered in the wrapper I built.</p> <p>So I wonder how I am going to be able to account for that? I guess you can do something like</p> <pre class="lang-js prettyprint-override"><code>fetch(endpoint, config as any).then(async (response) =&gt; { if (response.ok) { const json = await response.json() return json } else { try { const json = await response.json() return Promise.reject(json) } catch { return Promise.reject(new Error('Unknown Error')) } } }) </code></pre> <p>I wonder if there is some more elegant way to do that?</p> <p>Lastly, I am very aware of libraries like Axios. I built this partly to satisfy my intellectual curiosity.</p> <p>By the way, a lightly unrelated question but I wonder if the following snippets are equivalent?</p> <pre class="lang-js prettyprint-override"><code> if (response.ok) { const json = await response.json() return json } </code></pre> <pre class="lang-js prettyprint-override"><code> if (response.ok) { return response.json() } </code></pre>
[]
[ { "body": "<p>If you need to account for mixed response types (in your case &quot;unknown errors&quot; or JSON-formatted errors), then you could consider checking the Content-Type of the response. See <a href=\"https://stackoverflow.com/questions/37121301/how-to-check-if-the-response-of-a-fetch-is-a-json-object-in-javascript\">this</a> StackOverflow answer for reference. This, of course, trusts in the server echoing the correct content type header for a response.</p>\n<p>As you mentioned, <code>fetch</code> does not reject on HTTP error status, instead <code>response.ok</code> will be set to <code>false</code>. You can use this to decide if you want to <em>reject</em> or <em>resolve</em> your promise.</p>\n<pre><code>/* ... */.then(async response =&gt; {\n const contentType = response.headers.get(&quot;content-type&quot;);\n if (contentType &amp;&amp; contentType.indexOf(&quot;application/json&quot;) !== -1) {\n const json = await response.json();\n return response.ok\n ? Promise.resolve(json)\n : Promise.reject(json);\n } else {\n const text = await response.text();\n return response.ok\n ? Promise.resolve(text)\n : Promise.reject(new Error(&quot;Unknown Error!&quot;));\n }\n});\n</code></pre>\n<p>You could also (which is what the post linked above suggests aswell) use a <code>try-catch</code> block, if you do not trust the response headers.</p>\n<pre><code>/* ... */.then(async response =&gt; {\n const text = await response.text();\n try {\n const data = JSON.parse(text);\n\n // If the line above has not produced an error, the response contained valid JSON.\n // We can either choose to just return the resulting data, or, as in\n // example above, resolve/reject the Promise based on the status code.\n\n return response.ok\n ? Promise.resolve(data);\n : Promise.reject(data);\n }\n catch(err) {\n // This means that the response probably contained text. As above, you can\n // decide if this means an error has occurred, or if the result will just\n // be handled differently.\n\n return response.ok\n ? Promise.resolve(text);\n : Promise.reject(new Error(&quot;Unknown Error!&quot;));\n }\n});\n</code></pre>\n<hr />\n<p>As for your additional question on the difference between:</p>\n<pre><code>if (response.ok) {\n const json = await response.json();\n return json;\n}\n// ... and ...\nif (response.ok) {\n return response.json();\n}\n</code></pre>\n<p>This essentially boils down to the difference between:</p>\n<pre><code>return await response.json();\n// ... and ...\nreturn response.json();\n</code></pre>\n<p>The difference lies within the way that JavaScript handles <code>async/await</code> methods. The first line returns a generic <code>T</code>, while the second one returns <code>Promise&lt;T&gt;</code>. What this means is that the first one &quot;delays&quot; the execution of the <code>return</code> statement until the promise returned by <code>response.json()</code> is resolved, while the second one says &quot;I don't care that execution is continued, whoever calls me later will have to wait for my value to be resolved.&quot;, which is what happens when you perform <code>.then(...)</code> on a promise.</p>\n<p>Note that the first method <em>still</em> ultimately returns a <code>Promise&lt;T&gt;</code> though, since <code>async</code> methods are essentially just fancy wrappers for promise generations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T13:14:41.230", "Id": "258838", "ParentId": "258820", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T22:01:10.100", "Id": "258820", "Score": "1", "Tags": [ "javascript", "json", "http" ], "Title": "A simple wrapper around fetch" }
258820
<p>After a bit of struggling I've come up with the code</p> <pre class="lang-py prettyprint-override"><code> import discord import os import subprocess as sub import psutil client = discord.Client() my_path = os.getcwd() program_instance = False currently_installed = os.path.isdir(&quot;web-application&quot;) def run_command(command): value = sub.Popen(command, stdout = sub.PIPE, stderr = sub.PIPE) return value.communicate() def kill(): global program_instance if not program_instance: return &quot;Program instance not initiated&quot;; process = psutil.Process(program_instance.pid) for proc in process.children(recursive = True): proc.kill() process.kill() program_instance = False return &quot;Instance Killed&quot; def delete_if_exists(): global currently_installed kill() if currently_installed: os.system(&quot;rmdir /S /Q web-application&quot;) while currently_installed: currently_installed = os.path.isdir(&quot;web-application&quot;) def download_from_git(): #pull from git global currently_installed kill() delete_if_exists() instance = sub.Popen(&quot;git clone LINKTOWEBAPPLICATION&quot;) instance.communicate() currently_installed = True return &quot;Successfully downloaded&quot; def run(download = False): global program_instance folders = run_command(&quot;dir&quot;) if not currently_installed or download: download_from_git() kill() path = my_path+&quot;\\web-application&quot; #installing values in pipenv install_command_instance = sub.Popen(&quot;pipenv install&quot;, cwd = path) install_command_instance.communicate() program_instance = sub.Popen(&quot;pipenv run app.py&quot;, cwd = path) return &quot;App Running&quot; @client.event async def on_ready(): print(&quot;Gitty woke&quot;) @client.event async def on_message(message): if message.author.bot or not message.channel.id == MYDISCORDUSERID: return; command = message.content checker = lambda command_name: command == command_name if checker(&quot;run&quot;): await message.channel.send(run()) if checker(&quot;kill&quot;): await message.channel.send(kill()) if checker(&quot;download&quot;): await message.channel.send(download_from_git()) if checker(&quot;run download&quot;): await message.channel.send(run(download = True)) if checker(&quot;ping&quot;): currently_installed = os.path.isdir(&quot;web-application&quot;) await message.channel.send(&quot;Running:&quot; + f&quot;\n{program_instance=}, {currently_installed=}&quot;) with open(&quot;.key&quot;, &quot;r&quot;) as key: client.run(key.read()) </code></pre> <p>The biggest problem with this code was killing running processes. I just wanted to know if there are any easier ways to do this. And if I made any choices which are over complicated.</p> <p>Edit: This bot is built to pull a repo from GitHub which contains a web-application that needs to be run. The reason I have to kill the application is so I can download a new version and rerun the code (as multiple instances of the website would be bad). The issue is that when the website is running I also have to be able to send the bot commands and thus have to run it as a separate instance so that the bot doesn't get &quot;clogged&quot; up running the site and can still take inputs</p>
[]
[ { "body": "<p>This depends on the nature and purpose of the process.</p>\n<p>For example, you might schedule your process as a coroutine, and cancel its execution with <code>Future.cancel</code>: <a href=\"https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.cancel\" rel=\"nofollow noreferrer\">https://docs.python.org/3/library/asyncio-future.html#asyncio.Future.cancel</a></p>\n<p>Your process killing method is aggressive and quite risky, some more context around why you're cancelling processes and the nature of the processes would be useful for providing answers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T13:19:25.163", "Id": "258871", "ParentId": "258822", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-28T23:47:14.680", "Id": "258822", "Score": "2", "Tags": [ "python" ], "Title": "How to simplify a discord bot remote tool" }
258822
<p>I have implemented a custom concurrent queue on top of GCD which offers two additional pieces of functionality:</p> <ol> <li>Limit the maximum number of concurrently executing tasks.</li> <li>Give manual control over which enqueued task is scheduled for execution next.</li> </ol> <p>An <code>OperationQueue</code> could of course address the former but gives no control over the latter. Being able to influence the order in which the queue executes its task is however beneficial for the purposes of my app (anticipating and delaying expensive tasks that are likely to get cancelled), hence my attempt at this implementation.</p> <p>I have multiple concerns:</p> <ol> <li><p>The fact that this is <em>one</em> class providing <em>two</em> distinct pieces of functionality seems like a red flag. Implementing this in two separate types, possibly with one subclassing the other, would probably be better. But I can't see a straightforward way to untangle this without overcomplicating things.</p> </li> <li><p>Needing three queues and a semaphore to coordinate everything isn't great. Am I trying to be too clever?</p> </li> <li><p>Looking through some of the <a href="https://gist.github.com/tclementdev/6af616354912b0347cdf6db159c37057" rel="nofollow noreferrer">libdispatch guidelines</a>, particularly <a href="https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20170828/039405.html" rel="nofollow noreferrer">this post by the maintainer</a>, has me wondering if this entire use case is a bit of an anti-pattern anyway (specifically regarding the use of semaphores to wait for asynchronous work). Is it simply a bad idea to try retrofitting this kind of functionality onto GCD?</p> </li> </ol> <p>Given my initial requirements (i.e. limited bandwidth and custom scheduling order), is this approach remotely reasonable? If so, how could it be improved?</p> <p>Thanks in advance!</p> <pre class="lang-swift prettyprint-override"><code>final class Queue { let count: Int private let block: (Range&lt;Int&gt;) -&gt; Int private let semaphore: DispatchSemaphore private let objectQueue: DispatchQueue private let semaphoreQueue: DispatchQueue private let workItemQueue: DispatchQueue private var workItems = Array&lt;DispatchWorkItem&gt;() init(count: Int, qos: DispatchQoS = .default, block: @escaping (Range&lt;Int&gt;) -&gt; Int) { self.count = count self.block = block self.semaphore = .init(value: count) self.objectQueue = .init(label: &quot;object-queue&quot;, qos: qos) self.semaphoreQueue = .init(label: &quot;semaphore-queue&quot;, qos: qos) self.workItemQueue = .init(label: &quot;workitem-queue&quot;, qos: qos, attributes: [.concurrent]) } } extension Queue { func async(execute work: @escaping () -&gt; ()) { objectQueue.async { [self] in let workItem = DispatchWorkItem(flags: [.inheritQoS]) { work() semaphore.signal() } workItems.append(workItem) semaphoreQueue.async { semaphore.wait() objectQueue.async { let index = block(workItems.indices) let workItem = workItems.remove(at: index) workItemQueue.async(execute: workItem) } } } } func async(execute workItem: DispatchWorkItem) { async { workItem.perform() } } } </code></pre> <p><strong>Edit</strong></p> <p>The <code>block</code> closure selects the index of the next-to-be-scheduled work item. Its argument <code>Range</code> is guaranteed to be non-empty.</p> <p>The work items are in the same order in which they were enqueued. <code>block</code> isn't intended to relate to specific work items but rather to make a decision between choosing ones that have been awaiting execution for a while vs. ones that just arrived in the queue.</p> <p>I use it in this specific way:</p> <pre class="lang-swift prettyprint-override"><code>let count = max(1, ProcessInfo.processInfo.activeProcessorCount - 2) let queue = Queue(count: count) { indices in let value = sqrt(.random(in: 0 ..&lt; 1)) let index = Int(value * Double(indices.count)) return indices[index] } </code></pre> <p>In this configuration the queue picks work items at random, <em>skewing towards newer ones</em>. This might seem counterintuitive, but when dealing with a lot of expensive tasks which are subject to likely cancellation (in my case loading resources for display in a collection view while scrolling), this results in a measurable performance improvement.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T09:41:32.290", "Id": "510327", "Score": "0", "body": "If I understand it correctly, the `block` callback is called when an execution slot is available, and that returns the index of the next work item to be executed. But how does the callback make that decision bases on *indices* only, if there is no (public) correspondence between the indices and the work items? – A small usage example might be helpful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T09:42:45.777", "Id": "510328", "Score": "0", "body": "Btw, your code fails to compile in my Xcode 12 with some “Missing argument for parameter 'label' in call“ errors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T10:11:32.817", "Id": "510330", "Score": "0", "body": "@MartinR Oh, I forgot I had an extension on `DispatchQueue` to automatically generate a label." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T10:13:40.707", "Id": "510331", "Score": "1", "body": "@MartinR Added an example use case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T01:51:38.317", "Id": "528609", "Score": "0", "body": "I'm trying to understand what you're doing here that simply setting `queuePriority` for operations added to an `OperationQueue` would not achieve. E.g. [here](https://i.stack.imgur.com/nKvLL.png) I added 25 low priority tasks (in green) to a queue with a max concurrency of 6, then added 25 normal priority tasks (in yellow), and the operation queue correctly prioritized the higher priority tasks ahead of the low priority tasks that were added to the queue before the default priority tasks (as soon as, of course, the queue was free)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T11:14:56.510", "Id": "528623", "Score": "0", "body": "@Rob I am dealing with tasks that have all inherently the same priority. The ability to control the order of execution such that e.g. more recent task are treated preferentially can help with making the UI feel more responsive when the user demands many expensive resources in quick succession. Scrolling a collection view of images is an example. No individual image is more important than another while scrolling is in progress, but as soon as it stops, it makes sense to load the latest images first, instead of working yourself through the queue back to front." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T11:15:44.907", "Id": "528624", "Score": "0", "body": "@Rob The fact that this approach allows to introduce an element of randomness to the order of execution is also quite important to me, as it enables interesting effects in the UI. It feels subjectively faster to me, to not present resources in the \"obvious\" order sometimes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T16:38:01.937", "Id": "528640", "Score": "0", "body": "OK, I now understand your intent. Personally, I'd suggest that you need priorities, too, where the currently visible cells are medium priority, where the prefetched cells are low priority, and the cells that have scrolled out of view are very low priority, or simply canceled. You never want it fetching a cell that you don't yet need or don't need any more before you fetch the images for the visible cells. Now, if within those constraints, you also want randomness, fine, add that. But I don't think you want to rely solely on a probability curve (which is in effect what your approach is doing)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T17:17:45.953", "Id": "528642", "Score": "0", "body": "@Rob The thing is that for use cases like this, what is essentially needed are *dynamic* priorities. Currently needed resources can become unnecessary before they get a chance to load, prefetched resources can become needed immediately, etc. Associating a certain priority with a given task is (in my opinion) only really a good model if the priority is expected to be fixed, otherwise you are signing yourself up for a lot of bookkeeping." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T17:17:57.297", "Id": "528643", "Score": "0", "body": "@Rob Of coures you still don't want to load more resources than are actually needed, but I find that this is more easily accomplished within the body of the task itself. Check for relevance / cache volume / other metrics before you load the resource and abort of necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T18:16:40.450", "Id": "528645", "Score": "0", "body": "Yep, agreed re dynamic priorities. I am merely suggesting that a single, non-uniform distribution function is suboptimal, and you might instead want a notion of priority classes, and then some distribution within each (e,g., low priority LIFO for for cells that have scrolled out of view; random, evenly distributed for visible cells; and low priority FIFO for prefetched cells; ie fetch what you need now first, and then next prioritize the ones that may scroll into view soonest)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T18:16:43.177", "Id": "528646", "Score": "0", "body": "Re dispatch vs operation queues, I'd lean towards the latter if when dealing with dependencies between tasks that are themselves asynchronous. Dispatch work items won't wait until the task is finished unless you block the worker thread until the task is done. That having been said, I would probably abandon both dispatch and operation queues for this sort of dynamic prioritization (as they are both inherently FIFO queues and you have to contort yourself to get the dynamic and randomization logic you are looking for). I'll post something this weekend if you are interested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T19:12:56.427", "Id": "528652", "Score": "0", "body": "@Rob I agree, splitting things up across multiple queues with different behaviors could be a reasonable optimization (at least for the specific example of scrolling through resources). But it also introduces further complexity and requires knowledge about the properties of the task at the point of enqueueing. Plus it wouldn't necessarily generalize to other use cases, but maybe that's a good thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T19:13:13.593", "Id": "528653", "Score": "0", "body": "@Rob I would be very interested in an approach that doesn't use GCD or operation queues at all. I'm more than a little wary of my code, hence the question." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "14", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T01:33:30.103", "Id": "258824", "Score": "2", "Tags": [ "swift", "asynchronous", "concurrency", "queue", "grand-central-dispatch" ], "Title": "Fixed-width non-FIFO DispatchQueue" }
258824
<p>The code below is a Python module to flatten JSON-like structure (nested dictionaries and lists) to a single string. It also provides partial result in the form of flat list of strings. This flattening is intended to be used to generate commands for the command line variant of the Check Point Management API: <a href="https://sc1.checkpoint.com/documents/latest/APIs/" rel="nofollow noreferrer">https://sc1.checkpoint.com/documents/latest/APIs/</a></p> <p>The details of how it works and examples are documented in the code which uses docstrings made to be able to generate documentation using Sphinx.</p> <p>I am concerned mainly about:</p> <ul> <li>The style <ul> <li>Identifier naming</li> <li>Docstrings - aren't they excessive (for the private functions)?</li> <li>Later I noticed I can replace <code>_is_convertible_to_str(value)</code> by much simpler <code>isinstance(value, _CONVERTIBLE_TO_STR)</code> and define the constant tuple instead of the function. Which way should be preferred?</li> </ul> </li> <li>The way of defining the default behaviour while allowing some flexibility</li> <li>The module API design (public functions, parameters)</li> </ul> <pre class="lang-python prettyprint-override"><code>&quot;&quot;&quot; JSON-like structure flattening The module provides functions to flatten nested structures of dictionaries and lists to a flat list of strings or a single string. Functions: * `flatten_to_list()`: Convert structure to a flat list of strings. * `flist_to_str()`: Convert list of strings to a single string. Examples: &gt;&gt;&gt; flat_list1 = flatten_to_list({'name': 'John', 'surname': 'Doe'}) &gt;&gt;&gt; flist_to_str(flat_list1) 'name John surname Doe' &gt;&gt;&gt; flat_list2 = flatten_to_list({ ... 'add': 'access-rule', ... 'layer': 'policy1 Network', ... 'position': {'bottom': 'RADIUS rules'}, ... 'source': ['web_serers'], ... 'destination': ['internet'], ... 'action': 'Accept', ... 'track': {'type': 'Log'}}, ... key_order=('add', 'layer', 'position')) &gt;&gt;&gt; flat_list2 ['add', 'access-rule', 'layer', 'policy1 Network', 'position.bottom',\ 'RADIUS rules', 'source.1', 'web_serers', 'destination.1', 'internet',\ 'action', 'Accept', 'track.type', 'Log'] &gt;&gt;&gt; flist_to_str(flat_list2) 'add access-rule layer &quot;policy1 Network&quot; position.bottom &quot;RADIUS rules&quot;\ source.1 web_serers destination.1 internet action Accept track.type Log' &quot;&quot;&quot; from __future__ import annotations import string from typing import ( Any, Hashable, ItemsView, Iterator, Union, Callable, Iterable, Generator) # --- private constants # whitespace characters which cause a string to require quoting _WHITESPACE = set(string.whitespace) # --- private helper functions def _is_convertible_to_str(value: Any) -&gt; bool: &quot;&quot;&quot;Decide if we want to convert the value using `str(value)`. Return `False` for container types. (`dict`, `list`...) The function decides if we are willing to convert the `value` in a JSON-like structure to a string. Args: value: the value to test the convertibility of Returns: `True` if we want to convert the value using `str(value)` Examples: &gt;&gt;&gt; _is_convertible_to_str(1) True &gt;&gt;&gt; _is_convertible_to_str([]) False &quot;&quot;&quot; return (isinstance(value, str) or isinstance(value, int) or isinstance(value, float)) def _ordered_dict_items( dictionary: dict[Hashable, Any], key_order: Iterable[Hashable] = () ) -&gt; Generator[tuple[Hashable, Any], None, None]: &quot;&quot;&quot;Iterate dictionary like `dict.items()`_ with optional key order. Dictionary keys listed in `key_order` are iterated first in the order as listed. The rest is iterated in unspecified order. Args: dictionary: dictionary to iterate key_order: these keys will be iterated first in the given order Yields: `(key, value)` tuples as standard `dict.items()`_ does Examples: &gt;&gt;&gt; list(_ordered_dict_items({'key': 42})) [('key', 42)] &gt;&gt;&gt; list(_ordered_dict_items( ... {'key': 42, 'id': 8569, 'name': 'Marc'}, ['name', 'id'])) [('name', 'Marc'), ('id', 8569), ('key', 42)] .. _dict.items(): https://docs.python.org/3/library/stdtypes.html#dict.items &quot;&quot;&quot; dictionary = dictionary.copy() # we will remove processed keys for ordered_key in key_order: if ordered_key in dictionary: yield ordered_key, dictionary[ordered_key] del dictionary[ordered_key] yield from dictionary.items() # yield the rest in unspecified order def _contains_any(set1: Iterable[Hashable], set2: Iterable[Hashable]) -&gt; bool: r&quot;&quot;&quot;Test if `set1` contains any elements of `set2` or vice versa. The function tests if the intersection of the sets is not empty. Unlike the plain `&amp;` operator the function operates on any iterables of `Hashable`. For example the function is useful to test if one string contains any character from the other string (or any iterable of characters). Args: set1: an iterable for the intersection test set2: another iterable for the intersection test Returns: `True` if the intersection is not empty Examples: &gt;&gt;&gt; _contains_any('good morning', ' \t') True &gt;&gt;&gt; _contains_any('hello John', 'xXyY') False &quot;&quot;&quot; if not isinstance(set1, set): set1 = set(set1) if not isinstance(set2, set): set2 = set(set2) return bool(set1 &amp; set2) # --- public functions def flatten_to_list( json_struct: Union[dict[str, Any], list[Any]], /, *, parent: str = '', startindex: int = 1, parent_sep: str = '.', key_order: Iterable[str] = (), value_converter: Callable = str, key_converter: Callable = str) -&gt; list[str]: &quot;&quot;&quot;Flatten JSON-like structure to a list of strings. The JSON-like structure consists of dictionaries, lists and simple values. The resulting list consists of pairs: `[key1, value1, key2, value2 ...]`. Key produced for a JSON list item is an ordinal number of the position in the list: `1, 2, 3, ...` Key from a nested container is preceded by the parent container key: *parent_key.key*. Args: json_struct: the JSON-like structure to flatten parent: parent key name startindex: first number for indexing list items parent_sep: parent key or index separator string key_order: list of keys needing defined order value_converter: function converting values to strings key_converter: function converting keys to strings Returns: flat list of key, value pairs: `[key1, value1, key2, value2 ...]` Examples: &gt;&gt;&gt; flatten_to_list({'name': 'John', 'surname': 'Doe'}) ['name', 'John', 'surname', 'Doe'] &gt;&gt;&gt; flatten_to_list({'name': 'Alice', 'siblings': ['Jeff', 'Anna']}) ['name', 'Alice', 'siblings.1', 'Jeff', 'siblings.2', 'Anna'] &gt;&gt;&gt; flatten_to_list({ ... 'name': 'Zip', ... 'eye': {'left': 'red', 'right': 'black'}}) ['name', 'Zip', 'eye.left', 'red', 'eye.right', 'black'] &gt;&gt;&gt; flatten_to_list(['red', 'green', 'blue'], ... parent='color', startindex=0) ['color.0', 'red', 'color.1', 'green', 'color.2', 'blue'] &gt;&gt;&gt; flatten_to_list({'name': 'John', 'surname': 'Doe'},\ key_order=['surname']) ['surname', 'Doe', 'name', 'John'] &quot;&quot;&quot; result: list[str] = [] if parent: parent = parent + parent_sep struct_iterator: Union[ItemsView, Iterator] # will yield (key, value) if isinstance(json_struct, dict): struct_iterator = _ordered_dict_items(json_struct, key_order) elif isinstance(json_struct, list): struct_iterator = enumerate(json_struct, startindex) else: raise TypeError( f&quot;Unexpected data type {type(json_struct)} of the structure.&quot;) for key, value in struct_iterator: ext_key = parent + key_converter(key) if isinstance(value, (list, dict)): result.extend(flatten_to_list( value, parent=ext_key, startindex=startindex, parent_sep=parent_sep, key_order=key_order, value_converter=value_converter, key_converter=key_converter)) elif _is_convertible_to_str(value): result.extend([ext_key, value_converter(value)]) else: raise TypeError( f&quot;Unexpected data type {type(value)} inside structure.&quot;) return result def flist_to_str( flist: list[str], /, *, separator: str = ' ', quote_str: str = '&quot;', quote_always: bool = False) -&gt; str: &quot;&quot;&quot;Convert flat list of strings to a string with quoting. The function is useful to convert the resulting list from :py:func:`flatten_to_list()` to a single string. Args: flist: flat list of strings to be converted to a single string separator: separator between list items quote_str: character or string to quote list items if needed quote_always: if list items should be quoted even if not necessary Examples: &gt;&gt;&gt; flist_to_str(['good', 'morning']) 'good morning' &gt;&gt;&gt; flist_to_str(['good morning']) '&quot;good morning&quot;' Todo: * No escaping implemented for quote characters. We need to find out which way of escaping does Check Point CLI API support. &quot;&quot;&quot; def quote(string1: str) -&gt; str: &quot;&quot;&quot;Quote string1 as needed&quot;&quot;&quot; if quote_always or _contains_any(string1, _WHITESPACE) or not string1: return quote_str + string1 + quote_str return string1 return separator.join(quote(item) for item in flist) </code></pre>
[]
[ { "body": "<ul>\n<li>I agree with your assessment here; <code>isinstance(value, _CONVERTIBLE_TO_STR)</code> (where <code>_CONVERTIBLE_TO_STR = (str, int, float)</code>) is simpler and better than <code>_is_convertible_to_str(value)</code>. It is also a little bit faster. I determined this by measuring execution times with <a href=\"https://docs.python.org/3/library/timeit.html\" rel=\"nofollow noreferrer\"><code>timeit</code></a>.</li>\n<li><code>_contains_any</code> looks like it was written in a way so it can be useful in a general sense, e.g. it could be part of a utility library. But right now the only way it is used is to check if a string contains any whitespace. For simplicity, I would go with something like this instead:\n<pre class=\"lang-python prettyprint-override\"><code>def contains_whitespace(text: str) -&gt; bool:\n return any(character in _WHITESPACE for character in text)\n</code></pre>\nBased on measurements with <code>timeit</code> and randomly-generated strings, I found that this was also generally faster than <code>_contains_any(text, _WHITESPACE)</code>.</li>\n<li>You can get a small performance boost by using string interpolation with f-strings (<code>f&quot;{quote_str}{string1}{quote_str}&quot;</code>) instead of string concatenation via the <code>+</code> operator (<code>quote_str + string1 + quote_str</code>). Nothing huge, but improving performance without having to sacrifice readability is pretty nice.</li>\n<li>For <code>flist_to_str</code>, I would make some naming changes.\n<ul>\n<li>If I pretended that I didn't know the context of the larger problem statement, seeing the names <code>flist_to_str</code> and <code>flist: list[str]</code> and the documentation &quot;flat list of strings&quot;, I would probably wonder, &quot;Why call it a <em>flat</em> list of strings? How is that any different from a list of strings?&quot; And if we look at the type hints there really isn't a difference, so I would change the naming to make that more clear:\n<ul>\n<li><code>flist_to_str</code> -&gt; <code>list_to_str</code></li>\n<li><code>flist: list[str]</code> -&gt; <code>items: list[str]</code></li>\n<li>&quot;flat list of strings&quot; -&gt; &quot;list of strings&quot; (in the documentation)</li>\n</ul>\n</li>\n<li><code>quote_str: str</code> -&gt; <code>quote_mark: str</code>\n<ul>\n<li>I think this is a little more precise.</li>\n</ul>\n</li>\n<li><code>string1: str</code> -&gt; <code>text: str</code>\n<ul>\n<li>I totally understand choosing the name <code>string1</code> to avoid shadowing the <code>string</code> module, but <code>text</code> is probably a better name here.</li>\n<li>To be fair, coming up with a good generic name for a string in Python is hard because the two best candidates (<code>str</code> and <code>string</code>) are already taken by a built-in function and a standard library module, respectively. I always end up using something like <code>s</code> or <code>text</code> as a result.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<hr />\n<p>In summary, there were some small nits pointed out here and there but overall I found the code and the public API it exposes very well-documented and easy to read. The docstrings were useful and had illuminating examples; I didn't think they were excessive at all.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T03:17:18.277", "Id": "258909", "ParentId": "258825", "Score": "1" } }, { "body": "<p>A couple comments:</p>\n<h3><code>_is_convertible_to_str()</code></h3>\n<p>As you discovered, the second argument to <code>isinstance()</code> can be a tuple of classes:</p>\n<pre><code>def _is_convertible_to_str(value: Any) -&gt; bool:\n return isinstance(value, (str, int, float))\n</code></pre>\n<p>You can call <code>str()</code> on just about anything, so <code>_is_convertable_to_str()</code> isn't very descriptive. I'd drop the <code>_is_convertible_to_str()</code> function and just use <code>isinstance()</code> directly. You already use <code>isinstance(value, (list, dict))</code> in the same <code>if</code> statement.</p>\n<h3><code>_ordered_dict_items()</code></h3>\n<p><code>dict.keys()</code> acts like a set, so you can use set difference to determine the unordered keys, instead of making a copy of all the keys and deleting the ordered keys. For small dicts, they are about the same speed, so use which ever is clearer to you.</p>\n<pre><code>def _ordered_dict_items(\n dictionary: dict[Hashable, Any],\n key_order: Iterable[Hashable] = ()\n ) -&gt; Generator[tuple[Hashable, Any], None, None]:\n\n yield from ((key, dictionary[key] for key in key_order if key in dictionary)\n yield from ((key, dictionary[key] for key in dictionary.keys() - key_order)\n</code></pre>\n<h3><code>_contains_any()</code></h3>\n<p>The method form of <code>&amp;</code> takes an iterable, so it isn't necessary to convert <code>set2</code> to an actual set:</p>\n<pre><code>def _contains_any(set1: Iterable[Hashable], set2: Iterable[Hashable]) -&gt; bool:\n if not isinstance(set1, set):\n set1 = set(set1)\n return bool(set1.intersection(set2))\n</code></pre>\n<h3><code>flatten_to_list()</code></h3>\n<p><code>flatten_to_list()</code> has a lot of parameters to &quot;configure&quot; the function. They don't change when making a recursive call to handle a nested list or dict. To me, this suggests this might be a good use for a class. The &quot;configuration&quot; parameters can be passed to <code>__init__()</code>. A method then does the actual flattening. <code>json_struct</code> and <code>parent</code> change during recursion, so they can be method arguments.</p>\n<p>Lastly, <code>functools</code> in the standard library contains decorators for overloading functions or methods based on the types of their first argument. <a href=\"https://docs.python.org/3.8/library/functools.html#functools.singledispatchmethod\" rel=\"nofollow noreferrer\"><code>@singledispatchmethod</code></a> is used to decorate the &quot;default&quot; method to use. <code>.register(type)</code> is used to register a version of the method to handle the specified type. These decorators don't seem to get used a lot and there is some overhead, but I find they can be cleaner than a set of <code>if isinstance(...):... elif isinstance(...):...</code> statements.</p>\n<pre><code>from functools import singledispatchmethod\n\nclass Flattener:\n def __init__(self,\n startindex=1,\n parent_sep='.',\n key_order=(),\n value_converter=str,\n key_converter=str\n ):\n self.startindex = startindex\n self.parent_sep = parent_sep\n self.key_order = key_order\n self.value_converter = value_converter\n self.key_converter = key_converter\n\n \n @singledispatchmethod\n def flatten(self, thing, parent=''):\n &quot;&quot;&quot;Base 'flatten' method when a more specific method isn't\n defined for the type of 'thing'.\n \n Methods for specific types are registered below.\n &quot;&quot;&quot;\n yield from (parent, self.value_converter(thing))\n\n @flatten.register(dict)\n def flatten_dict(self, thing, parent=''):\n for key, value in _ordered_dict_items(thing, self.key_order):\n if parent:\n ext_key = f&quot;{parent}{self.parent_sep}{self.key_converter(key)}&quot;\n else:\n ext_key = self.key_converter(key)\n yield from self.flatten(value, ext_key)\n \n @flatten.register(list)\n def flatten_list(self, thing, parent=''):\n for key, value in enumerate(thing, self.startindex):\n if parent:\n ext_key = f&quot;{parent}{self.parent_sep}{self.key_converter(key)}&quot;\n else:\n ext_key = self.key_converter(key)\n yield from self.flatten(value, ext_key)\n</code></pre>\n<p>Here, the decorator <code>@singledispatchmethod</code> sets the <code>flatten</code> method up as the default version. The decorator <code>@flatten.register(dict)</code> registers a version that gets called when the first argument (after <code>self</code>) is a <code>dict</code> (the name of the registered method doesn't matter, the docs use <code>_</code>). Similarly, <code>@flatten.register(list)</code> registers a version to use for lists. This makes the bodies of the <code>flatten</code> methods much simpler and easier to understand.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T23:49:28.007", "Id": "259033", "ParentId": "258825", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T02:07:59.813", "Id": "258825", "Score": "6", "Tags": [ "python", "python-3.x", "strings", "json", "converting" ], "Title": "Flatten JSON to string" }
258825
<p>I want to determine the number of distinct subarrays that can form having at most a given number of odd elements. Two subarrays are distinct if they differ at even one position. The subarray is a contiguous position of an array. Please give some suggestions to improve the time and space complexity.</p> <pre class="lang-none prettyprint-override"><code>Exp1: Input: nums = [1, 2, 3, 4], k = 1 Output: 8 Explanation: [1], [2], [3], [4], [1, 2], [2, 3], [3, 4], [2, 3, 4] </code></pre> <pre class="lang-none prettyprint-override"><code>Exp2: Input: nums = [3, 2, 3, 4], k = 1 Output: 7 Explanation: [3], [2], [4], [3, 2], [2, 3], [3, 4], [2, 3, 4] Note we did not count [3, 2, 3] since it has more than k odd elements. </code></pre> <pre class="lang-none prettyprint-override"><code>Exp3: Input: nums = [3, 2, 3, 2], k = 1 Output: 5 Explanation: [3], [2], [3, 2], [2, 3], [2, 3, 2] [3], [2], [3, 2] - duplicates [3, 2, 3], [3, 2, 3, 2] - more than k odd elements </code></pre> <hr /> <pre><code>class result { static int numberOfSubarrays(int[] numbers, int k) { if(k == 0) return 0; boolean [] IsOdd = new boolean [numbers.length]; for(int i = 0; i &lt; numbers.length; i++){ IsOdd[i] = numbers[i] %2 != 0; } HashSet&lt;String&gt; subs = new HashSet&lt;String&gt;(); for(int i = 0; i &lt; numbers.length; i++){ StringBuilder sb = new StringBuilder(); int oddCount = 0; for(int j = i; j &lt; numbers.length; j++){ if(IsOdd[j]){ oddCount++; if(oddCount &gt; k){ break; } } sb.append(numbers[j] + &quot; &quot;); subs.add(sb.toString()); } } return subs.size(); } } </code></pre> <hr />
[]
[ { "body": "<p>Welcome to Stack Review, the first thing I see in your code is:</p>\n<pre><code>class result { ..your code }\n</code></pre>\n<p>Instead of <code>result</code> you should use <code>Result</code> as a classname because as specified in <a href=\"https://www.oracle.com/java/technologies/javase/codeconventions-namingconventions.html\" rel=\"nofollow noreferrer\">java_naming_conventions</a> : <em>Class names should be nouns, in mixed case with the first letter of each internal word capitalized</em>.</p>\n<p>The second thing I see in your code is:</p>\n<pre><code>HashSet&lt;String&gt; subs = new HashSet&lt;String&gt;();\n</code></pre>\n<p>Better to declare instead <code>Set&lt;String&gt; subs = new HashSet&lt;String&gt;();</code> that guarantees more flexibility in case you want to use another implementation of the<code>Set</code> interface.</p>\n<p>About performance, briefly you have a <code>for</code> loop where you instantiate a new <code>StringBuilder</code> object at every iteration like below:</p>\n<pre><code>for(int i = 0; i &lt; numbers.length; i++){\n StringBuilder sb = new StringBuilder();\n ...other instructions\n sb.append(numbers[j] + &quot; &quot;);\n}\n</code></pre>\n<p>There is a debated alternative to this scenario corresponding to instantiate one single <code>StringBuilder</code> object with a fixed capacity and resetting its length at every iteration of the loop with the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html#setLength-int-\" rel=\"nofollow noreferrer\"><code>StringBuilder.setLength</code></a> method like below:</p>\n<pre><code>StringBuilder sb = new StringBuilder(Arrays.toString(numbers).length());\nfor(int i = 0; i &lt; numbers.length; i++){\n ...other instructions\n sb.setLength(0);\n}\n\n</code></pre>\n<p>For every testcase I set the capacity of the <code>StringBuilder</code> object to\nthe length of the <code>String</code> representation of the initial array like <code>[1, 2, 3, 4]</code> that is the maximal string length the <code>StringBuilder</code> will contain.</p>\n<p><em>Update after @TorbenPutkonen comment</em> : better to use <code>StringBuilder.setLength(0)</code> at the beginning of the loop to improve readibility of the code, so the reader has a clear vision of the state of the <code>StringBuilder</code> at the beginning and not at the end.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T05:48:36.303", "Id": "510479", "Score": "1", "body": "When used in a loop, the preference should be to reset the `StringBuilder` with `setLength(0)` before it's use begins instead of after it has been used. This way the reader does not have to go through all the code to find out what the state of the StringBuilder is at the beginning of the loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-31T07:27:45.197", "Id": "510485", "Score": "0", "body": "@TorbenPutkonen - You are completely right, thank you for the advice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T10:34:17.977", "Id": "510739", "Score": "0", "body": "@dariosicily if I do that, it will mess up the output." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-04-02T10:59:23.923", "Id": "510744", "Score": "0", "body": "@wagaga I don't understand in which way it will mess up the output, I substituted the creation of one empty `StringBuilder` at every iteration with the creation of one `StringBuilder` that will be reset at every iteration." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-30T11:40:56.417", "Id": "258868", "ParentId": "258828", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T05:41:22.957", "Id": "258828", "Score": "3", "Tags": [ "java", "algorithm", "array", "dynamic-programming" ], "Title": "Count the number of distinct subarrays" }
258828
<pre><code>import csv class CSV: def __init__(self,title, row=[]): self.row = row self.title = title def create(self): csvfilename = &quot;{}&quot;.format(self.title) csvFileObj = open(csvfilename, 'w' , encoding='utf-8-sig', newline='') csvWriterObj = csv.writer(csvFileObj) csvWriterObj.writerow(self.row) csvFileObj.close() def createConsolidate(self): csvfilename = &quot;{}&quot;.format(self.title) csvFileObj = open(csvfilename, 'w' , encoding='utf-8-sig', newline='') csvWriterObj = csv.writer(csvFileObj) for row in self.row: csvWriterObj.writerow(row) csvFileObj.close() def appendConsolidate(self): csvfilename = &quot;{}&quot;.format(self.title) csvFileObj = open(csvfilename, 'a' , encoding='utf-8-sig', newline='') csvWriterObj = csv.writer(csvFileObj) for row in self.row: csvWriterObj.writerow(row) csvFileObj.close() def open(self):. rowData = [] csvfilename = &quot;{}&quot;.format(self.title) csvFileObj = open(csvfilename, encoding='utf-8-sig') readerObj = csv.reader(csvFileObj) for row in readerObj: rowData.append(row) return rowData csvFileObj.close() </code></pre> <p>it's working but not DRY. It can be easy to make it just a function but for learning purposes. Not familiar with python classes. Thank you for your help in advance.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T10:55:01.833", "Id": "258833", "Score": "1", "Tags": [ "python-3.x", "csv" ], "Title": "Open and update csv file" }
258833
<p>Hi there I would like to know if there's a better way of specifying an array of objects on a mongoose schema.</p> <p>This is what I have at the moment:</p> <pre><code>const mongoose = require('mongoose') const photoCode = mongoose.Schema( { value: { type: String, trim: true, unique: true }, status: { type: String, enum: ['valid', 'expired', 'attributed'], default: 'valid', }, }, { strict: true, timestamps: true }, ) const photoCodeSchema = new mongoose.Schema({ code: [photoCode], }) module.exports = mongoose.model('PhotoCode', photoCodeSchema) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T13:29:15.107", "Id": "510345", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T14:33:44.397", "Id": "510350", "Score": "0", "body": "The title could still be improved - we're interested in the *purpose* of the code, rather than its *mechanism*. We really need to understand the motivational context to give good reviews. Thanks!" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T11:36:45.807", "Id": "258835", "Score": "0", "Tags": [ "mongoose" ], "Title": "How to best reference a mongoose schema into another schema" }
258835