body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>We have this employees table, that looks like this: </p> <p><a href="https://i.stack.imgur.com/sgNG6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sgNG6.png" alt="enter image description here"></a></p> <p>that contains 16,530 employee rows. As expected, this table takes more than 30 seconds to load. I have been tasked with speeding it up somehow. </p> <p>As a stop-gap, we blocked this UI with a loading screen when the page is loading.</p> <p>Thus, our flow is as follows:</p> <ol> <li>Get all the employees from the API, for a store</li> <li>For each employee <ul> <li>convert it into an <code>Employee</code> object</li> <li>get its HTML representation (via template rendering)</li> <li>push that HTML representation into a collection</li> </ul></li> <li>initialize the Datatables object with that collection</li> <li>adjust the Datatables columns and draw the table</li> </ol> <p><strong>Implementation</strong></p> <p>On <code>$(document).ready</code>, we have the following table setup logic:</p> <pre><code>var addbutton = '&lt;button onclick="PopModel()" class="btn btn-success float-sm-left rounded"&gt;&lt;i class="fa fa-user-plus" aria-hidden="true"&gt;&lt;/i&gt; Add Employee&lt;/button&gt;' var table_height = $('#with-content') .height() - 175 var table = InitializeDatatable('#data-table', table_height, addbutton, 1, { paging: true, pageLength: 50, deferRender: true }) let start = Date.now() GetEmployees(function (result, success) { if (success) { var secondStep = Date.now() var hundredBatchStep = Date.now() let tableRows = [] console.log("Fetching the data from the server took %.3f seconds", (secondStep - start) / 1000) var ran = 0; for (let i = 0; i &lt; result.length; i++) { const element = result[i]; // progress bar logic setTimeout(function () { ran++; // adjust the progress bar state if it is defined if ($progressBar != null) { var percentValue = (ran / result.length) * 100 $progressBar .css('width', percentValue + "%") if (percentValue == 100) { $('.dataTables_scrollBody') .LoadingOverlay('hide') } } // extract an Employee object and add its HTML representation to datatables var employee = new Employee() .ExtractFrom(element), $employeeRow = employee.ToHTML() tableRows.push($employeeRow[0]) if (ran == result.length) { let intermediateStep = Date.now() table.rows.add($(tableRows)) let thirdStep = Date.now() console.log("adding the table rows to the Datatables API took %.3f seconds", (thirdStep - secondStep) / 1000) table.columns.adjust() .draw(); console.log("took %.3f seconds to draw", (Date.now() - thirdStep) / 1000) } if (ran == 50) { $('.dataTables_scrollBody') .LoadingOverlay("show", { image: "", custom: $progressBarDiv }); $progressBar = $('#progressbar .progress-bar') } }, 1) } if (result.length == 0 &amp;&amp; $('#task-selectpicker option') .length == 0) { Alert("It looks like there are no tasks created, would you like to create them before creating your employees?", "This can make things easier when setting up your employees.", function () { window.location = '/task/index' }) } } else { var response = new ErrorResponse(result.responseText) response.Show() } }) </code></pre> <p>Our <strong><code>InitializeDatatable</code></strong> is defined to be:</p> <pre><code>// Datatables function InitializeDatatable(selector, table_height, addbutton, autoColumn = 0, customOptions = {}) { var randomButtonID = RandomID() var defaultOptions = { dom: `&lt;"${randomButtonID}-addbutton"&gt;frtip`, scrollY: table_height, scrollCollapse: true, paging: true, info: false, order: [ [autoColumn, 'asc'] ], deferRender : true } $.extend(defaultOptions, customOptions) var table = $(selector) .DataTable(defaultOptions) $(`div.${randomButtonID}-addbutton`) .html(addbutton) return table } </code></pre> <p>Note that, once employees are fetched from the database, we convert those into <code>Employee</code> objects, which have the following HTML representation logic:</p> <pre><code>ToHTML() { // load in the employee template if (employeeTemplate == null) { employeeTemplate = FetchTemplate('employee/employee.html', "employee-template"); } // render it with this var $element = employeeTemplate.tmpl(this); // get the picture and attach it directly to the view element that's being rendered this.GetPicture(function (picture) { $element.find('.person-image') .attr('src', picture.Picture) .data(picture); }); // attach this model data to the view element and return it. return $element.data("model", this); } </code></pre> <p><strong>NOTE</strong>: I inserted benchmark logic at all the major steps of this.</p> <p><strong>Benchmark data</strong></p> <p>I have been benchmarking each step of this process (save the other API hits (not shown, because irrelevant to this)), and compiling that data into a spreadsheet. (I cannot share that spreadsheet directly here, so I screenshot it.)</p> <p><a href="https://i.stack.imgur.com/EGq68.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EGq68.png" alt="enter image description here"></a></p> <p>As I expected, the HTML data creation part of the process <strong>is the most expensive</strong> as it takes, on average, <strong>17.6 seconds</strong> to complete!</p> <p>I have been arguing about how to fix this: to only load a chunk of the server data in at once, and create API endpoints to serve specific part of that data. (After all, as implemented, it costs the client an average of <strong>3.7 seconds</strong> of load time, and seems inconsistent with the use case of the page itself.) </p> <p>However, I was told "the API is working just fine, and that we should find other way to speed up the page". I have tried the <a href="https://datatables.net/extensions/scroller/examples/initialisation/large_js_source.html" rel="nofollow noreferrer">infinite</a> <a href="https://datatables.net/extensions/scroller/examples/initialisation/server-side_processing.html" rel="nofollow noreferrer">scrolling</a> APIs, but as of the time of writing this, the client-side scrolling API is broken, and the server-side one, for some reason, either doesn't want to show in the view, or becomes straight up unresponsive. I changed the options to the following: </p> <p>In <code>InitializeDatatables</code>: </p> <pre><code>paging : false </code></pre> <p>In the main function on the employee page:</p> <pre><code> // paging: true, // pageLength: 50, ajax : function(data, callback, settings) { console.log(data), setTimeout( function () { callback( { draw: data.draw } ); }, 50 ); }, scroller : { loadingIndicator : true }, deferRender: true, stateSave: true </code></pre> <p>What should we do?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-17T20:52:20.620", "Id": "409408", "Score": "0", "body": "Is there a robust way to let Datatables handle the template logic for us, so that all we do is push data (not HTML strings) into the collection, at runtime?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:51:33.610", "Id": "409837", "Score": "1", "body": "Seems like a bad design? What is the application, I would suggest approaching the problem in a different way ( I am uncertain what is going on here )." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T14:21:16.447", "Id": "409929", "Score": "0", "body": "Ya, I'm not the original author of the code. The application is quite complicated to explain on here, but is more or less a centralized dashboard for company/store owners and their managers. \n\nI was able to get it \"working\" by just pushing the data to `table`, and in `rowCallback`, perform the custom rendering. (It works, except for that I get error because it's expecting data to be array, and I gave it object. I define `columns`, and it breaks completely.)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-17T20:49:08.487", "Id": "211720", "Score": "0", "Tags": [ "javascript", "template", "jquery-datatables" ], "Title": "Optimizing Datatables table of tens of thousands of client-provided rows" }
211720
<p>I'm working on a small side project at the moment - like a homemade CCTV system.</p> <p>This part is my Python Capture Client - it uses OpenCV to capture frames from a connected webcam and sends the frames to a connected server via a socket.</p> <p>The main thing I was going for was a small application with two services which operate independently once started. One for capturing frames from the camera, and another for sending + receiving network messages. If either of these fail, the other would still work with no issues.</p> <p>I have more or less achieved this but I'm not certain that I took the best approach - I'm not normally a Python developer so I sort of winged it with this application.</p> <p>Things I felt especially strange about were the use of queues. From my searching, they seemed to be the best way for sharing data between threads.</p> <p><strong>The application can be found <a href="https://github.com/TomSelleck101/cctv-capture-client" rel="nofollow noreferrer">here</a> - any advice or comments would be appreciated!</strong></p> <p>This is the main entry point into the application:</p> <p>main.py</p> <pre><code>from orchestrator import Orchestrator from connection_service import ConnectionService from capture_service import CaptureService HOST = "127.0.0.1" PORT = 11000 def main(): capture_service = CaptureService() connection_service = ConnectionService(HOST, PORT) orchestrator = Orchestrator(capture_service, connection_service) orchestrator.start() if __name__ == '__main__': main() </code></pre> <p>This is my orchestration service - it coordinates the main loop of retrieving frames + sending to the server:</p> <p>orchestrator.py</p> <pre><code>from connection_service import ConnectionService from capture_service import CaptureService from not_connected_exception import NotConnectedException import multiprocessing import cv2 import time class Orchestrator(): def __init__(self, capture_service, connection_service): self.manager = multiprocessing.Manager() self.connection_service = connection_service self.capture_service = capture_service self.SEND_FOOTAGE = True self.DETECT_MOTION = False self.RUN = True # End services def finish(self): self.RUN = False self.connection_service.disconnect() self.capture_service.stop_capture() # Start services, connect to server / start capturing from camera # Grab frames from capture service and display # Retrieve any messages from connection service # Deal with message e.g stop / start sending frames # If send footage is true, encode frame as string and send def start(self): print ("Starting Orchestration...") self.connection_service.connect() self.capture_service.start_capture() while self.RUN: message = None #Get camera frames frame = self.capture_service.get_current_frame() self.display_frame(frame) message = self.connection_service.get_message() self.handle_message(message) #Send footage if requested if self.SEND_FOOTAGE and frame is not None: #or (self.DETECT_MOTION and motion_detected): try: frame_data = cv2.imencode('.jpg', frame)[1].tostring() self.connection_service.send_message(frame_data) except NotConnectedException as e: self.connection_service.connect() def handle_message(self, message): if message is "SEND_FOOTAGE": self.SEND_FOOTAGE = True elif message is "STOP_SEND_FOOTAGE": self.SEND_FOOTAGE = False elif message is "DETECT_MOTION": self.DETECT_MOTION = True elif message is "STOP_DETECT_MOTION": self.DETECT_MOTION = False def display_frame(self, frame): if frame is not None: # Display the resulting frame cv2.imshow('orchestrator', frame) if cv2.waitKey(1) &amp; 0xFF == ord('q'): cv2.destroyAllWindows() raise SystemExit("Exiting...") </code></pre> <p>This is my capturing service - it's job is to capture frames from the camera and put the frames onto a queue:</p> <p>capture_service.py</p> <pre><code>import cv2 import multiprocessing class CaptureService(): FRAME_QUEUE_SIZE_LIMIT = 10 STOP_QUEUE_SIZE_LIMIT = 1 START_QUEUE_SIZE_LIMIT = 1 def __init__(self): self.frame = None manager = multiprocessing.Manager() # The queue to add frames to self.frame_queue = manager.Queue(self.FRAME_QUEUE_SIZE_LIMIT) # A queue to indicate capturing should be stopped self.stop_queue = manager.Queue(self.STOP_QUEUE_SIZE_LIMIT) # A queue to indicate that capturing should be started self.start_queue = manager.Queue(self.START_QUEUE_SIZE_LIMIT) # Start Capture # Empty the stop queue. If the start queue is empty - start a new capture thread # If start queue is not empty, service has already been started def start_capture(self): print ("Starting capture...") while not self.stop_queue.empty(): self.stop_queue.get() if self.start_queue.empty(): self.capture_thread = multiprocessing.Process(target=self.capture_frames) self.capture_thread.start() self.start_queue.put("") print ("Capturing started...") else: print ("Capture already started...") # Is Capturing # Return true if start queue has a value def is_capturing(self): return not self.start_queue.empty() # Get Current Frame # Return the current frame from the frame queue def get_current_frame(self): if not self.frame_queue.empty(): return self.frame_queue.get() return None # Stop Capture # Add a message to the stop queue # Empty the start queue def stop_capture(self): if self.stop_queue.empty(): self.stop_queue.put("") while not self.start_queue.empty(): self.start_queue.get() # Capture Frames # Captures frames from the device at 0 # Only add frames to queue if there's space def capture_frames(self): cap = None try: cap = cv2.VideoCapture(0) while True: #Empty Start / Stop queue signals if not self.stop_queue.empty(): while not self.stop_queue.empty(): self.stop_queue.get() while not self.start_queue.empty(): self.start_queue.get() break; ret, frame = cap.read() if self.frame_queue.qsize() &gt; self.FRAME_QUEUE_SIZE_LIMIT or self.frame_queue.full(): continue self.frame_queue.put(frame) # When everything done, release the capture cap.release() cv2.destroyAllWindows() except Exception as e: print ("Exception capturing images, stopping...") self.stop_capture() cv2.destroyAllWindows() if cap is not None: cap.release() </code></pre> <p>This is my connection service, it takes care of all network related comms.</p> <p>connection_service.py</p> <pre><code>from send_message_exception import SendMessageException from not_connected_exception import NotConnectedException import socket import time import multiprocessing import struct class ConnectionService(): MAX_QUEUE_SIZE = 1 def __init__(self, host, port): self.host = host self.port = port self.socket = None manager = multiprocessing.Manager() # The queue to put messages to send on self.send_message_queue = manager.Queue(self.MAX_QUEUE_SIZE) # The queue received messages go onto self.receive_message_queue = manager.Queue(self.MAX_QUEUE_SIZE) # A queue which indicates if the service is connected or not self.is_connected_queue = manager.Queue(self.MAX_QUEUE_SIZE) # A queue which indicateds if the service is trying to connect self.pending_connection_queue = manager.Queue(self.MAX_QUEUE_SIZE) # A queue to stop sending activity self.stop_send_queue = manager.Queue(self.MAX_QUEUE_SIZE) # A queue to stop receiving activity self.stop_receive_queue = manager.Queue(self.MAX_QUEUE_SIZE) # Connect to the server # 1) If already connected - return # 2) If pending connection - return # 3) Start the network thread - don't return until the connection status is pending def connect(self): if self.is_connected(): return elif not self.pending_connection_queue.empty(): return else: self.network_thread = multiprocessing.Process(target=self.start_network_comms) self.network_thread.start() #Give thread time to sort out queue while self.pending_connection_queue.empty(): continue # Start network communications # Mark connection status as pending via queue. Clear stop queues. # Get socket for connection, mark as connected via queue. # Start Send + Receive message queues with socket as argument def start_network_comms(self): self.pending_connection_queue.put("CONNECTING") self.clear_queue(self.stop_send_queue) self.clear_queue(self.stop_receive_queue) self.socket = self.connect_to_server(self.host, self.port) self.is_connected_queue.put("CONNECTED") self.pending_connection_queue.get() print ("Connected to server...") receive_message_thread = multiprocessing.Process(target=self.receive_message, args=(self.socket,)) receive_message_thread.start() send_message_thread = multiprocessing.Process(target=self.send_message_to_server, args=(self.socket,)) send_message_thread.start() # Return true if connected queue has a value def is_connected(self): return not self.is_connected_queue.empty() # Put message on stop queues to end send / receive threads # Clear connected state queues def disconnect(self): print ("Disconnecting...") self.stop_receive_queue.put("") self.stop_send_queue.put("") self.clear_queue(self.pending_connection_queue) self.clear_queue(self.is_connected_queue) print ("Connection closed") # Send a message # If connected and send queue isn't full - add message to send queue # Raise exception if not connected def send_message(self, message): if self.is_connected(): if self.send_message_queue.full(): print ("Send message queue full...") return self.send_message_queue.put(message) else: raise NotConnectedException("Not connected to server...") # Send message to server # If send queue isn't empty, send the message length + message (expects binary data) to server # If exception while sending and the stop queue isn't empty - disconnect def send_message_to_server(self, socket): while self.stop_send_queue.empty(): while not self.send_message_queue.empty(): print ("Message found on queue...") try: message = self.send_message_queue.get() message_size = len(message) print (f"Message: {message_size}") socket.sendall(struct.pack("&gt;L", message_size) + message) except Exception as e: if not self.stop_send_queue.empty(): return print (f"\nException sending message:\n\n{e}") self.disconnect() # Get a message # If the receive queue isn't empty - return a message def get_message(self): if not self.receive_message_queue.empty(): return self.receive_message_queue.get() return None # Receive messages from socket # Read data from socket according to the pre-pended message length def receive_message(self, socket): data = b"" payload_size = struct.calcsize("&gt;L") print ("Listening for messages...") while self.stop_receive_queue.empty(): #Get message size try: while len(data) &lt; payload_size: data += socket.recv(4096) packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("&gt;L", packed_msg_size)[0] print ("Received message size:") print (msg_size) #Get message while len(data) &lt; msg_size: data += socket.recv(4096) message = data[:msg_size] data = data[msg_size:] print (message) if self.receive_message_queue.qsize() &gt;= self.MAX_QUEUE_SIZE or self.receive_message_queue.full(): continue self.receive_message_queue.put(message) except Exception as e: print (f"\nException while receiving messages: {e}\n\n") break print ("\nDisconnecting...\n\n") self.disconnect() # Connect to the server def connect_to_server(self, host, port, wait_time=1): try: client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect((host, port)) return client_socket except Exception: print (f"Couldn't connect to remote address, waiting {wait_time} seconds to retry") time.sleep(wait_time) return self.connect_to_server(host, port, wait_time * 1) # Clear messages from the supplied queue (should live somewhere else) def clear_queue(self, queue): while not queue.empty(): queue.get() </code></pre> <p>not_connected_exception.py</p> <pre><code>class NotConnectedException(Exception): def __init__(self, message): super().__init__(message) </code></pre> <p>And a small test server just to test receiving messages..</p> <p>test_server.py</p> <pre><code>import socket import sys import struct HOST = "127.0.0.1" PORT = 11000 def main(): s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) print('Socket created') s.bind((HOST,PORT)) print('Socket bind complete') while True: s.listen(10) try: print('Socket now listening') conn,addr=s.accept() data = b"" payload_size = struct.calcsize("&gt;L") print("payload_size: {}".format(payload_size)) while True: while len(data) &lt; payload_size: data += conn.recv(4096) packed_msg_size = data[:payload_size] data = data[payload_size:] msg_size = struct.unpack("&gt;L", packed_msg_size)[0] print("msg_size: {}".format(msg_size)) while len(data) &lt; msg_size: data += conn.recv(4096) frame_data = data[:msg_size] data = data[msg_size:] except Exception as e: print("Whoops...") print (e) if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T17:06:11.570", "Id": "411162", "Score": "0", "body": "\"The application can be found here - any advice or comments would be appreciated!\" add readme - it will be useful for both yourself in N months and for others. Also, publishing code without releasing it on one of open licences gives you all negatives of open source without any positives (see http://choosealicense.com/ )" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T10:30:20.393", "Id": "411266", "Score": "1", "body": "Thanks for the heads-up - threw in a license, will work on a README later." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T21:41:00.353", "Id": "411345", "Score": "0", "body": "I am not sure whatever it deserves its own answers, but there is standard method of documenting functions, a bit different from format you used - see https://www.python.org/dev/peps/pep-0257/ PEP 257 -- Docstring Conventions" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T22:07:44.703", "Id": "411354", "Score": "0", "body": "Ah yes - I just wrote it this way before posting here, not properly as per PEP" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-17T22:28:01.900", "Id": "211722", "Score": "1", "Tags": [ "python", "object-oriented", "multithreading", "design-patterns", "opencv" ], "Title": "Image capture client - multi-threading + sharing data between services" }
211722
<p>I have a circle-growth algorithm (line-growth with closed links) where new points are added between existing points at each iteration.</p> <p>The linkage information of each point is stored as a tuple in a list. That list is updated iteratively.</p> <p><a href="https://i.stack.imgur.com/ap1Ic.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ap1Ic.png" alt="enter image description here"></a></p> <p><strong>QUESTIONS:</strong></p> <ul> <li><p>What would be the most efficient way to return <strong>the spatial order</strong> of these points as a list ?</p></li> <li><p>Do I need to compute the whole order at each iteration or is there a way to cumulatively insert the new points in a orderly manner into that list ?</p></li> </ul> <p><a href="https://i.stack.imgur.com/qqhO3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qqhO3.png" alt="enter image description here"></a></p> <p>All I could come up with is the following:</p> <pre><code>tuples = [(1, 4), (2, 5), (3, 6), (1, 6), (0, 7), (3, 7), (0, 8), (2, 8), (5, 9), (4, 9)] starting_tuple = [e for e in tuples if e[0] == 0][0] ## note: 'starting_tuple' could be either (0, 7) or (0, 8), starting direction doesn't matter order = [starting_tuple[0], starting_tuple[1]] ## order will always start from point 0 idx = tuples.index(starting_tuple) ## index of the starting tuple def findNext(): global idx for i, e in enumerate(tuples): if order[-1] in e and i != idx: ind = e.index(order[-1]) c = 0 if ind == 1 else 1 order.append(e[c]) idx = tuples.index(e) for i in range(len(tuples)/2): findNext() print order </code></pre> <p>It is working but it is neither elegant (non pythonic) nor efficient. It seems to me that a <strong>recursive algorithm</strong> may be more suitable but unfortunately I don't know how to implement such solution.</p> <p>Also, please note that I'm using Python 2 and can only have access to full python packages (no numpy). </p> <p>This question has also been <a href="https://stackoverflow.com/questions/54245191/python-most-efficient-way-to-find-spatial-order-from-a-list-of-tuples">posted</a> on SO.</p>
[]
[ { "body": "<p>No need for recursion. You may want to first convert the tuples to a <code>dict</code> to make it more readable. Then iterate over the <code>dict</code> to construct an ordered list.</p>\n\n<p>In terms of efficiency (or time / space complexity), your code is <span class=\"math-container\">\\$O(n^3)\\$</span> in time and <span class=\"math-container\">\\$O(1)\\$</span> in auxiliary space. Note that <code>idx = tuples.index(e)</code> is not necessary at all, since <code>tuples.index(e) == i</code>. Making use of this would allow your code to be <span class=\"math-container\">\\$O(n^2)\\$</span> in time. The most time-efficient solution is <span class=\"math-container\">\\$O(n)\\$</span>, which is also the time complexity of the proposed solution involving a <code>dict</code>. However, the auxiliary space complexity of that solution is <span class=\"math-container\">\\$O(n)\\$</span> -- inferior to your original approach.</p>\n\n<p>If you want to update the order after obtaining a new <code>tuples</code> list, you can keep the <code>dict</code> and iterate over the new <code>tuples</code>, comparing with values in the <code>dict</code> to see if there is any change. However, the efficiency of this approach would probably be in most cases worse than constructing a new <code>dict</code> from scratch.</p>\n\n<hr>\n\n<pre><code>from collections import defaultdict\n\ndef tuples_to_neighbors_dict(tuples):\n \"\"\"\n Covert `tuples` to a dict mapping each point to a list of its neighbors.\n \"\"\"\n neighbors = defaultdict(list)\n\n for (a,b) in tuples:\n neighbors[a].append(b)\n neighbors[b].append(a)\n\n return neighbors\n\ndef tuples_to_order(tuples, start=0):\n \"\"\"\n Covert `tuples` to a list of points.\n \"\"\"\n neighbors = tuples_to_neighbors_dict(tuples)\n order = []\n\n prev = None\n current = start\n\n while current != start or prev is None:\n # add the current value to the list\n order.append(current)\n\n # move to the next -- pick the neighbor which we haven't visited yet\n neigh = neighbors[current]\n new = neigh[1] if neigh[0] == prev else neigh[0]\n prev = current\n current = new\n\n return order\n</code></pre>\n\n<hr>\n\n<p><strong>EDIT</strong> &nbsp; I just now looked at the SO question and noticed that one answer is almost identical to mine </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T00:07:55.010", "Id": "211729", "ParentId": "211723", "Score": "1" } } ]
{ "AcceptedAnswerId": "211729", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-17T22:42:13.727", "Id": "211723", "Score": "2", "Tags": [ "python", "python-2.x", "sorting", "recursion" ], "Title": "Most efficient way to find spatial order from a list of tuples (Python)" }
211723
<p>I am learning C++ and I made a simple stack class using a (reversed) linked-list to test my knowledge.</p> <p>Are there any problems with the following code, or any suggestions to improve it?</p> <p>I want to make sure I am getting things correct in the beginning so I don't make the same mistakes again in the future - especially memory management and avoiding leaks.</p> <p>One thing to point out is that I included the implementation in the header file... I wouldn't normally do this but apparently there are problems when implementing methods with templates in .cpp files.</p> <pre><code>#ifndef TEST_STACK_H #define TEST_STACK_H #include &lt;stdexcept&gt; template &lt;class T&gt; class stack { struct node { T data; node* previous; node(T data, node *previous) : data(data), previous(previous) {} }; node* head = nullptr; int size = 0; int max = -1; // -1 so isFull() == false when default constructor used public: stack() = default; stack(int max) { if (max &lt;= 0) throw std::out_of_range("stack size must be &gt; 0"); this-&gt;max = max; } ~stack() { node* n = head; while (n != nullptr) { node* previous = n-&gt;previous; delete n; n = previous; } } void push(const T &amp;object) { if (isFull()) throw std::overflow_error("cannot push to a full stack"); head = new node(object, head); ++size; } T pop() { if (head == nullptr) throw std::underflow_error("cannot get item from empty stack"); T item = head-&gt;data; head = head-&gt;previous; --size; delete head; return item; } T peek() { if (head == nullptr) throw std::underflow_error("cannot get item from empty stack"); return head-&gt;data; } int getSize() { return size; } bool isFull() { return size == max; } bool isEmpty() { return head == nullptr; } }; #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T21:57:22.323", "Id": "409555", "Score": "0", "body": "Welcome to Code Review! I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information" } ]
[ { "body": "<h2>Bug</h2>\n\n<p>Your main issue is memory management.</p>\n\n<p>You did not implement the \"Rule of Three\" (you can google it).</p>\n\n<p>The problem is that if you do not define the copy constructor or the assignment operator the compiler will generate these methods for you automatically. Under most conditions these generated methods work correctly. <strong>BUT</strong> when your class contains an \"Owned\" pointer they do not work.</p>\n\n<p>Note: An \"Owned\" pointer is a pointer you are responsible for deleting.</p>\n\n<pre><code>{\n stack&lt;int&gt; x;\n x.push(12);\n\n\n stack&lt;int&gt; y(x); // Copy constructor used.\n // The default implementation does a shallow copy\n // of each member from x into y.\n // This means that x and y point at the same list.\n\n}\n// Here your destructor has destroyed the same list twice.\n// This is a bug.\n</code></pre>\n\n<p>To fix this you need to define the copy constructor and assignment operator. But there is a nice pattern that allows you to define the assignment operator in terms of the copy constructor. Look up the \"Copy And Swap Idiom\".</p>\n\n<p>You need to add the following to your class:</p>\n\n<pre><code>class stack\n{\n // Stuff\n public:\n stack(stack const&amp; rhs)\n : head(copyList(rhs.head))\n , size(rhs.size)\n , max(rhs.size)\n {}\n stack&amp; operator=(stack const&amp; rhs)\n {\n stack tmp(rhs); // make a copy using copy constructor.\n swap(tmp); // swap the tmp and this object\n return *this;\n }\n void swap(stack&amp; other) noexcept\n {\n using std::swap;\n swap(head, other.head);\n swap(size, other.size);\n swap(max, other.max);\n }\n\n private:\n node* copyList(node* l)\n {\n if (l == nullptr) {\n return null;\n }\n return new node{l-&gt;data, copyList(l-&gt;previous)};\n }\n // STUFF\n};\n</code></pre>\n\n<p>Your <code>pop()</code> has a bug. You delete the <strong>NEW</strong> head item before returning but leak the original head item.</p>\n\n<pre><code>T pop() {\n if (head == nullptr) throw std::underflow_error(\"cannot get item from empty stack\");\n\n T item = head-&gt;data;\n head = head-&gt;previous; // You just leaked the old head.\n // You need to keep a pointer to the old head\n\n --size;\n\n delete head; // So you can delete the old head here.\n return item;\n}\n</code></pre>\n\n<h2>Other Stuff</h2>\n\n<h3>Design of <code>pop()</code></h3>\n\n<p>You make your <code>pop()</code> method return the top value and remove it from the stack. This is fine if your <code>T</code> type is simple. But if <code>T</code> is a complex type there is no way to do this safely (and maintain \"Strong Exception Guarantee\"). So most implementations of stack split this into two separate functions. A <code>top()</code> that returns the top value and a <code>pop()</code> that simply removes the top value.</p>\n\n<p>So I would rewrite this:</p>\n\n<pre><code>void pop() {\n if (head == nullptr) throw std::underflow_error(\"cannot get item from empty stack\");\n\n node* old = head;\n head = head-&gt;previous;\n\n --size;\n delete old;\n}\nT const&amp; top() {\n if (head == nullptr) throw std::underflow_error(\"cannot get item from empty stack\");\n\n return head-&gt;data;\n}\n</code></pre>\n\n<h3>Return by reference</h3>\n\n<p>Your <code>pop()</code> and <code>peek()</code> return the result by value. This is OK for simple types of <code>T</code> (like integer). But if <code>T</code> is a complex object you are making a copy of this complex object. Instead you should return a reference to the object. If the user is doing somehting simple they can do the action without copying if they want to keep a copy they can make that decision and save the value in a local variable.</p>\n\n<pre><code>T peek()\n\n// Change to:\n\nT const&amp; peek(); // Don't really need this if you have top()\n // Or you could use peek instead of top()\n</code></pre>\n\n<p>But notice the <code>const&amp;</code> as the return type. You are returning a reference to the object so no copy is made. If you need a local copy then you can save it like this:</p>\n\n<pre><code>int val = x.top();\nx.pop();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T09:20:36.193", "Id": "409462", "Score": "0", "body": "Thanks for the guidance. One thing I was confused about was where you commented 'You just leaked the old head.' head->previous is a pointer to the next head (the name for previous comes from the order of the item placement in the stack rather than the order of retrieval in the linked list). So by assigning a pointer and then deleting the old head (which the new head has no relation to) should have no problem right? Another thing I was unsure of is how to get around returning T by value in pop(). I understand how to do it in peek, and I am not sure why I forgot to return by reference but..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T09:21:21.143", "Id": "409463", "Score": "0", "body": "In pop, how can we return a reference to something we are about to delete? This is why I returned by value in this situation to avoid returning back a dangling pointer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T17:04:44.153", "Id": "409524", "Score": "0", "body": "@Samueljh1 When you go `head = head->previous;` what happens to the old value of `head`. You no longer have a reference to the old value and thus it is leaked." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T17:06:03.470", "Id": "409525", "Score": "0", "body": "@Samueljh1 When you do `delete head;` in `pop()` you are calling delete on the current head of the list. Which makes no sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T17:08:32.827", "Id": "409526", "Score": "0", "body": "In your version of `pop()` you have to return by value. But I would change that so that `pop()` does not return anything. It just removes the top element from the stack. You can not implement `pop()` that returns a value and provide the \"Strong Exception Guarantee\". Separate the functionality into two functions. `pop()` simply removes the top value and `peek()` returns a reference to the top value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T21:53:35.577", "Id": "409554", "Score": "0", "body": "Ok thank you for the help. I have updated the question with the new code, and I also moved swap() to private, I couldn't see why that would be used externally. Please let me know what you think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T01:31:13.167", "Id": "409561", "Score": "0", "body": "@Samueljh1 We don't allow the editing of questions after an answer has been posted. That would confuse future readers. You need to ask a new question to get another review. Just add a link to this question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T01:32:16.850", "Id": "409562", "Score": "0", "body": "@Samueljh1 I would make swap public. Then you can implement the standard swap function simply by calling the swap member: `void swap(stack& lhs, stack& rhs){lhs.swap(rhs);}` The swap function is used all over the place in the standard libraries especially when move semantics kick in. PS. You should add move semantics to your next version." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T01:42:12.123", "Id": "211734", "ParentId": "211726", "Score": "4" } }, { "body": "<h1>Updated Code</h1>\n\n<p>Changes (with the help of Martin):</p>\n\n<ul>\n<li>Added copy constructor and assignment operator overload</li>\n<li>Changed return type of peek() to const T&amp; rather than T (this prevents unnecessary copying of data)</li>\n<li>Changed return type of pop() to void; it now only removes the top item rather than returning it on top. The user can call peek() and then call pop() to retrieve and then delete the item. This means we don't have to return T by value, and also maintains the \"Strong Exception Guarantee\".</li>\n<li>Fixed a bug in pop() where the new head is deleted rather than the old one</li>\n</ul>\n\n<pre><code>#ifndef TEST_STACK_H\n#define TEST_STACK_H\n\n#include &lt;stdexcept&gt;\n\ntemplate &lt;class T&gt;\nclass stack {\n\n struct node {\n T data;\n node* previous;\n\n node(T data, node *previous) : data(data), previous(previous) {}\n };\n\n node* head = nullptr;\n\n int size = 0;\n int max = -1; // -1 so isFull() == false when default constructor used\n\npublic:\n stack() = default;\n\n stack(int max) {\n if (max &lt;= 0) throw std::out_of_range(\"stack size must be &gt; 0\");\n this-&gt;max = max;\n }\n\n // copy constructor\n\n stack(stack const&amp; rhs) :\n head(copyList(rhs.head)),\n size(rhs.size),\n max(rhs.size) {}\n\n // assignment operator\n\n stack&amp; operator = (stack const&amp; rhs)\n {\n stack tmp(rhs);\n swap(tmp);\n\n return *this;\n }\n\n ~stack() {\n node* n = head;\n\n while (n != nullptr) {\n node* previous = n-&gt;previous;\n delete n;\n\n n = previous;\n }\n }\n\n void push(const T &amp;object) {\n if (isFull()) throw std::overflow_error(\"cannot push to a full stack\");\n\n head = new node(object, head);\n ++size;\n }\n\n const void pop() {\n if (head == nullptr) throw std::underflow_error(\"cannot get item from empty stack\");\n\n node* old = head;\n head = head-&gt;previous;\n\n --size;\n delete old;\n }\n\n T peek() {\n if (head == nullptr) throw std::underflow_error(\"cannot get item from empty stack\");\n return head-&gt;data;\n }\n\n int getSize() {\n return size;\n }\n\n bool isFull() {\n return size == max;\n }\n\n bool isEmpty() {\n return head == nullptr;\n }\n\nprivate:\n void swap(stack&amp; other) noexcept\n {\n using std::swap;\n swap(head, other.head);\n swap(size, other.size);\n swap(max, other.max);\n }\n\n node* copyList(node* l)\n {\n if (l == nullptr) {\n return nullptr;\n }\n return new node{l-&gt;data, copyList(l-&gt;previous)};\n }\n};\n\n#endif\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T01:34:02.630", "Id": "409563", "Score": "1", "body": "Make this a new question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T14:52:46.873", "Id": "409585", "Score": "0", "body": "@MartinYork done https://codereview.stackexchange.com/questions/211811/c-updated-stack-code-any-further-improvements" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T22:03:51.973", "Id": "211790", "ParentId": "211726", "Score": "0" } } ]
{ "AcceptedAnswerId": "211734", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-17T23:32:49.610", "Id": "211726", "Score": "5", "Tags": [ "c++", "beginner", "linked-list", "stack" ], "Title": "Stack implementation in C++ using linked list" }
211726
<p>I'm looking for feedback on how this can be improved. Basically what I'm trying to do is check if the cache has the object, else check from the database.</p> <p>I have a list of ids, then I separate them based on whether they already exist in the cache or not, based on the date as well. One list fetches from the cache, the other from the db. Then return the list. That way I don't have to make multiple calls to cache/db.</p> <p>The alternative is to implement a compound-key, but I would rather not go that route.</p> <p><a href="https://github.com/mel3kings/taxi-cab-api/blob/master/src/main/java/com/simple/controller/CabController.java" rel="nofollow noreferrer">https://github.com/mel3kings/taxi-cab-api/blob/master/src/main/java/com/simple/controller/CabController.java</a></p> <pre><code> private List&lt;Cab&gt; getFromCacheOrDb(CabTripsRequest request) { Map&lt;Boolean, List&lt;String&gt;&gt; cachedCabs = request.getMedallions().stream().collect( partitioningBy(key -&gt; { if (!cache.peek(key)) { return false; } return cache.get(key).stream().anyMatch(a -&gt; a.getPickupDateTime().equals(request.getDate())); })); List&lt;Cab&gt; response = cachedCabs.get(true).stream().map(k -&gt; cache.get(k)).flatMap(List::stream) .filter(cab -&gt; cab.getPickupDateTime().equals(request.getDate())).collect(toList()); if (cachedCabs.get(false).size() &gt; 0) { List&lt;Cab&gt; database = storage.fetch(cachedCabs.get(false), request.getDate()); response.addAll(database); cache.save(database); } log.info("response from cache/db size:" + response.size()); return response; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T09:08:24.810", "Id": "409460", "Score": "0", "body": "In your partitioning you can simplify a bit the code with : `return cache.peek(key) && cache.get(key).stream().anyMatch(...)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T09:14:26.963", "Id": "409461", "Score": "0", "body": "You can also change your `storage.fetch` to deal with empty list so that you can just do `List<Dab> database = storage.fetch(cachedCabs.get(false)) // may be empty` and remove the `if (cachedCabs.get(false).size()>0 )`" } ]
[ { "body": "<p>One approach you could pick here is to design your data stores in Storage interfaces in an increasing fashion.</p>\n\n<p><a href=\"https://i.stack.imgur.com/gtCyB.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/gtCyB.png\" alt=\"Storage classes ordered by access time\"></a></p>\n\n<pre><code>private List&lt;Cab&gt; getCabs(Key key) {\n List&lt;Cab&gt; cabsByKey = this.cache.stream().filter(c -&gt; c.equals(key)).anyMatch();\n if (cabsByKey.isEmpty()) {\n cabsByKey = this.higherStorage.getByKey(key);\n }\n\n return cabsByKey;\n}\n</code></pre>\n\n<p>The idea is to store its higher level cache instance for each data storage and to propagate request up whenever nothing has been found.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T23:58:46.943", "Id": "212107", "ParentId": "211728", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-17T23:56:49.090", "Id": "211728", "Score": "2", "Tags": [ "java", "object-oriented", "design-patterns", "cache" ], "Title": "Simple local cache that checks by date else get from db" }
211728
<p>Here is a variation on <a href="https://codereview.stackexchange.com/tags/fizzbuzz/info">a theme: fizzbuzz</a>. After providing <a href="https://codereview.stackexchange.com/a/211122/120114">this answer</a> recently, I decided to practice some VueJS skills with outputting the values and conditionally applying styles based on the value. The specific styles are as follows:</p> <ul> <li>red border for <code>Fizz</code></li> <li>blue border for <code>Buzz</code></li> <li>purple border for <code>FizzBuzz</code></li> </ul> <p>And then I decided to allow the user to change the height of the container, in case he/she wanted a smaller viewport.</p> <p>What, if anything, would you change?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const getIndex = (number, index) =&gt; index + 1; const app = new Vue({ el: "#app", data: { numbers: new Array(100).fill(1).map(getIndex), height: 3000 }, filters: { getOutput: function(number) { if (number % 3 === 0 &amp;&amp; number % 5 === 0) return 'FizzBuzz'; if (number % 3 === 0) return 'Fizz'; if (number % 5 === 0) return 'Buzz'; return number; } }, methods: { getClass: function(number) { const output = this.$options.filters.getOutput(number); if (isNaN(parseInt(output, 10))) { return output; } return ''; } } });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>body { padding: 4px; font-family: serif; } h1 { font: 400 20px cursive; } input[type="range"] { width: 100%; } #listContainer { overflow-y: hidden; } li { background: #fff; color: #000000; border-radius: 4px; border: 2px solid #6a737c; padding: 3px; } li.FizzBuzz { border-color: #f800ff; } li.Fizz { border-color: #f80000; } li.Buzz { border-color: #0000ff; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"&gt;&lt;/script&gt; &lt;div id="app"&gt; &lt;h1&gt; FizzBuzz with dynamic height container &lt;/h1&gt; &lt;div&gt; Height: {{ height }} &lt;/div&gt; &lt;input type="range" min="200" max="3000" v-model="height" /&gt; &lt;div id="listContainer" v-bind:style="{ height: height + 'px'}"&gt; &lt;ul&gt; &lt;li v-for="number in numbers" :class="getClass(number)"&gt; {{ number | getOutput }} &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:45:53.713", "Id": "410410", "Score": "0", "body": "This question is [being discussed on meta](https://codereview.meta.stackexchange.com/q/9068/120114)." } ]
[ { "body": "<p>Have not tried Vue.js. </p>\n\n<p><code>number</code> within <code>getIndex</code> is not used, the first parameter can be replaced with an underscore </p>\n\n<pre><code>const getIndex = (_, index) =&gt; index + 1;\n</code></pre>\n\n<p><p></p>\n\n<pre><code>Array.from({length: 100}, getIndex)\n</code></pre>\n\n<p>can be substituted for </p>\n\n<pre><code>new Array(100).fill(1).map(getIndex)\n</code></pre>\n\n<p>to reduce <code>Array</code> method calls. </p>\n\n<p><code>getOutput()</code> function body can be reduced to two lines with one <code>return</code> statement by using destructuring assignment, AND <code>&amp;&amp;</code> operator for variables <code>Fizz</code> and <code>Buzz</code>, which <code>FizzBuzz</code> is derived from, and OR <code>||</code> operator</p>\n\n<pre><code>function getOutput(number) {\n const [f, b, fb = f &amp;&amp; b &amp;&amp; 'FizzBuzz'] = [number % 3 &amp;&amp; 'Fizz', number % 5 &amp;&amp; 'Buzz'];\n return fb || f || b || number;\n}\n</code></pre>\n\n<p><code>FizzBuzz</code>, <code>Fizz</code> and <code>Buzz</code> variable names can be substituted for single character variable names <code>fb</code>, <code>f</code> and <code>b</code> variable names within <code>getOutput</code> function body if necessary.</p>\n\n<p>A single <code>return</code> statement can be substituted for two <code>return</code> statements within <code>getClass</code> function by using conditional operator <code>condition ? expression0 : expression1</code>.</p>\n\n<pre><code>function getClass(number) {\n const output = this.$options.filters.getOutput(number);\n return isNaN(parseInt(output, 10)) ? output : '';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T05:43:30.193", "Id": "211741", "ParentId": "211731", "Score": "1" } }, { "body": "<p><strong>Found a little inconsistency in your Vue template</strong></p>\n\n<p>Using <code>v-bind:</code> syntax here,</p>\n\n<pre><code>&lt;div id=\"listContainer\" v-bind:style=\"{ height: height + 'px'}\"&gt;\n</code></pre>\n\n<p>... but using <code>:</code> shorthand here:</p>\n\n<pre><code>&lt;li v-for=\"number in numbers\" :class=\"getClass(number)\"&gt;\n</code></pre>\n\n<p><strong>Useless variable <code>app</code></strong></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>const app = new Vue({ /* ... */ });\n</code></pre>\n\n<p>Do I need to say more?</p>\n\n<p><strong>EDIT:</strong> <em>YES.</em><br>\nFrom <a href=\"https://eslint.org/docs/rules/no-unused-vars\" rel=\"nofollow noreferrer\">ESLint</a>: \"<em>Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers.</em>\" </p>\n\n<p><strong>Object method notation shorthand</strong></p>\n\n<p>Instead of using:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>getOutput: function(number) { /* ... */ }\n// ...\ngetClass: function(number) { /* ... */ }\n</code></pre>\n\n<p>You could use:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>getOutput(number) { /* ... */ }\n// ...\ngetClass(number) { /* ... */ }\n</code></pre>\n\n<p><strong>Too specific CSS selector</strong></p>\n\n<p>You're specifying these selectors,</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>li.FizzBuzz { /* ... */ }\nli.Fizz { /* ... */ }\nli.Buzz { /* ... */ }\n</code></pre>\n\n<p>but there aren't any elements that would have these classes (<code>FizzBuzz</code>, <code>Fizz</code> and <code>Buzz</code>) other than <code>li</code>'s. This means you could simplify it to:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>.FizzBuzz { /* ... */ }\n.Fizz { /* ... */ }\n.Buzz { /* ... */ }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T16:17:36.293", "Id": "412786", "Score": "0", "body": "I know that `app` isn't used after it is assigned, but what are the main motivations for not assigning it to a constant? less memory allocation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-13T16:52:54.907", "Id": "412798", "Score": "1", "body": "@Sᴀᴍ Onᴇᴌᴀ From [ESLint](https://eslint.org/docs/rules/no-unused-vars): \"_Variables that are declared and not used anywhere in the code are most likely an error due to incomplete refactoring. Such variables take up space in the code and can lead to confusion by readers._\"" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T19:55:25.730", "Id": "211785", "ParentId": "211731", "Score": "2" } }, { "body": "<p>As the fizz has been done to death I will review this in terms of a page that displays a list of items, could be anything, dates, measurements, or whatnot.</p>\n<hr />\n<h2>Problems and bugs</h2>\n<h3>There is a sizing problem.</h3>\n<p>Not all the values indicated by the height slider can be scrolled to. This is because you set the container size incorrectly <code>&lt;div id=&quot;listContainer&quot; v-bind:style=&quot;{ height: height + 'px'}&quot;&gt;</code> it should be <code>height: height * listItemHeight + 'px'</code> with <code>listItemHeight</code> matching the height of a list item.</p>\n<p>Better yet don't set the height let the layout engine do that. You use colon property <code>:class=&quot;getClass(number)&quot;</code> You can add another class named <code>Empty</code> and return that if the function is called with a number greater than height.</p>\n<p>The containing div will size itself to fit the content.</p>\n<h3>You only display 100 items</h3>\n<p>Changing the height slider (min value is 200) I imagine changes the number of items in the list. However only 100 items are displayed no matter what the <code>height</code> value is.</p>\n<h3>The initial setting is incorrect</h3>\n<p>When the page loads you set the slider height to 3000 but the array you set to 100. Maybe a constant in the JS to set up the <code>height</code>, and <code>numbers</code> array would help. (See first example)</p>\n<h3>Use a label</h3>\n<p>Use a label to associate the height slider with the height value display rather than an unassociated div. You can just nest the input within the label to make the association implicit.</p>\n<hr />\n<h2>JavaScript style</h2>\n<ul>\n<li>Delimit single line statement blocks with curlies <code>if (foo) {...}</code></li>\n<li>isNaN does not require a number, the explicit convertion is supluflorouse. <code>isNaN(parseInt(output, 10))</code> is the same a <code>isNaN(output)</code> Also use Number to convert base 10 numbers if you know you are not rounding <code>Number(output)</code> is better than <code>parseInt(output, 10)</code></li>\n<li>Be consistency in style. In the function <code>getOutput</code> you use inline undelimited single\nline statements <code>if (number % 5) return 'Buzz';</code> yet in <code>getClass</code> you use 3 line delimited single line statements <code>if (isNaN(output)) {\\n return output;\\n }</code> with <code>\\n</code> for new lines.</li>\n<li>Less is best. Use the short form of code where you can. Eg last 4 lines of <code>getClass</code> can be on ternary. (see example)</li>\n</ul>\n<hr />\n<h2>Use dynamic views for large data sets.</h2>\n<p>I think that the approach is a little over the top. Having very long pages has a cost in resources. Considering that you can never see more than a screen full at a time it would be more effective to generate the list as a view in place as the user scrolls. That way you only need to create as many elements as can be seen at once. You could use the height slider to replace the scroll and us it to reference the top view item.</p>\n<p>With a little more effort such a list should be zoomable as well, only ever displaying one screenfull. (Really scroll bars are old, ugly, and awkward. Good design means weighted intuitive gesture control, even with a mouse)</p>\n<hr />\n<h2>Example 1</h2>\n<p>Addressing some of the problems and bugs. Uses a complete list (set to 1000 for practicality)</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" 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 getIndex = (number, index) =&gt; index + 1;\nconst MIN_HEIGHT = 100;\nconst MAX_HEIGHT = 1000;\n\nconst app = new Vue({\n el: \"#app\",\n data: {\n numbers: new Array(MAX_HEIGHT).fill(1).map(getIndex),\n height: MAX_HEIGHT,\n minHeight : MIN_HEIGHT,\n maxHeight : MAX_HEIGHT,\n },\n filters: {\n getOutput: function(number) {\n if (number % 3 === 0 &amp;&amp; number % 5 === 0) { return 'FizzBuzz' }\n if (number % 3 === 0) { return 'Fizz' }\n if (number % 5 === 0) { return 'Buzz' }\n return number;\n }\n },\n methods: {\n getClass: function(number) {\n if (number &gt; this.height) { return \"Empty\" }\n const output = this.$options.filters.getOutput(number);\n return isNaN(output) ? output : \"\";\n }\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n padding: 4px;\n font-family: serif;\n}\nh1 {\n font: 400 20px cursive;\n}\ninput[type=\"range\"] {\n width: 100%;\n}\n\n\nli {\n background: #fff;\n color: #000000;\n border-radius: 4px;\n border: 2px solid #6a737c;\n padding: 3px;\n}\n\nli.FizzBuzz {\n border-color: #f800ff; \n}\n\nli.Fizz {\n border-color: #f80000;\n}\n\nli.Buzz {\n border-color: #0000ff;\n}\nli.Empty {\n display: none;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"&gt;&lt;/script&gt;\n&lt;div id=\"app\"&gt;\n &lt;h1&gt;\n FizzBuzz with dynamic height container\n &lt;/h1&gt;\n &lt;label&gt;\n Height: {{ height }}\n &lt;input type=\"range\" :min=\"minHeight\" :max=\"maxHeight\" v-model=\"height\" /&gt;\n &lt;/label&gt;\n &lt;div id=\"listContainer\" &gt;\n &lt;ul&gt;\n &lt;li v-for=\"number in numbers\" :class=\"getClass(number)\"&gt;\n {{ number | getOutput }}\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt; \n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>Example 2</h2>\n<p>This does not create the long list, rather it uses a view controlled by the height slider replacing the scroll bar. This lets you display a much larger range of values without having to tax the device with a huge lists of elements.</p>\n<p>I have removed the title (not needed we know what the page does) and height label as that value is now the first fizzBuzz item. This gives needed realestate back to the app.</p>\n<p>Increased the view range to 10000. Also using HEX CSS alpha format colors thus will look a little ugly for some older browsers.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" 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 getIndex = (number, index) =&gt; index;\nconst MIN_HEIGHT = 1;\nconst MAX_HEIGHT = 10000;\nconst DATA_VIEW_SIZE = 7;\n\nconst app = new Vue({\n el: \"#app\",\n data: {\n numbers: new Array(DATA_VIEW_SIZE).fill(1).map(getIndex),\n height: MIN_HEIGHT,\n minHeight : MIN_HEIGHT,\n maxHeight : MAX_HEIGHT,\n },\n filters: {\n getOutput: function(number) {\n if (number % 3 === 0 &amp;&amp; number % 5 === 0) { return 'FizzBuzz' }\n if (number % 3 === 0) { return 'Fizz' }\n if (number % 5 === 0) { return 'Buzz' }\n return number;\n }\n },\n methods: {\n getClass: function(number) {\n const output = this.$options.filters.getOutput(number + Number(this.height));\n return isNaN(output) ? output : \"\";\n },\n getItem: function(number) {\n return this.$options.filters.getOutput(Number(number) + Number(this.height));\n },\n }\n});</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>body {\n padding: 0px;\n font-family: serif;\n}\n\ninput[type=\"range\"] {\n width: 100%;\n margin-top: -8px;\n}\nul {\n margin-top: -2px;\n}\nli {\n background: #0003;\n color: #000000;\n border-radius: 4px;\n border: 1px solid #6a737c;\n padding: 1px;\n}\n\nli.FizzBuzz {\n border-color: #f800ff; \n background: #f800ff33;\n}\n\nli.Fizz {\n border-color: #f80000;\n background: #f8000033;\n}\n\nli.Buzz {\n border-color: #0000ff;\n background: #00f3;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js\"&gt;&lt;/script&gt;\n&lt;div id=\"app\"&gt;\n &lt;input type=\"range\" :min=\"minHeight\" :max=\"maxHeight\" v-model=\"height\" /&gt;\n\n &lt;ul&gt;\n &lt;li v-for=\"number in numbers\" :class=\"getClass(number)\"&gt;\n {{ getItem(number) }}\n &lt;/li&gt;\n &lt;/ul&gt;\n\n&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": "2019-01-18T20:43:57.023", "Id": "211789", "ParentId": "211731", "Score": "2" } } ]
{ "AcceptedAnswerId": "211785", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T00:44:56.650", "Id": "211731", "Score": "3", "Tags": [ "javascript", "ecmascript-6", "html5", "fizzbuzz", "vue.js" ], "Title": "fizzbu| - Fizzbuzz with dynamic height" }
211731
<p>Basically what I'm trying to achieve here is I need to fetch a set of images based on the selected folder. Is this a correct way to do it?</p> <p>I'm using ZF 2.5, and have the following function in my RESTful <code>Images</code> controller:</p> <pre><code>public function getList() { $folder_id = $this-&gt;params()-&gt;fromQuery('folder_id', 0); $images = $this-&gt;ImagesTable-&gt;getImages($folder_id); // Code for returning response } </code></pre> <p>This is what my table function looks like:</p> <pre><code>public function getImages($folder_id) { $select = $this-&gt;tableGateway-&gt;getSql()-&gt;select(); if(!empty($folder_id)) { $select-&gt;where(array('folder_id' =&gt; $folder_id)); } $resultSet = $this-&gt;tableGateway-&gt;selectWith($select); return $resultSet-&gt;count() &gt; 0 ? $resultSet : null; } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T01:40:05.440", "Id": "211733", "Score": "1", "Tags": [ "php", "rest", "zend-framework" ], "Title": "Fetching specific records in a RESTful application" }
211733
<p>I have this code that reads a file and after processing a few lines writes the output to a second file:</p> <pre><code>num_reads = 7 with open('data.txt') as read_file: with open('new_data.txt', 'w') as write_file: while (True): lines = [] try: # expect errors if the number of lines in the file are not a multiplication of num_reads for i in range(num_reads): lines.append(next(read_file)) # when the file finishes an exception occurs here #do sutff with the lines (exactly num_reads number of lines) processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines))) write_file.write(processed + '\n') except StopIteration: # here we process the (possibly) insufficent last lines #do stuff with the lines (less that num_reads) processed = " ".join(list(map(lambda x: x.replace("\n", ''), lines))) write_file.write(processed + '\n') break </code></pre> <p>Here is the input file (<code>data.txt</code>):</p> <pre><code>line1 line2 line3 line4 line5 line7 line8 line9 </code></pre> <p>And this is the output file that has the desired state:</p> <pre><code>line1 line2 line3 line4 line5 line7 line8 line9 </code></pre> <p>This works correctly but as I wish to do the same processing and writing procedure in both cases (when the number of elements is 7 and when the file finishes and the exception is raised) I think the above code violates DRY principle even if I define a new function and call it once in <code>try</code> block and once in <code>except</code> before <code>break</code>. Any other ordering that I could come up with was either causing an infinite loop or losing the final lines. I appreciate any comments on handling this issue, as it is not limited to this case and I had faced it in other cases as well.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T05:23:57.227", "Id": "409437", "Score": "0", "body": "@200_success done! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T07:49:50.397", "Id": "409444", "Score": "1", "body": "(Welcom to Code Review!)" } ]
[ { "body": "<p>Disclaimer: This question belongs to Stack Overflow, and I voted to migrate it. Therefore, the answer is not a review.</p>\n\n<p>Keep in mind that principles are there to guide you. They should be treated like guard rails, rather than roadblocks.</p>\n\n<p>I would argue that</p>\n\n<pre><code> while (....) {\n foo(7);\n }\n foo(3);\n</code></pre>\n\n<p>does <em>not</em> violate DRY. Your situation is pretty much the same.</p>\n\n<p>That said, your idea of defining function is valid. You just factoring out the wrong code. Factor out reading. Consider</p>\n\n<pre><code> def read_n_lines(infile, n):\n lines = []\n try:\n for _ in range(n):\n lines.append(next(infile))\n except StopIteration:\n pass\n return lines\n</code></pre>\n\n<p>and use it as</p>\n\n<pre><code> while True:\n lines = read_n_lines(infile, 7)\n if len(lines) == 0:\n break\n process_lines(lines)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T06:05:22.887", "Id": "409438", "Score": "0", "body": "Thank you very much. Beautiful idea. I appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T06:00:24.110", "Id": "211743", "ParentId": "211737", "Score": "3" } }, { "body": "<p>You should avoid writing code with exception-handling altogether. Usually, when you want to write a fancy loop in Python, the <code>itertools</code> module is your friend. In this case, I would take advantage of <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"noreferrer\"><code>itertools.groupby()</code></a> to form groups of lines, assisted by <a href=\"https://docs.python.org/3/library/itertools.html#itertools.count\" rel=\"noreferrer\"><code>itertools.count()</code></a> to provide the line numbers.</p>\n\n<pre><code>import itertools\n\ndef chunks(iterable, n):\n i = itertools.count()\n for _, group in itertools.groupby(iterable, lambda _: next(i) // n):\n yield group\n\nwith open('data.txt') as read_f, open('new_data.txt', 'w') as write_f:\n for group in chunks(read_f, 7):\n print(' '.join(line.rstrip() for line in group), file=write_f)\n</code></pre>\n\n<p>A few other minor changes:</p>\n\n<ul>\n<li>You only need one <code>with</code> block to open both files.</li>\n<li><code>line.rstrip()</code> is more convenient than <code>lambda x: x.replace(\"\\n\", '')</code></li>\n<li><code>print(…, file=write_file)</code> is slightly more elegant than <code>write_file.write(… + '\\n')</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T08:10:37.733", "Id": "409447", "Score": "2", "body": "Isn't the `grouper` recipe more appropriate to make fixed-length chunks? Or did you purposefully avoid it to avoid dealing with the fill values at the end of the iteration?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T08:19:50.707", "Id": "409448", "Score": "1", "body": "@MathiasEttinger The `grouper()` recipe works best for complete groups; you would have to specify a `fillvalue`, then strip out that padding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T15:06:22.453", "Id": "409505", "Score": "0", "body": "@Graipher I don't see any reason to copy a recipe that doesn't do what we want, then work around the unwanted behavior by stripping off junk." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T15:07:29.733", "Id": "409506", "Score": "0", "body": "@200_success: I agree now that it is too cumbersome. We should probably clean up the comments." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T07:13:29.607", "Id": "211748", "ParentId": "211737", "Score": "6" } } ]
{ "AcceptedAnswerId": "211743", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T03:58:00.667", "Id": "211737", "Score": "3", "Tags": [ "python", "file" ], "Title": "Write output file, collating groups of up to 7 input lines" }
211737
<p>This is a follow up to my <a href="https://codereview.stackexchange.com/q/211593/78786">previous Code Review</a>, and I have incorporated feedback I received in this revision of the code, along with some other improvements.</p> <p>I would appreciate your feedback on this code, specifically the practice of placing project-wide constants in <code>config.h</code>, the <code>count_missing_letters</code> method which uses a function pointer to print the word state, as well as my <code>getchar</code> loop in <code>main.c</code>, where I am now continuing on invalid input and consuming white-space characters.</p> <p>Is there any cleaner way to write <code>count_missing_letters</code> which accomplishes the task of being easy to use as well as not having its code repeated. I opted to keep one function so that the single loop performs two different checks in one go, and the use of a function pointer decouples what happens on each iteration - unsure if this is 'idiomatic' C.</p> <p>Below are the source files and the CMakeLists file (which includes many runtime Clang sanitizers enabled). Alternatively, the code can be easily compiled with the following: <code>cc *.c -o hangman &amp;&amp; ./hangman</code></p> <p><strong>main.c</strong></p> <pre><code>/** * * Hangman in C * * O(1) lookup using pointers to 26 letters which each have a * state. A letter is either empty, or the letter itself. * I was inspired by seeing many other Hangman implementations which * relied on a multiple layers of iteration, this aims to be 'simple' * and 'idiomatic', by using a different approach. * * @version 2.0 * @date 1/18/19 * @author Faraz Fazli */ #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;ctype.h&gt; #include &lt;stdlib.h&gt; #include "rng.h" #include "utils.h" #include "config.h" // Returns length of an array #define len(x) (((sizeof(x)))/(sizeof((x)[0]))) int main() { char letters[ALPHABET_SIZE]; int tries = 0; rng_init(); memset(letters, HIDDEN_LETTER, ALPHABET_SIZE); size_t total_elems = len(words); char *word = words[rng_to(total_elems)]; size_t word_len = strlen(word); // excludes NUL size_t word_size = word_len + 1; // includes NUL char **word_to_guess = malloc(word_size * sizeof(*word_to_guess)); // Link letters in word to 'letters' array for (size_t i = 0; i &lt; word_len; i++) { word_to_guess[i] = &amp;letters[dst_from_a(word[i])]; } size_t num_prev_missing = word_len; count_missing_letters(word_to_guess, print_char); fputs("\nPick a letter: ", stdout); int chosen_letter; while ((chosen_letter = getchar()) != EOF) { // Consume newline and other white-space characters if (isspace(chosen_letter)) { continue; } if (!isalpha(chosen_letter)) { puts("Please enter a valid letter."); continue; } chosen_letter = tolower(chosen_letter); size_t letter_pos = dst_from_a(chosen_letter); if (letters[letter_pos] != (char) HIDDEN_LETTER) { puts("Please pick a different letter"); continue; } letters[letter_pos] = (char) chosen_letter; size_t num_missing = count_missing_letters(word_to_guess, print_char); if (num_missing == num_prev_missing) { tries++; } num_prev_missing = num_missing; if (num_missing == 0) { puts("-&gt; YOU WIN!"); break; } puts(""); int tries_left = TOTAL_TRIES - tries; print_hangman(tries_left); if (tries_left &gt; 0) { printf("\nTries Remaining: %d\n", tries_left); fputs("Pick a letter: ", stdout); } else { puts("No tries left! Game Over!"); break; } } free(word_to_guess); } </code></pre> <p><strong>config.h</strong></p> <pre><code>#ifndef HANGMAN_CONFIG_H #define HANGMAN_CONFIG_H /** * Use enum to replace "magic numbers" instead of #define or const * Ref: Practice of Programming, p.21 */ enum { ALPHABET_SIZE = 26, TOTAL_TRIES = 10, HIDDEN_LETTER = '_', }; static char *words[] = {"racing", "magic", "bow", "racecar"}; #endif //HANGMAN_CONFIG_H </code></pre> <p><strong>utils.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include "config.h" void print_hangman(int tries_left) { if (tries_left &gt; 7) { return; } switch (tries_left) { case 7: puts("┏━━━╤━"); puts("┃┃ "); puts("┃┃"); puts("┃┃"); puts("┃┃"); puts("┻┻━━━━━━━"); break; case 6: puts("┏━━━╤━"); puts("┃┃ O "); puts("┃┃"); puts("┃┃"); puts("┃┃"); puts("┻┻━━━━━━━"); break; case 5: puts("┏━━━╤━"); puts("┃┃ O "); puts("┃┃ | "); puts("┃┃ "); puts("┃┃ "); puts("┻┻━━━━━━━"); break; case 4: puts("┏━━━╤━"); puts("┃┃ O "); puts("┃┃ ╲| "); puts("┃┃ "); puts("┃┃ "); puts("┻┻━━━━━━━"); break; case 3: puts("┏━━━╤━"); puts("┃┃ O "); puts("┃┃ ╲|╱"); puts("┃┃ "); puts("┃┃ "); puts("┻┻━━━━━━━"); break; case 2: puts("┏━━━╤━"); puts("┃┃ O "); puts("┃┃ ╲|╱"); puts("┃┃ | "); puts("┃┃ "); puts("┻┻━━━━━━━"); break; case 1: puts("┏━━━╤━"); puts("┃┃ O "); puts("┃┃ ╲|╱"); puts("┃┃ | "); puts("┃┃ ╱ "); puts("┻┻━━━━━━━"); break; case 0: puts("┏━━━╤━"); puts("┃┃ O "); puts("┃┃ ╲|╱"); puts("┃┃ | "); puts("┃┃ ╱ ╲"); puts("┻┻━━━━━━━"); break; } } void print_char(char char_to_print) { putchar(char_to_print); putchar(' '); } size_t count_missing_letters(char **word_to_guess, const void(on_each(char))) { size_t num_missing = 0; while (*word_to_guess) { if (on_each != NULL) { on_each(**word_to_guess); } if (**word_to_guess++ == HIDDEN_LETTER) { num_missing++; } } return num_missing; } size_t dst_from_a(int letter) { return (size_t) abs(letter - 'a'); } </code></pre> <p><strong>utils.h</strong></p> <pre><code>#ifndef HANGMAN_UTILS_H #define HANGMAN_UTILS_H #include &lt;stdlib.h&gt; /** * Prints "hangman" ascii art * @param tries_left - must be &lt;= 7 to display */ void print_hangman(int tries_left); /** * Prints character, followed by a space * @param char_to_print */ void print_char(char char_to_print); /** * Prints the state of each letter and counts the number of missing letters * Optionally calls a function with each character read * @param word_to_guess - word being guessed (array of pointers) * @param on_each - optional function to call on each iteration * @return underscore count */ size_t count_missing_letters(char **word_to_guess, void(on_each(char))); /** * Returns the distance from 'a' * @param letter 'a' to 'z' (must be lower case) * @return 0 through 25 */ size_t dst_from_a(int letter); #endif //HANGMAN_UTILS_H </code></pre> <p><strong>rng.c</strong></p> <pre><code>#include "rng.h" #include &lt;stdlib.h&gt; #include &lt;time.h&gt; void rng_init(void) { srand((unsigned int) time(NULL)); } size_t rng_to(size_t max) { return (unsigned) rand() / ((unsigned) RAND_MAX / max + 1u); } </code></pre> <p><strong>rng.h</strong></p> <pre><code>#ifndef HANGMAN_RNG_H #define HANGMAN_RNG_H #include &lt;stdlib.h&gt; /** * Initializes Random Number Generator * Note: RNG is based on the current time and thus does not produce secure values. * This is intentional, as the RNG is solely used to select a random current word. */ void rng_init(void); /** * Helper method for Random Number Generation * @param max - max number * @return between 0 to max */ size_t rng_to(size_t max); #endif //HANGMAN_RNG_H </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code># Improved version adapted from https://codereview.stackexchange.com/a/210770/78786 cmake_minimum_required(VERSION 3.13) project(Hangman C) add_executable(${CMAKE_PROJECT_NAME} main.c utils.c utils.h rng.c rng.h config.h) set(CMAKE_C_COMPILER clang) target_compile_features(${CMAKE_PROJECT_NAME} PRIVATE c_std_99) target_compile_options(${CMAKE_PROJECT_NAME} PRIVATE $&lt;$&lt;C_COMPILER_ID:Clang&gt;: -Weverything -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto -fvisibility=default&gt;) target_link_options(${CMAKE_PROJECT_NAME} PRIVATE $&lt;$&lt;C_COMPILER_ID:Clang&gt;: -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto&gt;) </code></pre>
[]
[ { "body": "<p>This code is not bad at all, and I like the new ASCII art. Here are some ideas on how to improve it further:</p>\n\n<h2>Don't confuse the reader</h2>\n\n<p>By grouping things together in an <code>enum</code> it's true that it eliminates \"magic numbers\" but it also tends to mislead the reader into thinking that these items are related. In this case, there are really three independent constants whose only relation is that they are all used in this game. I'd use <code>const</code> for this and use the appropriate types for each, since <code>ALPHABET_SIZE</code> should probably be <code>size_t</code>, <code>HIDDEN_LETTER</code> a <code>char</code>, etc.</p>\n\n<h2>Consider reworking the interface</h2>\n\n<p>Right now, there is not much separation of concerns. The <code>main</code> program knows everything about every piece of the program. That works, but it might be nicer to separate things a little more. I'd rename <code>config.h</code> to <code>dictionary.h</code> and have a function named <code>get_random_word</code>: </p>\n\n<pre><code>const char *get_random_word() {\n static const char *words[] = {\"racing\", \"magic\", \"bow\", \"racecar\"};\n static const size_t word_count = sizeof(words)/sizeof(words[0]);\n return words[rng_to(word_count)];\n}\n</code></pre>\n\n<p>That eliminates the need for <code>main</code> to have the macro, and removes the need for it to know anything about the random number generation code.</p>\n\n<h2>Consider different data structures</h2>\n\n<p>The code relies on a number of related data structures, <code>letters</code>, <code>words</code> and <code>word_to_guess</code>. I would alter their use a bit. First, I'd hide <code>words</code> completely, as shown above. Right now, the actual underlying alphabet is implicit rather than explicit. It assumes that the alphabet consists of <code>ALPHABET_SIZE</code> contiguous characters beginning from <code>'a'</code>. This works for English and an ASCII encoding, but not for EBCDIC encodings and not for other languages such as Spanish, French or German. Instead, I'd suggest that there could be an explicit <code>alphabet</code> string associated with the previously mentioned <code>dictionary.h</code>. It could be <code>const</code>. Second, one could employ a <code>bool</code> array of the same length to keep track of which letters of the alphabet had been guessed. This would then be the only data structure that would need to be modified during game play. </p>\n\n<h2>An example</h2>\n\n<p>If we isolate dictionary things to the dictionary, it might look like this:</p>\n\n<pre><code>const char *dict_init () {\n static const char *alphabet = \"abcdefghijklmnopqrstuvwxyz\";\n rng_init();\n return alphabet;\n}\n\nconst char *get_random_word() {\n static const char *words[] = {\"racing\", \"magic\", \"bow\", \"racecar\"};\n static const size_t word_count = sizeof(words)/sizeof(words[0]);\n return words[rng_to(word_count)];\n}\n</code></pre>\n\n<p>Now from within <code>main</code> we might have this:</p>\n\n<pre><code>int main() {\n const char *alphabet = dict_init();\n bool *guessed = calloc(strlen(alphabet), sizeof(bool));\n int tries = 10;\n const char *word = get_random_word();\n size_t word_len = strlen(word);\n bool playing = true;\n\n while (playing) {\n display_word(word, word_len, alphabet, guessed);\n fputs(\"\\nPick a letter: \", stdout);\n int chosen_letter;\n for (chosen_letter = tolower(getchar()); isspace(chosen_letter); chosen_letter = tolower(getchar())) \n { }\n if (chosen_letter == EOF) {\n playing = false;\n continue;\n }\n const char *target = strchr(alphabet, chosen_letter);\n if (target == NULL) {\n puts(\"Please enter a valid letter.\");\n continue;\n }\n if (guessed[target - alphabet]) {\n puts(\"Please pick a different letter\");\n continue;\n }\n guessed[target - alphabet] = true;\n // is this letter in the word to be guessed?\n if (strchr(word, *target) != NULL) {\n if (display_word(word, word_len, alphabet, guessed)) {\n printf(\"\\nTries Remaining: %d\\n\", tries);\n } else {\n puts(\"-&gt; YOU WIN!\");\n playing = false;\n }\n } else { // guessed letter not in target word\n playing = print_hangman(--tries);\n }\n }\n free(guessed);\n}\n</code></pre>\n\n<p>Note that I've used <code>strchr</code> to see if the character is within the alphabet. I've also modified your <code>print_hangman</code> to return true if there are guesses left and added this function:</p>\n\n<pre><code>size_t display_word(const char *word, const size_t word_len, const char *alphabet, const bool *guessed) {\n size_t hidden = word_len;\n for (size_t i=0; i &lt; word_len; ++i) {\n bool revealed = guessed[strchr(alphabet, word[i]) - alphabet];\n if (revealed) {\n putchar(word[i]);\n --hidden;\n } else {\n putchar('_');\n }\n putchar(' ');\n }\n return hidden;\n}\n</code></pre>\n\n<p>It's not terribly efficient in terms of runtime performance, but it doesn't matter much since it will be fast enough for a human player.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T16:17:51.887", "Id": "409517", "Score": "0", "body": "Thanks for the advice. Can you please explain more about the last point regarding making an alphabet string and keeping track of letters with a bool array? What would that look like?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T17:01:13.273", "Id": "409523", "Score": "1", "body": "I've updated my answer to show what I mean." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T14:43:25.770", "Id": "211768", "ParentId": "211739", "Score": "2" } }, { "body": "<p>Minor ideas:</p>\n\n<p><strong>Repetitive calls</strong></p>\n\n<p>This is an alternative idea, not a recommendation.</p>\n\n<p>A way to avoid repeated calls to <code>puts()</code>, and still maintain code \"art\", use string literal concatenation.</p>\n\n<pre><code> puts(\n \"┏━━━╤━\\n\"\n \"┃┃\\n\"\n \"┃┃\\n\"\n \"┃┃\\n\"\n \"┃┃\\n\"\n \"┻┻━━━━━━━\");\n</code></pre>\n\n<p>Note an optimizing compiler may join the original <code>puts()</code> together anyways. </p>\n\n<p>Code could put the 8 strings in an array of strings <code>const char *art[8] = {...};</code> and then use <code>art[tries_left]</code> rather than a <code>switch</code>.</p>\n\n<p>As with such style issues: code to your group's coding standards.</p>\n\n<p><strong>Type naming</strong></p>\n\n<p>Rather than <code>unsigned int</code> and <code>unsigned</code> in code, use one of them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T16:22:42.913", "Id": "409519", "Score": "0", "body": "I am curious to hear your thoughts on count_missing_letters. Is this a clean way to express what is happening?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T17:47:20.610", "Id": "409529", "Score": "1", "body": "@Faraz I found `count_missing_letters(char **word_to_guess, ...)` confusing from the start. Perhaps it is the loose usage of the `word` here. For me a `word` would be a `char *`. Here `word` is a list of pointer to a letter. Consider Edward idea of \"employ a bool array of the same length to keep track of which letters of the alphabet had been guessed\". IMO, the word to guess should be `const` and variables descend from that. Consider a `struct hangman { const char *word_to_guess; bool *guessed; size_t word_length; size_t guessed_right_count; size_t guess_count }`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T15:26:35.790", "Id": "211772", "ParentId": "211739", "Score": "2" } } ]
{ "AcceptedAnswerId": "211768", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T05:05:18.873", "Id": "211739", "Score": "4", "Tags": [ "c", "ascii-art", "hangman", "c99" ], "Title": "Hangman v2 written in C" }
211739
<p>I have a stripe payment form and when I use different forms that get hidden, I must use separate IDs for the form to appear. I have found a way to do this but looking to simplify the code if this is possible.</p> <p>I have a page that has listings for purchase. Each listing can have variants. Because of this, I need to create separate Stripe JavaScript so the credit card form appears.</p> <p>I am wondering if there is a simpler route to go in instead of doing the following:</p> <pre><code> &lt;script&gt; var stripe = Stripe('pk_test_1234567890'); var elements = stripe.elements(); var style = { base: { color: '#32325d', lineHeight: '24px', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; var card = elements.create('card', {style: style}); card.mount('#card-element'); card.addEventListener('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); var form = document.getElementById('payment_form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createToken(card).then(function(result) { if (result.error) { var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { stripeTokenHandler(result.token); } }); }); function stripeTokenHandler(token) { var form = document.getElementById('payment_form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit(); } &lt;/script&gt; &lt;script&gt; var stripe = Stripe('pk_test_1234567890'); var elements = stripe.elements(); var style = { base: { color: '#32325d', lineHeight: '24px', fontFamily: '"Helvetica Neue", Helvetica, sans-serif', fontSmoothing: 'antialiased', fontSize: '16px', '::placeholder': { color: '#aab7c4' } }, invalid: { color: '#fa755a', iconColor: '#fa755a' } }; var card = elements.create('card', {style: style}); #HERE IS USE DIFFERENT CARD ID card.mount('#card-element-2'); card.addEventListener('change', function(event) { var displayError = document.getElementById('card-errors'); if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); var form = document.getElementById('payment_form'); form.addEventListener('submit', function(event) { event.preventDefault(); stripe.createToken(card).then(function(result) { if (result.error) { var errorElement = document.getElementById('card-errors'); errorElement.textContent = result.error.message; } else { stripeTokenHandler(result.token); } }); }); function stripeTokenHandler(token) { var form = document.getElementById('payment_form'); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); form.submit(); } &lt;/script&gt; </code></pre> <p>One of the forms:</p> <pre><code> &lt;div class="form-row"&gt; &lt;label for="card-element-2"&gt; Credit or debit card &lt;/label&gt; &lt;div id="card-element-2" class="form-control"&gt; &lt;/div&gt; &lt;div id="card-errors" role="alert"&gt;&lt;/div&gt; &lt;/div&gt; ... ... </code></pre> <p>As you see, if you look closely, there are different ids being called in each separate script. I have a commented out like <code>#HERE I USE DIFFERENT CARD ID</code>.</p> <p>Then, in the view, I have separate credit card forms with different IDs. It is like this because when one form is appearing, another is hidden.</p> <p>Is there a way where I can simplify this code and call the possibility of multiple IDs instead of having long JavaScript like the way I do?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T07:03:21.800", "Id": "409441", "Score": "0", "body": "Welcome to Code Review. 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 [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T07:53:30.157", "Id": "409445", "Score": "0", "body": "Please put your current approach in words, in addition to presenting code you think implements it. I strongly recommend adding such to the code (but not in this post - someone may have been busy for an hour or more writing an answer about just that!) as comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T16:37:52.553", "Id": "409521", "Score": "0", "body": "Welcome to Code Review! I don't see any element with `id=\"payment_form\"` in the sample HTML, despite my expectations after reading the JavaScript code... Is that attribute on a root element, or is it typically a child node of another element - e.g. `<div id=\"card-element-2\" class=\"form-control\">`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T21:49:53.643", "Id": "409552", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ The difference is the card-element for the `card.mount('#card-element');` --- i tried using an `||` to solve it with the full mount line and just the id's but didn't help. I basically need a way to say \"this can be `card-element` or `card-element-2`" } ]
[ { "body": "<p>instead of manually selecting each card every time like </p>\n\n<pre><code>card.mount('#card-element-2');\n\ncard.addEventListener('change', function(event) {\n var displayError = document.getElementById('card-errors');\n if (event.error) {\n displayError.textContent = event.error.message;\n } else {\n displayError.textContent = '';\n }\n});\n</code></pre>\n\n<p>you can select all the elements that start with <code>#card-element</code> and loop through them to add the eventListener : </p>\n\n<pre><code>document.querySelectorAll('[id^=card-element]').forEach(e =&gt; {\n var card = elements.create('card', {\n style: style\n });\n\n card.mount(`#${e.id}`);\n\n card.addEventListener('change', function(event) {\n var displayError = document.getElementById('card-errors');\n if (event.error) {\n displayError.textContent = event.error.message;\n } else {\n displayError.textContent = '';\n }\n });\n});\n</code></pre>\n\n<p>Final code should look like : </p>\n\n<pre><code>var stripe = Stripe('pk_test_1234567890');\n\nvar elements = stripe.elements();\n\nvar style = {\n base: {\n color: '#32325d',\n lineHeight: '24px',\n fontFamily: '\"Helvetica Neue\", Helvetica, sans-serif',\n fontSmoothing: 'antialiased',\n fontSize: '16px',\n '::placeholder': {\n color: '#aab7c4'\n }\n },\n invalid: {\n color: '#fa755a',\n iconColor: '#fa755a'\n }\n};\n\ndocument.querySelectorAll('[id^=card-element]').forEach(e =&gt; {\n var card = elements.create('card', {\n style: style\n });\n\n card.mount(`#${e.id}`);\n\n card.addEventListener('change', function(event) {\n var displayError = document.getElementById('card-errors');\n if (event.error) {\n displayError.textContent = event.error.message;\n } else {\n displayError.textContent = '';\n }\n });\n});\n\nvar form = document.getElementById('payment_form');\nform.addEventListener('submit', function(event) {\n event.preventDefault();\n\n stripe.createToken(card).then(function(result) {\n if (result.error) {\n var errorElement = document.getElementById('card-errors');\n errorElement.textContent = result.error.message;\n } else {\n stripeTokenHandler(result.token);\n }\n });\n});\n\nfunction stripeTokenHandler(token) {\n var form = document.getElementById('payment_form');\n var hiddenInput = document.createElement('input');\n hiddenInput.setAttribute('type', 'hidden');\n hiddenInput.setAttribute('name', 'stripeToken');\n hiddenInput.setAttribute('value', token.id);\n form.appendChild(hiddenInput);\n\n form.submit();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T00:12:01.993", "Id": "409860", "Score": "0", "body": "thanks for the input but that didn't seem to work. The forms won't appear unless the specific id is called." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T00:35:07.900", "Id": "409862", "Score": "0", "body": "@uno i just noticed i forgot to add the `#` before `e.id`, it should be `card.mount(\\`#${e.id}\\`);` or `card.mount('#' + e.id);` because the value of `e.id` would be the id without the `#`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T16:48:00.307", "Id": "211923", "ParentId": "211742", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T05:46:35.753", "Id": "211742", "Score": "2", "Tags": [ "javascript", "form", "e-commerce" ], "Title": "Stripe payment form" }
211742
<p>In this post, we are given two anagrams, and we wish to compute a <strong><em>shortest</em></strong> sequence of <strong><em>adjacent</em></strong> character swaps. For example, <code>DBAC -&gt; BDAC -&gt; BADC -&gt; ABDC -&gt; ABCD</code>, four adjacent swaps. I tried to split the algorithm into logical parts in order to facilitate better readability and would like to hear comments regarding it. Here is my code:</p> <p><strong>LeastAdjacentSwapAnagramTransformAlgorithm.java</strong></p> <pre><code>package net.coderodde.fun; import java.util.HashMap; import java.util.List; import java.util.Map; /** * This interface defines the API and basic infrastructure for algorithms * returning a shortest list of adjacent swaps required to transform one anagram * into another. * * @author Rodion "rodde" Efremov * @version 1.6 (Jan 5, 2019) */ public interface LeastAdjacentSwapAnagramTransformAlgorithm { /** * Encodes an adjacent pair of elements in an array. */ public static final class AdjacentSwapDescriptor { /** * The index of the left list element. We imply here, that the index of * the right list element is {@code startingIndex + 1}. */ public final int startingIndex; /** * Constructs a new, immutable descriptor. * * @param startingIndex the index of the left list element. */ public AdjacentSwapDescriptor(int startingIndex) { this.startingIndex = startingIndex; } @Override public boolean equals(Object o) { if (o == null) { return false; } if (!o.getClass().equals(this.getClass())) { return false; } AdjacentSwapDescriptor other = (AdjacentSwapDescriptor) o; return startingIndex == other.startingIndex; } @Override public String toString() { return "(" + startingIndex + ", " + (startingIndex + 1) + ")"; } } /** * Finds a shortest sequence of adjacent swaps, that transforms * {@code string1} into {@code string2}. * * @param string1 the source string. * @param string2 the target string. * @return the list of adjacent swaps transforming the source array into the * target array. */ public List&lt;AdjacentSwapDescriptor&gt; compute(String string1, String string2); /** * Checks that the two input strings are anagrams. * * @param string1 the first string. * @param string2 the second string. * @return {@code true} if the two input strings are anagrams. {@code false} * otherwise. */ static boolean areAnagrams(String string1, String string2) { Map&lt;Character, Integer&gt; characterCountMap1 = new HashMap&lt;&gt;(); Map&lt;Character, Integer&gt; characterCountMap2 = new HashMap&lt;&gt;(); for (char c : string1.toCharArray()) { characterCountMap1. put(c, characterCountMap1.getOrDefault(c, 0) + 1); } for (char c : string2.toCharArray()) { characterCountMap2. put(c, characterCountMap2.getOrDefault(c, 0) + 1); } return characterCountMap1.equals(characterCountMap2); } } </code></pre> <p><strong>BruteForceLeastAdjacentSwapAnagramTransformAlgorithm.java</strong></p> <pre><code>package net.coderodde.fun.support; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import static net.coderodde.fun.LeastAdjacentSwapAnagramTransformAlgorithm.areAnagrams; import net.coderodde.util.ListTupleIndexIterator; import net.coderodde.util.PermutationIterable; import net.coderodde.fun.LeastAdjacentSwapAnagramTransformAlgorithm; /** * This class implements a brute-force algorithm for computing shortest * inversions list transforming one input string into another. * * @author Rodion "rodde" Efremov * @version 1.6 (Jan 5, 2019) */ public final class BruteForceLeastAdjacentSwapAnagramTransformAlgorithm implements LeastAdjacentSwapAnagramTransformAlgorithm { /** * Computes and returns a shortest sequence of inversion required to * transform one string into another. * * @param string1 the first string. * @param string2 the second string. * @return a sequence (list) of inversions. */ @Override public List&lt;AdjacentSwapDescriptor&gt; compute(String string1, String string2) { checkInputStrings(string1, string2); if (string1.equals(string2)) { return new ArrayList&lt;&gt;(); } SolutionDescriptor solutionDescriptor = computeImpl(string1, string2); return toAdjacentSwapDescriptorList(solutionDescriptor); } /** * Converts internal representation of a solution to the one according to * API. * * @param solutionDescriptor the solution descriptor. * @return solution. */ private static final List&lt;AdjacentSwapDescriptor&gt; toAdjacentSwapDescriptorList(SolutionDescriptor solutionDescriptor) { List&lt;AdjacentSwapDescriptor&gt; list = new ArrayList&lt;&gt;(solutionDescriptor.permutationIndices.length); for (int index : solutionDescriptor.permutationIndices) { list.add( new AdjacentSwapDescriptor( solutionDescriptor.tupleIndices[index])); } return list; } /** * Runs preliminary checks on the two input strings. * * @param string1 the first string. * @param string2 the second string. */ private static void checkInputStrings(String string1, String string2) { Objects.requireNonNull(string1, "The first input string is null."); Objects.requireNonNull(string2, "The second input string is null."); checkStringsHaveSameLength(string1, string2); checkStringsAreAnagrams(string1, string2); } /** * Checks that the two input strings are of the same length. * * @param string1 the first string. * @param string2 the second string. */ private static void checkStringsHaveSameLength(String string1, String string2) { if (string1.length() != string2.length()) { throw new IllegalArgumentException( "The two input streams have different lengths: " + string1.length() + " vs. " + string2.length()); } } /** * Checks that the two input strings are of anagrams. In other worlds, * checks that one string can be transformed into the second string only by * rearranging the letters in one of them. * * @param string1 the first string. * @param string2 the second string. */ private static void checkStringsAreAnagrams(String string1, String string2) { if (!areAnagrams(string1, string2)) { throw new IllegalArgumentException( "The two input strings are not anagrams."); } } /** * Runs the topmost search of the algorithm. * * @param string1 the source string. * @param string2 the target string. * @return the smallest list of inversion descriptors required to transform * one string into another. */ private static SolutionDescriptor computeImpl(String string1, // DBAC -&gt; DABC -&gt; ADBC -&gt; ABDC -&gt; ABCD String string2) { // (1, 2) -&gt; (0, 1) -&gt; (1, 2) -&gt; (2, 3) char[] sourceStringChars = string1.toCharArray(); char[] targetStringChars = string2.toCharArray(); char[] bufferStringChars = new char[sourceStringChars.length]; for (int inversions = 1; true; inversions++) { SolutionDescriptor solutionDescriptor = computeImpl(sourceStringChars, targetStringChars, bufferStringChars, inversions); if (solutionDescriptor != null) { return solutionDescriptor; } } } /** * Holds internal representation of a solution. tupleIndices[i] holds the * index of the i'th adjacent swap to apply to the source array in order to * convert the source string to the target string. permutationIndices[i] * specifies the order the indices from tupleIndices should be applies. */ private static final class SolutionDescriptor { final int[] tupleIndices; final int[] permutationIndices; SolutionDescriptor(int[] tupleIndices, int[] permutationIndices) { this.tupleIndices = tupleIndices; this.permutationIndices = permutationIndices; } } /** * Attempts to find an inversion descriptor list of length * {@code inversions}. If no such exist, returns {@code null}. * * @param sourceStringChars the source string. * @param targetStringChars the target string. * @param inversions the requested number of inversions in the result. * @return if not such list exist. */ private static SolutionDescriptor computeImpl(char[] sourceStringChars, char[] targetStringChars, char[] bufferStringChars, int inversions) { // string1.length() - 1, i.e., there are at most n - 1 distinct // inversion pairs, with largest value n - 1: ListTupleIndexIterator iterator = new ListTupleIndexIterator(inversions, sourceStringChars.length - 2); int[] indices = iterator.getIndexArray(); do { SolutionDescriptor solutionDescriptor = applyIndicesToWorkArray(sourceStringChars, targetStringChars, bufferStringChars, indices); if (solutionDescriptor != null) { return solutionDescriptor; } iterator.generateNextTupleIndices(); } while (iterator.hasNext()); return null; } /** * Permutes all the entries in the {@code indices} and for each index * permutation applies the sequence and checks to see if they are sufficient * for transforming the source array to the target array. * * @param sourceCharArray the source character array. * @param targetCharArray the target character array. * @param bufferCharArray the buffer character array. * @param indices the adjacent swap indices. * @return a solution descriptor. */ private static SolutionDescriptor applyIndicesToWorkArray(char[] sourceCharArray, char[] targetCharArray, char[] bufferCharArray, int[] indices) { copy(sourceCharArray, bufferCharArray); PermutationIterable permutationIterable = new PermutationIterable(indices.length); int[] permutationIndices = permutationIterable.getIndexArray(); while (permutationIterable.hasNext()) { copy(sourceCharArray, bufferCharArray); // For each inversion pair permutation, apply it and see whether we // got to the source character array: for (int i : permutationIndices) { int inversionIndex = indices[i]; swap(bufferCharArray, inversionIndex, inversionIndex + 1); } if (Arrays.equals(bufferCharArray, targetCharArray)) { return new SolutionDescriptor(indices, permutationIndices); } permutationIterable.generateNextPermutation(); } return null; } private static void swap(char[] array, int index1, int index2) { char tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } /** * Throws entire {@code sourceArray} to [@code targetArray}. * @param sourceArray the source array. * @param targetArray the target array. */ private static void copy(char[] sourceArray, char[] targetArray) { System.arraycopy(sourceArray, 0, targetArray, 0, sourceArray.length); } } </code></pre> <p><strong>ListTupleIndexIterator.java</strong></p> <pre><code>package net.coderodde.util; /** * This class implements list tuples iterators. Given * {@code requestedMaximumIndexValue} and {@code numberOfIndices}, set all * {@code numberOfIndices} to zero. Than increments the first index until it has * value [@code requestedMaximumIndex}, after which, resets the index and sets * the second index to 1. This is continued until the second index becomes * {@code requestedMaximumIndex}, after which the two indices are set to all * and the third index is incremented. This continues until all indices are set * to {@code requestedMaximumIndexValue}. I * * @author Rodion "rodde" Efremov * @version 1.6 (Jan 5, 2019) */ public final class ListTupleIndexIterator { private final int requestedMaximumIndexValue; private final int[] indices; private boolean iterationExhausted = false; public ListTupleIndexIterator(int numberOfIndices, int requestedMaximumIndex) { this.indices = new int[numberOfIndices]; this.requestedMaximumIndexValue = requestedMaximumIndex; } public int[] getIndexArray() { return indices; } public boolean hasNext() { return !iterationExhausted; } public void generateNextTupleIndices() { int n = indices.length; int i = n - 1; while (i &gt;= 0 &amp;&amp; indices[i] == requestedMaximumIndexValue) { i--; } if (i &lt; 0) { iterationExhausted = true; return; } indices[i]++; for (int j = i + 1; j &lt; n; j++) { indices[j] = 0; } } } </code></pre> <p><strong>PermutationIterator.java</strong></p> <pre><code>package net.coderodde.util; import java.util.Arrays; import java.util.stream.IntStream; /** * This class permutes an integer index array. * * @author Rodde "rodde" Efremov * @version 1.6 (Jan 4, 2019) */ public final class PermutationIterator { private final int[] indices; private boolean iterationExhausted; public PermutationIterator(int numberoOfObjectsToPermute) { this.indices = IntStream.range(0, numberoOfObjectsToPermute).toArray(); this.iterationExhausted = false; } public boolean hasNext() { return !iterationExhausted; } public int[] getIndexArray() { return indices; } public void generateNextPermutation() { int inversionStartIndex = findAscendingPairStartIndex(); if (inversionStartIndex == -1) { iterationExhausted = true; return; } int largestElementIndex = findSmallestElementIndexLargerThanInputIndex( inversionStartIndex + 1, indices[inversionStartIndex]); swap(indices, inversionStartIndex, largestElementIndex); reverse(indices, inversionStartIndex + 1, indices.length); } /** * Seeks for the starting index of the rightmost ascending pair in the * index array. * * @return the starting index of the rightmost ascending pair. */ private final int findAscendingPairStartIndex() { for (int i = indices.length - 2; i &gt;= 0; i--) { if (indices[i] &lt; indices[i + 1]) { return i; } } return -1; } /** * Returns the index of the smallest integer no smaller or equal to * {@code lowerBound}. * * @param lowerBoundIndex the smallest relevant index into the array * prefix. * @param lowerBound * @return */ private int findSmallestElementIndexLargerThanInputIndex( int lowerBoundIndex, int lowerBound) { int smallestFitElement = Integer.MAX_VALUE; int smallestFitElementIndex = -1; for (int i = lowerBoundIndex; i &lt; indices.length; i++) { int currentElement = indices[i]; if (currentElement &gt; lowerBound &amp;&amp; currentElement &lt; smallestFitElement) { smallestFitElement = currentElement; smallestFitElementIndex = i; } } return smallestFitElementIndex; } private static final void swap(int[] array, int index1, int index2) { int tmp = array[index1]; array[index1] = array[index2]; array[index2] = tmp; } private static final void reverse(int[] array, int fromIndex, int toIndex) { for (int i = fromIndex, j = toIndex - 1; i &lt; j; i++, j--) { swap(array, i, j); } } } </code></pre> <p>(The entire Maven project is <a href="https://github.com/coderodde/LeastAdjacentSwapAnagramTransform" rel="nofollow noreferrer">here</a>.)</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T07:49:08.263", "Id": "211749", "Score": "1", "Tags": [ "java", "algorithm", "strings" ], "Title": "Brute force least adjacent swap anagram transform in Java" }
211749
<p>I know you must've been already tired of Python decorators, but this one seems new! There is a common practice of making <a href="//stackoverflow.com/q/739654">decorators with arguments</a>. But <a href="https://www.python.org/dev/peps/pep-0020/" rel="nofollow noreferrer">Flat is better than nested</a>, so let's flatten it up:</p> <pre><code>def decorator_with_args(arg): def wrapper(*args, **kwargs): print('decorated with arg: {}'.format(arg)) return wrapper.func(*args, **kwargs) def wrapper_creator(decorable): wrapper.func = decorable return functools.wraps(decorable)(wrapper) return wrapper_creator </code></pre> <p>Wrapped <code>func</code> is passed as an attribute, <code>arg</code> - via closure. They don't get overwritten with multiple <em>consequent</em> calls to <code>decorator_with_args</code>.</p> <p>But not <em>chained</em> ones - <code>functools.wraps</code> will update <code>wrapper</code>'s <code>__dict__</code>, overwriting its <code>func</code> attribute like this:</p> <pre><code>@decorator_with_args('This decorator will be applied') @decorator_with_args('Others will not') def gotcha(): pass </code></pre> <p>So, attributes are not a good place to store our <code>func</code>. But closure seems to be. Let's use it:</p> <pre><code>def decorator_with_args(arg): func = None def wrapper(*args, **kwargs): print('decorated with arg: {}'.format(arg)) return func(*args, **kwargs) def wrapper_creator(decorable): nonlocal func func = decorable return functools.wraps(decorable)(wrapper) return wrapper_creator </code></pre> <p>Now it looks good to me! Does it to you? Is it pythonic, idiomatic, correct and nicely performing?</p> <p>And a real example of making something useful (this is a part to be reviewed):</p> <pre><code>import functools import logging import logging.config def temp_loglevel(level): """ A decorator for setting temporary loglevel for the scope of the wrapped function, then reverting it back on wrapper exit Arguments: level: new logging level to set """ logger = logging.getLogger() func = None def wrapper(*args, **kwargs): old_level = logger.level logger.setLevel(level) rv = func(*args, **kwargs) logger.setLevel(old_level) return rv def wrapper_maker(decorable): nonlocal func func = decorable logger.warn( "temp_loglevel used, don't forget to " "remove it when debugging is done" ) return functools.wraps(decorable)(wrapper) return wrapper_maker logging.config.dictConfig(dict( version = 1, disable_existing_loggers = False, formatters = { 'default': { 'format': '%(asctime)-15s [%(levelname)s] %(message)s' } }, handlers = { 'std': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'default' } }, root = { 'handlers': ['std'], 'propagate': False, 'level': 'INFO' } )) @temp_loglevel(logging.DEBUG) def print_debug(): logging.getLogger().debug('This should be visible') if __name__ == '__main__': print_debug() </code></pre> <p>I would be glad if you put some critique of my code styling as well!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T08:32:27.840", "Id": "409451", "Score": "2", "body": "Welcome to Code Review! I don't understand what code we're reviewing, though. This decorator and it's argument doesn't seem to accomplish anything. It seems that you are asking for opinions about the general practice of splitting up arguments into multiple decorators, in which case I am voting to close this question as hypothetical." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T09:34:21.870", "Id": "409465", "Score": "0", "body": "@200_success Oh, sorry. It is a bit stripped off example to focus the attention on one aspect of the implementation - the decorator itself (not the wrapper), and to facilitate things for those willing to run it (to test their own ideas or use cases). I could add my real production code if needed. Should I?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T09:40:24.450", "Id": "409466", "Score": "3", "body": "@ogurets Yes, because unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see [Why is hypothetical example code off-topic for CR?](//codereview.meta.stackexchange.com/q/1709)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T10:06:01.013", "Id": "409472", "Score": "0", "body": "@MathiasEttinger Done!" } ]
[ { "body": "<p>I've found a couple bugs - lack of exception support and it doesn't work with generators. Well, it does in a way, but not the way someone would <em>expect</em> it to.</p>\n\n<p>To fix aforementioned issues, decorator have been changed into this (nevermind Python 2.7 compatibility modifications):</p>\n\n<pre><code>def temp_loglevel(level):\n \"\"\"\n Decorator to set temporary loglevel for the scope of this function\n (then revert it back on wrapper exit)\n\n Arguments:\n level: new logging level to set\n \"\"\"\n logger = logging.getLogger()\n p_closure = dict(func=None)\n\n def wrapper(*args, **kwargs):\n old_level = logger.level\n logger.setLevel(level)\n try:\n rv = p_closure['func'](*args, **kwargs)\n if isinstance(rv, types.GeneratorType):\n def wrapper_gen():\n # wrapper's finally block overrides initial setLevel after\n # returning a generator object\n logger.setLevel(level)\n try:\n for x in rv:\n yield x\n finally:\n logger.setLevel(old_level)\n\n return wrapper_gen()\n else:\n return rv\n finally:\n logger.setLevel(old_level)\n\n def wrapper_maker(decorable):\n p_closure['func'] = decorable\n logger.warn(\n \"temp_loglevel used, don't forget to \"\n \"remove it when debugging is done\"\n )\n\n return functools.wraps(decorable)(wrapper)\n\n return wrapper_maker\n</code></pre>\n\n<p>P.S. After thinking about how ugly would a flat version of <code>wrapper_gen</code> be, I've made a mental note to myself: \"flat is better than nested\", but if you <strong>absolutely need</strong> to make something nested, do it FFS!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T08:42:11.077", "Id": "211894", "ParentId": "211750", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T08:09:31.077", "Id": "211750", "Score": "4", "Tags": [ "python", "python-3.x" ], "Title": "Making a decorator with arguments in a flat manner" }
211750
<p>I'm using C# .NET Core 2.1 and Excel lib <code>DotnetCore.NPOI</code></p> <p>I'm converting <code>xls</code> file to <code>xlsx</code> by loading <code>xls</code> and copying sheet by sheet, cell by cell to <code>xlsx</code> - How can I improve performance / ram usage here?</p> <pre><code>private string ConvertToXSLX(string path) { using (var fs = File.OpenRead(path)) { var result = XLS_to_XLSX_Converter.Convert(fs); // (file.xls) + x = file.xlsx path = $"{path}x"; using (var fs2 = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write)) { fs2.Write(result, 0, result.Length); } } return path; } </code></pre> <hr> <pre><code>public static byte[] Convert(Stream sourceStream) { var source = new HSSFWorkbook(sourceStream); var destination = new XSSFWorkbook(); for (int i = 0; i &lt; source.NumberOfSheets; i++) { var hssfSheet = (HSSFSheet)source.GetSheetAt(i); var xssfSheet = (XSSFSheet)destination.CreateSheet(source.GetSheetAt(i).SheetName); CopyRows(hssfSheet, xssfSheet); } using (var ms = new MemoryStream()) { destination.Write(ms); return ms.ToArray(); } } private static void CopyRows(HSSFSheet hssfSheet, XSSFSheet destination) { for (int i = 0; i &lt; hssfSheet.PhysicalNumberOfRows; i++) { destination.CreateRow(i); var cells = hssfSheet.GetRow(i)?.Cells ?? new List&lt;ICell&gt;(); for (int j = 0; j &lt; cells.Count; j++) { var row = destination.GetRow(i); row.CreateCell(j); CopyCell((HSSFCell)cells[j], (XSSFCell)row.Cells[j]); } } } private static void CopyCell(HSSFCell oldCell, XSSFCell newCell) { CopyCellValue(oldCell, newCell); } private static void CopyCellValue(HSSFCell oldCell, XSSFCell newCell) { switch (oldCell.CellType) { case CellType.String: newCell.SetCellValue(oldCell.StringCellValue); break; case CellType.Numeric: newCell.SetCellValue(oldCell.NumericCellValue); break; case CellType.Blank: newCell.SetCellType(CellType.Blank); break; case CellType.Boolean: newCell.SetCellValue(oldCell.BooleanCellValue); break; case CellType.Error: newCell.SetCellErrorValue(oldCell.ErrorCellValue); break; default: break; } } </code></pre> <p><a href="https://i.stack.imgur.com/aa2OB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aa2OB.png" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/26otw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/26otw.png" alt="enter image description here"></a></p>
[]
[ { "body": "<p>You're writing to a <code>MemoryStream</code> only to get a <code>byte[]</code> to write to another stream, you can definitely avoid this intermediate conversion:</p>\n\n<pre><code>private string ConvertToXSLX(string inputPath) \n{\n string outputPath = Path.ChangeExtension(inputPath, \".xlsx\");\n\n using (var input = File.OpenRead(inputPath))\n using (var output = new FileStream(outputPath, FileMode.OpenOrCreate, FileAccess.Write))\n {\n XLS_to_XLSX_Converter.Convert(input, output);\n }\n\n return outputPath;\n}\n</code></pre>\n\n<p>The change in <code>Convert()</code> should be trivial.</p>\n\n<p>Also note that I'm using <code>Path.ChangeExtension()</code> instead of manually adding a character, code is clear without any comment and it handles <em>special</em> cases for you (for example a trailing space).</p>\n\n<hr>\n\n<p>In <code>CopyRows()</code> you create an empty <code>List&lt;ICell&gt;</code>, you do not need to and you can avoid the initial allocation simply using <code>Enumerable.Empty&lt;ICell&gt;()</code> (and changing your code to work with an enumeration) or - at least - reusing the same empty object (move it outside the loop and create it with an initial capacity of 0).</p>\n\n<hr>\n\n<p>In <code>CopyCellValue()</code> you have an empty <code>default</code> case for your <code>switch</code>. It's a good thing to always have <code>default</code> but it has a purpose: detect <em>unknown</em> cases. If you put a <code>break</code> then you're silently ignoring them. Is it on purpose? Write a comment to explain you ignore unknown cells. It's an error? Throw an exception.</p>\n\n<hr>\n\n<p>I never used DotnetCore.NPOI then I can't comment about the way you use it, be sure to dispose all the intermediate <code>IDisposable</code> objects.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T10:07:45.933", "Id": "211756", "ParentId": "211751", "Score": "5" } } ]
{ "AcceptedAnswerId": "211756", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T08:28:49.853", "Id": "211751", "Score": "6", "Tags": [ "c#", "performance", "excel" ], "Title": "Excel file format converter" }
211751
<p>I have already resolved several others using <code>Application.Index</code> with <code>Application.WorksheetFunction.Match</code> and reduced time to perform from about 7-8 seconds to milliseconds. But I feel there is still room for improvement. </p> <p>Should I use an array with <code>Index</code> and <code>Match</code>?</p> <p>I was also told to use <code>Scripting.Dictionary</code>, but I am looking for someone who can demonstrate how to do it the right away in this scenario. Because in my head I have to populate the dictionary with a loop before I can even use that, so wont it be similar in terms of speed?</p> <pre><code>'Production Quantity for Dashboard For i = 2 To Total_rows_Prod For j = 2 To Total_rows_Dash If ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 5) = ThisWorkbook.Worksheets("Dashboard").Cells(j, 1) Then ThisWorkbook.Worksheets("Dashboard").Cells(j, 4) = ThisWorkbook.Worksheets("Dashboard").Cells(j, 4) + ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 31) / ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 4) End If Next j Next i </code></pre> <p>After doing some bottleneck testing as shown below (run time of code is shown at row 10): <a href="https://i.stack.imgur.com/TWza1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TWza1.png" alt="enter image description here"></a></p> <p>However, when using <code>Index</code> and <code>Match</code> while only using 1 <code>for-next</code> loop as shown in the code below:</p> <pre><code>'Production Quantity for Dashboard For i = 2 To Total_rows_Prod m = Application.Match(ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 5), ThisWorkbook.Worksheets("Dashboard").Range("A:A"), 0) If Not IsError(m) Then ThisWorkbook.Worksheets("Dashboard").Cells(Application.WorksheetFunction.Match(ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 5), ThisWorkbook.Worksheets("Dashboard").Range("A:A"), 0), 4) = ThisWorkbook.Worksheets("Dashboard").Cells(Application.WorksheetFunction.Match(ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 5), ThisWorkbook.Worksheets("Dashboard").Range("A:A"), 0), 4) + ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 31) / ThisWorkbook.Worksheets("Prod. Qty.").Cells(i, 4) End If Next i </code></pre> <p>The run time would be negligible as shown below (still at row 10):</p> <p><a href="https://i.stack.imgur.com/vgSIy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vgSIy.png" alt="enter image description here"></a></p> <p>Any improvements that would make the time to perform optimally minimized would be great.</p> <p>The final time I was able to make everything run with <code>Index</code> and <code>Match</code> replacements was 2 seconds:</p> <p><a href="https://i.stack.imgur.com/LkszS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LkszS.png" alt="enter image description here"></a></p> <p>But on a slower netbook running a Pentium Atom processor, it takes 26 seconds to perform the same code. So I am wondering if there is way to bring down that 26 seconds.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:06:59.623", "Id": "410113", "Score": "0", "body": "You should read this article: [Excel VLOOKUP vs INDEX MATCH vs SQL vs VBA - The Analyst Cave](https://analystcave.com/excel-vlookup-vs-index-match-vs-sql-performance/)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:27:04.107", "Id": "410119", "Score": "0", "body": "Here is some demo code: [Dictionary Demo.txt](https://docs.google.com/document/d/13X8dPtXJXtHP-DSSRb9GDhvzN8E1N2JukH2Xa38EMEM/edit?usp=sharing) / 600,000 lookups is exactly why you should use a Dictionary. Dictionaries are optimized for lightning fast lookups. You have loop over the data once just to load the Dictionary but you have to pass the complete dataset into Application.Match 600,000 times." } ]
[ { "body": "<p>You've not provided a fully functional set of code with data, so I can only make untested suggestions as an example for you to incorporate into your application.</p>\n\n<p>Without seeing the data that you are working with, it's impossible to know if a <code>Dictionary</code> is the best approach. Using a <code>Dictionary</code> is a good idea, but only if all of the data in the table is unique. In your code fragment, for example, you are relying on the comparison of two specific cells and are not searching for a value within the entire range of data (which is better suited to a <code>Dictionary</code>).</p>\n\n<p>Using the <code>Index</code> or <code>Match</code> is also reasonable, but remember that these functions directly interact with the worksheet cells. With larger data sets in the <code>Range</code>, this results in slower execution because the <code>Range</code> object must be traversed to access the desired <code>Cells</code>.</p>\n\n<p>Memory-based arrays would be my recommendation for the execution speed improvements you're looking for, with a straight up array-to-array comparison. You can learn more information about using arrays <a href=\"https://powerspreadsheets.com/excel-vba-array/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"https://excelmacromastery.com/excel-vba-array/#How_To_Make_Your_Macros_Run_at_Super_Speed\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>Again, you didn't include a complete set of your code for review here, but there are a few observations I can make for improvement.</p>\n\n<ol>\n<li>Always use <code>Option Explicit</code>. <em>(You may be doing this, but we can't see it)</em></li>\n<li>Create intermediate objects/variables to make your code more readable. As an example, you are repeating the full reference for a worksheet as <code>ThisWorkbook.Worksheets(\"Prod. Qty.\")</code> everywhere. </li>\n</ol>\n\n<p>While it might seem more tedious at first, trust me when I say it will make your code far more readable and easier to maintain if you set it up like this:</p>\n\n<pre><code>Dim prodQtyWS As Worksheet\nDim dashboardWS As Worksheet\nSet prodQtyWS = ThisWorkbook.Worksheets(\"Prod. Qty.\")\nSet dashboardWS = ThisWorkbook.Worksheets(\"Dashboard\")\n</code></pre>\n\n<ol start=\"3\">\n<li>Establish your ranges explicitly so the extent of your data is clear.</li>\n</ol>\n\n<p>Again, it's a few extra lines of code, but it will not slow down the execution time. <em>(My example here may be an incorrect reading of your OP, you'll have to make adjustments.)</em></p>\n\n<pre><code>Dim prodQtyRange As Range\nSet prodQtyRange = prodQtyWS.Range(\"A2\").Resize(Total_rows_Prod, 31)\n</code></pre>\n\n<p>From here on out it's implementing your business logic to update the dashboard data. Here is my example <code>Sub</code>, which again, you have to adapt to your specific application. You will see a significant speed improvement with this method.</p>\n\n<pre><code>Option Explicit\n\nSub Example(ByVal Total_rows_Prod As Long, ByVal Total_rows_Dash As Long)\n Dim prodQtyWS As Worksheet\n Dim dashboardWS As Worksheet\n Set prodQtyWS = ThisWorkbook.Worksheets(\"Prod. Qty.\")\n Set dashboardWS = ThisWorkbook.Worksheets(\"Dashboard\")\n\n '--- establish the ranges and copy the data into a memory array\n Dim prodQtyRange As Range\n Dim prodQtyData As Variant\n Set prodQtyRange = prodQtyWS.Range(\"A2\").Resize(Total_rows_Prod, 31)\n prodQtyData = prodQtyRange.Value\n\n Dim dashboardRange As Range\n Dim dashboardData As Variant\n Set dashboardRange = dashboardWS.Range(\"A2\").Resize(Total_rows_Dash, 31)\n dashboardData = dashboardRange.Value\n\n Dim i As Long\n Dim j As Long\n For i = 2 To Total_rows_Prod\n '--- calc this factor once, since we're adding the same value\n ' to all the dashboard rows\n Dim prodQtyFactor As Double\n prodQtyFactor = prodQtyData(i, 31) / prodQtyData(i, 4)\n For j = 2 To Total_rows_Dash\n If prodQtyData(i, 5) = dashboardData(i, 1) Then\n dashboardData(j, 4) = dashboardData(j, 4) + prodQtyFactor\n End If\n Next j\n Next i\n\n '--- copy the updated data back to the dashboard\n dashboardRange.Value = dashboardData\n\nEnd Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T14:47:40.760", "Id": "409655", "Score": "0", "body": "About point 2: this isn't *just* about readability: repeatedly dereferencing the same object over and over at every iteration is extraneous work that doesn't *need* to be done every time. Pulling work out of the loop can positively affect performance, depending on how many iterations we're looking at (hard to tell with that little to chew on though)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:28:41.097", "Id": "409760", "Score": "0", "body": "Thanks for this post. Right i've seen someone post about the same point regarding setting a range that is used over and over to a variable, so you don't keep calling the range on every loop. With regards to how many iterations, since I have about 3 months worth of data, `Total_rows_prod` has about 1,500 rows, and `Dashboard` has about 100 rows. So it'll be 150,000 loops. In 1 year it'll be about 600,000 loops only for this part of my code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T18:53:30.867", "Id": "211823", "ParentId": "211752", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T08:35:59.080", "Id": "211752", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Getting totals of each primary key by matching it with another worksheet with a many relationship" }
211752
<p>I have been trying to solve "Wildcard Matching" on leetcode. I know there are more "manual" ways to solve this without using the RE library. But I would like to know if passing the time limit is possible without having to manually create a pattern finder from scratch.</p> <p>Currently this code times out at test case 1708 (out of 1800 or so). I will put the question, leet code examples and my try in the code block below. The case that exceeds the time limit has been included in the 'inps' list of test cases (it is the last one). Can anyone think of a way to make this faster?</p> <pre><code>"""Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*'. '?' Matches any single character. '*' Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial). Note: s could be empty and contains only lowercase letters a-z. p could be empty and contains only lowercase letters a-z, and characters like ? or *. Example 1: Input: s = "aa" p = "a" Output: false Explanation: "a" does not match the entire string "aa". Example 2: Input: s = "aa" p = "*" Output: true Explanation: '*' matches any sequence. Example 3: Input: s = "cb" p = "?a" Output: false Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'. Example 4: Input: s = "adceb" p = "*a*b" Output: true Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce". Example 5: Input: s = "acdcb" p = "a*c?b" Output: false """ class Solution: def isMatch(self, s, p): """ :type s: str :type p: str :rtype: bool """ import re from itertools import groupby grps = groupby(p) l = [(x, len(list(y))) for x, y in grps] new_p = '' for c, cnt in l: if c == '*': new_p = ''.join([new_p, '.*']) elif c == '?': new_p = ''.join([new_p, '.{', str(cnt), '}']) else: new_p = ''.join([new_p, c * cnt]) p = '^' + new_p + '$' MY_RE = re.compile(p) return True if MY_RE.match(s) else False # string, patter, expected inps = [ ("aa", "a", False), ("aa", "*", True), ("cb", "?a", False), ("adceb", "*a*b", True), ("acdcb", "a*c?b", False), ("abcdef", "", False), ("abcdef", "*", True), ("abcdef", "??????", True), ("abcdef", "a?c?e?", True), ("abcdef", "a?c?e?", True), ("abcdef", "********************", True), ("abcdef", "*****abcdef*****", True), ("abcdef", "?abcdef?", False), ("", "", True), ("", "*", True), ("", "*****", True), ("", "?", False), ("a", "*********?********", True), ("a", "?", True), ("abc", "?*?", True), ( "aaaabaaaabbbbaabbbaabbaababbabbaaaababaaabbbbbbaabbbabababbaaabaabaaaaaabbaabbbbaababbababaabbbaababbbba", "*****b*aba***babaa*bbaba***a*aaba*b*aa**a*b**ba***a*a*", True, ), ( "abbabaaabbabbaababbabbbbbabbbabbbabaaaaababababbbabababaabbababaabbbbbbaaaabababbbaabbbbaabbbbababababbaabbaababaabbbababababbbbaaabbbbbabaaaabbababbbbaababaabbababbbbbababbbabaaaaaaaabbbbbaabaaababaaaabb", "**aa*****ba*a*bb**aa*ab****a*aaaaaa***a*aaaa**bbabb*b*b**aaaaaaaaa*a********ba*bbb***a*ba*bb*bb**a*b*bb", False, ), ] sol = Solution() for s, p, exp in inps: #print(f"Doing string[{s}] with pattern[{p}] and asserting...") assert sol.isMatch(s, p) == exp </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T01:46:11.600", "Id": "409868", "Score": "1", "body": "I found someone else's technique of using regex and passing the time limit (@Stefan Pochmann, you are insane!) on leetcode. Here is the link: https://leetcode.com/problems/wildcard-matching/discuss/17888/Simple-greedy-Python-with-regexes." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T08:41:44.103", "Id": "211753", "Score": "3", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded", "regex" ], "Title": "Given an input string and a pattern, implement wildcard pattern matching" }
211753
<p>I'm trying to increase the speed of my application at the moment. My inserting/updating methods were opening every time a new connection which took too much time. I read that it's better to create a connection object and pass it to different methods. It worked fine but I'm just curious if this is a good practice.</p> <p>This is a part of my code I wrote:</p> <pre><code>public class BusinessRuleUpdaterDaoImplV2 extends OracleBaseDao implements BusinessRuleUpdaterDaoV2 { @Override public boolean updateBusinessRule(BusinessRule businessRule) { try(Connection con = super.getConnectionConfigDb()) { con.setAutoCommit(false); if (updateTableBusinessRule(con,businessRule)){ return true; } else { con.rollback(); return false; } } catch (SQLException e) { e.printStackTrace(); } return false; } private boolean updateTableBusinessRule(Connection con, BusinessRule businessRule){ String queryBr = "UPDATE BUSINESSRULE SET ERRORMESSAGE = ?, SQLCODE = ?, CUSTOMNAME = ?, OPERATOR_ID = ? WHERE BUSINESSRULE_ID = ?"; try(PreparedStatement pstmtBr = con.prepareStatement(queryBr)) { pstmtBr.setString(1,businessRule.getErrorMessage()); pstmtBr.setString(2,businessRule.getSqlQuery()); pstmtBr.setString(3,businessRule.getName()); pstmtBr.setInt(4,businessRule.getOperatorID()); pstmtBr.setInt(5,businessRule.getBusinessRuleID()); pstmtBr.executeUpdate(); pstmtBr.close(); return updateTableTargetTable(con,businessRule); } catch (SQLException e) { e.printStackTrace(); return false; } } private boolean updateTableTargetTable(Connection con, BusinessRule businessRule){ String queryTt = "UPDATE TARGETTABLE SET NAME = ? WHERE TABLE_ID = ?"; for (int i = 0 ; i &lt; businessRule.getTableListSize() ; i++) { try (PreparedStatement pstmtTt = con.prepareStatement(queryTt)) { pstmtTt.setString(1,businessRule.getListOfTables().get(i).getName()); pstmtTt.setInt(1, businessRule.getListOfTables().get(i).getId()); pstmtTt.executeUpdate(); pstmtTt.close(); } catch (SQLException e) { e.printStackTrace(); return false; } } return false; } private boolean updateTableAttribute(Connection con, BusinessRule businessRule){ // return updateTableValue(con, businessRule) return false; } private boolean updateTableValue(Connection con, BusinessRule businessRule){ //return updateTableStack(con, businessRule) return false; } private boolean updateTableStack(Connection con, BusinessRule businessRule){ return false; } } </code></pre> <p>As you can see in the first method, <code>updateBusinessRule()</code>, I'm opening a connection and passing it to the next method. If one of the methods returns false, it will make a roll back in the first method.</p> <p>I'm also curious about why intellij is telling me that <code>pstmtTt.close()</code> is redundant.</p>
[]
[ { "body": "<p>I think it is ok to re-use the <code>Connection</code>.</p>\n\n<p>I would not try-catch all the <code>SqlExceptions</code> in the <code>update*</code> methods. Just let them throw. Then you don't need all the <code>boolean</code> logic either. Makes it simpler I guess. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T10:57:14.540", "Id": "211759", "ParentId": "211754", "Score": "1" } }, { "body": "<p>You can use a connection pool like <a href=\"https://github.com/brettwooldridge/HikariCP\" rel=\"nofollow noreferrer\">HikariCP</a> or <a href=\"https://github.com/swaldman/c3p0\" rel=\"nofollow noreferrer\">c3p0</a>; it reduces the time for new connection setup.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T16:01:10.730", "Id": "211774", "ParentId": "211754", "Score": "-1" } }, { "body": "<p>If your application constantly/periodically makes DB queries it is logical to keep/store a DAO object as a singleton that connects to the service once (possibly on application startup). This way you are not going to lose time waiting until the connection appears every time</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T23:24:57.033", "Id": "213921", "ParentId": "211754", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T09:16:46.040", "Id": "211754", "Score": "2", "Tags": [ "java", "jdbc" ], "Title": "Business rule updater" }
211754
<p>I guess this has been made a couple of times by now, but i wanted to take my chance on creating a simple generic linked list in c#. What do you think ?</p> <p>This is the main class.</p> <pre><code>public class LinkedList&lt;T&gt;: IEnumerator&lt;T&gt; { private Node&lt;T&gt; head; private Node&lt;T&gt; tail; public T Current { get { return myCurrentNode.GetValue(); } } object IEnumerator.Current =&gt; Current; private Node&lt;T&gt; myCurrentNode; public LinkedList() { head = null; tail = null; } public void Add(T value) { if (head == null &amp;&amp; tail == null) { head = new Node&lt;T&gt;(value); tail = head; Reset(); return; } tail.SetNextNode(new Node&lt;T&gt;(value)); tail = tail.GetNextNode(); } public void RemoveCurrentNode() { var node = new Node&lt;T&gt;(); node.SetNextNode(head); while (node.GetNextNode() != myCurrentNode) { node = node.GetNextNode(); } var nextNode = myCurrentNode.GetNextNode(); node.SetNextNode(nextNode); if (head == myCurrentNode) { head = nextNode; } if (tail == myCurrentNode) { tail = node; } myCurrentNode = nextNode; } public bool MoveNext() { var nextNode = myCurrentNode.GetNextNode(); if (nextNode != null) { myCurrentNode = nextNode; return true; } return false; } public void Reset() { myCurrentNode = new Node&lt;T&gt;(); myCurrentNode.SetNextNode(head); } public void Dispose() { myCurrentNode = null; head = null; tail = null; } } </code></pre> <p>Node class.</p> <pre><code>public class Node&lt;T&gt; { private T _value; private Node&lt;T&gt; _nextNode; public Node() { } public T GetValue() { return _value; } public Node(T Value) { _value = Value; } public Node&lt;T&gt; GetNextNode() { return _nextNode; } public void SetNextNode(Node&lt;T&gt; nextNode) { _nextNode = nextNode; } } </code></pre> <p>And three unit tests to check my implementation.</p> <pre><code>public class LinkedListTest { private LinkedList.LinkedList&lt;int&gt; linkedList; private List&lt;int&gt; initialList; [Fact] public void LinkedListCanBeEnumerated() { //arange InitializeLinkedList(100); //act int[] array = new int[100]; int index = 0; while (linkedList.MoveNext()) { array[index++] = (linkedList.Current); } //assert array.ToList().ForEach(i =&gt; initialList.Contains(i).ShouldBe(true)); } private void InitializeLinkedList(int howMany) { linkedList = new LinkedList.LinkedList&lt;int&gt;(); initialList = Enumerable.Range(1, howMany).ToList(); initialList.ForEach(i =&gt; linkedList.Add(i)); } [Fact] public void RemovingCurrentNodeShouldAlterTheList() { //arange InitializeLinkedList(100); //act linkedList.MoveNext(); linkedList.RemoveCurrentNode(); linkedList.Reset(); int[] array = new int[100]; int index = 0; while (linkedList.MoveNext()) { array[index++] = (linkedList.Current); } //assert array.ToList().ForEach(i =&gt; i.ShouldNotBe(1)); } [Fact] public void RemovingTailNodeShouldResultInADifferentTailNode() { //arange InitializeLinkedList(3); //act linkedList.MoveNext(); linkedList.MoveNext(); linkedList.MoveNext(); linkedList.RemoveCurrentNode(); linkedList.Reset(); int[] array = new int[3]; int index = 0; while (linkedList.MoveNext()) { array[index++] = (linkedList.Current); } //assert array.ToList().ForEach(i =&gt; i.ShouldNotBe(3)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T14:23:52.957", "Id": "409496", "Score": "0", "body": "I added a new node in the reset to respect the corect implementation of the IEnumerator interface. Check the Remarks section over here https://docs.microsoft.com/en-us/dotnet/api/system.collections.ienumerator.movenext?view=netframework-4.7.2" } ]
[ { "body": "<h3>Collection != enumerator</h3>\n\n<p>The main problem I see here is that <code>LinkedList&lt;T&gt;</code> implements <code>IEnumerator&lt;T&gt;</code> instead of <code>IEnumerable&lt;T&gt;</code>. That's the wrong interface, which makes this class quite difficult to use: you now have to manually call <code>MoveNext()</code> and <code>Current</code>, instead of being able to use <code>foreach</code>. This also prevents you from using Linq methods, and you can't do simultaneous enumerations.</p>\n\n<p><code>IEnumerable&lt;T&gt;</code> represents a sequence of items that can be enumerated, such as an array, a (linked) list, or the result of a generator method (<code>yield</code>).</p>\n\n<p><code>IEnumerator&lt;T&gt;</code> represents the act of enumeration a collection. Enumerators are rarely used directly - they're usually 'hidden' behind a <code>foreach</code> statement (which calls <code>GetEnumerator</code> on the given enumerable to obtain an enumerator).</p>\n\n<hr>\n\n<p>The above means that <code>myCurrentNode</code> does not belong in this class - it should be part of an enumerator. The same goes for <code>Current</code>, <code>MoveNext</code>, <code>Reset</code> and <code>Dispose</code>.</p>\n\n<p>Regarding <code>RemoveCurrentNode</code>, it's both cumbersome and inefficient. Cumbersome, because you can't just pass the value (or node) that you want to remove as an argument - you have to look for it by enumerating the list. Inefficient, because once you've found the right node, <code>RemoveCurrentNode</code> also has to perform a linear search to find the preceding node.</p>\n\n<p>Take a look at <code>System.Collections.Generic.LinkedList&lt;T&gt;</code> to get some inspiration. It's a doubly linked list, so not all of its methods are applicable in your case, but it should give you an idea of how to play to the strengths of a linked list.</p>\n\n<h3>Other notes</h3>\n\n<ul>\n<li><code>IEnumerator.Reset</code> is essentially deprecated. Enumerating a collection again is done by obtaining a new enumerator. Modern enumerators typically throw an exception in <code>Reset</code>.</li>\n<li>Note that <code>IEnumerable&lt;T&gt;.GetEnumerator</code> is quite easy to implement with <code>yield</code>.</li>\n<li>There's no need to initialize <code>head</code> and <code>tail</code> to <code>null</code> - that's their default value already.</li>\n<li>There's also no need for disposal here - there are no unmanaged resources here that require disposal.</li>\n<li>Why does <code>Node</code> use Java-style get and set methods instead of properties? I'd expect to see <code>public T Value { get; }</code> and <code>public Node&lt;T&gt; NextNode { get; set; }</code>.</li>\n<li>Personally I would handle the <code>head == myCurrentNode</code> edge-case in <code>RemoveCurrentNode</code> without creating an extra node. With or without doesn't make much of a difference in terms of code complexity, so I'd pick the more efficient approach (the one without an extra allocation).</li>\n<li>A <code>LinkedList(IEnumerable&lt;T&gt; collection)</code> constructor would be useful.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T16:38:16.050", "Id": "409667", "Score": "0", "body": "Thank you @Pieter, now I understand the reason behind IEnumerator. I would improve this implementation with a IEnumerable instead." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T15:52:05.900", "Id": "211773", "ParentId": "211760", "Score": "16" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T11:09:27.210", "Id": "211760", "Score": "9", "Tags": [ "c#", "linked-list", "reinventing-the-wheel" ], "Title": "Simple LinkedList" }
211760
<p>I'm wondering if there is any way we can optimize the following code. Scenario is <code>Library</code>'s <code>active</code> field should be <code>true</code> if it has any <code>available</code> book.</p> <pre><code>class Book &lt; ApplicationRecord belongs_to :library scope :available, -&gt; { where.not(deleted: true) } after_commit :update_library_active, on: [:update, :create] def update_library_active self.library.update_active_status end end class Library &lt; ApplicationRecord has_many :books def update_active_status self.update(active: books.available.present?) end end </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T16:21:16.993", "Id": "409518", "Score": "0", "body": "Is the aim here to be able to list all of the libraries that are active, or for an individual library to be able to state whether it is active or not?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T00:50:25.617", "Id": "409560", "Score": "0", "body": "The aim is updating the library `active` attribute based on the associated books." } ]
[ { "body": "<p>A couple of things:</p>\n\n<ul>\n<li><p>I wouldn't do this in the <code>after_commit</code> handler. If you do it before the commit then an error here would cause the whole transaction to fail whereas doing it after committing could potentially result in an inconsistent database.</p></li>\n<li><p>You also want to update the library when a <code>destroy</code> happens which you currently doing. Even though it looks like you are using soft deletion I would consider it a good idea to cover all your bases.</p></li>\n<li><p><code>books.available.exists?</code> usually performs a little better than <code>books.available.present?</code> in this situation. (Because I can almost guarantee from experience that you are going to completely destroy bad data manually for some reason)</p></li>\n<li><p>If you are need to optimize for performance you might want to check <code>if destroyed? || deleted_changed?</code> before running the query. </p></li>\n<li><p>Additionally you could be more intelligent and factor in the value of the <code>deleted</code> flag on the current record. i.e. if it is false then you can make the library active without running a second query. </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T15:01:04.857", "Id": "211812", "ParentId": "211761", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T11:11:57.727", "Id": "211761", "Score": "0", "Tags": [ "ruby", "ruby-on-rails", "callback", "active-record" ], "Title": "Updating one model field based on the associated model's field" }
211761
<p>I am learning to program in Python and as my first project I decided to create a simple Tic Tac Toe game. The game is working properly now and I am wondering if there is anything I could do to improve my code.</p> <p>Notes:</p> <ol> <li><p>In my original code I am using pictures on buttons that allow to choose players, to draw moves and to cross out the winning combination. I have changed this in the code that is posted below to improve reviewer experience.</p></li> <li><p>While posting the code here on code review in noticed that some lines of my code exceed 79 char limit - sorry about that. I hope it won't get in the way too much.</p></li> </ol> <pre><code>import random from tkinter import * from tkinter import ttk def main_window(): root.title('Tic Tac Toe') remove_widgets() global frame frame = ttk.Frame(root, width=250, height=150, relief='groove') frame.pack_propagate(False) frame.pack(padx=25, pady=75) play = ttk.Button(frame, text='Play', command=lambda: play_menu(do=0)) play.pack(side='top', pady=(50, 0)) qb = ttk.Button(frame, text="Quit", command=root.destroy) qb.pack(side='top', pady=(0, 50)) def play_menu(do): root.title('Tic Tac Toe') remove_widgets() if do == 'redeclare': redeclare_vars() global frame label = ttk.Label(root, text='Choose your side', font=('French Script MT', 20)) label.pack(side='top', pady=(25, 0)) frame = ttk.Frame(root, width=250, height=150, relief='groove') frame.pack_propagate(False) frame.pack(padx=25, pady=25) player_x = ttk.Button(frame, text='X', command=lambda: game(pl='X')) player_x.grid(column=0, row=0, padx=(5, 0), pady=(5, 0)) player_o = ttk.Button(frame, text='O', command=lambda: game(pl='O')) player_o.grid(column=1, row=0, padx=(0, 5), pady=(5, 0)) back = ttk.Button(frame, text='Back', command=main_window) back.grid(column=0, row=1, sticky=(E, W), padx=(5, 5), pady=(0, 5), columnspan=2) def game(pl=None): root.title('Tic Tac Toe') remove_widgets() global frame, canvas, player, computer, move, stop_game frame = ttk.Frame(root, width=650, height=700) frame.pack_propagate(False) frame.pack() canvas = Canvas(frame, width=600, height=600) canvas.pack(side='top', pady=(25, 0)) restart = ttk.Button(frame, text='Restart', command=lambda: play_menu(do='redeclare')) restart.pack(side='bottom', pady=20) draw_board() canvas.bind('&lt;Button-1&gt;', square_selector) if pl == 'X': player = 'X' computer = 'O' move = 'player' elif pl == 'O': player = 'O' computer = 'X' move = 'computer' computer_move() def remove_widgets(): for widget in root.winfo_children(): widget.destroy() def square_status_lib(square): global statusLib, player status = None if player == 'X': status = 'X' elif player == 'O': status = 'O' statusLib[square-1] = status def square_selector(event): if 1 &lt;= event.x &lt;= 199: if 1 &lt;= event.y &lt;= 199: player_move(square=1) elif 1 &lt;= event.x &lt;= 199: if 201 &lt;= event.y &lt;= 399: player_move(square=2) elif 1 &lt;= event.x &lt;= 199: if 401 &lt;= event.y &lt;= 599: player_move(square=3) elif 201 &lt;= event.x &lt;= 399: if 1 &lt;= event.y &lt;= 199: player_move(square=4) elif 201 &lt;= event.x &lt;= 399: if 201 &lt;= event.y &lt;= 399: player_move(square=5) elif 201 &lt;= event.x &lt;= 399: if 401 &lt;= event.y &lt;= 599: player_move(square=6) elif 401 &lt;= event.x &lt;= 599: if 1 &lt;= event.y &lt;= 199: player_move(square=7) elif 401 &lt;= event.x &lt;= 599: if 201 &lt;= event.y &lt;= 399: player_move(square=8) elif 401 &lt;= event.x &lt;= 599: if 401 &lt;= event.y &lt;= 599: player_move(square=9) def computer_move(): global move, x1, y1, x2, y2 status, a = 0, 0 while status is not None: a = random.randint(1, 9) status = statusLib[a-1] x1, y1, x2, y2 = squareLib[a - 1][0], squareLib[a - 1][1], squareLib[a - 1][2], squareLib[a - 1][3] if computer == 'X': draw_move() statusLib[a-1] = 'X' elif computer == 'O': draw_move() statusLib[a-1] = 'O' end_game() if not stop_game: move = 'player' def player_move(square): global x1, y1, x2, y2, move, squareLib, stop_game if statusLib[square-1] is None: x1, y1, x2, y2 = squareLib[square-1][0], squareLib[square-1][1], squareLib[square-1][2], squareLib[square-1][3] draw_move() square_status_lib(square=square) end_game() if not stop_game: move = 'computer' computer_move() def draw_move(): global player, x1, y1, x2, y2, canvas, move if move == 'player': if player == 'X': canvas.create_line(x1, y1, x2, y2) canvas.create_line(x1, y2, x2, y1) elif player == 'O': canvas.create_oval(x1, y1, x2, y2) elif move == 'computer': if computer == 'X': canvas.create_line(x1, y1, x2, y2) canvas.create_line(x1, y2, x2, y1) elif computer == 'O': canvas.create_oval(x1, y1, x2, y2) def draw_board(): global canvas canvas.create_line(0, 200, 600, 200) canvas.create_line(0, 400, 600, 400) canvas.create_line(200, 0, 200, 600) canvas.create_line(400, 0, 400, 600) def check_end_game(): global tie, stop_game, fin if statusLib[0] == statusLib[1] == statusLib[2] == 'X' or statusLib[0] == statusLib[1] == statusLib[2] == 'O': stop_game, fin = True, 1 elif statusLib[3] == statusLib[4] == statusLib[5] == 'X' or statusLib[3] == statusLib[4] == statusLib[5] == 'O': stop_game, fin = True, 2 elif statusLib[6] == statusLib[7] == statusLib[8] == 'X' or statusLib[6] == statusLib[7] == statusLib[8] == 'O': stop_game, fin = True, 3 elif statusLib[0] == statusLib[3] == statusLib[6] == 'X' or statusLib[0] == statusLib[3] == statusLib[6] == 'O': stop_game, fin = True, 4 elif statusLib[1] == statusLib[4] == statusLib[7] == 'X' or statusLib[1] == statusLib[4] == statusLib[7] == 'O': stop_game, fin = True, 5 elif statusLib[2] == statusLib[5] == statusLib[8] == 'X' or statusLib[2] == statusLib[5] == statusLib[8] == 'O': stop_game, fin = True, 6 elif statusLib[2] == statusLib[4] == statusLib[6] == 'X' or statusLib[2] == statusLib[4] == statusLib[6] == 'O': stop_game, fin = True, 7 elif statusLib[0] == statusLib[4] == statusLib[8] == 'X' or statusLib[0] == statusLib[4] == statusLib[8] == 'O': stop_game, fin = True, 8 elif all(k is not None for k in statusLib): stop_game, tie, fin = True, True, 0 else: stop_game, fin = False, 0 def end_game(): global stop_game, tie, canvas check_end_game() text = '' if stop_game: canvas.unbind('&lt;Button-1&gt;') if move == 'player' and not tie: text = 'You win' elif move == 'computer' and not tie: text = 'You lose' elif tie: text = 'It\'s a tie' finisher() canvas.create_text(300, 300, text=text, font=('French Script MT', 50), fill='#000000') elif not stop_game: pass def finisher(): global fin x3, y3, x4, y4 = 0, 0, 0, 0 if fin != 0: if fin == 1: x3, y3, x4, y4 = 100, 100, 100, 500 elif fin == 2: x3, y3, x4, y4 = 300, 100, 300, 500 elif fin == 3: x3, y3, x4, y4 = 500, 100, 500, 500 elif fin == 4: x3, y3, x4, y4 = 100, 100, 500, 100 elif fin == 5: x3, y3, x4, y4 = 100, 300, 500, 300 elif fin == 6: x3, y3, x4, y4 = 100, 500, 500, 500 elif fin == 7: x3, y3, x4, y4 = 100, 500, 500, 100 elif fin == 8: x3, y3, x4, y4 = 100, 100, 500, 500 canvas.create_line(x3, y3, x4, y4) elif fin == 0: pass def redeclare_vars(): global statusLib, myVal, x1, x2, y1, y2, canvas, move, fin, stop_game, tie statusLib = [] myVal = None for l in range(0, 9): statusLib.append(myVal) x1, y1, x2, y2, canvas, move, fin = 0, 0, 0, 0, None, '', 0 stop_game, tie = False, False root = Tk() root.minsize(width=300, height=300) statusLib = [] myVal = None for i in range(0, 9): statusLib.append(myVal) x1, y1, x2, y2, canvas, move, fin = 0, 0, 0, 0, None, '', 0 stop_game, tie = False, False game_mode = IntVar() squareLib = [ [20, 20, 180, 180], [20, 220, 180, 380], [20, 420, 180, 580], [220, 20, 380, 180], [220, 220, 380, 380], [220, 420, 380, 580], [420, 20, 580, 180], [420, 220, 580, 380], [420, 420, 580, 580] ] main_window() root.mainloop() </code></pre> <p>I also do have some specific questions about what I could change:</p> <ol> <li><p>I have noticed that many tkinter applications posted on the internet as examples make use of classes. Is there any specific reason to do that? tkinter applications do seem to work fine without that and the code gets shorter without classes.</p></li> <li><p>In my app I am clearing the main tkinter window from any widgets whenever I go to a different menu. It seems a little bit strange to destroy and recreate objects while moving between screens, but I couldn't figure out a different solution. Is my approach a good practice? </p></li> <li><p>Should I create main() function to wrap up all the remaining code at the bottom of the program?</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T15:16:16.037", "Id": "409507", "Score": "0", "body": "Welcome to Code Review. Don't worry about the code exceeding 79 characters, that might get addressed by a reviewer, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T18:20:15.283", "Id": "409533", "Score": "0", "body": "_\"The game is working properly now \"_ - it doesn't seem to work properly for me. It seems to only allow me to click in the top row of boxes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T16:21:47.043", "Id": "409590", "Score": "0", "body": "Oh, thanks for pointing this out Bryan. I have recoded this part before posting (have been using some aditional stuff to be able to resize the game window to my liking) and probably forgot to fix the copy-pasted parts. I'll edit my post asap." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T16:31:26.830", "Id": "409591", "Score": "0", "body": "I fixed the function square_selector and also one place were the indentation was missing. Now the game seems to work fine for me. Looking forward to more comments." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:47:42.600", "Id": "411318", "Score": "0", "body": "I rolled back your last couple edits. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T07:23:37.123", "Id": "411375", "Score": "0", "body": "Ahh, sorry. I will refer to the information you provided when posting further. Thank you @Sᴀᴍ Onᴇᴌᴀ" } ]
[ { "body": "<p>I think I found the problem Bryan Oakley mentionned with the impossibilty to play on any row other than the first one.</p>\n\n<p>The <code>square_selector(event)</code> function is flawed: you check the position of the event by column but you always check for x before EACH y.</p>\n\n<pre><code>if 1 &lt;= event.x &lt;= 199:\n if 1 &lt;= event.y &lt;= 199:\n player_move(square=1)\nelif 1 &lt;= event.x &lt;= 199:\n if 201 &lt;= event.y &lt;= 399:\n player_move(square=2)\nelif 1 &lt;= event.x &lt;= 199:\n if 401 &lt;= event.y &lt;= 599:\n player_move(square=3)\n</code></pre>\n\n<p>But you never reach the <code>elif</code> statements. You should check for an <code>x</code> position, if true -> check EACH <code>y</code> position for that same <code>x</code> position. If the first check for <code>y</code> evaluates false, check the next <code>y</code>, in the same block. Like this :</p>\n\n<pre><code>if 1 &lt;= event.x &lt;= 199:\n if 1 &lt;= event.y &lt;= 199:\n player_move(square=1)\n elif 201 &lt;= event.y &lt;= 399:\n player_move(square=2)\n elif 401 &lt;= event.y &lt;= 599:\n player_move(square=3)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T16:35:52.333", "Id": "409592", "Score": "0", "body": "Yup, you are right @Clepsyd. I changed some things in this function before posting and didn't test it out. Now I changed all elif statments back to if statments in the square_selector() and the game seems to be working properly. Thanks for your note." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T04:47:57.137", "Id": "211798", "ParentId": "211766", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T14:41:11.373", "Id": "211766", "Score": "2", "Tags": [ "python", "beginner", "tic-tac-toe", "tkinter" ], "Title": "Tic Tac Toe game in Python 3.X using tkinter UI" }
211766
<p>I have written a piece of code where I have a simple GUI with an Tkinter Canvas. On this canvas I draw an Matplot. The Matplot is updated every second with fake sensor data i simulate in an SQLite DB (just for testing at the moment).</p> <p>I reached most of my Goals for this test case. But a few Things i would like to have reviewed:</p> <ol> <li>The Performance seems to be not really good. The window is lagging if you drag it over the Desktop. I think this is caused by the redrawing of the Canvas. I tried to use threads but failed to not Interrupt my mainloop while updating the canvas.</li> <li>My Code seems pretty messy (I am a beginner and just learning how to Code in a good style). Every criticism and ideas to make it better are welcome.</li> </ol> <p>So here is my Code so far:</p> <pre><code>from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import tkinter as tk import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import sqlite3 from datetime import datetime from random import randint class MainApplication(tk.Frame): def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent root.update_idletasks() f = Figure(figsize=(15,5), dpi=55) x=1 ax = f.add_subplot(111) line, = ax.plot(x, np.sin(x)) def animate(i): # Open Database conn = sqlite3.connect('Sensor_Data.db') c = conn.cursor() # Create some fake Sensor Data NowIs = datetime.now() Temperature = randint(0, 100) Humidity = randint(0, 100) # Add Data to the Database c = conn.cursor() # Insert a row of data c.execute("insert into Sensor_Stream_1 (Date, Temperature, Humidity) values (?, ?, ?)", (NowIs, Temperature, Humidity)) # Save (commit) the changes conn.commit() # Select Data from the Database c.execute("SELECT Temperature FROM Sensor_Stream_1 LIMIT 30 OFFSET (SELECT COUNT(*) FROM Sensor_Stream_1)-30") # Gives a list of all temperature values x = 1 Temperatures = [] for record in c.fetchall(): Temperatures.append(str(x)+','+str(record[0])) x+=1 # Setting up the Plot with X and Y Values xList = [] yList = [] for eachLine in Temperatures: if len(eachLine) &gt; 1: x, y = eachLine.split(',') xList.append(int(x)) yList.append(int(y)) ax.clear() ax.plot(xList, yList) ax.set_ylim(0,100) ax.set_xlim(1,30) ax.tick_params(axis='both', which='major', labelsize=12) ax.grid(b=None, which='major', axis='both', **kwargs) label = tk.Label(root,text="Temperature / Humidity").pack(side="top", fill="both", expand=True) canvas = FigureCanvasTkAgg(f, master=root) canvas.get_tk_widget().pack(side="left", fill="both", expand=True) root.ani = animation.FuncAnimation(f, animate, interval=1000) if __name__ == "__main__": root = tk.Tk() MainApplication(root).pack(side="top", fill="both", expand=True) root.mainloop() </code></pre> <p>Here is my DB Schema:</p> <pre><code>CREATE TABLE `Sensor_Stream_1` ( `Date` TEXT, `Temperature` INTEGER, `Humidity` INTEGER ); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T15:24:04.510", "Id": "409510", "Score": "0", "body": "What Python version did you write this for and can you share your SQL schema?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T15:36:27.543", "Id": "409512", "Score": "1", "body": "I write this for Python 3.6 (3.6.4 exactly). I never made an SQL Schema, how do i do this?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T16:01:23.300", "Id": "409515", "Score": "1", "body": "It depends a bit on your SQLite manager, but there should be a `database -> export database structure` option (or similar) somewhere." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T16:08:08.980", "Id": "409516", "Score": "1", "body": "I added it to the bottom of my post." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T14:42:57.563", "Id": "211767", "Score": "2", "Tags": [ "python", "performance", "beginner", "gui" ], "Title": "Python Plot showing live SQL data on Tkinter Canvas" }
211767
<p>This code is to gather a sorted list of IDs (first by ID, then by date) recursively from a directory that submitted a particular type of file (that, as you can tell, includes the word "Magic") and then outputs the IDs paired with the modified date (the closest proxy I have for the submission date) to a CSV. (Where I then dedupe by ID to get the earliest submission for each ID/find average number of unique IDs submitted a month over the year/ the total submitted for the year):</p> <pre><code>Get-ChildItem -Recurse -Include *Magic* | Where-Object {$_.lastWriteTime -gt '01/01/2018' -AND $_.lastWriteTime -lt '12/31/2018'} | Select-Object -Property Directory, lastWriteTime | ForEach-Object -Begin { $holder=@{} $results=@() } -Process { $holder.id= [regex]::match($_.Directory,'(\d{8})') $holder.modifiedDate = Get-Date $_.lastWriteTime -Format 'yyyy/MM/dd' $results+=[pscustomobject]$holder } -End { $results } | Sort-Object -Property @{Expression = "id"; Descending = $True;}, @{Expression = "modifiedDate"; Descending = $False} | Export-csv C:\Users\REDACTED\Desktop\REDACTED.csv </code></pre> <p>This is my first attempt at writing something in powershell purely using the command prompt (which is to say, not scripting in the ISE as if it were Ruby using ifs and so forth) How could I have done this better and should I have organized the pipeline differently? I tried to avoid using variables like would have in the past and focused purely on piping the data I was interested in from beginning to end.</p> <p><strong>EDIT</strong></p> <p>Based on the comment I got I made these changes. I wasn't able to get rid of all the pipelines and I haven't been able to test if it's faster or not, but I have a feeling even this version has some garbage that could go.</p> <pre><code>$sourceFiles = Get-ChildItem -Recurse -Include *Magic* $filteredFiles = @() ForEach($file in $sourceFiles){ If($file.LastWriteTime.Year -eq 2018){ $filteredFiles+=[PSCustomObject]@{ Agency = [regex]::match($file.Directory,'(\d{8})') ModifiedDate = Get-Date $file.lastWriteTime -Format 'yyyy/MM/dd' } } } $filteredfiles | Sort-Object -Property @{Expression = "Agency"; Descending = $True;}, @{Expression = "ModifiedDate"; Descending = $False} | Export-csv C:\Users\REDACTED\Desktop\REDACTED.csv -NoTypeInformation </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T02:36:25.253", "Id": "410456", "Score": "0", "body": "i'm curious why you want to do this in such an awkward manner that sacrifices speed for \"one liner! ooo!\". building and tearing down the pipeline adds to the total processing time when there are many objects - it's worth while to sacrifice speed when you need to reduce RAM use, but otherwise, it is generally not sensible. [*grin*] ///// on the improvement side of things, your date test seems to be checking for \"in the year 2018\". you can simplify that by using `$_.LastWriteTime.Year -eq 2018`. otherwise, things seem OK." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T02:40:32.090", "Id": "410457", "Score": "0", "body": "another idea ... your `$Holder` hashtable seems unneeded. plus, it seems likely to give you nearly random property order. just create the items in the `[PSCustomObject]` call. ///// yet another - your `$resutls` collection seems unneeded. simply put the `[PSCustomObject]` call on it's own line to send that to the pipeline." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:46:44.140", "Id": "410822", "Score": "0", "body": "@Lee_Dailey So, should I have done something more like `$sourceFiles = Get-ChildItem -Recurse -Include *Magic*\n$filteredFiles = Where-Object {$sourceFiles.lastWriteTime.Year -eq 2018}` \nand then found a way to get the ordered pairs of directories and dates from the files? I was using the pipeline because I was patterning things after a tutorial I watched, but didn't realize it was the reason everything was so incredibly slow" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T18:25:16.850", "Id": "410841", "Score": "1", "body": "i would replace the `-Include` with `-Filter`, then add `-File` to ensure i only got back files, and last would _explicitly_ indicate the path with either `-LiteralPath` or `-Path`. the 1st will handle embedded `[]` chars, the 2nd allows wildcards. ///// next i would remove the `+=` since adding to arrays is SLOW. simply use `$Result = foreach ($Thing in $Collection)` to assign the whole set of objects to the collection all at once. ///// last i would use a `[PSCustomObject]` for object-building instead of building a new object with `Select-Object`. a PSCO structure is usually easier to read." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:41:19.617", "Id": "412385", "Score": "0", "body": "@Lee_Dailey make an answer using the latter comment. It should comply with OP's request." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T11:42:47.833", "Id": "412386", "Score": "0", "body": "Just curious.. If you want to _get the earliest submission_, why cut off the time part of the `LastWriteTime` datetime property?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T12:50:10.730", "Id": "412390", "Score": "0", "body": "@JosefZ - i will do so. i will need to write something that is a tad different from his since i have no sample data to work with. [*grin*]" } ]
[ { "body": "<p>here is a solution that uses ... </p>\n\n<p><code>-Filter</code> instead of <code>-Include</code><br>\nthis is usually faster since the filtering is done by the provider [the filesystem in this case] instead of by the cmdlet. </p>\n\n<p><code>[PSCustomObject]</code> object construction<br>\nfaster than <code>Select-Object</code> for building custom objects, since it does not require building/tearing-down a pipeline. plus the <code>Select-Object</code> cmdlet has a great deal of complex logic that is not needed here. </p>\n\n<p><code>$AgencyList = foreach ($FL_Item in $FileList)</code> loop assignment<br>\nthis is VASTLY faster than <code>$AgencyList +=</code> for large collections, but only slightly faster for small ones. </p>\n\n<pre><code>$SourceDir = $env:TEMP\n$Filter = '*itunes*'\n$TargetYear = 2019\n$ExportFile = \"$env:TEMP\\jasonmadesomething_AgencyList.csv\"\n\n$GCI_Params = @{\n LiteralPath = $SourceDir\n Filter = $Filter\n File = $True\n Recurse = $True\n }\n$FileList = Get-ChildItem @GCI_Params |\n Where-Object {$_.LastWriteTime.Year -eq $TargetYear}\n\n$AgencyList = foreach ($FL_Item in $FileList)\n {\n [PSCustomObject]@{\n # i don't have any suitable directory info\n # so i used the BaseName of the file\n Agency = $FL_Item.BaseName.Split('.')[0] -replace '^Itunes_', ''\n LastWriteTime = $FL_Item.LastWriteTime\n }\n }\n\n# this gives a list sorted by ...\n# Agency [alfa sorted 'A' to 'Z' and/or '0' to '9']\n# LastWriteTime [oldest 1st]\n$AgencyList = $AgencyList |\n Sort-Object -Property Agency, LastWriteTime\n\n# on screen\n$AgencyList\n\n# to CSV\n$AgencyList |\n Export-Csv -LiteralPath $ExportFile -NoTypeInformation\n</code></pre>\n\n<p>truncated on screen output ... </p>\n\n<pre><code>Agency LastWriteTime \n------ ------------- \nAlbumAutoRating_Disable 2019-01-07 12:22:00 PM\nAlbumAutoRating_Disable 2019-01-14 12:20:36 PM\nAlbumAutoRating_Disable 2019-01-21 12:20:41 PM\nAlbumAutoRating_Disable 2019-01-28 12:22:14 PM\nAlbumAutoRating_Disable 2019-02-04 12:21:55 PM\n[*...snip...*] \nR-PC-SC_Save 2019-01-24 12:38:09 PM\nR-PC-SC_Save 2019-02-07 12:37:53 PM\n</code></pre>\n\n<p>truncated CSV file content ... </p>\n\n<pre><code>\"Agency\",\"LastWriteTime\"\n\"AlbumAutoRating_Disable\",\"2019-01-07 12:22:00 PM\"\n\"AlbumAutoRating_Disable\",\"2019-01-14 12:20:36 PM\"\n\"AlbumAutoRating_Disable\",\"2019-01-21 12:20:41 PM\"\n\"AlbumAutoRating_Disable\",\"2019-01-28 12:22:14 PM\"\n\"AlbumAutoRating_Disable\",\"2019-02-04 12:21:55 PM\"\n[*...snip...*] \n\"R-PC-SC_Save\",\"2019-01-24 12:38:09 PM\"\n\"R-PC-SC_Save\",\"2019-02-07 12:37:53 PM\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T13:07:06.197", "Id": "213188", "ParentId": "211771", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T15:19:55.263", "Id": "211771", "Score": "1", "Tags": [ "object-oriented", "console", "powershell" ], "Title": "Gather list of all IDs ordered by submission date and ID by parsing file path" }
211771
<p>I'm looking to solve the problem of setting the <code>Owner</code> property on modal dialogs in WPF, while using IoC and MVVM patterns. I've seen (and written) all sorts of hacks.</p> <p>To illustrate the problem, here's a naive example of a window with a viewmodel containing an ICommand which prompts the user. It works by having the view set <code>vm.Owner = this</code>, and then the viewmodel using <code>Owner</code> later in a MessageBox when the command is called.</p> <pre><code>public partial class MyWindow : Window { private readonly MyWindowViewModel vm; public MyWindow(MyWindowViewModel vm) { InitializeComponent(); DataContext = vm; vm.Owner = this; } } public class MyWindowViewModel { private readonly RelayCommand&lt;object&gt; fooCommand; public ICommand FooCommand =&gt; fooCommand; public Window Owner { get; set; } public MyWindowViewModel() { fooCommand = new RelayCommand&lt;object&gt;(OnFooCommand); } private void OnFooCommand(object obj) { if (MessageBox.Show(Owner, "Are you sure?", MessageBoxButton.OKCancel) == MessageBoxResult.OK) { // ... } } } </code></pre> <p>This works, but the ViewModel is doing View-related things like opening message boxes, and knowing who owns it.</p> <p>Here's an example that abstracts the dialog into a Func, which is set in the constructor of the Window.</p> <pre><code>public partial class MyWindow : Window { private readonly MyWindowViewModel vm; public MyWindow(MyWindowViewModel vm) { InitializeComponent(); DataContext = vm; vm.OkCancelBox = OkCancelBox; } private MessageBoxResult OkCancelBox(string text) { return MessageBox.Show(this, text, "Confirm", MessageBoxButton.OKCancel, MessageBoxImage.Question); } } public class MyWindowViewModel { private readonly RelayCommand&lt;object&gt; fooCommand; public ICommand FooCommand =&gt; fooCommand; public Func&lt;string, MessageBoxResult&gt; OkCancelBox { get; set; } = s =&gt; throw new NotImplementedException(); public MyWindowViewModel() { fooCommand = new RelayCommand&lt;object&gt;(OnFooCommand); } private void OnFooCommand(object obj) { if (OkCancelBox("Are you sure?") == MessageBoxResult.OK) { // ... } } } </code></pre> <p>This feels better, now my ViewModel calls OkCancelBox and gets back a MessageBoxResult, without knowing anything about the View. If you "forget" to set OkCancelBox, you'll get a NotImplementedException. In a test, I can trivially set the Func to simulate the user clicking "OK":</p> <pre><code>vm.OkCancelBox = s =&gt; MessageBoxResult.OK; </code></pre> <p>Still, I'm not sure I like it.</p> <p>There are other solutions like passing in (or service-locating) an IMessageBoxService, but I don't fully understand how you can specify the owner of a dialog without the ViewModel knowing who owns it.</p> <p>Any thoughts on my implementation using <code>Func&lt;string, MessageBoxResult&gt;</code>?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T16:16:09.800", "Id": "211776", "Score": "2", "Tags": [ "c#", "wpf", "mvvm" ], "Title": "Setting the Owner property on a modal dialog in WPF/MVVM using a Func" }
211776
<h2>Background</h2> <p>The following describes the real world problem that my code is intended to solve. It is may help you understand what the code is doing and why. I don't think this is strictly necessary in order to review the code, so feel free to skip to the section headed "Problem"</p> <p>I have an application that creates a season schedule for a sports league. There are two places where it needs to process all possible combinations of a given number of objects selected from a larger set of objects.</p> <ol> <li>If there are L clubs in the league and T clubs attend each tournament (T &lt; L), process all possible tournaments. This requires selecting all combinations of T objects selected from a set of L objects without repetition (a club is either at a tournament or not, it can't be there twice).</li> <li>If there are S rounds in the season and C possible ways a round can be configured, process all possible seasons. This requires selecting all combinations of S objects selected from a set of C objects with repetition allowed (there can be more than one round with the same configuration in a season).</li> </ol> <p>In both cases I can create a List of the objects to be selected from, so now I only have to deal with the index numbers of the objects in the List (instead of the objects themselves). I intend to process all the possible combinations, so I need a way to iterate over the set of combinations.</p> <h2>Problem</h2> <p>Create a class that implements <code>IEnumerable(Of Integer)</code> that will return all possible combinations of r integers selected from the first n non-negative integers, with the option to allow or disallow repetition. I also want to provide a property that calculates the number of possible combinations. </p> <h2>Code</h2> <pre><code>''' &lt;summary&gt;Represents a set of possible combinations of integers&lt;/summary&gt; &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")&gt; Public Class Combinations Implements IReadOnlyCollection(Of Integer()) Private ReadOnly choose, total As Integer, repetition As Boolean ''' &lt;summary&gt;Create a new Combinations object&lt;/summary&gt; ''' &lt;param name="pick"&gt;Number of items to be picked&lt;/param&gt; ''' &lt;param name="pickfrom"&gt;Number of items to pick from&lt;/param&gt; ''' &lt;param name="allowRepetition"&gt;True if items may be picked more than once&lt;/param&gt; ''' &lt;remarks&gt;'pick' is allowed to be zero, in which case zero combinations will returned&lt;/remarks&gt; Sub New(pick As Integer, pickFrom As Integer, allowRepetition As Boolean) If pick &lt; 0 Then Throw New ArgumentException( "Number of items to pick must be a non-negative integer", "pick") If pickFrom &lt;= 0 Then Throw New ArgumentException( "Number of items to pick from must be a positive integer", "pickFrom") If Not allowRepetition And pick &gt; pickFrom Then Throw New ArgumentException( "Number of items to pick must not exceed the number of items to pick from", "pick") repetition = allowRepetition choose = pick total = pickFrom End Sub ''' &lt;summary&gt;Returns the number of possible values&lt;/summary&gt; ''' &lt;exception cref="OverflowException"&gt;The number of possible values exceeds Integer.MaxValue&lt;/exception&gt; Public ReadOnly Property Count As Integer Implements IReadOnlyCollection(Of Integer()).Count Get Return CInt(LongCount) End Get End Property ''' &lt;summary&gt;Returns the number of possible values&lt;/summary&gt; ''' &lt;exception cref="OverflowException"&gt;The number of possible values exceeds or approaches Long.MaxValue&lt;/exception&gt; ''' &lt;remarks&gt;This replaces the LongCount extension method of IEnumerable which iterates through the entire collection&lt;/remarks&gt; &lt;System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId:="long")&gt; Public ReadOnly Property LongCount As Long Get If choose &lt; 1 Then Return 0 'If choosing 0 combinations, count must be 0 rather than 1 Dim minNumer As Long = If(repetition, total - 1, If(choose &lt; total - choose, total - choose, choose)) Dim maxDenom As Long = If(repetition, choose, If(choose &lt; total - choose, choose, total - choose)) Dim result As Long = 1 For iter As Long = 1 To maxDenom result *= minNumer + iter result \= iter Next Return result End Get End Property ''' &lt;summary&gt;Gets the enumerator that can be used to select each possible value&lt;/summary&gt; Public Iterator Function GetEnumerator() As IEnumerator(Of Integer()) Implements IEnumerable(Of Integer()).GetEnumerator If choose &lt; 1 Then Exit Function 'If choosing 0 combinations, exit without yielding a value Dim value(choose - 1) As Integer If Not repetition Then value = Enumerable.Range(0, choose).ToArray Dim index As Integer = choose - 1 Do Yield value 'Exit if iteration is complete If value(0) = total - If(repetition, 1, choose) Then Exit Do 'Find the rightmost element that can be incremented and increment it Dim oldIndex As Integer = index Do While value(index) = total - If(repetition, 1, choose - index) index -= 1 Loop value(index) += 1 'If index changed, reset all elements to the right of the new index If index &lt;&gt; oldIndex Then Do index += 1 value(index) = value(index - 1) + If(repetition, 0, 1) Loop Until index = choose - 1 End If Loop End Function ''' &lt;summary&gt;Non-generic method required for compatibility&lt;/summary&gt; Private Function GetEnumerator1() As IEnumerator Implements IEnumerable.GetEnumerator Return GetEnumerator() End Function End Class </code></pre> <h2>Request for review</h2> <p>I welcome any suggestions for improving speed of processing or readability of the code, as well as any edge cases I have missed or user interfaces that could be improved. There are also some specific areas where I am not sure I have made the right decision and would certainly appreciate your comments on them:</p> <ol> <li><p>The class implements <code>IReadOnlyCollection(Of Integer)</code> rather than <code>IEnumerable(Of Integer)</code> as the former provides a <code>Count</code> property. The latter has a <code>Count</code> extension method that iterates over the collection to count the items (and so can be slow for large collections), I believe that by implementing <code>IReadOnlyCollection(Of Integer)</code>, I am signalling to the user that my <code>Count</code> property is reasonably efficient.</p></li> <li><p>The number of possible combinations can quickly become very large, so in addition to a <code>Count</code> property that returns an <code>Integer</code>, I provide a <code>LongCount</code> property that returns a <code>Long</code>. In both cases, I allow an <code>OverflowException</code> to be thrown if the number of combinations is too high. I believe that I have ensured that I have avoided any <code>OverflowException</code> in other cases by alternating the multiplication and division operations during the calculations.</p></li> <li><p>I chose to allow the user to specify that zero numbers should be selected (and in that case, the iterator function exits without yielding anything. In my application, the number of items to be picked is calculated and could be zero; treating this as a collection of zero objects works for me, but I'm not sure whether or not that would seem reasonable to another user.</p></li> <li><p>I am forced to implement the non-generic <code>IEnumerable.GetEnumerator</code> function and have done so with the <code>GetEnumerator1</code> function. This looks odd to me, is there a better way of satisfying the requirements of the interface?</p></li> </ol> <h2>Methodology</h2> <p>The code for the <code>LongCount</code> and <code>GetEnumerator</code> methods may seem a little obscure. Here is some information about the methodology</p> <p><strong>LongCount</strong><br> The formula for the number of combinations of r items chosen without repetition from a set of n items is:</p> <p><span class="math-container">$$\frac{n!}{r! (n-r)!}$$</span></p> <p>This is implemented in code as:</p> <p><span class="math-container">$$(r+1) \backslash 1 \times (r+2) \backslash 2 \times (r+3) \backslash 3 \times \cdots \times n \backslash (n-r)$$</span></p> <p>The formula for the number of combinations of r items chosen with repetition from a set of n items is:</p> <p><span class="math-container">$$\frac{(n+r-1)!}{r! (n-1)!}$$</span></p> <p>This is implemented in code as:</p> <p><span class="math-container">$$(r+1) \backslash 1 \times (r+2) \backslash 2 \times (r+3) \backslash 3 \times \cdots \times (n+r-1) \backslash (n-1)$$</span></p> <p>The interesting thing about these sequences is that there is never a remainder in any of the division operations, so I can use integer division (the “<span class="math-container">\$\backslash\$</span>” operator) without losing precision.</p> <p><strong>GetEnumerator</strong><br> The current selection will be stored in an array of integers called <code>value</code>. The integers in <code>value</code> will always be in ascending order. If repetition is allowed, the array is initially all zeros, otherwise it is initialised to the first <code>choose</code> non-negative numbers. An integer called <code>index</code> contains the index of the element of the <code>value</code> array that is currently being incremented; its initial value is <code>choose - 1</code>, the last index of the array.</p> <p>The main part of the method is an infinite loop that <code>Yield</code>s the current <code>value</code> each time round the loop. The rest of the logic is difficult to describe; I'll do so with a simple example where we are picking 3 items from a set of 5.</p> <ul> <li><p>If repetition is allowed, <code>value</code> will initially be {0, 0, 0} and <code>index</code> will be 2. The element at index 2 is incremented each time round the loop until it is the highest it can be and <code>value</code> is {0, 0, 4}. Now <code>index</code> is decremented to 1 and we increment the element at index 1 until it is the highest it can be and <code>value</code> is {0, 4, 4}. Finally <code>index</code> is decremented to 0 and we increment the element at index 0 until it is the highest it can be and <code>value</code> is {4, 4, 4}. </p></li> <li><p>If repetition is not allowed, <code>value</code> will initially be {0, 1, 2} and <code>index</code> will be 2. The element at index 2 is incremented each time round the loop until it is the highest it can be and <code>value</code> is {0, 1, 4}. Now the 2nd element is incremented and the values after that element are reset to the lowest they can be making <code>value</code> {0, 2, 3}. The loop continues incrementing the 3rd element until value is {0, 2, 4}. The 2nd element is incremented again yielding {0, 3, 4}. The 1st element is incremented and the last two elements are set to the lowest they can be yielding {1, 2, 3}. The whole process is repeated yielding {1, 2, 4}, {1, 3, 4}, and {2, 3, 4}.</p></li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-27T15:36:44.097", "Id": "447145", "Score": "0", "body": "Thanks for the edit @dfhwze. It improves the format, but unfortunately the formatting causes the \"\\\" character (integer division operator) to be ignored. I am rolling back the edit. If you know how to escape the \"\\\", I would welcome an updated edit that includes the better formatting and retains the \"\\\" character." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-27T15:41:45.057", "Id": "447146", "Score": "0", "body": "I have no idea how to escape that, sorry." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-27T16:54:12.773", "Id": "447155", "Score": "2", "body": "@dfhwze, for future reference, the online tool \"detexify\" is helpful for finding the right incantation for symbols in TeX. I usually find it by going to math.meta and checking out the community-ads tag." } ]
[ { "body": "<blockquote>\n<pre><code> Public ReadOnly Property Count As Integer Implements IReadOnlyCollection(Of Integer()).Count\n Get\n Return CInt(LongCount)\n</code></pre>\n</blockquote>\n\n<p>Should this be</p>\n\n<pre><code> Return If(LongCount &gt; Integer.MaxValue, Integer.MaxValue, CInt(LongCount))\n</code></pre>\n\n<p>? MSDN doesn't seem to be explicit on what <code>Count</code> should return if the collection has more than <code>MaxValue</code> elements, but I can see some advantage to giving the nearest possible answer rather than the lowest bits.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> Public ReadOnly Property LongCount As Long\n</code></pre>\n</blockquote>\n\n<p>It seems to me that if the number of elements could be so big that you need a <code>LongCount</code> then <code>IEnumerable</code> is not the right interface to implement. At the very least, you need some way to randomly sample elements because you can't count on being able to iterate through all of them in your lifetime.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> If choose &lt; 1 Then Return 0 'If choosing 0 combinations, count must be 0 rather than 1\n</code></pre>\n</blockquote>\n\n<p>This may be appropriate for your use case, but it's non-standard. For general purpose use I would expect it to return the empty set, once.</p>\n\n<hr>\n\n<blockquote>\n<pre><code> Dim minNumer As Long = If(repetition, total - 1, If(choose &lt; total - choose, total - choose, choose))\n Dim maxDenom As Long = If(repetition, choose, If(choose &lt; total - choose, choose, total - choose))\n</code></pre>\n</blockquote>\n\n<p>The nested <code>If</code>s are a bit hard to follow, but I think that this has an optimisation which only applies when <code>Not repetition</code>. IMO it would be worth pulling out a static method which just calculates the binomial coefficient, employing the optimisation, and then this method would be reduced to little more than</p>\n\n<pre><code> return Binomial(If(repetition, total+choose-1, total), choose)\n</code></pre>\n\n<p>Also, I think you can use one fewer auxiliary variable if you reorder the calculation as </p>\n\n<p><span class=\"math-container\">$$n \\backslash 1 \\times (n-1) \\backslash 2 \\times (n-2) \\backslash 3 \\times \\cdots \\times (n-r+1) \\backslash r$$</span></p>\n\n<hr>\n\n<p><code>GetEnumerator()</code> looks fairly clean - I'm a C# user rather than a VB.Net user, and I find it ugly, but I think that's almost entirely VB syntax rather than your code. There is one thing which it would be nice to tidy up if possible:</p>\n\n<blockquote>\n<pre><code> Dim value(choose - 1) As Integer\n If Not repetition Then value = Enumerable.Range(0, choose).ToArray\n</code></pre>\n</blockquote>\n\n<p>I assume that the <code>Dim</code> assigns an array which is then thrown straight in the garbage <code>If Not repetition</code>. If so, can that be avoided?</p>\n\n<hr>\n\n<p>To your specific questions:</p>\n\n<blockquote>\n <ol>\n <li>The class implements <code>IReadOnlyCollection(Of Integer)</code> rather than <code>IEnumerable(Of Integer)</code> as the former provides a <code>Count</code> property. The latter has a <code>Count</code> extension method that iterates over the collection to count the items (and so can be slow for large collections), I believe that by implementing <code>IReadOnlyCollection(Of Integer)</code>, I am signalling to the user that my <code>Count</code> property is reasonably efficient.</li>\n </ol>\n</blockquote>\n\n<p>Yes. Unfortunately, the <code>Enumerable.Count</code> extension method only has a special case for <code>ICollection(Of T)</code>, and not for <code>IReadOnlyCollection(Of T)</code>.</p>\n\n<p>An idea for further extension would be to implement <code>IReadOnlyList(Of Integer())</code> and allow direct indexing. That would be a big step towards what I commented earlier about random selection.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>The number of possible combinations can quickly become very large, so in addition to a <code>Count</code> property that returns an <code>Integer</code>, I provide a <code>LongCount</code> property that returns a <code>Long</code>. In both cases, I allow an <code>OverflowException</code> to be thrown if the number of combinations is too high. I believe that I have ensured that I have avoided any <code>OverflowException</code> in other cases by alternating the multiplication and division operations during the calculations.</li>\n </ol>\n</blockquote>\n\n<p>Perhaps instead of returning a <code>Long</code> it should return a <code>System.Numerics.BigInteger</code>?</p>\n\n<blockquote>\n <ol start=\"3\">\n <li>I chose to allow the user to specify that zero numbers should be selected (and in that case, the iterator function exits without yielding anything. In my application, the number of items to be picked is calculated and could be zero; treating this as a collection of zero objects works for me, but I'm not sure whether or not that would seem reasonable to another user.</li>\n </ol>\n</blockquote>\n\n<p>As noted above, this is not the standard combinatorial interpretation of selecting 0 objects.</p>\n\n<blockquote>\n <ol start=\"4\">\n <li>I am forced to implement the non-generic <code>IEnumerable.GetEnumerator</code> function and have done so with the <code>GetEnumerator1</code> function. This looks odd to me, is there a better way of satisfying the requirements of the interface?</li>\n </ol>\n</blockquote>\n\n<p>I don't know enough about VB syntax to give a definite answer, but I suspect that there isn't a better way.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-27T19:33:24.740", "Id": "447172", "Score": "0", "body": "Thank you for a detailed and useful answer. With regard to the need for `LongCount`, I routinely need to process several billion combinations (it takes a few hours) and a 32-bit integer is not quite big enough." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-28T07:53:16.607", "Id": "447210", "Score": "0", "body": "Added a follow-up thought on `Count`. FWIW my personal rule of thumb is that if I'm going to have to loop over more than about a billion combinatorial objects then I should look for a better algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-28T22:55:06.783", "Id": "447309", "Score": "0", "body": "Hi Peter. The `Cint` function in my current code for the `Count` property throws and arithmetic overflow exception if `LongCount` return a number greater than `Integer.MaxValue` (rather than returning the lower 31/2 bits of `LongCount`)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-28T22:56:42.473", "Id": "447310", "Score": "0", "body": "With regard to needing a better algorithm, I thoroughly agree. In my sports league application, there are about 4*10^50 possible schedules for the season. I use various techniques to whittle this down to several billion, but I continue to look for a better way. It's outside the scope of this stack, but I'm surprised I can't find any algorithms for my problem anywhere (so far)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-27T17:19:27.447", "Id": "229755", "ParentId": "211783", "Score": "3" } } ]
{ "AcceptedAnswerId": "229755", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T18:51:53.850", "Id": "211783", "Score": "4", "Tags": [ ".net", "combinatorics", "vb.net" ], "Title": "Iterating over combinations" }
211783
<p>I am trying to learn Haskell doing some contest problems. I have worked a bit with the language but still have a very long way ahead.</p> <p>Right now I am working with a problem called <a href="https://open.kattis.com/problems/ants" rel="nofollow noreferrer">Ants</a>:</p> <blockquote> <p>An army of ants walk on a horizontal pole of length <em>l</em> cm, each with a constant speed of 1 cm/s. When a walking ant reaches an end of the pole, it immediatelly falls off it. When two ants meet they turn back and start walking in opposite directions. We know the original positions of ants on the pole, unfortunately, we do not know the directions in which the ants are walking. Your task is to compute the earliest and the latest possible times needed for all ants to fall off the pole.</p> <h3>Input</h3> <p>The first line of input contains one integer giving the number of cases that follow, at most 100. The data for each case start with two integer numbers: the length <em>l</em> of the pole (in cm) and <em>n</em>, the number of ants residing on the pole. These two numbers are followed by <em>n</em> integers giving the position of each ant on the pole as the distance measured from the left end of the pole, in no particular order. All input integers are between 0 and 1000000 and they are separated by whitespace.</p> <h3>Output</h3> <p>For each case of input, output two numbers separated by a single space. The first number is the earliest possible time when all ants fall off the pole (if the directions of their walks are chosen appropriately) and the second number is the latest possible such time.</p> <h3>Sample input</h3> <pre><code>2 10 3 2 6 7 214 7 11 12 7 13 176 23 191 </code></pre> </blockquote> <p>It is pretty straight forward, some parsing and minor calculation. My program finished running in 0.69 seconds, while the best result someone achieved with Haskell is something like 0.03! It is very annoying. </p> <p>I have tried to speed it up with some even uglier code, but the best I have managed with this is 0.66 seconds.</p> <p>Can anyone spot some obvious things about this code to improve the runtime?</p> <pre><code>main = do contents &lt;- getContents let cases = parse contents mapM_ putStrLn (map showcase cases) type Case = (Int, [Int]) showcase :: Case -&gt; String showcase (len, positions) = let ds = dists len positions edgiest = (snd . maximum) ds es = max (len - edgiest) edgiest midmost = (snd . minimum) ds mm = min (len - midmost) midmost in show mm ++ " " ++ show es dists :: Int -&gt; [Int] -&gt; [(Float, Int)] dists l = map (\x -&gt; (abs (fromIntegral x - m), x)) where m = fromIntegral l / 2.0 parse :: String -&gt; [Case] parse = parseCases . tail . words -- skip the first integer parseCases :: [String] -&gt; [Case] parseCases [] = [] parseCases xs = let (cs, rest) = parseCase xs in cs : parseCases rest parseCase :: [String] -&gt; (Case, [String]) parseCase (len:a:xs) = let ants = read a positions = (map read . take ants) xs rest = drop ants xs in ((read len, positions), rest) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T19:59:34.870", "Id": "211786", "Score": "3", "Tags": [ "performance", "programming-challenge", "haskell" ], "Title": "Kattis Ants challenge" }
211786
<p><strong>Objective</strong></p> <p>Plot the contour of the iso-doppler and iso-delay lines for a transmitter-receiver reflection on a specular plane.</p> <p><strong>Implementation</strong></p> <p>This Doppler shift can be expressed as follows: <span class="math-container">$$f_{D,0}(\vec{r},t_0) = [\vec{V_t} \cdot \vec{m}(\vec{r},t_0) - \vec{V_r} \cdot \vec{n}(\vec{r},t_0)]/\lambda$$</span></p> <p>where for a given time <span class="math-container">\$t_0\$</span>, <span class="math-container">\$\vec{m}\$</span> is the reflected unit vector, <span class="math-container">\$\vec{n}\$</span> is incident unit vector, <span class="math-container">\$\vec{V_t}\$</span> is the velocity of the transmitter, <span class="math-container">\$\vec{V_r}\$</span> is the velocity of the receiver, and <span class="math-container">\$\lambda\$</span> is the wavelength of the transmitted electromagnetic wave.</p> <p>The time delay of the electromagnetic wave is just the path it travels divided by the speed of light, assuming vacuum propagation. </p> <pre><code>#!/usr/bin/env python import scipy.integrate as integrate import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker h_t = 20000e3 # meters h_r = 500e3 # meters elevation = 60*np.pi/180 # rad # Coordinate Frame as defined in Figure 2 # J. F. Marchan-Hernandez, A. Camps, N. Rodriguez-Alvarez, E. Valencia, X. # Bosch-Lluis, and I. Ramos-Perez, “An Efficient Algorithm to the Simulation of # Delay–Doppler Maps of Reflected Global Navigation Satellite System Signals,” # IEEE Transactions on Geoscience and Remote Sensing, vol. 47, no. 8, pp. # 2733–2740, Aug. 2009. r_t = np.array([0,h_t/np.tan(elevation),h_t]) r_r = np.array([0,-h_r/np.tan(elevation),h_r]) # Velocity v_t = np.array([2121, 2121, 5]) # m/s v_r = np.array([2210, 7299, 199]) # m/s light_speed = 299792458 # m/s delay_chip = 1/1.023e6 # seconds # GPS L1 center frequency is defined in relation to a reference frequency # f_0 = 10.23e6, so that f_carrier = 154*f_0 = 1575.42e6 # Hz # Explained in section 'DESCRIPTION OF THE EMITTED GPS SIGNAL' in Zarotny # and Voronovich 2000 f_0 = 10.23e6 # Hz f_carrier = 154*f_0; def doppler_shift(r): ''' Doppler shift as a contribution of the relative motion of transmitter and receiver as well as the reflection point. Implements Equation 14 V. U. Zavorotny and A. G. Voronovich, “Scattering of GPS signals from the ocean with wind remote sensing application,” IEEE Transactions on Geoscience and Remote Sensing, vol. 38, no. 2, pp. 951–964, Mar. 2000. ''' wavelength = light_speed/f_carrier f_D_0 = (1/wavelength)*( np.inner(v_t, incident_vector(r)) \ -np.inner(v_r, reflection_vector(r)) ) #f_surface = scattering_vector(r)*v_surface(r)/2*pi f_surface = 0 return f_D_0 + f_surface def doppler_increment(r): return doppler_shift(r) - doppler_shift(np.array([0,0,0])) def reflection_vector(r): reflection_vector = (r_r - r) reflection_vector_norm = np.linalg.norm(r_r - r) reflection_vector[0] /= reflection_vector_norm reflection_vector[1] /= reflection_vector_norm reflection_vector[2] /= reflection_vector_norm return reflection_vector def incident_vector(r): incident_vector = (r - r_t) incident_vector_norm = np.linalg.norm(r - r_t) incident_vector[0] /= incident_vector_norm incident_vector[1] /= incident_vector_norm incident_vector[2] /= incident_vector_norm return incident_vector def time_delay(r): path_r = np.linalg.norm(r-r_t) + np.linalg.norm(r_r-r) path_specular = np.linalg.norm(r_t) + np.linalg.norm(r_r) return (1/light_speed)*(path_r - path_specular) # Plotting Area x_0 = -100e3 # meters x_1 = 100e3 # meters n_x = 500 y_0 = -100e3 # meters y_1 = 100e3 # meters n_y = 500 x_grid, y_grid = np.meshgrid( np.linspace(x_0, x_1, n_x), np.linspace(y_0, y_1, n_y) ) r = [x_grid, y_grid, 0] z_grid_delay = time_delay(r)/delay_chip z_grid_doppler = doppler_increment(r) delay_start = 0 # C/A chips delay_increment = 0.5 # C/A chips delay_end = 15 # C/A chips iso_delay_values = list(np.arange(delay_start, delay_end, delay_increment)) doppler_start = -3000 # Hz doppler_increment = 500 # Hz doppler_end = 3000 # Hz iso_doppler_values = list(np.arange(doppler_start, doppler_end, doppler_increment)) fig_lines, ax_lines = plt.subplots(1,figsize=(10, 4)) contour_delay = ax_lines.contour(x_grid, y_grid, z_grid_delay, iso_delay_values, cmap='winter') fig_lines.colorbar(contour_delay, label='C/A chips', ) contour_doppler = ax_lines.contour(x_grid, y_grid, z_grid_doppler, iso_doppler_values, cmap='winter') fig_lines.colorbar(contour_doppler, label='Hz', ) ticks_y = ticker.FuncFormatter(lambda y, pos: '{0:g}'.format(y/1000)) ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/1000)) ax_lines.xaxis.set_major_formatter(ticks_x) ax_lines.yaxis.set_major_formatter(ticks_y) plt.xlabel('[km]') plt.ylabel('[km]') plt.show() </code></pre> <p>Which produces this presumably right output:</p> <p><a href="https://i.stack.imgur.com/vr9fN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vr9fN.png" alt="enter image description here"></a></p> <p>Please feel free to provide recommendations about the implementation and style. </p> <p><strong>Questions</strong></p> <p>In order to compute the incident vector from a point <span class="math-container">\$r_t\$</span> I've implemented the following code:</p> <pre><code>def incident_vector(r): incident_vector = (r - r_t) incident_vector_norm = np.linalg.norm(r - r_t) incident_vector[0] /= incident_vector_norm incident_vector[1] /= incident_vector_norm incident_vector[2] /= incident_vector_norm return incident_vector </code></pre> <p>This works perfectly fine, but I think there must be a cleaner way to write this. I would like to write something like this:</p> <pre><code>def incident_vector(r): return (r - r_t)/np.linalg.norm(r - r_t) </code></pre> <p>But unfortunately it doesn't work with the meshgrid, as it doesn't know how to multiply the scalar grid with the vector grid:</p> <pre><code>ValueError: operands could not be broadcast together with shapes (3,) (500,500) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T21:09:57.253", "Id": "409549", "Score": "0", "body": "@Edward. How do you add the Latex formatting?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T21:11:59.663", "Id": "409550", "Score": "0", "body": "https://codereview.stackexchange.com/editing-help#latex" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-18T20:18:40.843", "Id": "211787", "Score": "3", "Tags": [ "python", "numpy" ], "Title": "Computing Doppler delay on a meshgrid" }
211787
<p>I was wondering if I could get some input on how to make my code more concise, since I think in particular with the force simulation sections I have some repetition. And any other input to make my code more readable would be great. I have a mixing of jQuery and D3 but that is just a quick demo for putting some working code together since there is a lot more to the final visualization, and it doesn't actually use jQuery.</p> <p>This code basically creates a force simulation using D3, reads in data (on sharks), and at first the nodes are sized based on the size of the shark and the nodes are clustered based on shark families. If the user clicks on the "Greenland shark" button then only the node with the <code>common_name</code> property "Greenland Shark" would be visible. And if the user clicks on the button "Sharks by family" then all the nodes would appear again clustered by family.</p> <p><a href="https://plnkr.co/edit/pBPJUhEKQIPnB0ammGDd?p=info" rel="nofollow noreferrer">Plnkr</a></p> <pre><code> var margin = { top: 50, right: 50, bottom: 20, left: 50 }; var width = 1200 - 300 - margin.left - margin.right; var heightInitial = 700; var height = heightInitial - margin.top - margin.bottom; var svg = d3.select("#graph") .style("width", width + margin.left + margin.right + "px") .append("svg") .style("width", width + margin.left + margin.right + "px") .style("height", height + margin.top + margin.bottom + "px") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom).attr("class", "svg") var g = svg.append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); var forceStrength = 0.03; var colorScale = d3.scaleOrdinal() .range(['#450303', '#6e0505', '#951f1f', '#d09b9b', '#ad5151', '#e7cdcd', '#b30000', '#e34a33' ]) var familyXScale = d3.scaleOrdinal() .range([width * 0.2, width * 0.4, width * 0.55, width * 0.7, width * 0.8, width * 0.9 ]); var familyYScale = d3.scaleOrdinal() .range([height * 0.2, height * 0.4, height * 0.55, height * 0.7, height * 0.8, height * 0.9 ]); var yPositionScale = d3.scaleLinear() .domain([1, 50]) .range([height / 2 - 50, height / 2 + 50]) var center = { x: (width + margin.left + margin.right) / 2, y: (height + margin.top + margin.bottom) / 2 }; var radiusScale = d3.scaleSqrt() .range([0, 1]) d3.queue() .defer(d3.csv, "./data2.csv") .await(ready) function ready(error, nodes) { var families = d3.map(nodes, function(d) { return d.family }).keys(); var sharks = nodes.map(function(d) { return d.name }); var indexarray = [...Array(families.length).keys()]; var mapIndex = d3.scaleOrdinal().domain(families).range(indexarray); colorScale .domain(families) familyXScale .domain(families) var simulation = d3.forceSimulation(); simulation.force('x', d3.forceX(function(d) { var i = mapIndex(d.family); return xposition(i) }).strength(0.03)) .force('y', d3.forceY(function(d) { var i = mapIndex(d.family); return yposition(i) }).strength((0.03))) .force('collide', d3.forceCollide(function(d) { return radiusScale(+d.size) })).velocityDecay(0.1).alphaDecay(0.001); var circles = g.selectAll(".sharks") .data(nodes) .enter().append("circle") .attr("class", "sharks") .attr("r", function(d) { return radiusScale(+d.size) }) .attr("fill", function(d) { return colorScale(d.family) }) .attr('stroke', '') simulation.nodes(nodes) .on('tick', ticked); nodes.forEach(function(d) { d.x = familyXScale(d.family) d.y = yPositionScale(sharks.indexOf(d.name)) }) function ticked() { circles .attr("cx", function(d) { return d.x }) .attr("cy", function(d) { return d.y }) } function charge(d) { return -Math.pow(d.radius, 2.0) * forceStrength; } $("#greenlandshark").on('click', function() { greenlandShark(); }) $("#sharksbyfamily").on('click', function() { sharksByFamilyRev(); }) function sharksByFamilyRev() { circles = g.selectAll(".sharks").data(nodes); circles.exit().transition().duration(750) .attr("r", 0) .remove(); circles.transition().duration(750) .attr("fill", function(d) { return colorScale(d.family) }).attr("r", function(d) { return radiusScale(+d.size); }) circles = circles.enter().append("circle").attr("class", "sharks") .attr("fill", function(d) { return colorScale(d.family) }).attr("r", function(d) { return radiusScale(+d.size); }) .attr('stroke', '') .merge(circles); simulation.force('x', d3.forceX(function(d) { var i = mapIndex(d.family); return xposition(i) }).strength(0.03)) .force('y', d3.forceY(function(d) { var i = mapIndex(d.family); return yposition(i) }).strength((0.03))) .force('collide', d3.forceCollide(function(d) { return radiusScale(+d.size) })).velocityDecay(0.1).alphaDecay(0.001); simulation.nodes(nodes) .on('tick', ticked); simulation.alpha(1).restart(); } function greenlandShark() { var newNodes = filterNodes('common_name', 'Greenland shark'); circles = g.selectAll(".sharks").data(newNodes); circles.exit() .transition() .duration(1000) .attr("r", 0) .remove(); circles .attr('r', function(d) { return radiusScale(+d.size) }) .attr('fill', function(d) { return colorScale(d.family) }); simulation.nodes(newNodes) .on('tick', ticked); simulation.force('x', d3.forceX().strength(0.03).x(center.x)) .force('y', d3.forceY(function(d) { return height / 2 }).strength((0.03))); simulation.alpha(1).restart(); } function filterNodes(key, group) { var newnodes = nodes.filter(function(d) { return d[key] == group; }); return newnodes; } } function xposition(i) { if (i % 6 == 0) { return width * 0.2 } else if (i % 6 == 1) { return width * 0.4 } else if (i % 6 == 2) { return width * 0.55 } else if (i % 6 == 3) { return width * 0.7 } else if (i % 6 == 4) { return width * 0.8 } else { return width * 0.9 } } function yposition(i) { if (i &gt;= 0 &amp;&amp; i &lt;= 5) { return width * 0.2 } else if (i &gt;= 6 &amp;&amp; i &lt;= 11) { return width * 0.4 } else if (i &gt;= 12 &amp;&amp; i &lt;= 17) { return width * 0.55 } else if (i &gt;= 18 &amp;&amp; i &lt;= 23) { return width * 0.7 } else if (i &gt;= 24 &amp;&amp; i &lt;= 29) { return width * 0.8 } else { return width * 0.9 } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T03:43:16.960", "Id": "211795", "Score": "1", "Tags": [ "javascript", "d3.js" ], "Title": "D3v4 force layout transition from clustered layout to one node" }
211795
<p>I started studying JavaScript about a week ago and I would like some opinions and advice on my code. This program just creates a canvas and instantiates 5 planets that orbit around a sun, giving them each a different speed, color, and size.</p> <p>It uses the <strong>p5.js</strong> library, the code can be run in the <a href="https://editor.p5js.org/" rel="nofollow noreferrer">p5.js web editor</a>. (You might want to expand the preview panel on the right after pasting the code, before you run the script.)</p> <p>The code is in different files (class <code>Orbiter</code>, extra math functions and main code) but I'll put it here in one go:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>// Converts from degrees to radians. Math.radians = function(degrees) { return degrees * Math.PI / 180; }; // Converts from radians to degrees. Math.degrees = function(radians) { return radians * 180 / Math.PI; }; class Orbiter { constructor(rad, orbitAlt, x = 0, y = 0, orbitAngle = 0, orbitAngleMod = 1, colorR=255, colorG=255, colorB=255, colorA=255){ this.orbitAngle = orbitAngle; // Angle formed by the radius of the orbit and the x plane. this.orbitAngleMod = orbitAngleMod; // Increment/decrement of orbitAngle this.rad = rad; // Radius this.orbitAlt = orbitAlt; // Distance to the orbited object's position (Alt for altitude) // Position this.x = x; this.y = y; // Color variables this.colorR = colorR; this.colorG = colorG; this.colorB = colorB; this.colorA = colorA; } orbit(object){ this.x = object.x + this.orbitAlt * cos(Math.radians(this.orbitAngle)); this.y = object.y + this.orbitAlt * sin(Math.radians(this.orbitAngle)); this.orbitAngle = this.orbitAngle + this.orbitAngleMod; // Reset the angle to 0 after a complete revolution to avoid an ever increasing value. if(this.orbitAngle &gt;= 360){ this.orbitAngle = 0; } } display(){ noStroke(); fill(this.colorR, this.colorG, this.colorB, this.colorA); return ellipse(this.x, this.y, this.rad, this.rad); } } let planets = []; let sun = new Orbiter(100, 0); function setup(){ createCanvas(windowWidth-3, windowHeight-3); frameRate(144); // Set up the Sun's colors and coordinates sun.colorR = 255; sun.colorG = 200; sun.colorB = 0; sun.x = windowWidth/2; sun.y = windowHeight/2; // Instantiate 5 planets for(i = 0; i &lt; 5; i++){ planets[i] = new Orbiter(5 + i * 15, 110 + i*70); planets[i].orbitAngleMod= 1.4 - i/7; planets[i].orbitAngle= i*5; planets[i].colorR = i * 50 + 5; planets[i].colorG = 255 - planets[i].colorR; planets[i].colorB = 255 - planets[i].colorR; } } function draw(){ background(0, 10, 40); for(planet of planets){ planet.orbit(sun); planet.display(); sun.display() } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js"&gt;&lt;/script&gt;</code></pre> </div> </div> </p> <p>I'd be really grateful if you could give me some feedback on the structure of my code, whether it's in line with JavaScript best practices, or in general if there's anything you see in there that you think is just wrong or should be written in a different way.</p>
[]
[ { "body": "<p>Looks fine for me. But I'm no JS expert. ;)</p>\n\n<p>One thing that \"jumps\" me:</p>\n\n<pre><code>if(this.orbitAngle &gt;= 360){\n this.orbitAngle = 0;\n}\n</code></pre>\n\n<p>Instead I'd do:</p>\n\n<pre><code>while (this.orbitAngle&gt;360) this.orbitAngle-=360;\nwhile (this.orbitAngle&lt;0) this.orbitAngle+=360;\n</code></pre>\n\n<p>Would be nice if you could provide a playground like jsfiddle.</p>\n\n<p>@Jamal asked me to edit:</p>\n\n<ul>\n<li>Your code misses the case when orbitAngles are decreasing.</li>\n<li>If the orbitAngle goes over 360 you set it to 0 but that might be incorrect. What if you get an orbitAngle of 365.1? Setting it to 0 is wrong because 5.1 would be the correct value. Same applies for decreasing values. -5.9 should become 350.1 and not something like 360.</li>\n</ul>\n\n<p>That is why I suggested a version where you correct the value by adding/substracting 360.</p>\n\n<p>And if somebody abuses the code and enters very high values to change the angle you might end up with orbitAngle>720 so substracting 320 would not be enough.</p>\n\n<p>Another suggestion might be to use modulo - now that I think about it. ;)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T02:54:24.077", "Id": "212036", "ParentId": "211796", "Score": "2" } }, { "body": "<p>Some of the lines are indented with four spaces and some are indented with eight spaces - pick one of the other and keep it consistent.</p>\n\n<hr>\n\n<p>The <code>display</code> method has a <code>return</code> statement but the only place that method is called (which is within the <code>draw()</code> function) doesn't utilize any return value, so the <code>return</code> is pointless. Did you intend to use that value in another place that method was to be called?</p>\n\n<hr>\n\n<p>The helper functions defined on <code>Math</code> could have more appropriate names that would be self-describing, and thus might eliminate the need for the comments above each one. For example, instead of <code>radians</code>, <code>radiansFromDegrees</code> or <code>degreesToRadians</code> would be self-explanatory. Similarly, <code>degreesFromRadians</code> or <code>radiansFromDegrees</code> would be more appropriate than just <code>degrees</code>.</p>\n\n<hr>\n\n<p>The variable <code>i</code> in the <code>for</code> loop of <code>setup()</code> is not declared with any block-level scope, which makes it accessible elsewhere in the <code>setup</code> method. This could unintentional consequences - e.g. if another <code>for</code> loop was needed and used a variable with the same name. It would be wise to narrow the scope with <code>let</code>:</p>\n\n<pre><code>for(let i = 0; i &lt; 5; i++){\n</code></pre>\n\n<p>The same is true for the <code>for...of</code> statement in the <code>draw()</code> function:</p>\n\n<blockquote>\n<pre><code>for(planet of planets){\n</code></pre>\n</blockquote>\n\n<p>The scope of <code>planet</code> can be limited with <code>let</code>:</p>\n\n<pre><code>for(let planet of planets){\n</code></pre>\n\n<hr>\n\n<p>Looking at the <code>setup</code> function I see it is 22 lines - that is a bit on the long side. Perhaps it would be wise to break it up by splitting out the blocks that set the sub attributes and create the planets. </p>\n\n<p>I wouldn't expect a beginner to think of this, but the block to create the planets could be moved out to a function to be used with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>Array.prototype.map()</code></a>:</p>\n\n<pre><code>function createPlanet(value, i) { \n const planet = new Orbiter(5 + i * 15, 110 + i*70);\n planet.orbitAngleMod= 1.4 - i/7;\n planet.orbitAngle= i*5;\n\n planet.colorR = i * 50 + 5;\n planet.colorG = 255 - planet.colorR;\n planet.colorB = 255 - planet.colorR;\n return planet;\n}\n</code></pre>\n\n<p>That way, when declaring the <code>planets</code> array, it can be combined with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill\" rel=\"nofollow noreferrer\"><code>Array.prototype.fill()</code></a></p>\n\n<pre><code>const planets = new Array(5).fill(1).map(createPlanet);\n</code></pre>\n\n<hr>\n\n<p>This <code>for</code> block at the end of <code>draw()</code> has interesting indentation:</p>\n\n<blockquote>\n<pre><code>for(planet of planets){\n planet.orbit(sun);\n planet.display();\nsun.display()\n}\n</code></pre>\n</blockquote>\n\n<p>Why not indent the last line within the block (i.e. <code>sun.display()</code>)? Maybe it was just a copy-paste inconsistency... Actually, why display the sun being displayed within the loop? it doesn't move so can just be displayed once. I'm not very familiar with p5.js but if there is a structure callback for initial draw, that call to display the sun could be moved there. </p>\n\n<hr>\n\n<p>Because <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> keywords like <code>let</code> are used, other es-6 keywords/features could be used:</p>\n\n<ul>\n<li><strong><code>const</code> keyword</strong> - for variables that don't get re-assigned (e.g. <code>planets</code>, <code>sun</code>). This can help prevent unintentional re-assignment</li>\n<li><p><strong>arrow functions</strong> - e.g. the math functions could be shortened with this syntax:</p>\n\n<pre><code>// Converts from degrees to radians.\nMath.radians = degrees =&gt; degrees * Math.PI / 180;\n\n// Converts from radians to degrees.\nMath.degrees = radians =&gt; radians * 180 / Math.PI;\n</code></pre></li>\n</ul>\n\n<h3>Rerwrite</h3>\n\n<p>Here is updated code, using the advice above</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"false\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>// Converts from degrees to radians.\nMath.radians = degrees =&gt; degrees * Math.PI / 180;\n\n// Converts from radians to degrees.\nMath.degrees = radians =&gt; radians * 180 / Math.PI;\n\n\nclass Orbiter {\n\n constructor(rad, orbitAlt, x = 0, y = 0, orbitAngle = 0, orbitAngleMod = 1, colorR=255, colorG=255, colorB=255, colorA=255){\n this.orbitAngle = orbitAngle; // Angle formed by the radius of the orbit and the x plane.\n this.orbitAngleMod = orbitAngleMod; // Increment/decrement of orbitAngle\n this.rad = rad; // Radius\n this.orbitAlt = orbitAlt; // Distance to the orbited object's position (Alt for altitude)\n\n // Position\n this.x = x;\n this.y = y;\n\n // Color variables\n this.colorR = colorR;\n this.colorG = colorG;\n this.colorB = colorB;\n this.colorA = colorA;\n }\n\n orbit(object){\n this.x = object.x + this.orbitAlt * cos(Math.radians(this.orbitAngle));\n this.y = object.y + this.orbitAlt * sin(Math.radians(this.orbitAngle));\n this.orbitAngle = this.orbitAngle + this.orbitAngleMod;\n\n // Reset the angle to 0 after a complete revolution to avoid an ever increasing value.\n if(this.orbitAngle &gt;= 360){\n this.orbitAngle = 0;\n }\n }\n\n display(){\n noStroke();\n fill(this.colorR, this.colorG, this.colorB, this.colorA);\n ellipse(this.x, this.y, this.rad, this.rad);\n }\n}\n\nconst planets = new Array(5).fill(1).map(createPlanet);\nconst sun = new Orbiter(100, 0);\n\nfunction setup(){\n createCanvas(windowWidth-3, windowHeight-3);\n frameRate(144);\n\n // Set up the Sun's colors and coordinates\n sun.colorR = 255;\n sun.colorG = 200;\n sun.colorB = 0;\n sun.x = windowWidth/2;\n sun.y = windowHeight/2;\n}\nfunction createPlanet(value, i) { \n const planet = new Orbiter(5 + i * 15, 110 + i*70);\n planet.orbitAngleMod= 1.4 - i/7;\n planet.orbitAngle= i*5;\n\n planet.colorR = i * 50 + 5;\n planet.colorG = 255 - planet.colorR;\n planet.colorB = 255 - planet.colorR;\n return planet;\n}\nfunction draw(){\n background(0, 10, 40);\n\n sun.display() //move to other draw method that is only called once?\n for(let planet of planets){ \n planet.orbit(sun);\n planet.display();\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js\"&gt;&lt;/script&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-25T12:36:53.903", "Id": "414274", "Score": "0", "body": "The mixed indent *might* be caused by a mix of spaces and tabs in the source (remember that SE converts to spaces using tab stops at four-char intervals). It's still something that ought to be consistent; I'm just mentioning this because it's something that might not be easily visible to the asker." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-03T12:45:55.207", "Id": "415061", "Score": "0", "body": "Just double-checked with my original file and yes, my code was originally indented consistently, but copy/pasting it here threw it all over the place :) I tried to correct what I could but evidently didn't find all the mistakes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-22T17:38:11.173", "Id": "214050", "ParentId": "211796", "Score": "2" } }, { "body": "<h2>Use of p5.js and JavaScript</h2>\n\n<p><code>Math</code> is part of the standard JavaScript library. You shouldn't pollute its namespace with your own code, because it could interfere with other JavaScript code on the page. In this case, <code>Math.degrees()</code> is never used, and you could just use p5.js's <a href=\"http://p5js.org/reference/#/p5/radians\" rel=\"nofollow noreferrer\"><code>radians()</code></a> function instead of writing <code>Math.radians()</code>.</p>\n\n<p>The constructor for <code>Orbiter</code> is very unwieldy, with up to 10 parameters. You can just eliminate most of them. Furthermore, you should specify colors as a single <a href=\"http://p5js.org/reference/#/p5.Color\" rel=\"nofollow noreferrer\">p5.Color</a> object rather than as four separate parameters.</p>\n\n<p>There should be a <code>windowResized()</code> handler, so that the window (or the Stack Snippet) can be resized gracefully.</p>\n\n<h2>Physics and animation</h2>\n\n<p>The object around which a satellite orbits is called its <a href=\"https://english.stackexchange.com/q/123813/16310\">primary</a>. I suggest that you name the parameter to the <code>orbit()</code> method accordingly.</p>\n\n<p>Your planets' angular velocity is given by <code>planets[i].orbitAngleMod= 1.4 - i/7</code>, which is <strong>not consistent with the laws of physics</strong>. According to <a href=\"https://en.wikipedia.org/wiki/Kepler%27s_laws_of_planetary_motion#Third_law_of_Kepler\" rel=\"nofollow noreferrer\">Kepler's Third Law</a>, <span class=\"math-container\">\\$T^2 \\propto r^3\\$</span> (where <span class=\"math-container\">\\$T\\$</span> and <span class=\"math-container\">\\$r\\$</span> are the orbital period and radius), so <span class=\"math-container\">\\$\\omega \\propto r^{-\\frac{3}{2}}\\$</span>. So, your inner planets are not as fast as they should be, and your outer planets are not as slow as they should be.</p>\n\n<p>Handling the revolution completion with <code>if(this.orbitAngle &gt;= 360){ this.orbitAngle = 0; }</code> can lead to round-off glitches. A modulo operation would be more appropriate.</p>\n\n<p>I don't see the point of initializing the initial angles of the planets to <code>i * 5</code> — an offset of up to 4° relative to the x axis is hardly visible.</p>\n\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>class Orbiter {\n constructor(sizeRadius, orbitRadius, orbitAngle=0) {\n this.sizeRadius = sizeRadius;\n this.orbitRadius = orbitRadius;\n this.orbitAngle = 0; // degrees relative to x axis\n\n // 2000 is an arbitrary animation speed (which also depends on the frame rate)\n // The -1.5 exponent is due to Kepler's 3rd Law\n this.orbitAngleDelta = 2000 * Math.pow(orbitRadius, -1.5);\n this.x = this.y = 0;\n this.color = 'white';\n }\n\n orbit(primary) {\n this.x = primary.x + this.orbitRadius * cos(radians(this.orbitAngle));\n this.y = primary.y + this.orbitRadius * sin(radians(this.orbitAngle));\n this.orbitAngle = (this.orbitAngle + this.orbitAngleDelta) % 360;\n }\n\n display() {\n noStroke();\n fill(this.color);\n return ellipse(this.x, this.y, this.sizeRadius, this.sizeRadius);\n }\n}\n\nlet planets = [];\nlet sun = new Orbiter(100, 0);\n\nfunction setup() {\n createCanvas(windowWidth - 3, windowHeight - 3);\n frameRate(144);\n\n sun.x = windowWidth / 2;\n sun.y = windowHeight / 2;\n sun.color = color(255, 200, 0);\n\n // Instantiate 5 planets\n for (i = 0; i &lt; 5; i++) {\n planets[i] = new Orbiter(5 + 15 * i, 110 + 70 * i);\n let red = i * 50 + 5;\n planets[i].color = color(red, 255 - red, 255 - red);\n }\n}\n\nfunction windowResized() {\n resizeCanvas(windowWidth - 3, windowHeight - 3);\n sun.x = windowWidth / 2;\n sun.y = windowHeight / 2;\n}\n\nfunction draw() {\n background(0, 10, 40);\n sun.display()\n for (planet of planets) {\n planet.orbit(sun);\n planet.display();\n }\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.js\"&gt;&lt;/script&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": "2019-02-22T22:03:35.133", "Id": "214069", "ParentId": "211796", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T03:57:59.180", "Id": "211796", "Score": "4", "Tags": [ "javascript", "beginner", "object-oriented", "ecmascript-6", "animation" ], "Title": "Basic orbiting planets in P5.js" }
211796
<p>I am currently developing a Bullet Hell (shoot-em-up) game for my school project.<br> I have implemented Object Pooling for my game to recycle mainly bullets. (Though I could use it to recycle enemies in the future if I do need to.)</p> <p>Currently I have tested this object pooling on bullet and it has worked.<br> I am looking to receive feedback about my code in order to see if I can do anything about it to make it more efficient and cleaner.</p> <p><strong>ObjectPool.cs</strong></p> <pre><code>using System; using System.Collections.Generic; using UnityEngine; using System.Linq; public class ObjectPool : Singleton&lt;ObjectPool&gt; { private List&lt;GameObject&gt; objectPool; private void Awake() { objectPool = new List&lt;GameObject&gt;(); } /// &lt;summary&gt; /// Add a gameobject to the object pool. /// &lt;/summary&gt; /// &lt;param name="objToPool"&gt;The gameobject to add to the object pool.&lt;/param&gt; /// &lt;param name="deactivateObj"&gt;Deactivate this gameobject upon storing into the object pool.&lt;/param&gt; public void AddToPool(GameObject objToPool, bool deactivateObj = true) { objectPool.Add(objToPool); // If we need to deactivate this gameobject. if (deactivateObj) { // Set it to not active. objToPool.SetActive(false); } } /// &lt;summary&gt; /// Fetch a gameobject from the pool, with the gameobject containing the desired component. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the component.&lt;/typeparam&gt; /// &lt;param name="removeFromPool"&gt;True if the fetched gameobject needs to be removed from the pool.&lt;/param&gt; /// &lt;returns&gt;The respective gameobject. (Null if none is found)&lt;/returns&gt; public GameObject FetchObjectByComponent&lt;T&gt;(bool removeFromPool = true) where T : MonoBehaviour { GameObject fetchedObject = null; // Foreach game object in the object pool foreach (var gameObj in objectPool) { // If this gameobject has the desired component. if (gameObj.GetComponent&lt;T&gt;() != null) { // Fetch this object. fetchedObject = gameObj; // End loop (an object with the desired component is found.) break; } } // If an object is fetched and we need to remove it from the pool. if (fetchedObject != null &amp;&amp; removeFromPool) { // Remove the fetched object from the pool. objectPool.Remove(fetchedObject); } return fetchedObject; } /// &lt;summary&gt; /// Fetch an array of gameobjects that contains the desired component. /// &lt;/summary&gt; /// &lt;typeparam name="T"&gt;The type of the component the gameobject must contain.&lt;/typeparam&gt; /// &lt;param name="maxSize"&gt;The max size of the array returned. (Negative for limitless)&lt;/param&gt; /// &lt;param name="removeFromPool"&gt;True to remove the respective fetched gameobject from the object pool.&lt;/param&gt; /// &lt;returns&gt;The respective fetched game objects.&lt;/returns&gt; public GameObject[] FetchObjectsByComponent&lt;T&gt;(int maxSize = -1, bool removeFromPool = true) where T : MonoBehaviour { List&lt;GameObject&gt; temp = new List&lt;GameObject&gt;(); // Loop through the object pool as long as the size limit it not reached. for (int i = 0; i &lt; objectPool.Count &amp;&amp; i &lt; maxSize; ++i) { // If this current object contains the desired component. if (objectPool[i].GetComponent&lt;T&gt;() != null) { // Add to the temporary list temp.Add(objectPool[i]); } } var fetchedObjects = temp.ToArray(); // If we need to remove the fetched objects from the object pool, remove. if (removeFromPool) { RemoveObjectsFromPool(fetchedObjects); } return fetchedObjects; } /// &lt;summary&gt; /// Fetch an array of gameobject based on the given condition. /// &lt;/summary&gt; /// &lt;param name="condition"&gt;The condition to check on when fetching gameobjects.&lt;/param&gt; /// &lt;param name="maxSize"&gt;The maximum size of the array returned. (Negative for limitless.)&lt;/param&gt; /// &lt;param name="removeFromPool"&gt;True to remove the respective fetched gameobject from the object pool.&lt;/param&gt; /// &lt;returns&gt;The respective fetched game objects.&lt;/returns&gt; public GameObject[] FetchObjectsByCondition(Func&lt;GameObject, bool&gt; condition, int maxSize = -1, bool removeFromPool = true) { // Fetch all the matching objects. var fetchedObjects = objectPool.Where(condition).ToArray(); // If an array size limit is given. if (maxSize &gt;= 1) { List&lt;GameObject&gt; temp = new List&lt;GameObject&gt;(); // Loop through the fetched objects, adding to the list as long as the list stays in it's given size limit. for (int i = 0; i &lt; fetchedObjects.Length &amp;&amp; i &lt; maxSize; ++i) { temp.Add(fetchedObjects[i]); } fetchedObjects = temp.ToArray(); } // If we need to remove the fetched objects from the object pool if (removeFromPool) { RemoveObjectsFromPool(fetchedObjects); } return fetchedObjects; } #region Util private void RemoveObjectsFromPool(GameObject[] objectsToRemove) { // For each given object. foreach (var gameObject in objectsToRemove) { // Remove the given object from the object pool. objectPool.Remove(gameObject); } } #endregion } </code></pre> <p>I am currently using Unity 2018.3.1f1, if that matters.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T19:17:57.100", "Id": "409600", "Score": "3", "body": "Please do not update the code in your question to incorporate feedback from answers (even if it is your own), 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 you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. Feel free to post the improved variant in a new question, if you want to, or add it into your existing answer." } ]
[ { "body": "<p>I have added some improvement of my own after some further researching, though I am still welcoming further suggestions/improvements to my code.</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing UnityEngine;\nusing System.Linq;\n\npublic class ObjectPool : Singleton&lt;ObjectPool&gt; {\n\n private HashSet&lt;GameObject&gt; objectPool;\n\n private void Awake() {\n objectPool = new HashSet&lt;GameObject&gt;();\n }\n\n /// &lt;summary&gt;\n /// Add a gameobject to the object pool.\n /// &lt;/summary&gt;\n /// &lt;param name=\"objToPool\"&gt;The gameobject to add to the object pool.&lt;/param&gt;\n /// &lt;param name=\"deactivateObj\"&gt;Deactivate this gameobject upon storing into the object pool.&lt;/param&gt;\n public void AddToPool(GameObject objToPool, bool deactivateObj = true) {\n objectPool.Add(objToPool);\n\n // If we need to deactivate this gameobject.\n if (deactivateObj) {\n // Set it to not active.\n objToPool.SetActive(false);\n }\n }\n\n /// &lt;summary&gt;\n /// Fetch a gameobject from the pool, with the gameobject containing the desired component.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of the component.&lt;/typeparam&gt;\n /// &lt;param name=\"removeFromPool\"&gt;True if the fetched gameobject needs to be removed from the pool.&lt;/param&gt;\n /// &lt;returns&gt;The respective gameobject. (Null if none is found)&lt;/returns&gt;\n public GameObject FetchObjectByComponent&lt;T&gt;(bool removeFromPool = true) where T : MonoBehaviour {\n GameObject fetchedObject = null;\n\n // Foreach game object in the object pool\n foreach (var gameObj in objectPool) {\n // If this gameobject has the desired component.\n if (gameObj.GetComponent&lt;T&gt;() != null) {\n // Fetch this object.\n fetchedObject = gameObj;\n // End loop (an object with the desired component is found.)\n break;\n }\n }\n\n // If an object is fetched and we need to remove it from the pool.\n if (fetchedObject != null &amp;&amp; removeFromPool) {\n // Remove the fetched object from the pool.\n objectPool.Remove(fetchedObject);\n }\n\n return fetchedObject;\n }\n\n /// &lt;summary&gt;\n /// Fetch an array of gameobjects that contains the desired component.\n /// &lt;/summary&gt;\n /// &lt;typeparam name=\"T\"&gt;The type of the component the gameobject must contain.&lt;/typeparam&gt;\n /// &lt;param name=\"maxSize\"&gt;The max size of the array returned. (Negative for limitless)&lt;/param&gt;\n /// &lt;param name=\"removeFromPool\"&gt;True to remove the respective fetched gameobject from the object pool.&lt;/param&gt;\n /// &lt;returns&gt;The respective fetched game objects.&lt;/returns&gt;\n public GameObject[] FetchObjectsByComponent&lt;T&gt;(int maxSize = -1, bool removeFromPool = true) where T : MonoBehaviour {\n\n HashSet&lt;GameObject&gt; temp = new HashSet&lt;GameObject&gt;();\n\n // For counting how many objects we already have in the temporary list.\n int i = 0;\n // Go through the object pool.\n foreach (var obj in objectPool) {\n // If we have already reached the max array size.\n if (i &gt;= maxSize) {\n // Exit loop.\n break;\n }\n // If the current object contains the desired component.\n else if (obj.GetComponent&lt;T&gt;() != null) {\n // Add to the temporary list.\n temp.Add(obj);\n // An object has been added.\n ++i;\n }\n }\n\n var fetchedObjects = temp.ToArray();\n\n // If we need to remove the fetched objects from the object pool, remove.\n if (removeFromPool) {\n RemoveObjectsFromPool(fetchedObjects);\n }\n\n return fetchedObjects;\n }\n\n /// &lt;summary&gt;\n /// Fetch an array of gameobject based on the given condition.\n /// &lt;/summary&gt;\n /// &lt;param name=\"condition\"&gt;The condition to check on when fetching gameobjects.&lt;/param&gt;\n /// &lt;param name=\"maxSize\"&gt;The maximum size of the array returned. (Negative for limitless.)&lt;/param&gt;\n /// &lt;param name=\"removeFromPool\"&gt;True to remove the respective fetched gameobject from the object pool.&lt;/param&gt;\n /// &lt;returns&gt;The respective fetched game objects.&lt;/returns&gt;\n public GameObject[] FetchObjectsByCondition(Func&lt;GameObject, bool&gt; condition, int maxSize = -1, bool removeFromPool = true) {\n HashSet&lt;GameObject&gt; temp = new HashSet&lt;GameObject&gt;();\n\n // For counting how many objects we already have in the temporary list.\n int i = 0;\n // Go through the object pool.\n foreach (var obj in objectPool) {\n // If we have already reached the max array size.\n if (i &gt;= maxSize) {\n // Exit loop.\n break;\n }\n // If the current object meets the condition.\n else if (condition(obj)) {\n // Add to the temporary list.\n temp.Add(obj);\n // An object has been added.\n ++i;\n }\n }\n\n var fetchedObjects = temp.ToArray();\n\n // If we need to remove the fetched objects from the object pool\n if (removeFromPool) {\n RemoveObjectsFromPool(fetchedObjects);\n }\n\n return fetchedObjects;\n }\n\n /// &lt;summary&gt;\n /// Fetch a gameobject with the given condition.\n /// &lt;/summary&gt;\n /// &lt;param name=\"condition\"&gt;The condition based on to fetch the gameobject&lt;/param&gt;\n /// &lt;param name=\"removeFromPool\"&gt;True to remove this gameobject from the object pool.&lt;/param&gt;\n /// &lt;returns&gt;The fetched gameobject by the respective condition. (Null if none is found.)&lt;/returns&gt;\n public GameObject FetchObjectByCondition(Func&lt;GameObject, bool&gt; condition, bool removeFromPool = true) {\n\n GameObject fetchedObject = null;\n\n // Loop through the object pool.\n foreach (var obj in objectPool) {\n // If this object's condition meets the given condition.\n if (condition(obj)) {\n // Fetch this object.\n fetchedObject = obj;\n // Stop loop (object is found.)\n break;\n }\n }\n\n // Remove this object pool if required.\n if (removeFromPool &amp;&amp; fetchedObject != null){\n objectPool.Remove(fetchedObject);\n }\n\n return fetchedObject;\n }\n\n #region Util\n\n private void RemoveObjectsFromPool(GameObject[] objectsToRemove) {\n // For each given object.\n foreach (var gameObject in objectsToRemove) {\n // Remove the given object from the object pool.\n objectPool.Remove(gameObject);\n }\n }\n\n #endregion\n}\n</code></pre>\n\n<p>I have changed from using a <code>List&lt;T&gt;</code> to using a <code>HashSet&lt;T&gt;</code> since I read up that HashSet has been proven to be faster than a list.<br> (though it takes away the functionality of being able to access a list through it's index, but I do not need the functionality.)</p>\n\n<h1>EDIT</h1>\n\n<p><strong>(Further improvement)</strong></p>\n\n<pre><code>using System.Collections.Generic;\nusing UnityEngine;\n\npublic class ObjectPool&lt;T&gt; {\n\n private Dictionary&lt;T, HashSet&lt;GameObject&gt;&gt; objectPools;\n\n public ObjectPool() {\n objectPools = new Dictionary&lt;T, HashSet&lt;GameObject&gt;&gt;();\n }\n\n /// &lt;summary&gt;\n /// Add the object to the respective object pool\n /// &lt;/summary&gt;\n /// &lt;param name=\"type\"&gt;The type of object to add.&lt;/param&gt;\n /// &lt;param name=\"obj\"&gt;The object to add into the object pool.&lt;/param&gt;\n /// &lt;param name=\"deactiveObj\"&gt;True to deactive this object when adding to the pool.&lt;/param&gt;\n public void AddToObjectPool(T type, GameObject obj, bool deactiveObj = false) {\n // Get the respective object pool.\n var pool = FetchObjectPoolByType(type);\n // Add the object to the pool\n pool.Add(obj);\n\n if (deactiveObj) {\n obj.SetActive(false);\n }\n }\n\n /// &lt;summary&gt;\n /// Fetch the first inactive object in the object pool by type.\n /// &lt;/summary&gt;\n /// &lt;param name=\"type\"&gt;The type of object to fetch.&lt;/param&gt;\n /// &lt;returns&gt;An inactive object based on the given type. (Null if none was found)&lt;/returns&gt;\n public GameObject FetchObjByType(T type) {\n // Get the respective bullet pool.\n var pool = FetchObjectPoolByType(type);\n\n return FetchAnyInactiveObjIfExists(pool);\n }\n\n #region Util\n\n private static GameObject FetchAnyInactiveObjIfExists(HashSet&lt;GameObject&gt; pool) {\n GameObject fetchObj = null;\n\n // Loop through the pool\n foreach (var obj in pool) {\n // If this object is not active.\n if (!obj.activeInHierarchy) {\n // Fetch this object\n fetchObj = obj;\n // Stop loop, an inactive object is fetched.\n break;\n }\n }\n\n return fetchObj;\n }\n\n private HashSet&lt;GameObject&gt; FetchObjectPoolByType(T type) {\n // If the pool does not exists yet.\n if (!objectPools.ContainsKey(type)) {\n // Create it\n objectPools.Add(type, new HashSet&lt;GameObject&gt;());\n }\n\n // Return the pool with given type.\n return objectPools[type];\n }\n\n #endregion\n}\n</code></pre>\n\n<p>Rather than dumping everything into a single <code>HashSet</code> pool I have decided to use generic implementation to further separate into different object pools of respective types.<br>\nAlso, I am now using an Object Pool manager to manage the different instances of ObjectPool.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T19:10:54.323", "Id": "211825", "ParentId": "211800", "Score": "0" } }, { "body": "<p>I'm going to look over this in further detail later this evening, but from an initial review I would not remove objects from the pool and add them back later. I would only remove from the pool if the object should never be used again.</p>\n\n<hr>\n\n<h2>Adding and Removing</h2>\n\n<p>It's easy to understand a fundamental concept of adding and removing objects from a collection. However, when your collection is meant to hold reusable data, why are you removing from it every time you want an object that isn't active. Instead, just set the object to an active state to ensure the same object cannot be pulled twice. Then only remove objects once you determine they are no longer needed. Some eligible criteria for removing objects from your pool are:</p>\n\n<ol>\n<li>Enough time has passed that you no longer need to store above <strong>n</strong> objects.</li>\n<li>Your scene has ended and you no longer need any of the objects.\n\n<ul>\n<li>The exception to this is if your objects are shared across scenes; revert to case 1.</li>\n</ul></li>\n</ol>\n\n<hr>\n\n<p>I will add more later this evening along with an example to further assist.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T20:18:35.650", "Id": "212020", "ParentId": "211800", "Score": "2" } }, { "body": "<p>This script is pretty good. But I recommend using a Queue instead of a List.\nTry this custom class\n<a href=\"https://www.technoob.me/2019/05/pooling-system-for-unity-technoob.html\" rel=\"nofollow noreferrer\">Object Pooling, Custom pool classs</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-14T11:19:30.647", "Id": "425500", "Score": "2", "body": "Welcome to Code Review! You can improve your answer by providing a reason for this suggestion. This will help the OP and others to learn from it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-14T06:58:35.517", "Id": "220218", "ParentId": "211800", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T07:12:26.640", "Id": "211800", "Score": "5", "Tags": [ "c#", "game", "unity3d" ], "Title": "C# Unity Object Pooling (for a shooter game)" }
211800
<p>I'm trying to improve my code and algorithm to find out the longest word from a dictionary occurring as the sub-sequence in the given string. </p> <p>Example : For example, given the input of S = "abppplee" and D = {"able", "ale", "apple", "bale", "kangaroo"} the correct output would be "apple". </p> <p><strong>Currently my algorithm compares each character of the dictionary-word with the given-word and advances to next char in dictionary-word on finding a match and so on till either the dictionary-word is iterated over completely(which means the word is a valid sub-sequence) or the given word is iterated over completely(which means not a valid string).</strong> </p> <p>Being a beginner to c++ and algorithms in general, my methods and logic could be further improved. So kindly suggest if any improvements in the algorithm or code which can improve the performance. Thanks. </p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;tuple&gt; #include &lt;vector&gt; class StringManipulater { public: StringManipulater(const std::string&amp; p) : given_string_{p} {} std::string given_string_; std::tuple&lt;std::string, typename std::string::size_type&gt; current_longest_ = { "", 0}; const std::string&amp;&amp; FindLongestSubSeq(const std::vector&lt;std::string&gt;&amp; dict) { // flag determines whether current word is present in given_string input bool flag; // iterate through each of the dict-words for (const std::string&amp; word : dict) { flag = false; auto word_len = word.size(); // fair optimization : only consider current word if its // length is greater than previous one if (word_len &gt; std::get&lt;1&gt;(this-&gt;current_longest_)) { // iterate through the letters in both given string and current word // to be compared for (typename std::string::size_type i = 0, j = 0; j &lt; word_len; ++i) { // no need to go further checking if we have iterated over given // string if (i == this-&gt;given_string_.size()) break; // compare each letter of both words if (word[j] == given_string_[i]) { flag = true; // advance to next charcter in the dictionary word ++j; } else { // if the char couldn't be found flag = false; } } // end of comparison loop if (flag) { std::get&lt;0&gt;(this-&gt;current_longest_) = word; std::get&lt;1&gt;(this-&gt;current_longest_) = word_len; } } // top if } // end of iteration of dictionary words return std::move(std::get&lt;0&gt;(this-&gt;current_longest_)); } }; int main() { StringManipulater s_manip{"abppplee"}; std::cout &lt;&lt; "Longest subsequence = " &lt;&lt; s_manip.FindLongestSubSeq( {"able", "ale", "apple", "bale", "kangaroo"}) &lt;&lt; "\n"; return 0; } </code></pre>
[]
[ { "body": "<ul>\n<li><p>C++ is not Java. You don't need to spell out <code>this-&gt;</code>.</p></li>\n<li><p>Flat is better than nested. Consider</p>\n\n<pre><code>if (word_len &lt;= std::get&lt;1&gt;(current_longest_)) {\n continue;\n}\n// Follow with the business logic unindented\n</code></pre></li>\n<li><p>I'd prefer to alias <code>typename std::string::size_type</code> as</p>\n\n<pre><code>using size_type = typename std::string::size_type;\n</code></pre>\n\n<p>or, even better, use iterators.</p></li>\n<li><p>The inner loop can be streamlined. When we see <code>bool flag;</code> the instinct tells to get rid of it. Upon the loop termination the same information is available as <code>j == word_len</code> (or <code>word_it == word_end()</code> in the iterator version). We just need to lift <code>j</code> (or <code>word_it</code>) out of the loop.</p>\n\n<p>Another problem with the inner loop is that it manages two indices in a not-so-obvious way. A cleaner approach is to let the loop manage just the <code>word</code>, and another (innermost) loop to search through the given string. Consider</p>\n\n<pre><code>auto str_it = given_string.begin();\nauto word_it = word.begin();\nwhile (word_it != word.end()) {\n while (str_it != given_string.end() &amp;&amp; *str_it != *word_it) {\n ++str_it;\n }\n if (str_it == given_string.end()) {\n break;\n }\n ++word_it;\n}\n</code></pre>\n\n<p>Now we notice that the innermost loop does the same job as <code>std::find_first</code>. Use it:</p>\n\n<pre><code>while (word_it != word.end()) {\n if ((str_it = std::find_first(str_it, str.end(), *word_it)) == str_end()) {\n break;\n }\n ++word_it;\n}\n</code></pre></li>\n<li><p>I also recommend to factor a body of the <code>for (const std::string&amp; word : dict)</code> loop out into a function:</p>\n\n<pre><code>const std::string&amp;&amp; FindLongestSubSeq(const std::vector&lt;std::string&gt;&amp; dict)\n{\n std::tuple&lt;std::string, typename std::string::size_type&gt; current_longest_\n = { \"\", 0 };\n for (const std::string&amp; word : dict) {\n if (word_len &lt;= std::get&lt;1&gt;(current_longest_)) {\n continue;\n }\n\n if (is_subsequence(given_string, word)) {\n std::get&lt;0&gt;(this-&gt;current_longest_) = word;\n std::get&lt;1&gt;(this-&gt;current_longest_) = word.size();\n }\n return std::move(std::get&lt;0&gt;(this-&gt;current_longest_));\n}\n</code></pre></li>\n<li><p>Finally, I recommend to get rid of the <code>class StringManipulater</code> altogether, and implement everything as free functions. The class does not add any value (an C++ is not Java).</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T03:31:34.070", "Id": "409619", "Score": "0", "body": "This helps a lot. Several questions though -> 1)Should iterators be preferred over usual for(i=0;...;i<size) or for(const int val&: container) loops for iterating containers? If yes, why? 2) I started using OOP in everything after hearing a talk by Bjarne Stroustrup. Are there any caveats/overheads by using a Class in every program?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T18:46:03.463", "Id": "211822", "ParentId": "211801", "Score": "4" } }, { "body": "<p>You know, if you want to improve performance, the first thing to do is get a high-level overview of what your code does to achieve its aim. Currently, you do this:</p>\n\n<ol>\n<li>Iterate over all words in <em>D</em>.\n\n<ol>\n<li>Iterate over the whole string <em>S</em> trying to prove it a sub-sequence.</li>\n</ol></li>\n</ol>\n\n<p>That's trivially proven to be an <span class=\"math-container\">\\$O(\\#D * \\#S)\\$</span> algorithm.</p>\n\n<p>You can do better, by using the proper data structure:</p>\n\n<ol>\n<li>Build a <a href=\"https://en.wikipedia.org/wiki/Trie\" rel=\"noreferrer\">prefix-tree</a> from the words, noting the longest word which can be found from there.</li>\n<li>Iterate over the string.\n\n<ol>\n<li>Continue if the current character doesn't fit.</li>\n<li>Update the best found if it is a terminal node.</li>\n<li>recurse with the sub-tree.</li>\n</ol></li>\n</ol>\n\n<p>Regarding your code:</p>\n\n<ol>\n<li><p>Your use of a class is completely unmotivated. There are no invariants to protect, as evidenced by you marking it all <code>public</code>, and you only create it to call one single function anyway. Just make it a free function. Ok, if you change the algorithm, you might want to break it up it into building the trie, using a pre-computed trie, and putting it all together.</p></li>\n<li><p><code>auto</code> would allow you to always have the proper type, without cluttering your code with long and obscure names. Read <a href=\"https://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/\" rel=\"noreferrer\">\"<em>Almost Always Auto</em>\"</a>.</p></li>\n<li><p>I'm not sure why you use a <code>std::tuple</code>. Maybe for obfuscation? If so, I confirm you are on the right way.</p></li>\n<li><p>Always define variables in the smallest scope possible, unless there are significant advantages (most likely in performance) for a <em>slightly</em> longer lifetime.</p></li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code>.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T03:08:50.390", "Id": "409618", "Score": "0", "body": "This helps! Several questions though -> 1) Did you know by heart the time complexity of my algorithm or did you compute it somehow? I wanted to properly learn the computation of time/space complexities. Any recommendations for learning materials/courses? -> 2) I did not understand \"defining variables in smallest scope\" part. Did you mean, like declaration of flag could have been inside the for loop rather than outside? -> 3) I used the tuple to hold the longest string and it's length(which i use for comparison). Are tuples or usage of other containers like so not a good practice?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T11:01:27.353", "Id": "409640", "Score": "0", "body": "@Yedhin 1. Computed: At worst, none of the words are found. Then just look at the loops. 2. `current_longest` should obviously not be a member, but a local of the function. And yes to `flag`. 3. Using tuples iwhen you need a bag is no problem, and can help composability. That's not the case though, there was no downside to having two independent symbols at all, so being more descriptive and convenient is far better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:21:37.880", "Id": "211835", "ParentId": "211801", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T08:16:20.590", "Id": "211801", "Score": "6", "Tags": [ "c++", "performance", "algorithm", "c++11" ], "Title": "Given a string S and a set of words D, find the longest word in D that is a subsequence of S" }
211801
<p>I have written the following Repository in C#, using NetCore 2.2 and EF Core.</p> <p>I was thinking how to write properly the Search method according to the SOLID principles.</p> <p>This code gives a null reference exception when "Title" or "Genre" property is null. It means I will need to put an if to check for null values, and in that case, it does not respect the single responsibility principle: as this method is returning a set of elements from the DB and also making some operations with strings.</p> <p>How can I refactor this to avoid null exception and respect the SRP?</p> <pre><code>public class MovieRepository: IMovieRepository { private readonly MovieDbContext _moviesDbContext; public MovieRepository(MovieDbContext moviesDbContext) { _moviesDbContext = moviesDbContext; } public IEnumerable&lt;Movie&gt; GetAll() { return _moviesDbContext.Movies; } public IEnumerable&lt;Movie&gt; Search(MovieFilters filters) { var title = filters.Title.ToLower(); var genre = filters.Genre.ToLower(); return _moviesDbContext.Movies.Where( p =&gt; (p.Title.Trim().ToLower().Contains(title) | string.IsNullOrWhiteSpace(p.Title)) &amp; (p.Genre.Trim().ToLower().Contains(genre) | string.IsNullOrWhiteSpace(p.Genre)) &amp; (p.YearOfRelease == filters.YearOfRelease | filters.YearOfRelease == null) ); } } </code></pre> <p>And this is the code that works in case of null values but I don't know how to refactor this according to with SOLID, I will appreciate some ideas to move those IFs sentences:</p> <pre><code>public IEnumerable&lt;Movie&gt; Search(MovieFilters filters) { string title = ""; if (string.IsNullOrWhiteSpace(filters.Title) == false) { title = filters.Title.ToLower(); } string genre = ""; if (string.IsNullOrWhiteSpace(filters.Genre) == false) { genre = filters.Genre.ToLower(); } return _moviesDbContext.Movies.Where( p =&gt; (p.Title.Trim().ToLower().Contains(title) | string.IsNullOrWhiteSpace(p.Title)) &amp; (p.Genre.Trim().ToLower().Contains(genre) | string.IsNullOrWhiteSpace(p.Genre)) &amp; (p.YearOfRelease == filters.YearOfRelease | filters.YearOfRelease == null) ); } </code></pre>
[]
[ { "body": "<p>There is a difference between &amp; and &amp;&amp; as well as | and ||. There is a null coalescing operator ?. and ?? that you can use and string equals method has a second parameter where you can pass StringComparison.OrdinalIgnoreCase.</p>\n\n<p>The lambda could look like:</p>\n\n<pre><code>o =&gt; p.Title?.Trim().Equals(title ?? \"\", StringComparison.OrdinalIgnoreCase) \n || p.Genre?.Trim().Equals(genre ?? \"\", StringComparison.OrdinalIgnoreCase)\n</code></pre>\n\n<p>What the SOLID means is that you pass that in a an argument to a method like</p>\n\n<pre><code>public IEnumerable&lt;T&gt; Search&lt;T&gt;(System.Linq.Expressions.Expression&lt;Func&lt;T, bool&gt;&gt; predicate)\n{\n return _dbContext.Set&lt;T&gt;()\n .Where(predicate)\n .AsEnumerable();\n}\n</code></pre>\n\n<p>and it would not contain your validation checks or business logic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T07:53:23.803", "Id": "409629", "Score": "0", "body": "Regarding the || in the lambda expressions, is not what I want, I would like all the conditions to be checked: so if the movie title has something and also the genre I want to apply the filter for both conditions. Not sure if I understood well you code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T16:38:01.463", "Id": "211818", "ParentId": "211803", "Score": "0" } } ]
{ "AcceptedAnswerId": "211818", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T09:18:11.637", "Id": "211803", "Score": "-2", "Tags": [ "c#", "repository", ".net-core" ], "Title": "Repository Pattern and SOLID principles" }
211803
<p>In several places I need to compute the next value, given a N:</p> <pre><code>double size = 1.0 / Math.Pow(2, N); </code></pre> <p>Since I won't be computing this value for N > 15 I have thought of the following performance optimization:</p> <pre><code> public static readonly double[] RegionSizes = { 1, 0.5, 0.25, 0.125, 0.0625, 0.03125, 0.015625, 0.0078125, 0.00390625, 0.001953125, 0.000976563, 0.000488281, 0.000244141, 0.00012207, 0.00006103515625, 0.000030517578125 }; //Usage double size = RegionSizes[N]; </code></pre> <p>Is this a good solution? Why / why not?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T12:17:18.537", "Id": "409574", "Score": "4", "body": "Why don't you test it for a trillion iterations and see?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T13:07:33.513", "Id": "409787", "Score": "0", "body": "\"Is this a good solution?\" It depends on how often and how you're going to use it. By the looks of it though, it looks like micro-optimization. Probably in the wrong place too." } ]
[ { "body": "<p>It can be called a <strong>precomputed local cache immutable field array</strong>. </p>\n\n<p>It is <strong>fine</strong> and definitely is better than computing the value every time.</p>\n\n<hr>\n\n<p>While I say immutable, I do not mean that it is deeply immutable - all of the values can be changed, only the array reference itself is immutable. If you need to pass it to methods that you do not fully trust, then you can pass a copy - if they mess with the values it is their local copy of it.</p>\n\n<p>Please make sure that you use the correct initial values in the first place. To do so you can compute them with: <a href=\"https://www.wolframalpha.com/input/?i=N%5B1%2F2%5E(0..15),+15%5D\" rel=\"nofollow noreferrer\">https://www.wolframalpha.com/input/?i=N%5B1%2F2%5E(0..15),+15%5D</a></p>\n\n<pre><code>N[1/2^(0..15), 15]\n</code></pre>\n\n<p>this would produce values</p>\n\n<pre><code>{\n 1.00000000000000, \n 0.500000000000000, \n 0.250000000000000, \n 0.125000000000000, \n 0.0625000000000000, \n 0.0312500000000000, \n 0.0156250000000000, \n 0.00781250000000000, \n 0.00390625000000000, \n 0.00195312500000000, \n 0.000976562500000000, \n 0.000488281250000000, \n 0.000244140625000000, \n 0.000122070312500000, \n 0.0000610351562500000, \n 0.0000305175781250000\n}\n</code></pre>\n\n<p>The type <strong>double</strong> is approximated value and has the maximum of 15 places you can trust also referred to as <strong>significant digits</strong>. Counting starts not from decimal places, but from the highest value. For type <strong>float</strong> it is just 7 and <strong>decimal</strong> is 28. That is why I showed just 15 digits.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T16:31:21.760", "Id": "409666", "Score": "2", "body": "depending on the program structure, passing a copy of the array might result in many copy operations (which implies allocating memory), which might result in an actually worse performance. If you're really going for speed, you want to avoid allocating memory as much as possible." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T17:32:36.220", "Id": "409670", "Score": "1", "body": "The garbage collector works in a manner that it is cheap to allocate memory for short life-span. Creating a copy is actually the recommended approach as allocating memory is very fast and GC does not need to check for multiple contexts if it can dispose of the memory.\n\nBesides in the current case you are talking about allocating memory for the creation of 16 double elements array, that is just 64 bytes total. I do not even want to mention that on PC the compiler itself would probably use branch prediction and use L1 cache if you would put it in a 100m loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:21:56.177", "Id": "409708", "Score": "1", "body": "When I test your approach on my machine (10 million calls of a method that uses all values from the array, release build), it takes about 300ms without copying the array, about 1.500 ms with copying, so it's about 5 times slower. Still significantly faster than calculating every time, but allocating memory is definitely not for free." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:42:48.020", "Id": "409715", "Score": "0", "body": "Sorry, I forgot: For comparison i tested ReadOnlySpan<double>, took about 370 ms." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T21:54:37.540", "Id": "409728", "Score": "0", "body": "@d_hippo ReadOnlySpan<T> is a good wrapper, but it has lots of limitations that are nicely documented under Microsoft docs remarks section. However, you are right, the speed difference can be roughly 0.000113 ms per item for 10m set." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T11:29:31.340", "Id": "409778", "Score": "0", "body": "yes, it's not the solution for every problem, and probably not even needed in this case. I just wanted to point out what you can save by not allocating for every call." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T16:17:14.307", "Id": "211816", "ParentId": "211805", "Score": "2" } }, { "body": "<p>It isn't a good solution and there are several reasons.</p>\n\n<p>1.: Your values are less precise than what the double data type allows for. For example, </p>\n\n<pre><code>1.0 / Math.Pow(2, 12)\n</code></pre>\n\n<p>computes to 0.000244140625, while your lookup value is just 0.000244141. Depending on the following calculations, this can make quite a big difference. </p>\n\n<p>2.: Your array is public and mutable. While the array reference is readonly (so you can't assign a new array to the reference), the array itself is not. For example</p>\n\n<pre><code>RegionSizes[2] = 5;\n</code></pre>\n\n<p>compiles and runs without any problems. You (or every other dev) can override values in the array as he desires. Better use an immutable collection, like <code>ReadOnlyCollection&lt;double&gt;</code>, to prevent your cached values from manipulation during runtime. (If this is a little fun-project with you as the only dev this might not become a problem; in bigger projects with >1 dev this type of oversight can lead to hard-to-track bugs.)</p>\n\n<p>3.: Experience tells that assumptions like </p>\n\n<blockquote>\n <p>I won't be computing this value for N > 15</p>\n</blockquote>\n\n<p>do not always hold true. To be sure, a more flexible approach (like calculating every value once it's first needed, then store it and use it when needed again) would allow for more flexibility. Of course, without any information about what you intend to do in your program it's hard to tell if this is relevant.</p>\n\n<p>4.: I strongly suspect you are doing premature optimizations (because you mention neither actual performance problems, nor any measurements indicating that floting-point operations are the cause for such problems). Donald Knuth said </p>\n\n<blockquote>\n <p>The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming.</p>\n</blockquote>\n\n<p>and I have nothing to add. From my experience, in >95% of all software projects you don't need to worry about the performance of >95% of your code. So when making an optimization, you should follow these steps:</p>\n\n<ol>\n<li>Set a realistic measurable performance goal. This is important, you can optimize code forever, so you have to have some definition of 'good enough' and stop once your code is good enough.</li>\n<li>Measure if there is an actual performance problem (by comparing actual performance to your definition of 'good enough').</li>\n<li>Identify the parts of your code that cause the performance problem; that involves measuring again. For example measure how much time the program spends in each method, then measure how much time the operations in the slow methods take. Do this until you know for sure what makes your program run slow.</li>\n<li>Optimize the code that you found out to be slow in step 3 and measure again, to make sure your optimizations are making your code run faster (it's suprising how many 'optimizations' actually make things worse).</li>\n<li>Go back to 2.</li>\n</ol>\n\n<p>Yes, I know, optimizing code is fun - but you can quickly get lost and spend hundreds of hours optimizing code that never needed any optimization. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:42:12.737", "Id": "409609", "Score": "1", "body": "Good answer, thanks. Actually I have measured and in my context I gained like 30% increase in speed for the method when this is called (it is called a lot of times). It is indeed a personal project." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T21:07:28.720", "Id": "211830", "ParentId": "211805", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T11:05:54.063", "Id": "211805", "Score": "3", "Tags": [ "c#", "performance", "array" ], "Title": "Storing computed values in an array" }
211805
<p>I would like to get you opinion on this class, which is used to send HTTP requests (at that moment only POST method).</p> <p>It is working ok, but I would like to get response on maintainability, reusability, security, code formatting, etc...</p> <pre><code>Class HttpRequest{ private $POST = 'POST'; private $PUT = 'PUT'; private $GET = 'GET'; private $DELETE = 'DELETE'; private $PATCH = 'PATCH'; private $body; private $options; private $handle; private $httpCode; private $response; public function __construct(){} /** * send post request * @param url * @param header * @param options * @param body * @return json object */ public function post($url, $header, $options, $body){ if(!$this-&gt;handle || get_resource_type($this-&gt;handle) == "Unknown"){ $this-&gt;handle = curl_init(); } curl_setopt($this-&gt;handle, CURLOPT_URL, $url); curl_setopt($this-&gt;handle, CURLOPT_HTTPHEADER, $header); curl_setopt_array($this-&gt;handle, $options); // curl_setopt($this-&gt;handle, CURLOPT_SSL_VERIFYPEER, true); // curl_setopt($this-&gt;handle, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($this-&gt;handle, CURLOPT_RETURNTRANSFER, true); curl_setopt($this-&gt;handle, CURLOPT_CUSTOMREQUEST, $this-&gt;POST); curl_setopt($this-&gt;handle, CURLOPT_POSTFIELDS, $body); $this-&gt;response = curl_exec($this-&gt;handle); $this-&gt;httpCode = curl_getinfo($this-&gt;handle, CURLINFO_HTTP_CODE); curl_close($this-&gt;handle); return $this-&gt;response; } public function getResponse(){ return $this-&gt;response; } public function getHttpCode(){ return $this-&gt;httpCode; } /** * send get request * @param url * @param header * @param options */ public function get($url,$header=array(), $options=array()){ /** * @todo * implemets this method */ } /** * send patch request */ public function patch(){ /** * @todo * implemets this method */ } /** * send delete request */ public function delete(){ /** * @todo * implemets this method */ } /** * send put request */ public function put(){ /** * @todo * implemets this method */ } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T12:38:12.647", "Id": "409577", "Score": "0", "body": "Instead of defining POST/GET as variables, define constants." } ]
[ { "body": "<p><strong>Use class constants to store values that will remain the same and are unchangeable</strong></p>\n\n<p>Your HTTP method verbs are better off set as class constants than class properties since they will remain the same and are unchangeable. (i.e. <em>constant</em>)</p>\n\n<pre><code>private $POST = 'POST';\nprivate $PUT = 'PUT';\nprivate $GET = 'GET';\nprivate $DELETE = 'DELETE';\nprivate $PATCH = 'PATCH';\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>const POST = 'POST';\nconst PUT = 'PUT';\nconst GET = 'GET';\nconst DELETE = 'DELETE';\nconst PATCH = 'PATCH';\n</code></pre>\n\n<p>You can then refer to them using <code>self</code></p>\n\n<pre><code>self::POST\n</code></pre>\n\n<p><strong>No need for an empty constructor</strong></p>\n\n<p>If your contractor doesn't have any code in it you could, and should omit it. It's just noise otherwise. You can always add it if the constructor definition changes. </p>\n\n<p><strong>Be sure to use docblock comments for your class properties</strong> </p>\n\n<p>Not just class methods should have well written docblock comments, so should your class properties.</p>\n\n<pre><code>/**\n * @var string The body of the HTTP request\n */\nprivate $body; \n</code></pre>\n\n<p><strong>Follow PSR coding standards</strong> </p>\n\n<p>The PSR coding standards exist to ensure a high level of technical interoperability between shared PHP code. They also ensure conformity for projects with multiple developers. </p>\n\n<p><a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">PSR-2 </a> says that:</p>\n\n<blockquote>\n <p>Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.\n and\n Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.</p>\n</blockquote>\n\n<pre><code>Class HttpRequest{\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>Class HttpRequest\n{\n</code></pre>\n\n<p>and </p>\n\n<pre><code>public function post($url, $header, $options, $body){\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>public function post($url, $header, $options, $body)\n{\n</code></pre>\n\n<p><strong>Use type hinting to variable types in class methods</strong> </p>\n\n<p>From <a href=\"http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration\" rel=\"nofollow noreferrer\">the manual</a>:</p>\n\n<blockquote>\n <p>Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated</p>\n</blockquote>\n\n<p>To use your code as an example, you can declare that <code>$url</code> must be a string and <code>$header</code> and <code>$options</code> must be arrays. This will be enforced by PHP at run time and prevent obvious and non obvious errors from occurring.</p>\n\n<pre><code>public function get($url,$header=array(), $options=array()){\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>public function get(string $url, array $header=[], array $options=[])\n{\n</code></pre>\n\n<p>(I used shortened array syntax <code>[]</code> versus the more verbose <code>array()</code> for brevity.) </p>\n\n<p><strong>Use return type declarations</strong></p>\n\n<p>Just like you can enforce that class method parameters are a certain data type, you can also enforce the value returned by that method is a certain data type. Since all of your methods are stubs I'll pretend your <code>HttpRequestget()</code> method returns a Boolean to use as an example.</p>\n\n<pre><code>public function get(string $url, array $header=[], array $options=[]): bool\n{\n</code></pre>\n\n<p>Now my calling code will know that a Boolean, and only a Boolean value, will be returned by that method. </p>\n\n<p><strong>When doing comparisons use === whenever possible</strong></p>\n\n<p>Unlike <code>==</code> which compares values only, <code>===</code> compares both values and <em>type</em>. This strict comparison helps to avoid error, and attacks, that occur when PHP encounters a comparison of two variables of different types it will coerce one of the variables into the type of the other variable in order to do the comparison.</p>\n\n<p>For example</p>\n\n<pre><code>1 == '1' // true\n1 === '1' // false\n</code></pre>\n\n<p>How much does this matter? It depends. If you get into a situation where you are getting numbers as strings but you are trying to use them as numbers, for something like sorting, you can get unexpected results if your check only checks value instead of type. And those of us who remember phpBB remember when it was subject to a slew of high profile vulnerabilities many of which were resolved simply by using a stricter comparison. So, yes, it matters. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T06:49:57.963", "Id": "409626", "Score": "0", "body": "how do you recommend use this class in other classes ? right now its been injected as a dependecy" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T07:11:20.383", "Id": "409628", "Score": "0", "body": "@dev why you're injecting it? What's the problem with just creating a new instance when needed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T15:47:07.673", "Id": "409661", "Score": "0", "body": "@dev I agree with your decision to inject it into your dependant classes. This will allow you to mock this class when you unit test your other classes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:24:29.800", "Id": "409889", "Score": "0", "body": "This is a questionable recommendation as this class has a state linked to a particular request. It you want to inject something, then you must inject a factory that would give you a new instance for each request, not just a single instance that could be possibly used in several places." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T19:10:52.403", "Id": "211824", "ParentId": "211806", "Score": "1" } }, { "body": "<p>The most critical part is that this code is not a class. It's a function. A function just written in a form of a class method but it's a function all the same. Ok, it is using distinct methods to get the response and the code, but that's not enough to become a class. For this purpose you can make a function to return an array, like this</p>\n<pre><code>return ['response' =&gt; $response, 'code' =&gt; $code];\n</code></pre>\n<p>and no class would be ever needed.</p>\n<p>I even have a feeling that this class is a direct attempt to convert a function into a class. But you really have to decompose this function into different methods.</p>\n<h3>Duplicated code</h3>\n<p>Suppose you are going to implement the GET method. Are you going to <strong>duplicate</strong> all this curl_init stuff in it? Come on, classes are written to reduce the duplication, not to multiply it. So you have to make a protected common execution method that would contain all the code common for all requests.</p>\n<h3>Constructor</h3>\n<p>Then remove from the function body that code to initialize curl, as it looks being a rudiment from the time when this class was a function, but now it looks alien here. This is <em>the</em> code that goes into constructor.</p>\n<h3>Configuration</h3>\n<p>Notice these 2 lines commented out</p>\n<pre><code> // curl_setopt($this-&gt;handle, CURLOPT_SSL_VERIFYPEER, true);\n // curl_setopt($this-&gt;handle, CURLOPT_SSL_VERIFYHOST, 0);\n</code></pre>\n<p>suppose you are going to comment and uncomment them when required. This is not how classes are used. Move these lines in a distinct method and call it when you have to bypass the SSL verification.</p>\n<h3>Method chaining</h3>\n<p>Given there could be several methods called in consequence, consider returning <code>$this</code> from methods. It will allow you to use the neat practice called &quot;method chaining&quot;:</p>\n<pre><code>$request = new HttpRequest();\n$body = $request-&gt;setHeaders($headers)\n -&gt;setNoSSLverification()\n -&gt;post($url, $post_body)\n -&gt;getResponse();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T07:08:08.203", "Id": "211849", "ParentId": "211806", "Score": "1" } }, { "body": "<p>I like that you've tried to include some processing within object's methods, which is what objects should look like from OOP perspective, but you've chosen wrong case for it IMO.</p>\n\n<h3>Naming &amp; API</h3>\n\n<p>The class name and its API is confusing. Request itself shouldn't produce the response - the remote server does. Request is usually the data structure type which contains values that can be read from it, so that class representing remote server could fetch response based on it. The API of this server (that, in your case, encapsulates bunch of <strong>curl commands</strong>) would be:</p>\n\n<pre><code>$response = $httpServer-&gt;send($request);\n</code></pre>\n\n<p>Your <code>get()</code>, <code>post()</code>, ...etc. methods are a good candidates for static factory methods (named constructors) producing concrete, possibly immutable request object, while replacing method parameter in primary constructor:</p>\n\n<pre><code>class HttpRequest\n{\n public static function post($url, $header, $options, $body)\n {\n return self::__construct('POST', $url, $header, $options, $body);\n }\n\n public function __construct($method, $url, $header, $options, $body)\n {\n $this-&gt;method = $method;\n $this-&gt;url = $url;\n ...\n }\n\n public function method(): string\n {\n return $this-&gt;method;\n }\n ...\n}\n</code></pre>\n\n<h3>Encapsulating I/O</h3>\n\n<p>Since http structure is well defined and request contains complete information, its handler (remote server object) will be generic low level library - it won't need to change depending on where this request is sent.</p>\n\n<p>The layer (might be a single class) where you create this request, pass it to server object and process the response will be an <strong>adapter</strong> to abstract data <strong>port</strong> (google for <code>ports and adapters</code>). For example (ignore names here):</p>\n\n<pre><code>class FacebookService implements UserDataGateway\n{\n public function __construct(APIConfig $config, RemoteServer $server)\n {\n $this-&gt;config = $config;\n $this-&gt;server = $server;\n }\n\n public function userData($userId): array\n {\n $request = ... //prepare request using $this-&gt;config and given $userId\n $response = $this-&gt;server-&gt;send($request);\n\n return json_decode($response-&gt;body(), true);\n }\n ...\n}\n</code></pre>\n\n<p>By encapsulating http, the class that will get (and call) <code>UserDataGateway</code> might work with this <code>FacebookService</code> as well as with local SQL database or other remote service providing user data - it only needds to return it based on some user's id. It can also be tested in isolation from remote/database calls (this example likely returns plain view model data, so ther will be no logic to test).</p>\n\n<h3>Already invented stuff</h3>\n\n<p>Take a look at <a href=\"https://www.php-fig.org/psr/psr-7/\" rel=\"nofollow noreferrer\">PSR-7</a> and its implementations like <a href=\"https://github.com/zendframework/zend-diactoros\" rel=\"nofollow noreferrer\">Zend-Diactoros</a> and remote server libraries like <a href=\"https://github.com/guzzle/guzzle\" rel=\"nofollow noreferrer\">Guzzle</a> which will implement <a href=\"https://www.php-fig.org/psr/psr-18/\" rel=\"nofollow noreferrer\">PSR-18</a>* in near future.</p>\n\n<p>*) Calling remote server a <code>Client</code> is another kind of naming blunder IMO where you look at object from perspective of the entity it internally communicates with instead object that makes calls, but what can you do ¯\\_(ツ)_/¯</p>\n\n<p>Anyway, it would be strange if someone called me a \"customer\" at home after coming back with groceries for breakfast.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T15:33:40.097", "Id": "409802", "Score": "0", "body": "thanks for the inputs, I can't upvote for lack of reputation. I've just read a post about ports and adapters and i understand why you mention it, if you have a good link please let me know" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T02:40:29.063", "Id": "211888", "ParentId": "211806", "Score": "0" } } ]
{ "AcceptedAnswerId": "211824", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T11:21:19.737", "Id": "211806", "Score": "2", "Tags": [ "php", "http" ], "Title": "PHP HTTP request class" }
211806
<p>I have the Repository below, but I have noticed that there is a recurrent pattern <code>try</code> / <code>catch</code> which does not seem to be that clean, is there a better way to achieve or to extract that sort logic elsewhere?</p> <pre><code>public class FlightRepository : IFlightRepository { private readonly FlightManagerDbContext _context; public FlightRepository(FlightManagerDbContext context) { _context = context; } public Result CreateFlight(Flight flight) { try { var tmp = _context.Flight.FirstOrDefault(f =&gt; f.Code == flight.Code); if (tmp != null) return Result.Conflict($"Flight {flight.Code} already exists"); _context.Flight.Add(flight); _context.SaveChanges(); return Result.Ok("Flight successfully saved"); } catch (Exception e) { return Result.Fail(new List&lt;string&gt;() {$"An error occured, {e.Message}"}); } } public Result UpdateFlight(Flight flight) { try { var tmp = _context.Flight.FirstOrDefault(f =&gt; f.Code == flight.Code); if (tmp == null) return Result.NotFound($"Flight { flight.Code} not found"); var toUpdate = _context.Flight.First(f =&gt; f.Code == flight.Code); toUpdate.Distance = flight.Distance; toUpdate.DepartureLatitude = flight.DepartureLatitude; toUpdate.DepartureLongitude = flight.DepartureLongitude; toUpdate.DepartureName = flight.DepartureName; toUpdate.DepartureTime = flight.DepartureTime; toUpdate.ArrivalLatitude = flight.ArrivalLatitude; toUpdate.ArrivalLongitude = flight.ArrivalLongitude; toUpdate.ArrivalName = flight.ArrivalName; toUpdate.ArrivalTime = flight.ArrivalTime; toUpdate.ConsumptionPerKm = flight.ConsumptionPerKm; toUpdate.TakeOffEffort = flight.TakeOffEffort; toUpdate.FlightTime = flight.FlightTime; toUpdate.FuelNeeded = flight.FuelNeeded; _context.SaveChanges(); return Result.Ok($"Flight {flight.Code} successfully updated"); } catch (Exception e) { return Result.Fail(new List&lt;string&gt;() {$"An error occured, {e.Message}"}); } } public Result&lt;Flight&gt; SelectFlight(string code) { try { var flight = _context.Flight.FirstOrDefault(f =&gt; f.Code == code); if (flight == null) return Result&lt;Flight&gt;.NotFound($"Flight {code} not found"); return Result&lt;Flight&gt;.Ok(flight); } catch (Exception e) { return Result&lt;Flight&gt;.Fail(new List&lt;string&gt;(){$"An error occured, {e.Message}"}); } } public Result&lt;List&lt;Flight&gt;&gt; SelectFlights() { try { return Result&lt;List&lt;Flight&gt;&gt;.Ok(_context.Flight.Any() ? _context.Flight.ToList() : new List&lt;Flight&gt;()); } catch (Exception e) { return Result&lt;List&lt;Flight&gt;&gt;.Fail(new List&lt;string&gt;() {$"An error occured,{e.Message}"}); } } } </code></pre>
[]
[ { "body": "<p>The repository does not need to take responsibility for the errors - remove them from here. The flight repository should add CRUD operations to Flight Dto and not return a result - remove the result. Validation should be done before calling the methods. You are not an automapper, use a tool. You do not need to invent a bicycle every time you need a new repository, use generics. Additionally, you do not need to repeat Flight in every method name, they exist in the Flight repository you can infer that from context. \nAll error messages should be unique.</p>\n\n<p>For example, implement an interface:</p>\n\n<pre><code>public interface IRepository&lt;T&gt; where T : EntityBase\n{\n T GetById(int id);\n IEnumerable&lt;T&gt; List();\n void Add(T entity);\n void Delete(T entity);\n void Edit(T entity);\n}\n\npublic abstract class EntityBase\n{\n public int Id { get; protected set; }\n}\n</code></pre>\n\n<p>For more info: <a href=\"https://deviq.com/repository-pattern/\" rel=\"noreferrer\">https://deviq.com/repository-pattern/</a></p>\n\n<p>The model that contains the list of flights should contain the validation rules and validate flights or the model of the Flight should validate itself. </p>\n\n<p>What you get from the database is not a Flight model, but a dto. You should use a translator to create a model from dto. Dto's should not contain any business logic just data. Clear separation of concerns helps is needed for clear code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T16:09:59.853", "Id": "409589", "Score": "2", "body": "As for the try-catch, it is fine if you write code like that, this is not the kind of duplication that you need to worry about. Before you start using Rx observables or enterprise level patterns try-catch without failover policy and logging is fine as is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T19:04:13.233", "Id": "409598", "Score": "0", "body": "not sure then, what kind of layer is taking care of the error then? For now the chain is something like: `DB => Repository => Service => Controller => UI` (React / Angular)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T13:06:34.130", "Id": "409648", "Score": "1", "body": "First of all, any DB admin would tell you that unique indexes/constraints/data validation/triggers should be in the database. On the other hand, React / Angular are full MVVM frameworks themselves and can do everything themselves and use an ex: Firebase. Typically service and the controller should do validation. In short - everything except the repository itself. :P" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T16:05:25.163", "Id": "211815", "ParentId": "211808", "Score": "5" } } ]
{ "AcceptedAnswerId": "211815", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T13:48:39.210", "Id": "211808", "Score": "2", "Tags": [ "c#", ".net", "entity-framework" ], "Title": "Repository to update flights" }
211808
<p>The original question can be seen here: <a href="https://codereview.stackexchange.com/questions/211726/stack-implementation-in-c-using-linked-list/211790#211790">Stack implementation in C++ using linked list</a></p> <p>Changes (with the help of Martin):</p> <ul> <li>Added copy constructor and assignment operator overload</li> <li>Changed return type of peek() to const T&amp; rather than T (this prevents unnecessary copying of data)</li> <li>Changed return type of pop() to void; it now only removes the top item rather than returning it on top. The user can call peek() and then call pop() to retrieve and then delete the item. This means we don't have to return T by value, and also maintains the "Strong Exception Guarantee".</li> <li>Fixed a bug in pop() where the new head is deleted rather than the old one</li> </ul> <pre><code>#ifndef TEST_STACK_H #define TEST_STACK_H #include &lt;stdexcept&gt; template &lt;class T&gt; class stack { struct node { T data; node* previous; node(T data, node *previous) : data(data), previous(previous) {} }; node* head = nullptr; int size = 0; int max = -1; // -1 so isFull() == false when default constructor used public: stack() = default; stack(int max) { if (max &lt;= 0) throw std::out_of_range("stack size must be &gt; 0"); this-&gt;max = max; } // copy constructor stack(stack const&amp; rhs) : head(copyList(rhs.head)), size(rhs.size), max(rhs.size) {} // assignment operator stack&amp; operator = (stack const&amp; rhs) { stack tmp(rhs); swap(tmp); return *this; } ~stack() { node* n = head; while (n != nullptr) { node* previous = n-&gt;previous; delete n; n = previous; } } void push(const T &amp;object) { if (isFull()) throw std::overflow_error("cannot push to a full stack"); head = new node(object, head); ++size; } const void pop() { if (head == nullptr) throw std::underflow_error("cannot get item from empty stack"); node* old = head; head = head-&gt;previous; --size; delete old; } T peek() { if (head == nullptr) throw std::underflow_error("cannot get item from empty stack"); return head-&gt;data; } int getSize() { return size; } bool isFull() { return size == max; } bool isEmpty() { return head == nullptr; } void swap(stack&amp; other) noexcept { using std::swap; swap(head, other.head); swap(size, other.size); swap(max, other.max); } private: node* copyList(node* l) { if (l == nullptr) { return nullptr; } return new node{l-&gt;data, copyList(l-&gt;previous)}; } }; #endif </code></pre>
[]
[ { "body": "<pre><code>#include &lt;stdexcept&gt;\n</code></pre>\n\n<p>And either <code>&lt;utility&gt;</code> or <code>&lt;algorithm&gt;</code>, for <code>std::swap</code>.</p>\n\n<hr>\n\n<pre><code>stack(int max) {\n</code></pre>\n\n<p>I very strongly recommend you make this constructor <code>explicit</code>. Right now it's a non-explicit (implicit) conversion, which means you're permitting your users to convert integers to stacks implicitly:</p>\n\n<pre><code>void foo(stack&lt;int&gt; s);\nvoid bar() {\n foo(42); // compiles and calls foo with stack&lt;int&gt;(42)\n}\n</code></pre>\n\n<p>The general rule (at least for user codebases) is \"make everything <code>explicit</code> unless you have some specific reason that it <em>needs</em> to be implicit.\" So you should make your <code>node</code> constructor <code>explicit</code> as well.</p>\n\n<p>(I say \"at least for user codebases\" because the STL itself doesn't follow that principle — partly because the principle wasn't understood in 1998, and partly due to differences of opinion among the authors. \"STL style\" would be to make <code>stack(int)</code> explicit because it's a one-argument constructor, but leave all zero- and two-argument constructors implicit. I recommend against doing that.)</p>\n\n<hr>\n\n<pre><code>int max = -1; // -1 so isFull() == false when default constructor used\n</code></pre>\n\n<p>This comment doesn't help me understand. I would understand <code>INT_MAX</code>, but <code>-1</code> just looks like it's breaking the class invariant enforced by the one-argument constructor:</p>\n\n<pre><code>if (max &lt;= 0) throw std::out_of_range(\"stack size must be &gt; 0\");\n</code></pre>\n\n<p>Looking at these two lines in isolation, actually, I briefly wondered \"wait, doesn't that <em>always</em> throw? You don't initialize <code>max</code> before that <code>if</code>, so it would have its default value, which <em>is</em> less than zero...\" But then I realized that the name <code>max</code> here is overloaded: the <code>max</code> in the <code>if</code> statement is testing the <em>function parameter</em>, not the <em>data member</em>.</p>\n\n<p>To eliminate confusion about name overloading, I strongly recommend that you sigil each of your data members with a trailing underscore: <code>max_</code>, <code>size_</code>, <code>head_</code>.\nThen you don't have to write <code>this-&gt;</code> when you access a member:</p>\n\n<pre><code>this-&gt;max = max;\n</code></pre>\n\n<p>can become just</p>\n\n<pre><code>max_ = max;\n</code></pre>\n\n<p>You don't need the disambiguating <code>this-&gt;</code>, because there's no confusion anymore about which <code>max</code>/<code>max_</code> you mean.</p>\n\n<hr>\n\n<pre><code>stack(stack const&amp; rhs) :\n head(copyList(rhs.head)),\n size(rhs.size),\n max(rhs.size) {}\n</code></pre>\n\n<p>Do you see the typo?</p>\n\n<p>Write some unit tests for your code! In particular, now that you've spotted a bug, <em>write a unit test that would have caught this bug</em> and commit it as part of the bugfix. That's called a \"regression test.\"</p>\n\n<hr>\n\n<pre><code>stack&amp; operator = (stack const&amp; rhs)\n{\n stack tmp(rhs);\n swap(tmp);\n\n return *this;\n}\n</code></pre>\n\n<p>FYI, the copy-and-swap idiom can be written more concisely if you want to:</p>\n\n<pre><code>stack&amp; operator=(stack const&amp; rhs)\n{\n stack(rhs).swap(*this);\n return *this;\n}\n</code></pre>\n\n<hr>\n\n<pre><code>const void pop() {\n</code></pre>\n\n<p>The <code>const</code> here <a href=\"https://quuxplusone.github.io/blog/2019/01/03/const-is-a-contract/\" rel=\"noreferrer\">is useless</a>; remove it. (I wonder if it was a mistake for something similar — <code>void pop() const</code>? <code>constexpr void pop()</code>? but neither of those makes sense either.)</p>\n\n<hr>\n\n<pre><code>T peek() {\n</code></pre>\n\n<p>OTOH, <em>this</em> method should be const:</p>\n\n<pre><code>T peek() const {\n if (head == nullptr) throw std::underflow_error(\"cannot get item from empty stack\");\n return std::as_const(head-&gt;data);\n}\n</code></pre>\n\n<p>I threw in an <code>as_const</code> just to illustrate complete paranoia. We don't know what type <code>T</code> is, right? So when you construct the return value <code>T</code>, which constructor do you want to call — <code>T(T&amp;)</code> or <code>T(const T&amp;)</code>? Write a unit test for a type <code>T</code> where it makes a difference, and see what happens.</p>\n\n<hr>\n\n<p><code>getSize()</code>, <code>isFull()</code>, and <code>isEmpty()</code> should all be <code>const</code> methods as well.</p>\n\n<hr>\n\n<pre><code>void swap(stack&amp; other) noexcept\n</code></pre>\n\n<p>Good! You also do the <code>using std::swap;</code> dance correctly — although, since you're not swapping anything but ints and pointers, the dance is unnecessary in this case, but hey it's good practice.</p>\n\n<p>You did forget, though, that if you want the <code>using std::swap;</code> dance to work for anyone else who <em>uses</em> your <code>stack</code> class, you'll need to provide that free ADL function <code>swap</code>. So we add an inline friend:</p>\n\n<pre><code>friend void swap(stack&amp; a, stack&amp; b) noexcept {\n a.swap(b);\n}\n</code></pre>\n\n<p>Now</p>\n\n<pre><code>using std::swap;\nswap(redstack, bluestack);\n</code></pre>\n\n<p>will be as efficient as possible.</p>\n\n<hr>\n\n<p>Consider adding move semantics to your class — <code>stack(stack&amp;&amp;) noexcept</code>, <code>stack&amp; operator=(stack&amp;&amp;) noexcept</code>, <code>void push(T&amp;&amp;)</code> (or just <code>void push(T)</code> at that point). I assume you left them out on purpose for this simple example.</p>\n\n<hr>\n\n<p>Your <code>copyList</code> is recursive. This could blow your stack if you're copying a very long list. You successfully eliminated the recursion from your destructor — why not eliminate it here too?</p>\n\n<pre><code>node* copyList(node* l)\n</code></pre>\n\n<p>Since this member function doesn't need the <code>this</code> pointer for anything, it should be marked <code>static</code>. And it wouldn't hurt to add <code>const</code> to the node you don't intend to modify, just for a tiny bit of self-documentation:</p>\n\n<pre><code>static node *copyList(const node *l)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:12:52.423", "Id": "409608", "Score": "0", "body": "That was very helpful, thank you. Also for some reason the peek() method had the wrong return type. Shouldn’t it be const T& rather than T to prevent unnecessary copying of the object? This would be bad if T was large." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T23:04:26.377", "Id": "409611", "Score": "1", "body": "@Samueljh1: Yes, there is an efficiency advantage to returning `const T&`. There is also a disadvantage in that it opens the possibility of dangling-reference bugs. It depends on your use-case. If you're frequently going to do e.g. `if (x < stk.peek())` or `std::cout << x.peek()` — so returning by const ref would frequently save you a copy — then yeah, it's totally worth thinking about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T18:10:13.050", "Id": "409680", "Score": "0", "body": "Yes, I did think of that possibility, but the user should be responsible enough to not try to access the value after calling pop(). With the suggestion of move semantics you made, for example push(T&&), what exactly do I need to put in that method? Do i just call the regular push from there, or do I have to do something more complicated?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T20:22:52.643", "Id": "409721", "Score": "0", "body": "That's a question for a different forum. Read all the answers to [What are move semantics?](https://stackoverflow.com/questions/3106110/what-are-move-semantics) at least. But basically it'd be the same as `push(const T&)` except that you'd say `head = new node(std::move(object), head)` instead of `head = new node(object, head)`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T16:53:06.273", "Id": "211819", "ParentId": "211811", "Score": "6" } } ]
{ "AcceptedAnswerId": "211819", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T14:52:20.460", "Id": "211811", "Score": "1", "Tags": [ "c++", "beginner", "stack" ], "Title": "C++ Updated Stack Code" }
211811
<p>I've written classes <code>Store</code>, <code>Cart</code>, <code>User</code> that manages methods that allow the user to add/remove products from a shopping cart, as well as being able to query different descriptions about the item (id, price, quantity). The <code>User</code> class hasn't fully been utilized yet. I'm wondering if there is any way to make this more compact/efficient? I use some recursion while generating an ID, but I'm wondering if it can be implemented in a better way. Any and all suggestions are welcomed! Thank you! There is also a test file (linked at bottom) I use to generate items and test the methods within the class.</p> <p><strong>store.py</strong></p> <pre><code>import random class Store(): def __init__(self): self.products = {} self.product_ids = [] """ Adds a product dict to the self.products dict """ def add_product(self, product): self.products[product['name']] = { 'id': self.generate_product_id(), 'price': product['price'], 'quantity': product['quantity'] } """ Removes a product dict from self.products dict, unless the user is not an admin or the store doesn't have the item, then it raises an exception """ def delete_product(self, product, user): if not user.is_admin(): raise Exception('Must be admin to delete') if not self.has_product(product_id): raise Exception('Unknown product id') del self.products[product['name']] """ Returns true if the product id passed does not appear in the product_ids array, else returns false """ def existing_id(pid): for x in self.product_ids: if pid == x: return True return False """ Returns a random number used to distinguish between products and makes sure it isn't already in use by appending it to an array. """ def generate_product_id(self): rnum = random.randint(100000,999999) if not existing_id(rnum): self.product_ids.append(rnum) return rnum else: self.generate_product_id() """ Methods for getting product information """ def get_product(self, product): return self.products[product['name']] def get_product_id(self, product): return self.products[product['name']]['id'] def get_product_price(self, product): return self.products[product['name']]['price'] def get_product_quantity(self, product): return self.products[product['name']]['quantity'] """ Reduces quantity of specified product, unless amount is greater than the product['quantity'], then it raises an exception """ def reduce_quantity(self, product, amount): if amount &gt; self.products[product['name']]['quantity']: raise Exception('Amount greater than quantity!') self.products[product['name']]['quantity'] -= amount </code></pre> <p><strong>cart.py</strong></p> <pre><code>class Cart(): def __init__(self): self.items = {} self.final_price = 0 """ Adds product to cart, then updates final price """ def add_to_cart(self, product): self.items[product['name']] = { 'price': product['price'], 'quantity': product['quantity'] } self.final_price += (product['price'] * product['quantity']) """ Prints each element of self.items, their price &amp; quantity """ def print_cart(self): for x in self.items: print(x) print(' ' + "Price: $" + str(self.items[x]['price'])) print(' ' + "Quantity: " + str(self.items[x]['quantity'])) """ Returns self.final_price, being calculated in 'add_to_cart' """ def get_final_price(self): return self.final_price </code></pre> <p><strong>user.py</strong></p> <pre><code>class User(): def __init__(self, admin=False): self.admin = admin def is_admin(self): return self.admin </code></pre> <p><strong>main.py</strong></p> <pre><code>from store import * from cart import * from user import * def main(): store = Store() cart = Cart() name = ['Fancy Shoes', 'Fancy Pants'] price = [147.00, 162.00] quantity = [10, 8] for i in range(len(name)): product = { 'name': name[i], 'price': price[i], 'quantity': quantity[i] } store.add_product(product) cart.add_to_cart(product) cart.print_cart() print("Final Price: $" + str(cart.get_final_price())) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<ol>\n<li><p>For efficiency, I would change <code>Store</code> to have only a <code>products</code> attribute, which maps the product id to the product object. You can then have functions which look up products by name, price, etc. if desired.</p></li>\n<li><p>Bug:</p>\n\n<pre><code>def generate_product_id(self):\n rnum = random.randint(100000,999999)\n if not existing_id(rnum):\n self.product_ids.append(rnum)\n return rnum\n else:\n # FIX\n return self.generate_product_id()\n</code></pre></li>\n<li><p>Some of your methods are unnecessary:</p>\n\n<pre><code>def get_product_price(self, product):\n return self.products[product['name']]['price']\n</code></pre>\n\n<p>Simply use <code>product['price']</code> instead of calling this method with a product.</p></li>\n<li><p>Perhaps it makes sense to also have a <code>Product</code> class in the future.</p></li>\n<li><p><code>Cart.items</code> makes more sense as a list I think.</p></li>\n<li><p><code>Cart.final_price</code>: I would calculate it dynamically, which makes code for adding and removing products simpler. Performance difference is insignificant.</p></li>\n<li><p>Finally, in Python, the docstring is placed inside the function (doesn't change the output, but allows Python documentation tools to recognize your docstrings):</p>\n\n<pre><code>def my_function():\n \"\"\" Docstring \"\"\"\n return True\n</code></pre></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:50:28.480", "Id": "211838", "ParentId": "211813", "Score": "4" } }, { "body": "<p>I agree with all points mentioned in the <a href=\"https://codereview.stackexchange.com/a/211838/98493\">other answer</a> by <a href=\"https://codereview.stackexchange.com/users/167170/pj-dewitte\">@pj.dewitte</a>.</p>\n\n<p>In addition, in Python it is frowned upon to write explicit getters and setters for your attributes if they are not needed. Just use the attribute directly. If you need to add more stuff around it later, then you can still write a getter/setter and use <code>@property</code> so the interface does not change.</p>\n\n<pre><code>class User():\n def __init__(self, admin=False):\n self.is_admin = admin\n</code></pre>\n\n<p>Python also has an official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using a consistent amount of whitespace for indentation. Currently you seem to be using two spaces for methods and four spaces for indentation within those methods. Just use four spaces everywhere.</p>\n\n<p>Python has something called <a href=\"https://www.python-course.eu/python3_magic_methods.php\" rel=\"nofollow noreferrer\">magic methods</a> (sometimes also called dunder methods, for \"double-underscore\", you will see why in a moment). They allow you to give your custom classes built-in behavior. For example, if you implement the <code>__str__</code> method, you can then do <code>print(obj)</code> and this method will be called internally to create a readable string to display to the user. </p>\n\n<p>In Python 3.6, <code>f-string</code>s were introduced (described in <a href=\"https://www.python.org/dev/peps/pep-0498/\" rel=\"nofollow noreferrer\">PEP498</a>), which makes writing formatted strings a lot easier.</p>\n\n<pre><code>class Cart():\n\n def __init__(self):\n self.items = {}\n\n def __str__(self):\n \"\"\"\n Returns a string with each element of self.items, their price &amp; quantity\n \"\"\"\n lines = []\n for name, product in self.items.items():\n lines.append(name)\n lines.append(f\" Price: ${product['price']}\")\n lines.append(f\" Quantity: {product['quantity']}\")\n return \"\\n\".join(lines)\n\n @property\n def final_price(self):\n return sum(product[\"price\"] * product[\"quantity\"]\n for product in self.items.values())\n\n def add_to_cart(self, product):\n \"\"\"Adds product to cart.\"\"\"\n self.items[product['name']] = {\n 'price': product['price'],\n 'quantity': product['quantity']\n }\n</code></pre>\n\n<p>By making <code>final_price</code> a <code>property</code> that is evaluated everytime it is accessed, this also allows you to implement <code>delete_item_from_cart</code> and <code>reduce_quantity_in_cart</code> methods without having to make sure to always update the price properly. Of course if your carts become very large (> 10000 items), doing it like you did with an attribute that is updated where necessary will be faster.</p>\n\n<p>One other point: It might make sense to make <code>cart.items</code> into a <code>list</code>, instead of a <code>dict</code>. Or at least add additional checks to <code>add_to_cart</code> against an item being added multiple times (with a <code>dict</code> it will just be overwritten, instead of the quantity added and checked that it actually is the same product and does not just have the same name).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T12:43:24.480", "Id": "409646", "Score": "2", "body": "This actually clarifies some points in my answer, good work!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T09:11:59.497", "Id": "211851", "ParentId": "211813", "Score": "3" } } ]
{ "AcceptedAnswerId": "211838", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T15:32:26.920", "Id": "211813", "Score": "2", "Tags": [ "python" ], "Title": "Store interface" }
211813
<p>I am experimenting with JavaScript ES6 import and export and wanted to achieve the following:</p> <ul> <li>Use the import / export style of including JavaScript files.</li> <li>Import a class file and create an instance</li> <li>Import a class file that extends another class</li> <li>Expose functions to the index.html scope - call from an inline onclick event</li> <li>Is document. available within the module scope</li> </ul> <p>Is this the correct, or recommended way of doing this, or is there a better way?</p> <p>index.html</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="UTF-8"&gt; &lt;title&gt;Javascript - Import and Export class examples&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt;Javascript Import and Export class examples&lt;/h1&gt; &lt;div id="myDiv"&gt;&lt;/div&gt; &lt;button onclick="window.updateScreen()"&gt;Do it&lt;/button&gt; &lt;script type="module"&gt; import('./main.js').then(module =&gt; { /* This function is now available on the button onclick */ window.updateScreen = module.updateScreen; }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>main.js</p> <pre><code>import { Animal } from './animal.js'; import { Human } from './human.js'; import { Dog, Cat } from './pets.js'; const petOwner = new Human('Bob', 'Male', '21/03/19'); const pets = [ new Dog('Riley', petOwner), new Cat('Sherry', petOwner) ]; petOwner.speak(); pets[1].speak(); pets[0].speak(); function updateScreen() { let elem = document.getElementById('myDiv'); elem.textContent = 'HELLO'; } export { updateScreen }; </code></pre> <p>animal.js</p> <pre><code>class Animal { constructor(alive, hr) { this.isAlive = alive; this.heartRate = hr; } } export { Animal }; </code></pre> <p>human.js</p> <pre><code>import {Animal} from './animal.js'; class Human extends Animal { constructor(name, sex, dob) { super(true, 60); this.name = name; this.dob = dob; this.sex = sex; } speak() { console.log('Hello'); } get age() { return now-dob; } } export { Human }; </code></pre> <p>pets.js</p> <pre><code>import {Animal} from './animal.js'; class Cat extends Animal { constructor(name, owner) { super(true, 200); this.name = name; this.owner = owner; } speak() { console.log('Meow'); } } class Dog extends Animal { constructor(name, owner) { super(true, 120); this.name = name; this.owner = owner; } speak() { document.getElementById('myDiv').textContent = 'Woof'; } } export { Cat, Dog }; </code></pre>
[]
[ { "body": "<p>Looks good to me for the most part. Some things I noticed:</p>\n\n<ul>\n<li><p>You can export a function/class directly, e.g.</p>\n\n<pre><code>export class Foo {}\n</code></pre>\n\n<p>is a shorthand for </p>\n\n<pre><code>class Foo {}\nexport { Foo }\n</code></pre>\n\n<p>The same holds for functions and variable declarations. What you. prefer comes down to preference.</p></li>\n<li><p>Since <code>import()</code> is asynchronous, your <code>onclick</code> on the button will throw an error if you click the button before the <code>Import</code> is finished (e.g. when the network is slow or something). So you should check if <code>window.updateScreen</code> is already defined and/or adapt the UX (e.g. deactivate the button until the import is finished)</p></li>\n<li><p>Instead of doing a dynamic import, you could bind the <code>onclick</code> in <code>main.js</code> similar to how you did with the div.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T12:12:14.840", "Id": "409643", "Score": "0", "body": "Thanks inyono, I kind of like the export at the end as a pure style thing. Good tips." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T13:30:57.737", "Id": "409651", "Score": "0", "body": "Glad I could help :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T01:00:11.193", "Id": "211842", "ParentId": "211814", "Score": "0" } }, { "body": "<p>Your main.js does not have a direct dependency on Animal class, so much there is no reason to import it there. In fact, from standpoint of minimizing browser calls to include files, it might make better sense to keep all classes in a related hierarchy together in a single file. So, I would probably have Animal, Human, Cat and Dog in the same file unless the was a compelling reason to split them - like Human was used on every page while Cat an Dog were only used sparingly in the site.</p>\n\n<p>Generally, it is a good idea to be consistent about what sort of “side effects” a piece of code (class) makes. I know this is just an example, but it seems odd for these classes to log out the results of the speak() methods, when it really is the caller that should determine what happens with the result of the method call (logging it, updating Page with it, etc.)</p>\n\n<p>Main.js seems a little odd with regards to why you are exporting the updateScreen function. This function doesn’t really do anything different after the first time it is executed so not sure why it is exported as a function. Also, this module creates the side effect off all of the instantiated objects speaking upon inclusion of the module. This would happen even if the updateScreen function was never called. Again this seems like odd behavior to be happening upon import.</p>\n\n<p>In Human class, is date of birth a property specific only to humans, or should this exist on Animal class. You should consider passing and setting a proper date object for this property. Should age be a property on the object? This is able to be determined in the constructor, right? It seems odd to me to have getter method for this “property” and not the others. In the age getter, there is reference to “now” variable that is undefined and you are further trying to perform subtraction using dob string value that has not been converted to proper Date object. Use Dates here for this math.</p>\n\n<p>In Dog class to have especially questionable side effect in the speak method in that you have hard coded a reference to a div to be updated. This class should not need to understand Dom at all. The way it is now limits reuse of this class because it is tightly coupled to the Dom via this logic which has nothing to do with a dog at all.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T14:57:20.727", "Id": "409658", "Score": "0", "body": "Thanks Mike, great suggestions. updateScreen is just an example of what I may need one day, but I'll have a tidy up based on your comments." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T14:49:50.737", "Id": "211860", "ParentId": "211814", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T15:48:44.113", "Id": "211814", "Score": "0", "Tags": [ "javascript", "ecmascript-6" ], "Title": "JavaScript ES6 import / export" }
211814
<p>I'm creating a filter in python/django. I want to make a datetime human-readable. You have multiple options: Plain Datetime ("04. Februar 2018, 18:18")</p> <pre><code>(bools="False,False"), </code></pre> <p>sentence Datetime ("am 04. Februar 2018 um 18:18")</p> <pre><code>(bools="True,False"), </code></pre> <p>onlydate Datetime ("04. Februar 2018")</p> <pre><code>(bools="False,True"), </code></pre> <p>sentence and onlyDate ("am 04. Februar 2018")</p> <pre><code>(bools="True,True") </code></pre> <p>Here's my filter:</p> <pre><code>@register.filter def naturaldaytime(daytime, bools="False,False"): if daytime is None: return daytime sentence = str2bool(bools.split(",")[0]) onlyDate = str2bool(bools.split(",")[1]) now = datetime.datetime.now() difference = now.day - daytime.replace(tzinfo=None).day loc = locale.setlocale(locale.LC_TIME, "de") if onlyDate: if difference == 0: return daytime.strftime(settings.DATE_FORMAT_TODAY) if not sentence else daytime.strftime(settings.DATE_FORMAT_SENTENCE) elif difference == 1: return daytime.strftime(settings.DATE_FORMAT_YESTERDAY) if not sentence else daytime.strftime(settings.DATE_FORMAT_YESTERDAY) elif now.isocalendar()[0] == daytime.isocalendar()[0]: if now.isocalendar()[1] == daytime.isocalendar()[1]: return daytime.strftime(settings.DATE_FORMAT_THIS_WEEK) if not sentence else daytime.strftime(settings.DATE_FORMAT_THIS_WEEK_SENTENCE) return daytime.strftime(settings.DATE_FORMAT_THIS_YEAR) if not sentence else daytime.strftime(settings.DATE_FORMAT_THIS_YEAR_SENTENCE) return daytime.strftime(settings.DATE_FORMAT) if not sentence else daytime.strftime(settings.DATE_FORMAT_SENTENCE) else: pass #so what... def str2bool(v): return v.lower() in ("yes", "true", "t", "1") </code></pre> <p>and my settings vars:</p> <pre><code>TIME_FORMAT = "%H:%M" DATE_FORMAT = "%d. %B %Y, {0}".format(TIME_FORMAT) DATE_FORMAT_THIS_YEAR = "%d. %B, {0}".format(TIME_FORMAT) DATE_FORMAT_THIS_WEEK = "%A, {0}".format(TIME_FORMAT) DATE_FORMAT_YESTERDAY = "Gestern, {0}".format(TIME_FORMAT) DATE_FORMAT_TODAY = "Heute, {0}".format(TIME_FORMAT) DATE_FORMAT_SENTENCE = "am %d. %B %Y um {0} Uhr".format(TIME_FORMAT) DATE_FORMAT_THIS_YEAR_SENTENCE = "am %d. %B um {0} Uhr".format(TIME_FORMAT) DATE_FORMAT_THIS_WEEK_SENTENCE = "diesen %A um {0} Uhr".format(TIME_FORMAT) DATE_FORMAT_YESTERDAY_SENTENCE = "gestern um {0} Uhr".format(TIME_FORMAT) DATE_FORMAT_TODAY_SENTENCE = "heute um {0} Uhr".format(TIME_FORMAT) </code></pre>
[]
[ { "body": "<h2>Set your locale globally</h2>\n\n<p>I would recommend doing this in your <code>settings.py</code> file or within a global <code>__init__.py</code> file.</p>\n\n<pre><code>locale.setlocale(locale.LC_TIME, \"de\")\n</code></pre>\n\n<h2>Django template tags allow multiple parameters, use them</h2>\n\n<p>Right now you have a single complex parameter which is being used to store two pieces of information: whether to use a sentence and if only the date should be rendered. Since this is passed in as a single string, you have to use <a href=\"https://stackoverflow.com/q/715417/359284\">the <code>str2bool</code> function from Stack Overflow</a> in order to parse it. You don't need to parse that string if you use separate arguments.</p>\n\n<pre><code>@register.filter\ndef naturaldaytime(daytime, sentence=False, only_date=False):\n from django.conf import settings\n\n if daytime is None:\n return daytime\n</code></pre>\n\n<h2>Use descriptive variable names in your comparisons</h2>\n\n<p>Right now you have to look into nested calls to understand what comparisons are actually being done. While this still needs to happen, you can make us to intermediate variables which makes it a lot more clear what is happening.</p>\n\n<pre><code>todays_date = datetime.now().date()\nyesterdays_date = todays_date - timedelta(days=1)\n\ndaytime_week_number = daytime.date().isocalendar()[1]\ntodays_week_number = todays_date.isocalendar()[1]\n</code></pre>\n\n<h2>Construct the format key you need so you can avoid repetition</h2>\n\n<p>Right now you have a complex set of conditional statements that you are using to determine what date format to use. This is resulting in a ton of repetition when it comes to doing the actual formatting, so I would recommend separating the \"getting the right format settings\" part from the actual \"do the formatting\".</p>\n\n<pre><code>if not only_date:\n setting_key = \"DATETIME_FORMAT\"\nelse:\n setting_key = \"DATE_FORMAT\"\n\nif daytime.date() == todays_date:\n setting_key += \"_TODAY\"\nelif daytime.date() == yesterdays_date:\n setting_key += \"_YESTERDAY\"\nelif daytime_week_number == todays_week_number:\n setting_key += \"_THIS_WEEK\"\nelif daytime.date().year == todays_date.year:\n setting_key += \"_THIS_YEAR\"\n\nif sentence:\n setting_key += \"_SENTENCE\"\n</code></pre>\n\n<p>This way you don't need to keep repeating the same logic for every \"sentence\" or \"not only the date\" variant, and you can keep settings keys consistent at the same time.</p>\n\n<h2>Get the right date format using that settings key you already built</h2>\n\n<p>This part doesn't change much, except you now need to dynamically retrieve the setting from the <code>settings</code> object.</p>\n\n<pre><code>date_format = getattr(settings, setting_key)\n\nreturn daytime.strptime(date_format)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:06:09.420", "Id": "412506", "Score": "0", "body": "Great, thank you! But I dont understand why you need to import settings from django.conf (Second code, line 3, \"`from django.conf import settings`\")" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-11T17:12:38.290", "Id": "412508", "Score": "0", "body": "And how do I use this filter in a template?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T22:37:08.450", "Id": "213217", "ParentId": "211820", "Score": "2" } } ]
{ "AcceptedAnswerId": "213217", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T17:27:18.780", "Id": "211820", "Score": "1", "Tags": [ "python", "django" ], "Title": "Python/Django Filter with Datetime and extra options" }
211820
<p>Below is my code that 1) writes a CSV file with three columns of integer data (plus column names on the first line) and 2) reads the CSV file. I'm new to C++ and would appreciate some code review. </p> <p>Also, I'm bothered by the fact that my technique requires all of the data to be integers. I'd appreciate advice on how I could generalize this code to write/read data with a mix of integers, doubles, strings, etc.</p> <pre><code>#include &lt;string&gt; // std::string #include &lt;fstream&gt; // std::ofstream, std::ifstream #include &lt;vector&gt; // std::vector #include &lt;utility&gt; // std::pair #include &lt;stdexcept&gt; // std::runtime_error #include &lt;sstream&gt; // std::stringstream #include &lt;iostream&gt; // std::cout, std::cin void write_csv(std::string filename, std::vector&lt;std::pair&lt;std::string, std::vector&lt;int&gt;&gt;&gt; dataset){ // Make a CSV file with one or more columns of integer values // Each column of data is represented by the pair &lt;column name, column data&gt; // as std::pair&lt;std::string, std::vector&lt;int&gt;&gt; // The dataset is represented as a vector of these columns // Note that all columns should be the same size // Create an output filestream object std::ofstream myFile(filename); // Send column names to the stream for(int j = 0; j &lt; dataset.size(); ++j) { myFile &lt;&lt; dataset.at(j).first; if(j != dataset.size() - 1) myFile &lt;&lt; ","; // No comma at end of line } myFile &lt;&lt; "\n"; // Send data to the stream for(int i = 0; i &lt; dataset.at(0).second.size(); ++i) { for(int j = 0; j &lt; dataset.size(); ++j) { myFile &lt;&lt; dataset.at(j).second.at(i); if(j != dataset.size() - 1) myFile &lt;&lt; ","; // No comma at end of line } myFile &lt;&lt; "\n"; } // Close the file myFile.close(); } std::vector&lt;std::pair&lt;std::string, std::vector&lt;int&gt;&gt;&gt; read_csv(std::string filename){ // Reads a CSV file into a vector of &lt;string, vector&lt;int&gt;&gt; pairs where // each pair represents &lt;column name, column values&gt; // Create a vector of &lt;string, int vector&gt; pairs to store the result std::vector&lt;std::pair&lt;std::string, std::vector&lt;int&gt;&gt;&gt; result; // Create an input filestream std::ifstream myFile(filename); // Make sure the file is open if(!myFile.is_open()) throw std::runtime_error("Could not open file"); // Helper vars std::string line, colname; int val; // Read the column names if(myFile.good()) { // Extract the first line in the file std::getline(myFile, line); // Create a stringstream from line std::stringstream ss(line); // Extract each column name while(std::getline(ss, colname, ',')){ // Initialize and add &lt;colname, int vector&gt; pairs to result result.push_back({colname, std::vector&lt;int&gt; {}}); } } // Read data, line by line while(std::getline(myFile, line)) { // Create a stringstream of the current line std::stringstream ss(line); // Keep track of the current column index int colIdx = 0; // Extract each integer while(ss &gt;&gt; val){ // Add the current integer to the 'colIdx' column's values vector result.at(colIdx).second.push_back(val); // If the next token is a comma, ignore it and move on if(ss.peek() == ',') ss.ignore(); // Increment the column index colIdx++; } } // Close file myFile.close(); return result; } int main() { // // Make three vectors, each of length N filled with 1s, 2s, and 3s int N = 1000; std::vector&lt;int&gt; vec1(N, 1); std::vector&lt;int&gt; vec2(N, 2); std::vector&lt;int&gt; vec3(N, 3); // Wrap into a vector std::vector&lt;std::pair&lt;std::string, std::vector&lt;int&gt;&gt;&gt; vals = {{"One", vec1}, {"Two", vec2}, {"Three", vec3}}; // Write the vector to CSV write_csv("three_cols.csv", vals); // Read three_cols.csv std::vector&lt;std::pair&lt;std::string, std::vector&lt;int&gt;&gt;&gt; three_cols = read_csv("three_cols.csv"); // Print row and column counts to check if this was successful std::cout &lt;&lt; "Rows: " &lt;&lt; three_cols.at(0).second.size() &lt;&lt; ", Columns: " &lt;&lt; three_cols.size() &lt;&lt; std::endl; return 0; } </code></pre>
[]
[ { "body": "<p>My first observation is that your object model is quite confusing; you have a vector of pairs with vectors, and it is very difficult to keep track of what is what. If I'm reading this code correctly, you should consider extracting this pair into a <code>column</code> class, giving you <code>std::vector&lt;column&gt;</code>.</p>\n\n<p>Once you have this <code>column</code> class, you can add additional properties to it, such as what type of data it contains, and a <code>void*</code> to the data in each cell.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:10:20.780", "Id": "409607", "Score": "1", "body": "I would strongly advise against `void*`. Some template metaprogramming might have higher development cost, but it will sure payoff in learning and correctness of user code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:02:29.047", "Id": "211832", "ParentId": "211826", "Score": "0" } }, { "body": "<h2>Good documentation</h2>\n\n<p>Every time I wanted to say \"but it behaves badly in case ...\", I found specification disallowing that case. One nitpick might be that \"with one or more columns\" could be explicitly written as \"<em>requires</em> at least one column\". The only thing left is to pray that people will read it.</p>\n\n<h2>Pass by const reference for only read purposes</h2>\n\n<p>Copying non-scalar and heavy data structures (strings, vectors) might incur significant overhead. Prefer to pass by const reference.</p>\n\n<h2>Check if file is opened</h2>\n\n<p>The check is performed when reading, but not performed when writing.</p>\n\n<h2>Do not use at() unless exception-throwing version is desired</h2>\n\n<p><code>.at()</code> incurs overhead by performing in-range check, and also throws if out of range. </p>\n\n<h2>Use emplace back to construct and push in place</h2>\n\n<pre><code>result.push_back({colname, std::vector&lt;int&gt; {}});\n</code></pre>\n\n<p>This could be rewritten as</p>\n\n<pre><code>result.emplace_back(colname, std::vector&lt;int&gt; {});\n</code></pre>\n\n<p>From C++17, if I'm not mistaken, the two are equivalent due to copy elision, but emplace version is a bit clearer.</p>\n\n<h2>Improve printing algorithm</h2>\n\n<p>This is a general problem of string joining. <a href=\"https://codereview.stackexchange.com/a/142912/93301\">This answer</a> shows a great implementation for a simple case. One can remove templates from them if needed.</p>\n\n<h2>Do not explicitly close file</h2>\n\n<p>Destructor of <code>std::ifstream</code> and of it's twin automatically close the file.</p>\n\n<h2>Create type alias where useful</h2>\n\n<pre><code>using column = std::pair&lt;std::string, std::vector&lt;int&gt;&gt;;\n</code></pre>\n\n<p>would save users a lot of typing.</p>\n\n<h2>Use locales for reading from csv</h2>\n\n<p>Whenever I want casual reading of csv files I just copy/paste from <a href=\"https://stackoverflow.com/a/25225612/4593721\">this asnwer</a> and march on.</p>\n\n<h2>Unreliable reading algorithm</h2>\n\n<p>I would be a bit worried to use it as is. It tends to assume the layout to be the same as in writing, but I'm afraid edge cases slip in and hit like a truck. This is one of the rare cases when enabling exceptions on the stream might be a good idea.</p>\n\n<hr>\n\n<h2>Architecture for generic reading/writing</h2>\n\n<p>I don't think implementing reading algorithm is a viable option, because it involves extreme amounts of error checking to be useful. As for writing:</p>\n\n<ul>\n<li><p>Upstream and downstream invariances</p>\n\n<p>Upstream invariance in this case is CSV format, which the final output has to obey. Downstream invariance is requirements on the result of object getting streamed (<code>file &lt;&lt; myObject</code>). One will need to specify the requirements on data type very clearly and with great scrutiny. For example, if one wants to accept <code>std::string</code> as data type, the user has to override default streaming for the type, which pulls them into realm of undefined behavior. This functionality clearly requires a lot of thought put into it in order to be correct and robust.</p></li>\n<li><p>Data layout</p>\n\n<p>This is one is just a speculation, but the way data is stored might be problematic in terms of performance. It would be better to create a data structure that stores headers, and then stores values row-wise. Access could be done by using header value as first subscript, and row index as second subscript. Horizontal offset can be saved for each header value to access the right cell in a row. This also would be a great learning exercise.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T16:57:38.647", "Id": "409813", "Score": "0", "body": "Lots of good tips in this answer and I've update my code to make use of most of them. Now I need to work on my generic CSV reader that can read ints, doubles, and strings.. Thanks for your help." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:09:02.157", "Id": "211834", "ParentId": "211826", "Score": "4" } }, { "body": "<h1>General design</h1>\n\n<p>Your dataset representation is a bit unconventional: since you need to write/read the file line by line, having the dataset oriented the other way might prove a hindrance. I understand that you might need to include / exclude columns from a particular file: but it isn't a sufficient reason to rotate your dataset: a more general, line-oriented dataset representation would allow you to do so too. In principle, you should separate concerns: handling your data on the one hand, reading/writing it from/to a csv file on the other hand.</p>\n\n<p>Also, your design forces the user to create headers, which isn't required by the format. The explanation, if I understood correctly, is that you weren't able to provide a type-erasing interface, so it was either headers for everyone or for no one.</p>\n\n<h1>Type-flexible cell</h1>\n\n<p>There are lots of ways to achieve that, and none is indisputably superior. You could consider <code>std::variant</code>, which is a standard, type-safe <code>union</code>:</p>\n\n<pre><code>#include &lt;variant&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nint main() {\n\n using Cell = std::variant&lt;int, double, std::string&gt;; // Cell can contain any of these types\n std::vector&lt;Cell&gt; record{\"John\", \"Doe\", 41, 1.75};\n for (const auto&amp; cell : record) {\n std::visit([](const auto&amp; content) { std::cout &lt;&lt; content &lt;&lt; ' '; }, cell);\n }\n}\n</code></pre>\n\n<p>Any column or line can now be represented by a sequence of <code>Cell</code>s. It means that you don't need to hard-code a header, or to store your data by type-homogeneous columns. You can even have your whole dataset in one big vector: it can be a lot faster because you have better locality (in your current implementation, the processor has to fetch the cells of a given line from as many places in memory).</p>\n\n<p>If you're ready to anticipate the next standard (<code>C++20</code>), and that you have your dataset contained in one big <code>std::vector&lt;Cell&gt;</code>, you can then have rows and columns as <code>range::view</code>s over your dataset: </p>\n\n<pre><code>#include &lt;variant&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n#include &lt;range/v3/core.hpp&gt;\n#include &lt;range/v3/view.hpp&gt;\n\nusing namespace ranges;\nusing namespace ranges::view;\n\nint main() {\n\n using Cell = std::variant&lt;int, double, std::string&gt;; \n std::vector&lt;Cell&gt; records{\"John\", \"Doe\", 41, 1.75, \"Jane\", \"Smith\", 35, 1.63}; \n const int row_sz = 4;\n\n auto column = [row_sz](int n) {\n // to get column n, skip the n first elements\n // then take every row-szth element\n return drop(n) | stride(row_sz);\n };\n\n for (auto cell : records | column(1)) {\n std::visit([](const auto&amp; content) { std::cout &lt;&lt; content &lt;&lt; ' '; }, cell);\n }\n std::cout &lt;&lt; std::endl;\n\n auto row = [row_sz](int n) { return slice(n*row_sz, n*row_sz+row_sz); };\n for (auto cell : records | row(1)) {\n std::visit([](const auto&amp; content) { std::cout &lt;&lt; content &lt;&lt; ' '; }, cell);\n }\n std::cout &lt;&lt; std::endl;\n\n}\n</code></pre>\n\n<h1>Performance</h1>\n\n<p>Your csv reader is inefficient. You read each line (one memory allocation and copy), then cut the line into pieces (as many allocations / conversions as pieces). You can build your dataset from the file without reading it into lines first: every time you read a ';' you push_back a cell, and every time you read a '\\n' you push_back a last cell in the record, and then push_back the record (conceptually, because as I said I believe a flat std::vector with row-size as an additional information is better). It is a simplification of course, because you have to take care of quoted fields, <code>eof</code> and error-handling, but that's the general idea. You can design it as a state-machine with customization points for the cell and record handlers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T16:53:49.027", "Id": "409811", "Score": "1", "body": "This is incredibly helpful. I will spend the next week studying std::variant and ranges thanks to your advice. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:21:00.270", "Id": "211902", "ParentId": "211826", "Score": "4" } } ]
{ "AcceptedAnswerId": "211834", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T20:38:25.637", "Id": "211826", "Score": "7", "Tags": [ "c++", "beginner", "csv" ], "Title": "Code to read and write CSV files" }
211826
<p>I'm working through the curriculum at The Odin Project. I recently completed the <a href="https://www.theodinproject.com/courses/web-development-101/lessons/etch-a-sketch-project" rel="nofollow noreferrer">Etch-A-Sketch project</a> and am looking for some help/feedback regarding my code. Specifically, I feel that the functions in my JavaScript contain too much repeat code. But, I'm having trouble understanding how to refactor the functions without breaking them.</p> <p><a href="https://htmlpreview.github.io/?https://github.com/BookDisorder/etch-a-sketch/blob/master/index.html" rel="nofollow noreferrer">Github HTML Preview</a></p> <p><a href="https://github.com/BookDisorder/etch-a-sketch" rel="nofollow noreferrer">Full project code</a></p> <pre><code>const gridContainer = document.getElementById('gridContainer'); function createGrid(size){ let totalSquares = size * size; for (let i = 0; i &lt; totalSquares; i++){ const newSquare = document.createElement('div'); newSquare.classList.add('newSquare'); gridContainer.appendChild(newSquare); newSquare.addEventListener('mouseover', function(e){ newSquare.style.backgroundColor = 'black'; }); } document.documentElement.style.setProperty("--rowNum", size); document.documentElement.style.setProperty("--colNum", size); } function pencilGrid(size){ let totalSquares = size * size; for (let i = 0; i &lt; totalSquares; i++){ const newSquare = document.createElement('div'); newSquare.classList.add('newSquare'); gridContainer.appendChild(newSquare); newSquare.addEventListener('mouseover', function(e){ newSquare.style.backgroundColor = 'black'; newSquare.style.opacity -= '-0.1'; }); } document.documentElement.style.setProperty("--rowNum", size); document.documentElement.style.setProperty("--colNum", size); } function colorfulGrid(size){ let totalSquares = size * size; for (let i = 0; i &lt; totalSquares; i++){ const newSquare = document.createElement('div'); newSquare.classList.add('newSquare'); gridContainer.appendChild(newSquare); newSquare.addEventListener('mouseover', function(e){ let randomColor = Math.floor(Math.random()*16777215).toString(16); newSquare.style.backgroundColor = randomColor; newSquare.style.border = '0px'; }); } document.documentElement.style.setProperty("--rowNum", size); document.documentElement.style.setProperty("--colNum", size); } function clearGrid(){ while (gridContainer.firstChild){ gridContainer.removeChild(gridContainer.firstChild); } } createGrid(16); const newGridButton = document.getElementById('newGridButton'); newGridButton.addEventListener('click', function(e){ clearGrid(); let newSize = prompt('New Grid Size:'); createGrid(newSize); }); const pencilButton = document.getElementById('pencilButton'); pencilButton.addEventListener('click', function(e){ clearGrid(); let newSize = prompt('New Grid Size') pencilGrid(newSize); }); const colorfulButton = document.getElementById('colorfulButton'); colorfulButton.addEventListener('click', function(e){ clearGrid(); let newSize = prompt('New Grid Size') colorfulGrid(newSize); }); </code></pre>
[]
[ { "body": "<p>It appears to me that the main difference between each of your methods is the event listener you are providing. This can be made a parameter to a generic method.</p>\n\n<p>For example:</p>\n\n<pre><code>function genericGrid(size, eventListener) {\n let totalSquares = size * size;\n for (let i = 0; i &lt; totalSquares; i++){\n const newSquare = document.createElement('div');\n newSquare.classList.add('newSquare');\n gridContainer.appendChild(newSquare);\n newSquare.addEventListener('mouseover', eventListener); \n\n }\n document.documentElement.style.setProperty(\"--rowNum\", size);\n document.documentElement.style.setProperty(\"--colNum\", size);\n}\n\nfunction pencilGrid(size){\n genericGrid(size, function(e) {\n newSquare.style.backgroundColor = 'black';\n newSquare.style.opacity -= '-0.1';\n });\n}\n</code></pre>\n\n<p>Note: You should refactor and test each method one at a time, to minimise the scope of potential breakages.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:07:52.677", "Id": "211833", "ParentId": "211827", "Score": "0" } }, { "body": "<h2>Bug</h2>\n<p>There is a small chance (about 1 in 16) that the random color function will generate an bad color as you don't check for leading zeros. See code below for an alternative.</p>\n<h2>DRYing out code (Don't Repeat Yourself)</h2>\n<p>Yes there is way to much repeated code.</p>\n<p>Repeated code is not only a pain to create, it is a source of bugs when it comes time to make changes.</p>\n<h2>Differences as arguments.</h2>\n<p>To reduce repetition we use functions to wrap up code that has only slight differences, passing the differences as arguments.</p>\n<p>For example you have the 3 button event handlers with 3 sections of almost identical code.</p>\n<blockquote>\n<pre><code>const newGridButton = document.getElementById('newGridButton');\nnewGridButton.addEventListener('click', function(e){\n clearGrid();\n let newSize = prompt('New Grid Size:');\n createGrid(newSize);\n});\n\nconst pencilButton = document.getElementById('pencilButton');\npencilButton.addEventListener('click', function(e){\n clearGrid();\n let newSize = prompt('New Grid Size')\n pencilGrid(newSize);\n});\n\nconst colorfulButton = document.getElementById('colorfulButton');\ncolorfulButton.addEventListener('click', function(e){\n clearGrid();\n let newSize = prompt('New Grid Size')\n colorfulGrid(newSize);\n});\n</code></pre>\n</blockquote>\n<p>The only difference in each is the Id of the button and the function called at the end. Thus we can simply wrap one of those sections in a function passing the <code>Id</code> and the setup function as arguments.</p>\n<pre><code>function setUpButton(buttonId, createGrid) {\n const button = document.getElementById(buttonId);\n button.addEventListener('click', function(e){\n clearGrid();\n let newSize = prompt('New Grid Size')\n createGrid(newSize);\n });\n}\n</code></pre>\n<h2>Reduce code noise</h2>\n<p>Shorten it little by removing code noise,</p>\n<ul>\n<li>The <code>prompt</code> can move into the function call.</li>\n<li>The <code>clearGrid</code> can move to the <code>createGrid</code> function</li>\n<li>We can use direct DOM reference for the button element when we call the function, so we don't need <code>document.getElementById</code></li>\n<li>Use an arrow function for the event, and we don't need to <code>event</code> argument.</li>\n</ul>\n<p>Thus we get the whole thing done in 6 lines.</p>\n<pre><code>function setUpButton(button, createGrid) {\n button.addEventListener('click', () =&gt; createGrid(prompt('New Grid Size')))\n}\nsetUpButton(newGridButton, createGrid);\nsetUpButton(pencilButton, pencilGrid);\nsetUpButton(colorfulButton, colorfulGrid);\n</code></pre>\n<p>18 lines down to 6.</p>\n<h2>Using names to reference functions</h2>\n<p>Looking at the create grid function the only difference is the mouse event, all the rest is identical. Create the mouse event functions separately. We need a reference to the <code>newSquare</code>, that can be found in the event as <code>event.target</code></p>\n<p>To make accessing the functions easier we can add them to an object and use their names in the create grid function.</p>\n<pre><code>const draw = {\n colorful(e) {\n e.target.style.background = (Math.random()*0xFFFFFF|0).toString(16).padStart(7,&quot;#000000&quot;);\n e.target.style.border = '0px';\n },\n pencil(e) {\n e.target.style.background = 'black';\n e.target.style.opacity += 0.1;\n },\n create(e) { e.target.style.background = 'black' }\n}\n</code></pre>\n<p>and modify the create grid function to take the name of the draw function as well as the size. Also move the clear grid function into this function.</p>\n<h2>The end result</h2>\n<p>Putting it all together we get it all done in about half the code.</p>\n<pre><code>const drawing = {\n colorful(e) {\n e.target.style.background = (Math.random()*0xFFFFFF|0).toString(16).padStart(7,&quot;#000000&quot;);\n e.target.style.border = &quot;0px&quot;;\n },\n pencil(e) {\n e.target.style.backgroundColor = 'black';\n e.target.style.opacity += 0.1;\n },\n black(e) { e.target.style.backgroundColor = 'black' },\n};\nsetUpButton(newGridButton, &quot;black&quot;);\nsetUpButton(pencilButton, &quot;pencil&quot;&quot;);\nsetUpButton(colorfulButton, &quot;colorful&quot;); \ncreateGrid(&quot;black&quot;);\n\nfunction setUpButton(button, name) {\n button.addEventListener('click', () =&gt; createGrid(name, prompt('New Grid Size')))\n}\n\nfunction createGrid(name, size = 16){\n var count = size ** 2;\n while (gridContainer.firstChild) { gridContainer.removeChild(gridContainer.firstChild) }\n while (count--) {\n const cell = Object.assign(document.createElement(&quot;div&quot;), {className : &quot;newSquare&quot;});\n gridContainer.appendChild(cell);\n cell.addEventListener(&quot;mouseover&quot;, drawing[name]); \n }\n [&quot;--rowNum&quot;,&quot;--colNum&quot;].forEach(p =&gt; document.documentElement.style.setProperty(p, size));\n} \n</code></pre>\n<p>I used direct element reference for <code>gridContainer</code>, <code>newGridButton</code>, <code>colorfulButton</code>, and <code>pencilButton</code> so you must ensure that they are unique ids on the page.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T16:23:25.127", "Id": "409665", "Score": "0", "body": "Thanks for the thorough and thoughtful response! I've just started working with objects as per The Odin Project Curriculum, so it's especially great to have some insight into new concepts fitting into projects I've already worked through.\n\nI will be reworking the current code and paying attention to these suggestions in further work as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T11:53:07.057", "Id": "211855", "ParentId": "211827", "Score": "1" } } ]
{ "AcceptedAnswerId": "211855", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T20:46:08.950", "Id": "211827", "Score": "0", "Tags": [ "javascript" ], "Title": "JavaScript Etch-A-Sketch implementation from The Odin Project" }
211827
<p>New to the C language. Which design mistakes have I made in my first C program? Or what can I improve? Any little detail is appreciated.</p> <p>Note: I have experience in multiple coding languages. (this is the beginning of my C journey) </p> <p>Description of the program: checks if a string/array of characters is a bit string. Example: "010100" -> valid.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; int main() { char str[100]; fgets(str, 100, stdin); int len = strlen(str); int len2 = len - 1; int count = 0; //loop through string for(int i = 0; i &lt; len2; i++) { switch (str[i]) { case '0': case '1': count++; break; } } //is string a bit string if (count == len2) printf("Valid!\n"); else printf("Not Valid...\n"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T10:46:00.507", "Id": "409775", "Score": "0", "body": "Use `len` i.o. `len2`, as `str[len] == '\\0'`, the function `strlen` giving size - 1." } ]
[ { "body": "<p>Ultimately, you are looking to see if any character is not either '0' or '1'. The moment you find such a character, you can break the loop immediately: </p>\n\n<pre><code>int isBitString = 1;\nfor(int i = 0; i &lt; len2; i++) {\n if (str[i] != '0' &amp;&amp; str[i] != '1') {\n isBitString = 0;\n break;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T17:47:49.277", "Id": "409675", "Score": "0", "body": "That is correct Abigail. And Joe C; your break loop is much more neater than my variant. Appreciate the input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T17:49:34.560", "Id": "409676", "Score": "0", "body": "Fair enough, I've edited my answer to account for that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:31:30.050", "Id": "211836", "ParentId": "211831", "Score": "4" } }, { "body": "<h1>Take care with <code>&lt;stdio.h&gt;</code></h1>\n<p>Output and (especially) input can be quite error-prone activities. Users and systems have an annoying habit of interacting with your program in unexpected ways. So we definitely need to check the return value of <code>fgets()</code>; if it's a null pointer, then we didn't read any input, and the contents of <code>str</code> are still uninitialised (so we should print an error message to <code>stderr</code> and return a non-zero status instead of continuing).</p>\n<p>Another possibility is that the user enters more than 98 digits, in which case we ignore the 99th and subsequent ones. One approach to this is to check whether the last character of the string is a newline; if it's not, then we'll need to read another block of <code>sizeof str</code> characters and continue. A simpler alternative is to read a character at a time rather than trying to read whole lines; although you might think that's less efficient, the <code>stdio</code> library buffers input so that it's not noticeably slower.</p>\n<h1>Early return</h1>\n<p>We can return before reading to end of string if we find an invalid character. Then we know that if we reach the final newline, then all of the input was valid.</p>\n<h1>A simplification</h1>\n<p>To print a fixed string ending with newline, we can use <code>puts()</code> instead of <code>printf()</code>.</p>\n<hr />\n<p>Taking the above suggestions into account, I end up quite a different program:</p>\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void)\n{\n while (1) {\n switch (getc(stdin)) {\n case EOF:\n fputs(&quot;Read error!\\n&quot;, stderr);\n return 1;\n\n case '0':\n case '1':\n /* valid character */\n continue;\n\n case '\\n':\n /* end of a valid input line */\n puts(&quot;Valid!&quot;);\n return 0;\n\n default:\n /* invalid character */\n puts(&quot;Not Valid...&quot;);\n return 0;\n }\n }\n}\n</code></pre>\n<p>What we now have is an extremely simple state machine. The starting state is &quot;valid so far&quot;, and the end states are &quot;all valid&quot; and &quot;error&quot;. The transitions are all in the <code>switch</code> statement.</p>\n<p>Note that like the original code in the question, this program considers empty input to be a valid binary string. That may or may not be what's wanted.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T10:26:03.297", "Id": "211906", "ParentId": "211831", "Score": "0" } }, { "body": "<p><strong>Avoid assumptions</strong></p>\n\n<p>Code subtracts 1 with no explanation. A usual reason to do so here is an <em>assumed</em> <code>'\\n'</code> at the end of <code>str</code>.</p>\n\n<pre><code>fgets(str, 100, stdin);\nint len = strlen(str);\nint len2 = len - 1; // Why - 1?\n</code></pre>\n\n<p>Consider why this is not always correct.</p>\n\n<p>1) User input was long like <code>\"000...(98 total zero characters)...000x\\n\"</code>. <code>fgets()</code> would read the first 99 characters into <code>str</code> and code would identify that as a good string, even though it had a <code>x</code> in <code>str</code>.</p>\n\n<p>2) User input was <code>\"012\"</code> and then input was closed. <code>fgets()</code> would read <code>\"012\"</code> into <code>str</code> and code would identify that as a good string, even though it had a <code>2</code> in <code>str</code>.</p>\n\n<p>3) Some hacker is messing with the program and inputs <code>\"0z\\0\\n\"</code> and code would identify that as a good string, even though input had a <code>'z'</code>.</p>\n\n<p>4) <code>fgets()</code> suffered a rare input error. The state of <code>str</code> in indeterminate. <code>strlen(str)</code> leads to UB.</p>\n\n<p>To fix 1,2, 4 and partially #3</p>\n\n<pre><code>if (fgets(str, 100, stdin) == NULL) {\n printf(\"End of file or input error\\n\");\n return 0;\n}\nint len = strlen(str);\nif (len &gt; 0 &amp;&amp; str[len-1] == '\\n') str[--len] = '\\0';\nint len2 = len;\n</code></pre>\n\n<p><strong>Code passes the empty line</strong></p>\n\n<p>I'd expect an input of <code>\"\\n\"</code> to warrant a <code>\"Not Valid...\\n\"</code></p>\n\n<p><strong>Goal not cleanly met</strong></p>\n\n<p>Given the task of \"Is a string a bit string\", code should have a function like </p>\n\n<pre><code>bool is_bit_string(const char *s);\n</code></pre>\n\n<p>Instead OP's code answered \"Is a <em>line</em> of input a bit string\".</p>\n\n<p>In C:</p>\n\n<blockquote>\n <p>A <em>string</em> is a contiguous sequence of characters terminated by and including the first null character.</p>\n \n <p>A text stream is an ordered sequence of characters composed into <em>lines</em>, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined.</p>\n</blockquote>\n\n<p><code>'a'</code>, <code>'b'</code>, <code>'c'</code>, <code>'\\0'</code> is a string.<br>\n<code>'a'</code>, <code>'b'</code>, <code>'c'</code>, <code>'\\n'</code> is a line.</p>\n\n<p><strong>Separate core function</strong></p>\n\n<p>The input/output should not be part of \"Is a string a bit string\". Perhaps:</p>\n\n<pre><code>#include &lt;stdbool.h&gt;\n\nbool is_bit_string(const char *s) {\n if (*s == '\\0') {\n return false;\n }\n while (*s &gt;= '0' &amp;&amp; *s &lt;= '1') {\n s++;\n }\n return *s == '\\0';\n}\n</code></pre>\n\n<p><strong>Test code</strong></p>\n\n<p>Move testing of \"Is a string a bit string\" away from <code>is_bit_string()</code> definition. perhaps even in separate .c files.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdbool.h&gt;\n#define TEST_SZ 256\n\nbool is_bit_string(const char *s);\n\nint main(void) {\n char str[TEST_SZ];\n if (fgets(str, sizeof str, stdin) == NULL) {\n fprintf(stderr, \"End of file or input error\\n\");\n return EXIT_FAILURE;\n } \n\n // Lop off potential \\n\n str[strcspn(str, \"\\n\")] = '\\0';\n\n if (is_bit_string(str)) {\n printf(\"Valid!\\n\");\n } else {\n printf(\"Not Valid...\\n\");\n }\n\n return EXIT_SUCESS;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T18:18:39.757", "Id": "212012", "ParentId": "211831", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T21:54:27.480", "Id": "211831", "Score": "1", "Tags": [ "beginner", "c" ], "Title": "Is a string a bit string" }
211831
<p><a href="https://i.stack.imgur.com/I3piw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I3piw.png" alt="enter image description here"></a></p> <p>I'm currently developing an application in ASP.NET Core 2.2 with Domain Driven Design. What you see in here is a Unit Creation page. </p> <p>A Unit is composed of competences. A unit must have at least one competence and its name must not be in blank.</p> <p>A Competence must have a descriptor, at least one indicator, and three evidence (one of the types shown above). </p> <p>Once inserted into the DB, they're read by another Bounded Context which is called evaluations. </p> <p>Competences, Indicators, and Evidence need to have Ids (They're going to become Entities) since they will be need to be fetched individually and referenced for a further evaluation operation. </p> <p>Competences, Indicators, and evidences are all used separately in another bounded context called "Evaluation". </p> <p>I'm looking for some feedback on how I structured these aggregates (They are simple), and if the Evidence, Indicators, and Competences are OK to be entities instead of value objects, considering that for "Unit Bounded Context" (The one shown above) doesn't necessarily view them as entities (It operates them all as part of the unit). But then, the "Evaluation Bounded Context" does see them as Entities. </p> <p>I'm modeling them like entities so I can insert in the data store the right Ids and references immediately (Even though they are separate Bounded Context they all share the same data store).</p> <p>Here are the aggregates so far (I haven't finished adding the domain logic)</p> <pre><code>public class Unit { public UnitId Id { get; private set; } public string Name { get; private set; } public List&lt;Competence&gt; Competences { get; private set; } public Unit(UnitId Id, string Name, List&lt;Competence&gt; Competences) { Validate.AssertArgumentNotEmpty(Name, "Name cannot be blank"); Validate.AssertArgumentNotNull(Competences, "Competences can't be null"); Validate.AssertArgumentEnumarationNotEmpty(Competences, "There must be at least one Competence"); Name = Name; Competences = Competences; } } public class Competence { public CompetenceId Id { get; set; } public string Descriptor { get; set; } public string Name { get; set; } public List&lt;Indicator&gt; Indicatores { get; set; } public List&lt;Evidence&gt; Evidences { get; set; } /// &lt;summary&gt; /// When the Competence is created, a new "CompetenceCreatedEvent" shall be dispatched that needs /// to be read by the message broker and get it to the other bounded context so it can be read. /// &lt;/summary&gt; /// &lt;param name="id"&gt;&lt;/param&gt; /// &lt;param name="Name"&gt;&lt;/param&gt; /// &lt;param name="descriptor"&gt;&lt;/param&gt; public Competence(CompetenceId id, string Name, string descriptor, List&lt;Indicator&gt; Indicatores, List&lt;Evidence&gt; Evidences) { Validate.AssertArgumentNotEmpty(Name, "Name can't be blank"); Validate.AssertArgumentNotEmpty(descriptor, "Descriptor can't be empty or null"); Validate.AssertArgumentNotNull(Indicatores, "Indicatores can't be empty"); Validate.AssertArgumentNotNull(Evidences, "Evidences can't be empty"); Validate.AssertArgumentEnumarationNotEmpty(Indicatores, "Indicatores can't be empty"); Validate.AssertArgumentEnumarationNotEmpty(Evidences, "Evidences can't be empty"); Indicatores = Indicatores; Evidences = Evidences; CheckThatEachEvidenceTypeIsPresent(); } private void CheckThatEachEvidenceTypeIsPresent() { var allEvidencesArePresent = Evidences.Any(x =&gt; x.TipoEvidence == TipoEvidence.Conocimiento) &amp;&amp; Evidences.Any(x =&gt; x.TipoEvidence == TipoEvidence.Desmepeno) &amp;&amp; Evidences.Any(x =&gt; x.TipoEvidence == TipoEvidence.Producto); if (!allEvidencesArePresent) { throw new NotAllEvidencesArePresent(); } } } public class Evidence { public string Id { get; set; } public string IstrumentId { get; set; } public string Description { get; set; } public TypeEvidence TypeEvidence { get; set; } public Evidence(string id, string instrumentId, string Description, TypeEvidence typeEvidence) { Validate.AssertArgumentNotEmpty(Description, "Description can't be empty"); Validate.AssertArgumentNotEmpty(instrumentId, "instrumentId can't be empty"); Id = id ?? Guid.NewGuid().ToString(); InstrumentId = instrumentId; Description = Description; TypeEvidence = TypeEvidence; } } /** * In a true DDD scenario, in this bounded context, * Indicator would be a Value Object. A domain event would be published * once the Indicator has been created that would automatically * create an entity in another bounded context. "It would duplicate the data". * **/ public class Indicator : IAggregate { public Guid Key { get; private set; } public string Description { get; set; } public Indicator(string Description) { Validate.AssertArgumentNotEmpty(Description, "Description can't be empty"); } } </code></pre> <p>I need some helps verifying the aggregates' structure. In addition, I have some concerns:</p> <ul> <li><p>Rephrasing what I said above: A unit is the aggregate root that's going to be saved (They work together in a transaction). That's why it has nested all those other aggregates. Right now, they are modeled as Entities, but I also think that in this bounded context they could potentially be modeled as Value Objects instead. Since the "Evaluation Bounded Context" is the one that needs to have them referenced. Therefore, the approach would be that once the Unit is created or modified, an Event is fired that communicates with the other bounded context, and the other bounded context is the one who performs the... Would this be the right approach? Or could I model it as an Entity from the Unit bounded context? (I understand that's a domain question, I just don't want to be adding additional layers of complexity for no special reason)</p></li> <li><p>From <a href="https://softwareengineering.stackexchange.com/questions/385771/domain-events-cqrs-and-dependency-resolution-in-handlers/385779#385779">this question</a> that I asked, is it OK for me to pass the Event Bus via a dependency in the needed aggregates?</p></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-19T22:47:05.003", "Id": "211837", "Score": "1", "Tags": [ "c#", "event-handling", "asp.net-core", "ddd" ], "Title": "Modeling the Aggregates in the following Bounded Context - Domain Driven Design" }
211837
<p>The following code is a solution to a textbook (<a href="http://csapp.cs.cmu.edu/2e/home.html" rel="nofollow noreferrer">Bryant&amp;O'Hallaron: Computer Systems A programmer's Perspective 2nd Ed</a>) problem in bit-level data manipulation (attempted for the challenge, not a class). The function <code>srl</code> is not written necessarily in a practical manner, but within the constraints required by the problem. The task is to convert the result of an arithmetic right shift to what would be the result of a logical right shift. </p> <h2>Questions</h2> <p>Is there is a clearer, more straight-forward way to write this <strong>within the required constraints of the problem</strong> (perhaps with fewer <code>~</code> operations)?</p> <p>There is a need to avoid undefined behavior of the left shift, when <code>k = 0</code>. In this case <code>int_bits - k = int_bits</code>, which causes the shift to work unpredictably. Is there a better way to handle the undefined behavior of the shift operations, when the shift is larger than the number of bits in the interger?</p> <p>It seems to work correctly, but I lack an answer, so any feedback on the solution would be appreciated.</p> <h2>Requirements</h2> <ul> <li><p>No additional right shifts or type casts may be used beyond the given expression </p> <pre><code> /*Perform shift arithmetically*/ unsigned xsra = (int) x &gt;&gt; k; </code></pre></li> <li><p>Only addition or subtraction may be used, no multiplication, division, or modulus</p></li> <li><p>No comparison operators and no conditionals</p></li> <li><p>Only bit-wise operations (except further right shifts) and logical operators may be used</p></li> </ul> <h2>Code</h2> <pre><code>unsigned srl(unsigned x, int k) { /*Perform shift arithmetically*/ unsigned xsra = (int) x &gt;&gt; k; unsigned int_bits = sizeof(int) &lt;&lt; 3;//calculates the number of bits in int (assumes 8-bit byte) unsigned zero_or_all_bits = ~0 + !k;//for k = 0, corrects for the undefined behavior in //the left shift produced from int_bits - k = int_bits //if k != 0, !k == 0, and zero_or_all_bits == ~0 //if k == 0, zero_or_all_bits == 0 unsigned high_bit_mask = ~(zero_or_all_bits &lt;&lt; (zero_or_all_bits &amp; (int_bits - k))); /******************************************/ //creates a mask of either all bits set in an unsigned int (UINT_MAX) //or a mask with k high bits cleared. //if k == 0, then high_bit_mask = ~(0 &lt;&lt; 0) = ~0. //if k != 0, then high_bit_mask = ~(~0 &lt;&lt; (~0 &amp; (int_bits - k))) //ex. k == 3, high_bit_mask == 0x1FFFFFFF //ex. k == 0, high_bit_mask == 0xFFFFFFFF //ex. k == 31, high_bit_mask == 0xFFFFFFFE /******************************************/ return xsra &amp; high_bit_mask; } </code></pre> <hr> <h2>Test Code</h2> <pre><code>printf("Test srl:\n"); printf("srl(-1, 1): 0x%.8x\n", srl(-1, 1)); printf("srl(-1, 4): 0x%.8x\n", srl(-1, 4)); printf("srl(-1, 5): 0x%.8x\n", srl(-1, 5)); printf("srl(-1, 31): 0x%.8x\n", srl(-1, 31)); printf("srl(-1, 0): 0x%.8x\n", srl(-1, 0)); printf("srl(0x7FFFFFFF, 1): 0x%.8x\n", srl(0x7FFFFFFF, 1)); printf("srl(0x7FFFFFFF, 4): 0x%.8x\n", srl(0x7FFFFFFF, 4)); printf("srl(0x7FFFFFFF, 5): 0x%.8x\n", srl(0x7FFFFFFF, 5)); printf("srl(0x7FFFFFFF, 31): 0x%.8x\n", srl(0x7FFFFFFF, 31)); printf("srl(0x7FFFFFFF, 0): 0x%.8x\n", srl(0x7FFFFFFF, 0)); printf("srl(0x80000000, 1): 0x%.8x\n", srl(0x80000000, 1)); printf("srl(0x80000000, 4): 0x%.8x\n", srl(0x80000000, 4)); printf("srl(0x80000000, 5): 0x%.8x\n", srl(0x80000000, 5)); printf("srl(0x80000000, 31): 0x%.8x\n", srl(0x80000000, 31)); printf("srl(0x80000000, 0): 0x%.8x\n", srl(0x80000000, 0)); printf("srl(0, 1): 0x%.8x\n", srl(0, 1)); printf("srl(0, 4): 0x%.8x\n", srl(0, 4)); printf("srl(0, 5): 0x%.8x\n", srl(0, 5)); printf("srl(0, 31): 0x%.8x\n", srl(0, 31)); printf("srl(0, 0): 0x%.8x\n", srl(0, 0)); printf("srl(1, 1): 0x%.8x\n", srl(1, 1)); printf("srl(1, 4): 0x%.8x\n", srl(1, 4)); printf("srl(1, 5): 0x%.8x\n", srl(1, 5)); printf("srl(1, 31): 0x%.8x\n", srl(1, 31)); printf("srl(1, 0): 0x%.8x\n", srl(1, 0)); </code></pre> <hr> <h2>Output</h2> <pre class="lang-none prettyprint-override"><code>Test srl: srl(-1, 1): 0x7fffffff srl(-1, 4): 0x0fffffff srl(-1, 5): 0x07ffffff srl(-1, 31): 0x00000001 srl(-1, 0): 0xffffffff srl(0x7FFFFFFF, 1): 0x3fffffff srl(0x7FFFFFFF, 4): 0x07ffffff srl(0x7FFFFFFF, 5): 0x03ffffff srl(0x7FFFFFFF, 31): 0x00000000 srl(0x7FFFFFFF, 0): 0x7fffffff srl(0x80000000, 1): 0x40000000 srl(0x80000000, 4): 0x08000000 srl(0x80000000, 5): 0x04000000 srl(0x80000000, 31): 0x00000001 srl(0x80000000, 0): 0x80000000 srl(0, 1): 0x00000000 srl(0, 4): 0x00000000 srl(0, 5): 0x00000000 srl(0, 31): 0x00000000 srl(0, 0): 0x00000000 srl(1, 1): 0x00000000 srl(1, 4): 0x00000000 srl(1, 5): 0x00000000 srl(1, 31): 0x00000000 srl(1, 0): 0x00000001 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T04:15:17.543", "Id": "409738", "Score": "0", "body": "@Reinderien Thanks for the edit. How do you get the closing brace \"}\" in the code section? It always drops out on me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T04:16:56.617", "Id": "409739", "Score": "1", "body": "Make sure that it's 4-tabbed in." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T07:13:58.617", "Id": "409750", "Score": "0", "body": "Code is to do a \"Logical Right Shift\" yet is is called `srl()`. What does _srl_ mean? Shift-Right-Logical? That 'l' is easier to see as implying _left_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T13:14:48.013", "Id": "409790", "Score": "0", "body": "@chux that was what the problem called it. I could have changed it to make it clearer, but did not bother." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T13:19:46.390", "Id": "409791", "Score": "0", "body": "@chux I did the change from logical to arithmetic last night with same requirements. The book called it sra. Real descriptive." } ]
[ { "body": "<p>LGTM.</p>\n\n<p>One recommendation is to split <code>unsigned zero_or_all_bits = ~0 + !k;</code> into two lines, like</p>\n\n<pre><code> unsigned zero_or_all_bits = ~0;\n\n // for k = 0, corrects for the undefined behavior in\n // the left shift produced from int_bits - k = int_bits\n // if k != 0, !k == 0, and zero_or_all_bits == ~0\n // if k == 0, zero_or_all_bits == 0\n\n zero_or_all_bits += !k;\n</code></pre>\n\n<p>Two other comments (<code>// calculates</code> and <code>// creates mask</code>) add no value. I recommend to remove them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T17:58:04.360", "Id": "409677", "Score": "0", "body": "Thank you. I have never posted a question, so I figured I'd over comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T18:02:25.453", "Id": "409678", "Score": "0", "body": "Good suggestion. The question said to write clear, understandable code. I found that difficult here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T07:07:23.203", "Id": "409748", "Score": "0", "body": "`~0` will not provide an all ones pattern to `unsigned` here on now rare non-2's complement machines. Best to use `~0u` or `-1u`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T13:20:57.497", "Id": "409792", "Score": "0", "body": "@chux Actually, I did not state it in my post, but the problem said to assume two's complement." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:52:07.773", "Id": "410006", "Score": "0", "body": "@chux The ~ operator (as well as `| & ^`) doesn't care about the signedness format. ~ simply performs a bitwise complement of all bits. Not to be confused with 1's and 2's complement. It is however good practice to avoid signed integer constants when dealing with bitwise arithmetic, so `0u` is good practice still." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T14:54:53.297", "Id": "410049", "Score": "0", "body": "@Lundin It is not the `~0` will not make an all ones pattern for as you say it is a bitwise complement of all bits. It is the _assignment_ of that `int `values to an `unsigned` which can change the pattern. e.g. [`~0` --> `-0`](https://en.wikipedia.org/wiki/Ones%27_complement) --> `0u`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T17:48:08.650", "Id": "211867", "ParentId": "211847", "Score": "2" } }, { "body": "<ul>\n<li><p>Regarding all the implementation-defined behavior present:</p>\n\n<ul>\n<li>In the general case, it is implementation-defined if right-shifting a negative number results in arithmetic shift or logical shift. It is up to the compiler to pick.</li>\n<li>In your specific case, you go from <code>unsigned</code>x type to signed type <code>(int)x</code>. You have implicit, implementation-defined conversions from signed type to unsigned type and back. The program is allowed to raise a signal when going from a large <code>unsigned int</code> to <code>int</code>. So it is not a good idea, but no way around it as your program is written. </li>\n<li>Meaning, at the point when we have executed the first line of your function, we have no idea of the state of the variable or the program as whole. On a specific system, it's another story, but your question is about generic C.</li>\n</ul></li>\n<li><p><code>sizeof(int) &lt;&lt; 3</code>. Replacing multiplication by 8 with shifts manually is bad practice, known as \"pre-mature optimization\". Never do this, let the compiler handle it. Correct code should be <code>8 * sizeof(int)</code> or <code>CHAR_BIT * sizeof(int)</code>.</p></li>\n<li><p>Regarding <code>~0 + !k</code>. If k is 0, the result is <code>-1 + 1</code> = 0, assuming two's complement. Otherwise, if k is not 0, the result is <code>-1</code>, which you then implicitly convert to unsigned type. What's the reason for writing such obfuscated code, are you trying to make the code more branch-friendly or something? Don't do that before you have found a bottleneck during benchmarking. Instead write:</p>\n\n<pre><code>if(k==0)\n{\n zero_or_all_bits = 0;\n}\nelse\n{\n zero_or_all_bits = ~0u;\n}\n</code></pre></li>\n</ul>\n\n<p>or if you prefer, <code>unsigned int zero_or_all_bits = (k==0) ? 0u : ~0u</code>.</p>\n\n<hr>\n\n<p>As for how to convert the result of an arithmetic shift to a logical, without any questionable conversions or UB hiccups, simply do:</p>\n\n<pre><code>int val = x &gt;&gt; y; // some manner of arithmetic shift\n...\nconst size_t int_bits = sizeof(int) * 8;\nunsigned int mask = (1u &lt;&lt; y)-1; // create a mask corresponding to the number of shifts\nmask = mask &lt;&lt; (int_bits-y); // shift the mask in place from MSB and down\nmask = ~mask; // then invert the whole integer, making mask bits zero, rest ones\nval = val &amp; mask; // set the bits to zero\n</code></pre>\n\n<p>That is, simply clear the bits which were set by arithmetic shift. This code was intentionally written in several steps to make it easier to understand.</p>\n\n<p>For example, given <code>x = -8</code> and <code>y = 2</code>:</p>\n\n<ul>\n<li><code>x = -8</code> is <code>0xFFFFFFF8</code> hex (2's complement).</li>\n<li><code>-8 &gt;&gt; 2</code> arithmetic shift gives <code>0xFFFFFFFE</code>. Two zeroes getting shifted out, two ones shifted in.</li>\n<li>The corresponding logical shift would be <code>0x3FFFFFFE</code>. Two zeroes getting shifted out, two zeroes shifted in.</li>\n<li><code>(1u &lt;&lt; 2)</code> gives 0x4. <code>(1u &lt;&lt; 2)-1</code> gives 0x3, a mask of ones 2 bits wide.</li>\n<li>Shift the mask 0x3 in place, 32-2=30 bits to the left. Temporary value <code>0xC0000000</code>.</li>\n<li>Invert this, we get <code>0x3FFFFFFF</code> which is the desired mask.</li>\n<li>Data AND mask gives: <code>0xFFFFFFFE</code> AND <code>0x3FFFFFFF</code> = <code>0x3FFFFFFE</code>.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T16:08:35.010", "Id": "409942", "Score": "0", "body": "@RJM Uh, sorry, that was posted in a hurry. Of course you'll want a generic case, not sure what I was thinking. I have updated the answer with a generic C code and an example, hope it is clearer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T16:10:28.383", "Id": "409943", "Score": "0", "body": "@RJM As for UB, it doesn't apply unless we left shift a signed `int` with negative value, or in case we left shift data into the sign bit of a signed `int`. Which we avoid entirely by using `unsigned int`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T16:44:14.327", "Id": "409951", "Score": "0", "body": "So, when I was getting a zero left shift when int_bits - k == 32, ex 0xFFFFFFFF << 32 == 0xFFFFFFFF, there must have been an implicit cast to make 0xFFFFFFFF signed?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T16:59:57.133", "Id": "409953", "Score": "0", "body": "Sorry to belabor this, but wouldn't (1u << y)-1; require an implicit cast of (1u << y) to int?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T17:55:15.793", "Id": "409958", "Score": "0", "body": "Suggest `~u` --> `~0u`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:42:19.220", "Id": "410001", "Score": "1", "body": "@RJM It's the type used that determines undefined behavior, not the raw binary representation. If you store `0xFFFFFFFF` (-1) in an `int` and left shift, you get undefined behavior. If you store the same in an `unsigned int` and shift, it is well-defined. The C standard C17 6.5.7 is quite easy to read here: \"The result of E1 << E2 is E1 left-shifted E2 bit positions\" ... \"If E1 has a signed type and non-negative value, and E1 × 2^E2 is representable in the result type, then that is the resulting value; otherwise, the behavior is undefined.\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:45:39.807", "Id": "410002", "Score": "1", "body": "@RJM `(1u << y)-1` evaluates the shift based on the type of the left operand. The result of the shift operators always have the type of the left operand (special case for shifts specifically). `1u` has type `unsigned int` and so does the result. Then the result - 1 is evaluated. The rule called _the usual arithmetic conversions_ (\"type balancing\") applies, the signed operand `1` is converted to unsigned, since the other operand is unsigned. More info: [Implicit type promotion rules](https://stackoverflow.com/questions/46073295/implicit-type-promotion-rules)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:47:04.733", "Id": "410004", "Score": "1", "body": "@RJM Also, mind the terms _cast_ and _conversion_. A conversion is when an operand changes type, either implicitly or explicitly. A cast is when the programmer explicitly enforces a conversion with the cast `()` operator." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:03:18.040", "Id": "410110", "Score": "0", "body": "@Lundin Excellent. Thanks Lundin. Other than StackExchange, do you have a recommendation for where I can read more about this stuff? Something more consolidated?" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T08:31:57.420", "Id": "211980", "ParentId": "211847", "Score": "4" } } ]
{ "AcceptedAnswerId": "211980", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T06:53:00.670", "Id": "211847", "Score": "3", "Tags": [ "c", "integer", "bitwise" ], "Title": "Change Arithmetic Right Shift to Logical Right Shift" }
211847
<p>After one year of learning coding by my own I just finished a little mowing robot simulation project. Because I have no one to show my code to (as already mentioned self taught) I'm uploading it <a href="https://github.com/HubGitDesktop/MyProjects" rel="nofollow noreferrer">here</a>. I would be very happy to get some feedback to improve my skills and write cleaner and better code. I used the MVC concept to build this project. Because I had to use an accurate timer to build this and c# has no built-in timer with the accuracy I needed I used the code ken.loveday wrote <a href="https://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer" rel="nofollow noreferrer">here</a>. I've splitted up my model, view and controller into different folders so hopefully it's clear to you what is model, what is view and what is controller. I've also added much comments in my code so hopefully you can understand what the code is supposed to do.</p> <pre><code> public abstract class RobSimulationObject { #region FIELDS // The bounds of the simulation object public Rect Bounds { get; protected set; } #endregion #region CONSTRUCTORS /// &lt;summary&gt; /// sets the objects bounds /// &lt;/summary&gt; /// &lt;param name="bounds"&gt;bounds of the simulation object&lt;/param&gt; public RobSimulationObject(Rect bounds) { Bounds = bounds; } #endregion } public sealed class ChargingStation : RobSimulationObject { #region CONSTANTS // Standard Constants for some the ChargingStation Fields public static Rect STANDARD_CHARGING_STATION_BOUNDS { get; } = new Rect(90, 90, 10, 10); private static readonly SolidColorBrush _STANDARD_CHARGING_STATION_COLOR = Brushes.Black; #endregion #region FIELDS public SolidColorBrush ChargingStationColor { get; private set; } #endregion #region CONSTRUCTORS /// &lt;summary&gt; /// calls the more specific Constructor passing the standard charging station color /// &lt;/summary&gt; /// &lt;param name="bounds"&gt;&lt;/param&gt; public ChargingStation(Rect bounds) : this(bounds, _STANDARD_CHARGING_STATION_COLOR) { } /// &lt;summary&gt; /// calls the base constructor passing in the bounds param /// sets the charging station color /// &lt;/summary&gt; /// &lt;param name="bounds"&gt;The bounds of the charging station&lt;/param&gt; /// &lt;param name="chargingStationColor"&gt;The color of the charging station&lt;/param&gt; public ChargingStation(Rect bounds, SolidColorBrush chargingStationColor) : base(bounds) { ChargingStationColor = chargingStationColor; } #endregion } public sealed class Court : RobSimulationObject { #region CONSTANTS // Standard values for some of the court's fields public static Rect STANDARD_COURT_BOUNDS { get; } = new Rect(0, 0, 600, 230); public static Rect STANDARD_GRASS_BOUNDS { get; } = new Rect(5, 5, 590, 220); private static readonly SolidColorBrush _STANDARD_GRASS_COLOR = Brushes.Green; private static readonly SolidColorBrush _STANDARD_COURT_BORDER_COLOR = Brushes.Brown; private static readonly SolidColorBrush _STANDARD_CUTTED_GRASS_COLOR = Brushes.White; #endregion #region FIELDS public Rect GrassBounds { get; private set; } public SolidColorBrush GrassColor { get; private set; } public SolidColorBrush CourtBorderColor { get; private set; } public SolidColorBrush CuttedGrassColor { get; private set; } #endregion #region CONSTRUCTORS /// &lt;summary&gt; /// calls more specific controller passing in the standard constant values defined in the constants block /// &lt;/summary&gt; /// &lt;param name="courtBounds"&gt;The bounds of the complete court&lt;/param&gt; /// &lt;param name="grassBounds"&gt;The bounds of the grass tile in the court&lt;/param&gt; public Court(Rect courtBounds, Rect grassBounds) : this(courtBounds, grassBounds, _STANDARD_GRASS_COLOR, _STANDARD_COURT_BORDER_COLOR, _STANDARD_CUTTED_GRASS_COLOR) { if (!courtBounds.Contains(grassBounds)) throw new ArgumentException("The Court doesn't contain the grassBounds"); GrassBounds = grassBounds; } /// &lt;summary&gt; /// calls base constructor passing in the court's bounds /// Initializes the object fields /// &lt;/summary&gt; /// &lt;param name="courtBounds"&gt;The bounds of the complete court&lt;/param&gt; /// &lt;param name="grassBounds"&gt;The bounds of the grass tile in the court&lt;/param&gt; /// &lt;param name="grassColor"&gt;The grasses color&lt;/param&gt; /// &lt;param name="courtBorderColor"&gt;The borders color&lt;/param&gt; /// &lt;param name="cuttedGrassColor"&gt;The color of the cutted grass area&lt;/param&gt; public Court(Rect courtBounds, Rect grassBounds, SolidColorBrush grassColor, SolidColorBrush courtBorderColor, SolidColorBrush cuttedGrassColor) : base(courtBounds) { GrassColor = grassColor; CourtBorderColor = courtBorderColor; CuttedGrassColor = cuttedGrassColor; } #endregion } public sealed class Robot : RobSimulationObject { #region CONSTANTS // Standard values for some of the robot's fields public static Rect STANDARD_ROBOT_BOUNDS { get; } = new Rect(5, 5, 10, 10); public const double STANDARD_ROBOT_CUTTING_KNIFE_RADIUS = 4.5; private static readonly SolidColorBrush _STANDARD_ROBOT_COLOR = Brushes.Blue; private static readonly SolidColorBrush _STANDARD_ROBOT_CUTTING_KNIFE_AREA_COLOR = Brushes.Yellow; private const double _STANDARD_BATTERY_CAPACITY = 3500.00; private const double _STANDARD_BATTERY_LOADING_SPEED = 5; private const double _STANDARD_BATTERY_DISCHARGING_SPEED = 0.1; private const double _STANDARD_ROBOT_MOVING_SPEED = 0.2; private static readonly Vector _STANDARD_ROBOT_MOVING_DIRECTION_VECTOR = new Vector(0, 1); private static Random _random = new Random(); #endregion #region FIELDS public SolidColorBrush Color { get; private set; } public SolidColorBrush CuttingKnifeAreaColor { get; private set; } public double CuttingKnifeRadius { get; private set; } public double BatteryCapacity { get; private set; } public double CurrentBatteryCapacity { get; private set; } public double MovingSpeed { get; private set; } private bool _isCharging; private double _batteryLoadingSpeed; private double _batteryDischargingSpeed; private Vector _robotMovingDirectionVector; #endregion #region CONSTRUCTORS /// &lt;summary&gt; /// calls the more specific constructor passing in the standard constant values /// &lt;/summary&gt; /// &lt;param name="bounds"&gt;The bounds of the robot&lt;/param&gt; /// &lt;param name="cuttingKnifeRadius"&gt;The radius of the robot's cutting knife&lt;/param&gt; public Robot(Rect bounds, double cuttingKnifeRadius) : this(bounds, _STANDARD_ROBOT_COLOR, _STANDARD_ROBOT_CUTTING_KNIFE_AREA_COLOR, cuttingKnifeRadius, _STANDARD_BATTERY_CAPACITY, _STANDARD_BATTERY_LOADING_SPEED, _STANDARD_BATTERY_DISCHARGING_SPEED, _STANDARD_ROBOT_MOVING_SPEED, _STANDARD_ROBOT_MOVING_DIRECTION_VECTOR) { } /// &lt;summary&gt; /// calls the base constructor passing in the robots bounds /// initializes the robots fields /// &lt;/summary&gt; /// &lt;param name="bounds"&gt;&lt;/param&gt; /// &lt;param name="robotColor"&gt;&lt;/param&gt; /// &lt;param name="cuttingKnifeAreaColor"&gt;&lt;/param&gt; /// &lt;param name="cuttingKnifeRadius"&gt;&lt;/param&gt; /// &lt;param name="batteryCapacity"&gt;&lt;/param&gt; /// &lt;param name="batteryLoadingSpeed"&gt;&lt;/param&gt; /// &lt;param name="batteryDischargingSpeed"&gt;&lt;/param&gt; /// &lt;param name="movingSpeed"&gt;&lt;/param&gt; /// &lt;exception cref="ArgumentException"&gt;Thrown when the diameter of the cutting knife is bigger than the robots bounds&lt;/exception&gt; public Robot(Rect bounds, SolidColorBrush robotColor, SolidColorBrush cuttingKnifeAreaColor, double cuttingKnifeRadius, double batteryCapacity, double batteryLoadingSpeed, double batteryDischargingSpeed, double movingSpeed, Vector robotMovingDirectionVector) : base(bounds) { Color = robotColor; CuttingKnifeAreaColor = cuttingKnifeAreaColor; if (cuttingKnifeRadius * 2 &gt;= Bounds.Width || cuttingKnifeRadius * 2 &gt;= Bounds.Height) throw new ArgumentException("The Cutting Knife Diameter can't be bigger than the whole Robot"); CuttingKnifeRadius = cuttingKnifeRadius; BatteryCapacity = batteryCapacity; CurrentBatteryCapacity = batteryCapacity; _batteryLoadingSpeed = batteryLoadingSpeed; _batteryDischargingSpeed = batteryDischargingSpeed; MovingSpeed = movingSpeed; _robotMovingDirectionVector = robotMovingDirectionVector; } #endregion #region METHODS /// &lt;summary&gt; /// Moves robot by the specific vectors values /// Discharges the robot /// &lt;/summary&gt; /// &lt;param name="vector"&gt;vector by that the robot is being moved&lt;/param&gt; public void MoveRobot() { if (CurrentBatteryCapacity &gt; 0) { Vector movingVector = new Vector(_robotMovingDirectionVector.X * MovingSpeed, _robotMovingDirectionVector.Y * MovingSpeed); var bounds = Bounds; bounds.Offset(movingVector); Bounds = bounds; CurrentBatteryCapacity -= _batteryDischargingSpeed; if(_isCharging) _isCharging = false; } } /// &lt;summary&gt; /// Moves robot by a specific vector /// &lt;/summary&gt; /// &lt;param name="vec"&gt;&lt;/param&gt; public void MoveRobotBy(Vector vec) { _robotMovingDirectionVector = vec; MoveRobot(); } /// &lt;summary&gt; /// Lets the robot turn by random degree /// &lt;/summary&gt; public void Collide() { if (!_isCharging) { var robBounds = Bounds; _robotMovingDirectionVector.Negate(); robBounds.Offset(_robotMovingDirectionVector); Bounds = robBounds; var radians = _random.Next(30, 330) * (Math.PI / 180); _robotMovingDirectionVector = new Vector(_robotMovingDirectionVector.X * Math.Cos(radians) - _robotMovingDirectionVector.Y * Math.Sin(radians), _robotMovingDirectionVector.X * Math.Sin(radians) + _robotMovingDirectionVector.Y * Math.Cos(radians)); } } /// &lt;summary&gt; /// Resets the robots values to the initial standard constant values /// &lt;/summary&gt; public void ResetRobot() { Bounds = STANDARD_ROBOT_BOUNDS; BatteryCapacity = _STANDARD_BATTERY_CAPACITY; CurrentBatteryCapacity = BatteryCapacity; _robotMovingDirectionVector = _STANDARD_ROBOT_MOVING_DIRECTION_VECTOR; } public void ChargeRobot() { if (CurrentBatteryCapacity &lt; BatteryCapacity) { CurrentBatteryCapacity += _batteryLoadingSpeed; _isCharging = true; } else _isCharging = false; } /// &lt;summary&gt; /// Returns the current battery live in percentage /// &lt;/summary&gt; /// &lt;returns&gt;Battery live in percentage&lt;/returns&gt; public double GetBatteryLiveInPercentage() { return (CurrentBatteryCapacity / BatteryCapacity) * 100; } #endregion } public sealed class RobotSimulationModel { #region FIELDS // Model Objects public Robot Robot { get; private set; } public Court Court { get; private set; } public ChargingStation ChargingStation { get; private set; } #endregion #region CONSTRUCTORS /// &lt;summary&gt; /// Calls more specific constructor passing in the model objects standard data constants /// &lt;/summary&gt; public RobotSimulationModel() : this(Robot.STANDARD_ROBOT_BOUNDS, Robot.STANDARD_ROBOT_CUTTING_KNIFE_RADIUS, Court.STANDARD_COURT_BOUNDS, Court.STANDARD_GRASS_BOUNDS, ChargingStation.STANDARD_CHARGING_STATION_BOUNDS) { } /// &lt;summary&gt; /// Initializes the Model /// &lt;/summary&gt; /// &lt;param name="robot_Bounds"&gt;The bounds the robot will have&lt;/param&gt; /// &lt;param name="robot_CuttingKnifeRadius"&gt;The cutting knife radius the robot will have&lt;/param&gt; /// &lt;param name="court_Bounds"&gt;The bounds the court will have&lt;/param&gt; /// &lt;param name="court_GrassBounds"&gt;The courts grass tile bounds&lt;/param&gt; /// &lt;param name="chargingStation_Bounds"&gt;The charging station bounds&lt;/param&gt; public RobotSimulationModel(Rect robot_Bounds, double robot_CuttingKnifeRadius, Rect court_Bounds, Rect court_GrassBounds, Rect chargingStation_Bounds) { Robot = new Robot(robot_Bounds, robot_CuttingKnifeRadius); Court = new Court(court_Bounds, court_GrassBounds); ChargingStation = new ChargingStation(chargingStation_Bounds); } #endregion } public sealed class MainRobotSimulationController { #region FIELDS // model and view private RobotSimulationModel _robotSimulationModel; private MainWindow _robotSimulationView; private ViewUpdater _viewUpdater; private RobotMover _robotMover; private RobotCollisionDetector _robotCollisionDetector; // Model updating timer private AccurateTimer _accurateSimulationUpdatingTimer; private Stopwatch _simulationStopwatch; private bool _isSimulationRunning; private double _simulationSpeed; private int _viewUpdatingRate = 1; private int _viewUpdatingRateCounter; #endregion #region CONSTRUCTORS /// &lt;summary&gt; /// Initializes the controller /// Standard constructor /// &lt;/summary&gt; public MainRobotSimulationController() { _robotSimulationModel = new RobotSimulationModel(); _robotSimulationView = new MainWindow(); _viewUpdater = new ViewUpdater(_robotSimulationModel, _robotSimulationView); _robotMover = new RobotMover(_robotSimulationModel); _robotCollisionDetector = new RobotCollisionDetector(_robotSimulationModel); _accurateSimulationUpdatingTimer = new AccurateTimer(33_000); _accurateSimulationUpdatingTimer.MicroTimerElapsed += AccurateSimulationUpdatingTimer_Tick; _simulationStopwatch = new Stopwatch(); _simulationSpeed = 1; _robotSimulationView.Show(); SubscribeToViewEvents(); } #endregion #region METHODS private void SubscribeToViewEvents() { _robotSimulationView.btn_StartSimulation.Click += View_Btn_StartSimulation_Click; _robotSimulationView.btn_StopSimulation.Click += View_Btn_StopSimulation_Click; _robotSimulationView.btn_ResetSimulation.Click += View_Btn_ResetSimulation_Click; _robotSimulationView.btn_Home.Click += View_Btn_Home_Click; _robotSimulationView.cb_SelectSpeed.SelectionChanged += View_Cb_SelectSpeed_SelectionChanged; _robotSimulationView.Closed += View_Window_Closed; _robotSimulationView.btn_StartAutomaticMowing.Click += View_Btn_StartAutomaticMowing_Click; } #endregion #region EVENT_HANDLERS public void AccurateSimulationUpdatingTimer_Tick(object sender, AccurateTimerEventArgs e) { // model updating _robotCollisionDetector.CheckForCollisions(); _robotMover.MoveRobot(); // view updating if necessary if(_viewUpdatingRateCounter &gt;= _viewUpdatingRate) { Application.Current.Dispatcher.Invoke(() =&gt; _viewUpdater.UpdateView(_simulationStopwatch.Elapsed)); _viewUpdatingRateCounter = 0; } else { _viewUpdatingRateCounter++; } } #endregion #region VIEW_EVENT_HANDLERS public void View_Btn_StartSimulation_Click(object sender, EventArgs e) { if (!_isSimulationRunning) { _accurateSimulationUpdatingTimer.Start(); _simulationStopwatch.Start(); _isSimulationRunning = true; _robotSimulationView.btn_StartSimulation.IsEnabled = false; _robotSimulationView.btn_StopSimulation.IsEnabled = true; _robotSimulationView.tb_RobotAutomaticMowingEndingTime.IsEnabled = false; _robotSimulationView.tb_RobotAutomaticMowingStartingTime.IsEnabled = false; } } public void View_Btn_StopSimulation_Click(object sender, EventArgs e) { if (_isSimulationRunning) { _accurateSimulationUpdatingTimer.Stop(); _simulationStopwatch.Stop(); _isSimulationRunning = false; _robotSimulationView.btn_StartSimulation.IsEnabled = true; _robotSimulationView.btn_StopSimulation.IsEnabled = false; _robotSimulationView.tb_RobotAutomaticMowingEndingTime.IsEnabled = true; _robotSimulationView.tb_RobotAutomaticMowingStartingTime.IsEnabled = true; } } public void View_Btn_ResetSimulation_Click(object sender, EventArgs e) { if (_isSimulationRunning) { View_Btn_StopSimulation_Click(null, null); } _simulationStopwatch.Reset(); _robotSimulationModel.Robot.ResetRobot(); _viewUpdater.ResetView(); _robotMover.MoveRobotToChargingStation = false; } public void View_Btn_Home_Click(object sender, EventArgs e) { _robotMover.MoveRobotToChargingStation = true; } public void View_Btn_StartAutomaticMowing_Click(object sender, EventArgs e) { DispatcherTimer automaticMowingTimer = new DispatcherTimer(); int minutesStarting = 0; int minutesEnding = 0; bool isSecondTime = false; try { minutesStarting = Convert.ToInt32(_robotSimulationView.tb_RobotAutomaticMowingStartingTime.Text); minutesEnding = Convert.ToInt32(_robotSimulationView.tb_RobotAutomaticMowingEndingTime.Text); } catch { _robotSimulationView.btn_StartAutomaticMowing.Foreground = Brushes.Red; return; } if (_robotSimulationView.btn_StartAutomaticMowing.Foreground == Brushes.Red) _robotSimulationView.btn_StartAutomaticMowing.Foreground = Brushes.Black; automaticMowingTimer.Interval = new TimeSpan(0, minutesStarting, 0); automaticMowingTimer.Tick += (tickSender, tickArgs) =&gt; { if (!isSecondTime) { View_Btn_StartSimulation_Click(null, null); automaticMowingTimer.Interval = new TimeSpan(0, minutesEnding, 0); } else { View_Btn_StopSimulation_Click(null, null); automaticMowingTimer.Stop(); } isSecondTime = true; }; automaticMowingTimer.Start(); } public void View_Cb_SelectSpeed_SelectionChanged(object sender, SelectionChangedEventArgs e) { var item = e.AddedItems[0]; if (item is ComboBoxItem) { // updating the simulationSpeed, timer interval and updating rate based on the selected speed double speed = Convert.ToDouble(((ComboBoxItem)item).Tag); _simulationSpeed = speed; _accurateSimulationUpdatingTimer.Interval = (long)(33000 / _simulationSpeed); _viewUpdatingRate = (int)(16000 / (33000 / _simulationSpeed)); } } public void View_Window_Closed(object sender, EventArgs e) { _accurateSimulationUpdatingTimer.Abort(); } #endregion } public sealed class RobotCollisionDetector { #region FIELDS private RobotSimulationModel _simulationModel; #endregion #region CONSTRUCTORS public RobotCollisionDetector(RobotSimulationModel simulationModel) { _simulationModel = simulationModel; } #endregion #region METHODS /// &lt;summary&gt; /// Calls the Robot.Collide() method when the robot is colliding with another obstacle /// &lt;/summary&gt; public void CheckForCollisions() { Rect robBounds = _simulationModel.Robot.Bounds; double robKnifeDiam = _simulationModel.Robot.CuttingKnifeRadius * 2; double robKnifeOffset = (robBounds.Width - robKnifeDiam) / 2; Rect knifeBounds = new Rect(robBounds.X + robKnifeOffset, robBounds.Y + robKnifeOffset, robKnifeDiam, robKnifeDiam); if (!_simulationModel.Court.GrassBounds.Contains(knifeBounds)) _simulationModel.Robot.Collide(); else if (robBounds.IntersectsWith(_simulationModel.ChargingStation.Bounds)) _simulationModel.Robot.Collide(); } #endregion } public sealed class RobotMover { #region FIELDS private RobotSimulationModel _simulationModel; public bool MoveRobotToChargingStation { get; set; } #endregion #region CONSTRUCTORS /// &lt;summary&gt; /// Default constructor /// Initializes the RobotMover /// &lt;/summary&gt; /// &lt;param name="simulationModel"&gt;The simulation model object passed in by the MainRobotSimulationController&lt;/param&gt; public RobotMover(RobotSimulationModel simulationModel) { _simulationModel = simulationModel; } #endregion #region METHODS /// &lt;summary&gt; /// Moves the robot /// &lt;/summary&gt; public void MoveRobot() { if (!MoveRobotToChargingStation) { _simulationModel.Robot.MoveRobot(); if (_simulationModel.Robot.GetBatteryLiveInPercentage() &lt; 10) MoveRobotToChargingStation = true; } else { Robot r = _simulationModel.Robot; Rect chargBounds = _simulationModel.ChargingStation.Bounds; if ((int)r.Bounds.Y &lt; (int)chargBounds.Y) r.MoveRobotBy(new Vector(0, 1)); else if ((int)r.Bounds.Y &gt; (int)chargBounds.Y) r.MoveRobotBy(new Vector(0, -1)); else if (r.Bounds.X &gt; chargBounds.X + chargBounds.Width) r.MoveRobotBy(new Vector(-1, 0)); else if (r.Bounds.X + r.Bounds.Width &lt; chargBounds.X) r.MoveRobotBy(new Vector(1, 0)); if (r.Bounds.IntersectsWith(chargBounds)) if (r.GetBatteryLiveInPercentage() &gt;= 100) MoveRobotToChargingStation = false; else r.ChargeRobot(); } } #endregion } public sealed class ViewUpdater { #region FIELDS private RobotSimulationModel _simulationModel; private MainWindow _simulationView; #endregion #region CONSTRUCTORS /// &lt;summary&gt; /// Initializes the ViewUpdater /// &lt;/summary&gt; /// &lt;param name="simulationModel"&gt;The simulation model passed in by MainRobotSimulationController&lt;/param&gt; public ViewUpdater(RobotSimulationModel simulationModel, MainWindow simulationView) { _simulationModel = simulationModel; _simulationView = simulationView; InitializeView(); } #endregion #region METHODS /// &lt;summary&gt; /// Initializes the view /// &lt;/summary&gt; private void InitializeView() { Rect robBounds = _simulationModel.Robot.Bounds; double robKnifeDiam = _simulationModel.Robot.CuttingKnifeRadius * 2; double robKnifeOffset = (robBounds.Width - robKnifeDiam) / 2; Rect complCourtBounds = _simulationModel.Court.Bounds; Rect grassCourtBounds = _simulationModel.Court.GrassBounds; Rect chargingStationBounds = _simulationModel.ChargingStation.Bounds; _simulationView.InitializeSimulationDrawingComponents(new Point(robBounds.Width, robBounds.Height), _simulationModel.Robot.Color, new Point(robKnifeDiam, robKnifeDiam), _simulationModel.Robot.CuttingKnifeAreaColor, new Point(robKnifeDiam, robKnifeDiam), _simulationModel.Court.CuttedGrassColor, new Point(complCourtBounds.Width, complCourtBounds.Height), _simulationModel.Court.CourtBorderColor, new Point(grassCourtBounds.Width, grassCourtBounds.Height), _simulationModel.Court.GrassColor, new Point(chargingStationBounds.Width, chargingStationBounds.Height), _simulationModel.ChargingStation.ChargingStationColor); _simulationView.AddInitializedDrawingComponentsToCanvas(new Vector(robBounds.X, robBounds.Y), new Vector(robBounds.X + robKnifeOffset, robBounds.Y + robKnifeOffset), new Vector(complCourtBounds.X, complCourtBounds.Y), new Vector(grassCourtBounds.X, grassCourtBounds.Y), new Vector(chargingStationBounds.X, chargingStationBounds.Y)); } /// &lt;summary&gt; /// Updates the simulation view based on the model /// &lt;/summary&gt; public void UpdateView(TimeSpan simulationTimeRunning) { Rect robBounds = _simulationModel.Robot.Bounds; double robKnifeDiam = _simulationModel.Robot.CuttingKnifeRadius * 2; double robKnifeOffset = (robBounds.Width - robKnifeDiam) / 2; Rect knifeBounds = new Rect(robBounds.X + robKnifeOffset, robBounds.Y + robKnifeOffset, robKnifeDiam, robKnifeDiam); _simulationView.MoveDrawingComponentBy(_simulationView.RobotDrawingRectangle, robBounds); _simulationView.MoveDrawingComponentBy(_simulationView.RobotCuttingKnifeDrawingEllipse, knifeBounds); _simulationView.pb_RobotBatteryLive.Value = _simulationModel.Robot.GetBatteryLiveInPercentage(); _simulationView.lbl_TimePassedSinceSimulationStart.Content = string.Format("{0:00}:{1:00}", simulationTimeRunning.Minutes, simulationTimeRunning.Seconds); // Adding the robot positions _simulationView.AddRobotPosition(knifeBounds); } public void ResetView() { UpdateView(new TimeSpan()); _simulationView.ResetView(); } #endregion } &lt;Window x:Class="RobotSimulation.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:RobotSimulation" mc:Ignorable="d" Title="MainWindow" Height="500" Width="800"&gt; &lt;Grid&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="1*"/&gt; &lt;RowDefinition Height="5*"/&gt; &lt;RowDefinition Height="1*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid Grid.Column="0" Grid.Row="0"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="1*"/&gt; &lt;ColumnDefinition Width="1*"/&gt; &lt;ColumnDefinition Width="1*"/&gt; &lt;ColumnDefinition Width="1*"/&gt; &lt;ColumnDefinition Width="1*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Button Grid.Column="0" x:Name="btn_StartSimulation" Content="Start Simulation" Width="Auto"/&gt; &lt;Button Grid.Column="1" x:Name="btn_StopSimulation" Content="Stop Simulation" IsEnabled="False" Width="Auto"/&gt; &lt;Button Grid.Column="2" x:Name="btn_ResetSimulation" Content="Reset Simulation" Width="Auto"/&gt; &lt;Label HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Column="3" x:Name="lbl_TimePassedSinceSimulationStart" Content="00:00"/&gt; &lt;ProgressBar Grid.Column="4" x:Name="pb_RobotBatteryLive" Value="100"/&gt; &lt;/Grid&gt; &lt;Grid Grid.Row="2" Grid.Column="0"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="1*"/&gt; &lt;ColumnDefinition Width="4*"/&gt; &lt;ColumnDefinition Width="6*"/&gt; &lt;ColumnDefinition Width="2*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;ComboBox VerticalContentAlignment="Center" HorizontalContentAlignment="Center" Grid.Column="1" Grid.Row="2" x:Name="cb_SelectSpeed" Width="Auto" SelectedIndex="0"&gt; &lt;ComboBoxItem Content="x1.0" Tag="1,0"/&gt; &lt;ComboBoxItem Content="x1.5" Tag="1,5"/&gt; &lt;ComboBoxItem Content="x2.0" Tag="2,0"/&gt; &lt;ComboBoxItem Content="x5.0" Tag="5,0"/&gt; &lt;ComboBoxItem Content="x7.5" Tag="7,5"/&gt; &lt;ComboBoxItem Content="x10.0" Tag="10,0"/&gt; &lt;ComboBoxItem Content="x20.0" Tag="20,0"/&gt; &lt;ComboBoxItem Content="x50.0" Tag="50,0"/&gt; &lt;/ComboBox&gt; &lt;Label Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Content="Speed"/&gt; &lt;Grid Grid.Column="2"&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="2*"/&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;Grid&gt; &lt;Grid.ColumnDefinitions&gt; &lt;ColumnDefinition Width="*"/&gt; &lt;ColumnDefinition Width="2*"/&gt; &lt;/Grid.ColumnDefinitions&gt; &lt;Grid.RowDefinitions&gt; &lt;RowDefinition Height="*"/&gt; &lt;RowDefinition Height="*"/&gt; &lt;/Grid.RowDefinitions&gt; &lt;TextBox Grid.Column="1" Grid.Row="0" VerticalContentAlignment="Center" x:Name="tb_RobotAutomaticMowingStartingTime" TextWrapping="Wrap"/&gt; &lt;TextBox Grid.Column="1" Grid.Row="1" VerticalContentAlignment="Center" x:Name="tb_RobotAutomaticMowingEndingTime" TextWrapping="Wrap"/&gt; &lt;Label Grid.Column="0" Grid.Row="0" Content="Starting Time" HorizontalAlignment="Center" VerticalAlignment="Center"/&gt; &lt;Label Grid.Column="0" Grid.Row="1" Content="Ending Time" HorizontalAlignment="Center" VerticalAlignment="Center"/&gt; &lt;/Grid&gt; &lt;Button Grid.Column="2" Grid.Row="1" x:Name="btn_StartAutomaticMowing" Content="Start"/&gt; &lt;/Grid&gt; &lt;Button Grid.Column="3" x:Name="btn_Home" Content="Home"/&gt; &lt;/Grid&gt; &lt;Canvas Grid.Row="1" x:Name="cnv_SimulationCanvas" HorizontalAlignment="Center" Height="230" VerticalAlignment="Center" Width="600"/&gt; &lt;/Grid&gt; &lt;/Window&gt; public partial class MainWindow : Window { #region FIELDS // Simulation Drawing Components public Ellipse RobotCuttingKnifeDrawingEllipse { get; set; } public Rectangle RobotDrawingRectangle { get; set; } public Rectangle CourtCompleteDrawingRectangle { get; set; } public Rectangle CourtGrassTileDrawingRectangle { get; set; } public Rectangle ChargingStationDrawingRectangle { get; set; } private SolidColorBrush _robotPositionColor; #endregion #region CONSTRUCTORS public MainWindow() { InitializeComponent(); } #endregion #region METHODS /// &lt;summary&gt; /// Initializes the simulation drawing components /// &lt;/summary&gt; public void InitializeSimulationDrawingComponents(Point robotDrawingRectangleDimensions, SolidColorBrush robotDrawingEllipseColor, Point robotCuttingKnifeDrawingEllipseDimensions, SolidColorBrush robotCuttingKnifeDrawingRectangleColor, Point robotCuttedGrassDrawingPathDimensions, SolidColorBrush robotCuttedGrassDrawingPathColor, Point courtCompleteDrawingRectangleDimensions, SolidColorBrush courtCompleteDrawingRectangleColor, Point courtGrassTileDrawingRectangleDimensions, SolidColorBrush courtGrassTileDrawingRectangleColor, Point chargingStationDrawingRectangleDimensions, SolidColorBrush chargingStationDrawingRectangleColor) { RobotCuttingKnifeDrawingEllipse = new Ellipse() { Width = robotCuttingKnifeDrawingEllipseDimensions.X, Height = robotCuttingKnifeDrawingEllipseDimensions.Y, Fill = robotCuttingKnifeDrawingRectangleColor }; RobotDrawingRectangle = new Rectangle() { Width = robotDrawingRectangleDimensions.X, Height = robotDrawingRectangleDimensions.Y, Fill = robotDrawingEllipseColor }; CourtCompleteDrawingRectangle = new Rectangle() { Width = courtCompleteDrawingRectangleDimensions.X, Height = courtCompleteDrawingRectangleDimensions.Y, Fill = courtCompleteDrawingRectangleColor }; CourtGrassTileDrawingRectangle = new Rectangle() { Width = courtGrassTileDrawingRectangleDimensions.X, Height = courtGrassTileDrawingRectangleDimensions.Y, Fill = courtGrassTileDrawingRectangleColor }; ChargingStationDrawingRectangle = new Rectangle() { Width = chargingStationDrawingRectangleDimensions.X, Height = chargingStationDrawingRectangleDimensions.Y, Fill = chargingStationDrawingRectangleColor }; _robotPositionColor = robotCuttedGrassDrawingPathColor; } /// &lt;summary&gt; /// Adds the Initialized drawing components to the canvas /// &lt;/summary&gt; public void AddInitializedDrawingComponentsToCanvas(Vector robotDrawingEllipseOffset, Vector robotCuttingKnifeDrawingEllipseOffset, Vector courtCompleteDrawingRectangleOffset, Vector courtGrassTileDrawingRectangleOffset, Vector chargingStationDrawingRectangleOffset) { cnv_SimulationCanvas.Children.Add(CourtCompleteDrawingRectangle); Canvas.SetTop(CourtCompleteDrawingRectangle, courtCompleteDrawingRectangleOffset.Y); Canvas.SetLeft(CourtCompleteDrawingRectangle, courtCompleteDrawingRectangleOffset.X); cnv_SimulationCanvas.Children.Add(CourtGrassTileDrawingRectangle); Canvas.SetTop(CourtGrassTileDrawingRectangle, courtGrassTileDrawingRectangleOffset.Y); Canvas.SetLeft(CourtGrassTileDrawingRectangle, courtGrassTileDrawingRectangleOffset.X); cnv_SimulationCanvas.Children.Add(ChargingStationDrawingRectangle); Canvas.SetTop(ChargingStationDrawingRectangle, chargingStationDrawingRectangleOffset.Y); Canvas.SetLeft(ChargingStationDrawingRectangle, chargingStationDrawingRectangleOffset.X); cnv_SimulationCanvas.Children.Add(RobotDrawingRectangle); Canvas.SetTop(RobotDrawingRectangle, robotDrawingEllipseOffset.Y); Canvas.SetLeft(RobotDrawingRectangle, robotDrawingEllipseOffset.X); cnv_SimulationCanvas.Children.Add(RobotCuttingKnifeDrawingEllipse); Canvas.SetTop(RobotCuttingKnifeDrawingEllipse, robotCuttingKnifeDrawingEllipseOffset.Y); Canvas.SetLeft(RobotCuttingKnifeDrawingEllipse, robotCuttingKnifeDrawingEllipseOffset.X); } /// &lt;summary&gt; /// Moves the UIElement by the rects bounds /// &lt;/summary&gt; /// &lt;param name="drawingComponent"&gt;&lt;/param&gt; /// &lt;param name="rect"&gt;&lt;/param&gt; public void MoveDrawingComponentBy(UIElement drawingComponent, Rect rect) { if (drawingComponent is Rectangle) { ((Rectangle)drawingComponent).Width = rect.Width; ((Rectangle)drawingComponent).Height = rect.Height; } else if(drawingComponent is Ellipse) { ((Ellipse)drawingComponent).Width = rect.Width; ((Ellipse)drawingComponent).Width = rect.Width; } Canvas.SetTop(drawingComponent, rect.Y); Canvas.SetLeft(drawingComponent, rect.X); } // adds a robot position to the canvas public void AddRobotPosition(Rect bounds) { Ellipse e = new Ellipse() { Width = bounds.Width, Height = bounds.Height, Fill = _robotPositionColor }; cnv_SimulationCanvas.Children.Insert(2, e); Canvas.SetTop(e, bounds.Y); Canvas.SetLeft(e, bounds.X); } public void ResetView() { cb_SelectSpeed.SelectedIndex = 0; cnv_SimulationCanvas.Children.RemoveRange(2, cnv_SimulationCanvas.Children.Count - 5); } #endregion } namespace MicroLibrary { /// &lt;summary&gt; /// MicroStopwatch class /// &lt;/summary&gt; public class MicroStopwatch : System.Diagnostics.Stopwatch { readonly double _microSecPerTick = 1000000D / System.Diagnostics.Stopwatch.Frequency; public MicroStopwatch() { if (!System.Diagnostics.Stopwatch.IsHighResolution) { throw new Exception("On this system the high-resolution " + "performance counter is not available"); } } public long ElapsedMicroseconds { get { return (long)(ElapsedTicks * _microSecPerTick); } } } /// &lt;summary&gt; /// MicroTimer class /// &lt;/summary&gt; public class MicroTimer { public delegate void MicroTimerElapsedEventHandler( object sender, MicroTimerEventArgs timerEventArgs); public event MicroTimerElapsedEventHandler MicroTimerElapsed; System.Threading.Thread _threadTimer = null; long _ignoreEventIfLateBy = long.MaxValue; long _timerIntervalInMicroSec = 0; bool _stopTimer = true; public MicroTimer() { } public MicroTimer(long timerIntervalInMicroseconds) { Interval = timerIntervalInMicroseconds; } public long Interval { get { return System.Threading.Interlocked.Read( ref _timerIntervalInMicroSec); } set { System.Threading.Interlocked.Exchange( ref _timerIntervalInMicroSec, value); } } public long IgnoreEventIfLateBy { get { return System.Threading.Interlocked.Read( ref _ignoreEventIfLateBy); } set { System.Threading.Interlocked.Exchange( ref _ignoreEventIfLateBy, value &lt;= 0 ? long.MaxValue : value); } } public bool Enabled { set { if (value) { Start(); } else { Stop(); } } get { return (_threadTimer != null &amp;&amp; _threadTimer.IsAlive); } } public void Start() { if (Enabled || Interval &lt;= 0) { return; } _stopTimer = false; System.Threading.ThreadStart threadStart = delegate() { NotificationTimer(ref _timerIntervalInMicroSec, ref _ignoreEventIfLateBy, ref _stopTimer); }; _threadTimer = new System.Threading.Thread(threadStart); _threadTimer.Priority = System.Threading.ThreadPriority.Highest; _threadTimer.Start(); } public void Stop() { _stopTimer = true; } public void StopAndWait() { StopAndWait(System.Threading.Timeout.Infinite); } public bool StopAndWait(int timeoutInMilliSec) { _stopTimer = true; if (!Enabled || _threadTimer.ManagedThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId) { return true; } return _threadTimer.Join(timeoutInMilliSec); } public void Abort() { _stopTimer = true; if (Enabled) { _threadTimer.Abort(); } } void NotificationTimer(ref long timerIntervalInMicroSec, ref long ignoreEventIfLateBy, ref bool stopTimer) { int timerCount = 0; long nextNotification = 0; MicroStopwatch microStopwatch = new MicroStopwatch(); microStopwatch.Start(); while (!stopTimer) { long callbackFunctionExecutionTime = microStopwatch.ElapsedMicroseconds - nextNotification; long timerIntervalInMicroSecCurrent = System.Threading.Interlocked.Read(ref timerIntervalInMicroSec); long ignoreEventIfLateByCurrent = System.Threading.Interlocked.Read(ref ignoreEventIfLateBy); nextNotification += timerIntervalInMicroSecCurrent; timerCount++; long elapsedMicroseconds = 0; while ( (elapsedMicroseconds = microStopwatch.ElapsedMicroseconds) &lt; nextNotification) { System.Threading.Thread.SpinWait(10); } long timerLateBy = elapsedMicroseconds - nextNotification; if (timerLateBy &gt;= ignoreEventIfLateByCurrent) { continue; } MicroTimerEventArgs microTimerEventArgs = new MicroTimerEventArgs(timerCount, elapsedMicroseconds, timerLateBy, callbackFunctionExecutionTime); MicroTimerElapsed(this, microTimerEventArgs); } microStopwatch.Stop(); } } /// &lt;summary&gt; /// MicroTimer Event Argument class /// &lt;/summary&gt; public class MicroTimerEventArgs : EventArgs { // Simple counter, number times timed event (callback function) executed public int TimerCount { get; private set; } // Time when timed event was called since timer started public long ElapsedMicroseconds { get; private set; } // How late the timer was compared to when it should have been called public long TimerLateBy { get; private set; } // Time it took to execute previous call to callback function (OnTimedEvent) public long CallbackFunctionExecutionTime { get; private set; } public MicroTimerEventArgs(int timerCount, long elapsedMicroseconds, long timerLateBy, long callbackFunctionExecutionTime) { TimerCount = timerCount; ElapsedMicroseconds = elapsedMicroseconds; TimerLateBy = timerLateBy; CallbackFunctionExecutionTime = callbackFunctionExecutionTime; } } } [1]: https://github.com/HubGitDesktop/MyProjects [2]: https://www.codeproject.com/Articles/98346/Microsecond-and-Millisecond-NET-Timer </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T10:42:11.793", "Id": "409632", "Score": "0", "body": "https://codereview.stackexchange.com/editing-help" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T10:44:33.973", "Id": "409633", "Score": "0", "body": "@πάνταῥεῖ the problem is that I formatted my code exactly like the link you posted is telling me to do. I also googled why it's not working but I wasn't able to find a working solution for this" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T10:45:40.067", "Id": "409634", "Score": "2", "body": "Not working code isn't ready for review here anyways. Try Stack Overflow may be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T10:46:50.943", "Id": "409636", "Score": "0", "body": "@πάνταῥεῖ My code is working. The only Thing I would be really happy about is some feedback. I'm not having any issues with my code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T10:48:11.847", "Id": "409637", "Score": "2", "body": "Then post your code here properly formatted and not as links. Just indent every line of code with four blanks, what's so hard about that? You can even select all your code lines and press CTRL-K which does that automatically for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T10:51:05.873", "Id": "409638", "Score": "0", "body": "@πάνταῥεῖ As I've already said I would really want to do that but it just doesnt work. And I did exactly the same for formatting my code as the link you've posted tells me to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T10:53:20.890", "Id": "409639", "Score": "0", "body": "You must have been doing something wrong then." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T11:10:32.427", "Id": "409641", "Score": "0", "body": "@πάνταῥεῖ I think it just gave me an error because I had titles between the classes. So know I had to put everything into one code snippet to get it working. It's not nice to read I know and I'm absolutely sorry for that but the other way didn't work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T11:22:44.293", "Id": "409642", "Score": "0", "body": "@πάνταῥεῖ can you please explain to me why this post is getting so many downvotes? I dont want it to be a bad post and if you explain to me why this is a bad post I'll do anything to get this fixed." } ]
[ { "body": "<p>For reference purposes your application UI looks like:\n<a href=\"https://i.stack.imgur.com/3A3KR.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/3A3KR.png\" alt=\"Mower\"></a></p>\n\n<p>There are following parts in the simulation:</p>\n\n<ul>\n<li>red fence</li>\n<li>green grass</li>\n<li>yellow/black automatic mower</li>\n<li>black charging station</li>\n</ul>\n\n<p>The mower picks a direction and starts mowing until he reaches the fence, then it will change its direction, or it is at below 10&lt; on battery and it will return to the charging station. The battery lasts roughly 25s at x50 speed. </p>\n\n<p>If the mower had an AI that picks optimal path then it would mow the whole field in roughly 12 minutes 50 seconds or 15.4 seconds at x50 speed, without needing to recharge once.</p>\n\n<p>Instead of optimizing for time/cost efficiency, it has no guarantee that it will actually complete its task or have an estimation when complete. It can be used as a reference to others as being a brute force solution that roughly does the task as well.</p>\n\n<p>So how good is it? Well, at x50 speed it took about 4 min of simulation time to roughly covered 95% of the area and after 6 min it has reached roughly 99%. However, after this, the efficiency drops. </p>\n\n<p><a href=\"https://i.stack.imgur.com/CSOPA.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/CSOPA.png\" alt=\"enter image description here\"></a></p>\n\n<p>(6 min x50 speed = 5 hours at x1 speed)</p>\n\n<hr>\n\n<p>There are too many things to note that can be improved, so I will try to just name a few obvious ones. Let's say that you have a goal to separate code into MVVM (model, view model and view) where the view is the XAML, view mode is the data context that the view uses and model is your data structures and logic. </p>\n\n<p>View model should not virtually know anything about the view. Instead of having controls with names that you reference from your view model, you should use bindings to the view model properties. </p>\n\n<pre><code>&lt;StackPanel&gt;\n &lt;ProgressBar \n Minimum=\"0\" \n Maximum=\"100\" \n Value=\"{Binding Battery}\" \n Name=\"pb_RobotBatteryLive\" /&gt;\n &lt;!--Note that even here you can replace \n 'ElementName=pb_RobotBatteryLive, Path=Value' \n with just 'Battery' --&gt; \n &lt;TextBlock \n Text=\"{Binding ElementName=pb_RobotBatteryLive, Path=Value, StringFormat={}{0:0}%}\" \n HorizontalAlignment=\"Center\" \n VerticalAlignment=\"Center\" /&gt;\n&lt;/StackPanel&gt;\n</code></pre>\n\n<p>and in the code:</p>\n\n<pre><code>_simulationView.pb_RobotBatteryLive.Value = _simulationModel.Robot.GetBatteryLiveInPercentage();\n//vs\nBattery = _simulationModel.Robot.GetBatteryLiveInPercentage();\n</code></pre>\n\n<p>in c# the region, autodoc/comments are often an antipattern. Comments do not fix the poorly written code - try to write clean code and comments are not needed.</p>\n\n<p>What could really benefit the quality and tests would be a use of virtual time scheduler. However, at this point, there are no clear requirements to test and you should work on that - what is the real world problem that you are trying to solve. </p>\n\n<p>At the moment, you have interwoven several layers and there is no clear separation of concerns. In addition, this accurate time does have a thread, but you use it just to kick off a timer event that calls method AccurateSimulationUpdatingTimer_Tick and all the work seems to happen on the dispatcher thread.</p>\n\n<p>When the properties are changed then they generally should implement INotifyProperty. Generally, a code library weaver like <a href=\"https://github.com/Fody/PropertyChanged\" rel=\"nofollow noreferrer\">https://github.com/Fody/PropertyChanged</a> is used to add the implementation, so you would just need to add the interface. This would allow you to update UI correctly as well as do something when any model property changes.</p>\n\n<hr>\n\n<p>The variable names are chosen decently, property access visibility is mostly fine, app does deadlock the main thread if you tab out and in a few times but until then it does work. What you have managed to write is a working base for something you can use later. Its functionality resembles 90s screen saver. </p>\n\n<p>Personally, I would recommend you try something simpler, doing graphic in c# with threads is not beginner-friendly. Check out Khan Academy, for example, I wrote the following demo under 15 min:\n<a href=\"https://www.khanacademy.org/computer-programming/walkers-redgreenblueblackwhite-x10/5113615912009728\" rel=\"nofollow noreferrer\">https://www.khanacademy.org/computer-programming/walkers-redgreenblueblackwhite-x10/5113615912009728</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T16:38:03.263", "Id": "211863", "ParentId": "211853", "Score": "2" } } ]
{ "AcceptedAnswerId": "211863", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T10:39:53.480", "Id": "211853", "Score": "-1", "Tags": [ "c#", "performance" ], "Title": "RobotSimulation c# wpf project code cleaning and performance optimization" }
211853
<p>Lately, I was working on some experimental <code>java.util.Set</code> extension, <code>IdSet</code>:</p> <pre><code>package idSet; import java.util.Collection; import java.util.Set; public interface IdSet&lt;E extends Identifiable&gt; extends Set&lt;E&gt; { boolean containsId(Object o); E getByElem(E e); E get(Object id); E removeId(Object o); boolean containsAllIds(Collection&lt;?&gt; c); boolean removeAllIds(Collection&lt;?&gt; c); boolean retainAllIds(Collection&lt;?&gt; c); Set&lt;Object&gt; idSet(); Set&lt;E&gt; entrySet(); } </code></pre> <p>Implemented by FlexSet, source code can be found in <a href="https://github.com/WojtekKarwacki/id-set" rel="nofollow noreferrer">this repo</a>.</p> <p>Apart from standard Set interface, by using <code>IdSet</code> we are able to find/remove elements by their properties, called ids. Example usage:</p> <p>Let's say we persist objects in DB. Each object needs to have defined id (primary-key) in its respective table. Usually (for ORM) this id is a field in object definition. We can then use this id, as a key in such an <code>IdSet</code> and easily perform access/find operations without explicitly defining a key for each relation.</p> <p>Instead of <code>Map&lt;Integer, SomeObject&gt;</code> we have <code>IdSet&lt;SomeObject&gt;</code>, where <code>SomeObject</code> implements <code>Identifiable</code> with overridden method <code>getId()</code>, such as in the following case:</p> <pre><code>private static class IntegerIdentifiable implements Identifiable { private final int integer; private IntegerIdentifiable(int integer) { this.integer = integer; } @Override public Object getId() { return integer; } @Override public boolean equals(Object o) { return o != null &amp;&amp; integer == ((IntegerIdentifiable) o).integer; } @Override public int hashCode() { return integer; } } </code></pre> <p>The repo contains about 60 unit tests concerning <code>FlexSet</code> and one benchmark test covering combinations of:</p> <ol> <li>3 containers: <code>HashSet</code>, <code>HashMap</code>, <code>FlexSet</code></li> <li>3 operations: add, contains, remove</li> <li>1-131072 number of elements for each operation</li> <li>4 types of id calculation</li> <li>2 types of objects added</li> </ol> <p>Results of these tests are attached in jmh-result.xlsx. For the aforementioned params, <code>FlexSet</code> wins at 86% against <code>HashMap</code> + <code>HashSet</code> performance-wise.</p> <p>I would greatly appreciate any comments/hints/questions on performance, usability and code quality of the package.</p> <p>Regarding code quality/performance I'm particularly interested in code review for the following areas:</p> <ol> <li>rebuild mechanizm - <code>rebuild()</code>, </li> <li>treeifying algorithm - <code>treeifyIfNeeded(IdRef&lt;E&gt; idRef, int modHashCode, IdRef&lt;E&gt;[] elements)</code>,</li> <li>tree balancing algorithm - <code>rebuildTreeIdRef()</code></li> </ol> <p>Below is the code I would like to have reviewed. </p> <pre><code>package idSet; import java.lang.reflect.Array; import java.util.*; public class FlexSet&lt;E extends Identifiable&gt; implements IdSet&lt;E&gt;, Identifiable { private static final int MAX_CAPACITY = Integer.MAX_VALUE &gt;&gt; 1; private static final int DEFAULT_INITIAL_CAPACITY = 16; // must be greater than or equal 16 // package private access for test purposes static final int ID_REF_TREEIFY_THRESHOLD = 7; // package private access for test purposes static final int ID_REF_UNTREEIFY_THRESHOLD = 5; // package private access for test purposes IdRef&lt;E&gt;[] elements; private int size; // package private access for test purposes int capacity; // package private access for test purposes int modCapacity; // package private access for test purposes int expansionThreshold; // package private access for test purposes int shrinkThreshold; private FlexSet(int initialCapacity) { if (initialCapacity &lt;= 0) { throw new IllegalArgumentException("Parameter initialCapacity should be greater than 0."); } size = 0; int highestOneBit = Integer.highestOneBit(initialCapacity); capacity = initialCapacity == highestOneBit ? initialCapacity : highestOneBit &lt;&lt; 1; calculateModCapacity(); calculateResizeThresholds(); elements = initElements(); } public static &lt;T extends Identifiable&gt; FlexSet&lt;T&gt; instance() { return instance(DEFAULT_INITIAL_CAPACITY); } public static &lt;T extends Identifiable&gt; FlexSet&lt;T&gt; instance(int initialCapacity) { return new FlexSet&lt;&gt;(initialCapacity); } @SafeVarargs public static &lt;T extends Identifiable&gt; FlexSet fromArray(T... a) { FlexSet&lt;T&gt; flexSet = instance(a.length); Collections.addAll(flexSet, a); return flexSet; } public static &lt;K, V&gt; FlexSet&lt;IdWrapper&lt;K, V&gt;&gt; fromMap(Map&lt;K, V&gt; map) { Objects.requireNonNull(map); FlexSet&lt;IdWrapper&lt;K, V&gt;&gt; flexSet = instance(map.size()); for (Map.Entry&lt;K, V&gt; entry : map.entrySet()) { flexSet.add(new IdWrapper&lt;&gt;(entry.getKey(), entry.getValue())); } return flexSet; } private IdRef&lt;E&gt;[] initElements() { @SuppressWarnings("unchecked") IdRef&lt;E&gt;[] elements = (IdRef&lt;E&gt;[]) Array.newInstance(IdRef.class, capacity); for (int i = 0; i &lt; elements.length; i++) { elements[i] = new IdRef&lt;&gt;(); } return elements; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size == 0; } @Override public boolean contains(Object o) { return containsId(ensureTypeValid(o).getId()); } @Override public boolean containsId(Object o) { return get(o) != null; } @Override public E getByElem(E e) { Objects.requireNonNull(e); return get(e.getId()); } @Override public E get(Object id) { int hashCode = id.hashCode(); return elements[modHashCode(hashCode)].get(id, hashCode); } @Override public Object[] toArray() { Object[] a = new Object[size]; return copyToArray(a); } @SuppressWarnings("unchecked") @Override public &lt;T&gt; T[] toArray(T[] a) { Objects.requireNonNull(a); ensureCapacityOfGivenArray(a); a = (T[]) Array.newInstance(a.getClass().getComponentType(), size); return copyToArray(a); } @SuppressWarnings("unchecked") public &lt;K&gt; Map&lt;K, E&gt; toHashMap() { Map&lt;K, E&gt; map = new HashMap&lt;&gt;(); for (E e : this) { map.put((K) e.getId(), e); } return map; } private &lt;T&gt; void ensureCapacityOfGivenArray(T[] a) { if (a.length &lt; size) { throw new IllegalArgumentException(String.format("Cannot fit idSet.FlexSet elements into array of length %s.", a.length)); } } @SuppressWarnings("unchecked") private &lt;T&gt; T[] copyToArray(T[] a) { int i = 0; for (E e : this) { a[i] = (T) e; i++; } return a; } @Override public boolean add(E e) { Objects.requireNonNull(e); int hashCode = e.getId().hashCode(); int modHashCode = modHashCode(hashCode); IdRef&lt;E&gt; idRef = elements[modHashCode]; if (idRef.add(e, hashCode)) { if (expandOnAdditionIfNeeded()) { treeifyIfNeeded(idRef, modHashCode, elements); } return true; } return false; } private boolean expandOnAdditionIfNeeded() { size++; if ((capacity &lt; MAX_CAPACITY) &amp;&amp; (size &gt; expansionThreshold)) { capacity &lt;&lt;= 1; rebuild(); return false; } return true; } private void treeifyIfNeeded(IdRef&lt;E&gt; idRef, int modHashCode, IdRef&lt;E&gt;[] elements) { if (idRef.size == ID_REF_TREEIFY_THRESHOLD &amp;&amp; idRef.getClass() == IdRef.class) { elements[modHashCode] = TreeIdRef.fromIdRef(idRef); } } private void rebuild() { calculateModCapacity(); calculateResizeThresholds(); this.elements = rebuildElements(); } private IdRef&lt;E&gt;[] rebuildElements() { IdRef&lt;E&gt;[] elements = initElements(); for (IdRef&lt;E&gt; element : this.elements) { rebuildElement(elements, element); } return elements; } private void rebuildElement(IdRef&lt;E&gt;[] elements, IdRef&lt;E&gt; idRef) { while (idRef != null) { if (idRef.e != null) { doRebuildElement(elements, idRef); } idRef = idRef.next; } } private void doRebuildElement(IdRef&lt;E&gt;[] elements, IdRef&lt;E&gt; idRef) { int hashCode = idRef.hashCode; int modHashCode = modHashCode(hashCode); IdRef&lt;E&gt; idRefToRebuild = elements[modHashCode]; idRefToRebuild.add(idRef.e, hashCode); treeifyIfNeeded(idRefToRebuild, modHashCode, elements); } @Override public boolean remove(Object o) { Objects.requireNonNull(o); return removeId(ensureTypeValid(o).getId()) != null; } @Override public E removeId(Object id) { int hashCode = id.hashCode(); int modHashCode = modHashCode(hashCode); IdRef&lt;E&gt; idRef = elements[modHashCode]; E e = idRef.removeId(id, hashCode); if (e != null) { if (shrinkOnRemovalIfNeeded()) { untreeifyIfNeeded(idRef, modHashCode, elements); } } return e; } private boolean shrinkOnRemovalIfNeeded() { size--; if ((capacity &gt; 63) &amp;&amp; (size &lt; shrinkThreshold)) { capacity &gt;&gt;= 2; rebuild(); return false; } return true; } private void untreeifyIfNeeded(IdRef&lt;E&gt; idRef, int modHashCode, IdRef&lt;E&gt;[] elements) { if (idRef.size == ID_REF_UNTREEIFY_THRESHOLD &amp;&amp; idRef.getClass() == TreeIdRef.class) { elements[modHashCode] = TreeIdRef.toIdRef(idRef); } } @Override public boolean containsAll(Collection&lt;?&gt; c) { if (checkNecessaryConditionsForContainsAll(c)) { return false; } for (Object o : c) { if (!(o instanceof Identifiable) || !containsId(((Identifiable) o).getId())) { return false; } } return true; } @Override public boolean containsAllIds(Collection&lt;?&gt; c) { if (checkNecessaryConditionsForContainsAll(c)) { return false; } for (Object o : c) { if (!containsId(o)) { return false; } } return true; } private boolean checkNecessaryConditionsForContainsAll(Collection&lt;?&gt; c) { Objects.requireNonNull(c); return c instanceof Set &amp;&amp; size &lt; c.size(); } @Override public boolean addAll(Collection&lt;? extends E&gt; c) { Objects.requireNonNull(c); boolean result = false; for (E e : c) { if (add(e)) { result = true; } } return result; } @Override public boolean removeAll(Collection&lt;?&gt; c) { Objects.requireNonNull(c); boolean result = false; for (Object o : c) { if (o instanceof Identifiable &amp;&amp; removeId(((Identifiable) o).getId()) != null) { result = true; } } return result; } @Override public boolean removeAllIds(Collection&lt;?&gt; c) { Objects.requireNonNull(c); boolean result = false; for (Object o : c) { if (removeId(o) != null) { result = true; } } return result; } @Override public boolean retainAll(Collection&lt;?&gt; c) { Objects.requireNonNull(c); boolean result = false; for (E e : this) { if (!c.contains(e)) { if (remove(e)) { result = true; } } } return result; } @Override public boolean retainAllIds(Collection&lt;?&gt; c) { Objects.requireNonNull(c); boolean result = false; for (E e : this) { Object id = e.getId(); if (!c.contains(id)) { if (removeId(id) != null) { result = true; } } } return result; } @Override public void clear() { size = 0; elements = initElements(); } @Override public Iterator&lt;E&gt; iterator() { return new Iterator&lt;E&gt;() { private IdRef&lt;E&gt; current; private int index; @Override public boolean hasNext() { while (index &lt; elements.length) { if (hasNextForCurrent()) { return true; } prepareForNext(); } return false; } private boolean hasNextForCurrent() { if (current == null) { current = elements[index]; } return current.next != null; } private void prepareForNext() { current = null; index++; } @Override public E next() { E result = current.e; current = current.next; return result; } }; } @Override public Set&lt;Object&gt; idSet() { Set&lt;Object&gt; idSet = new HashSet&lt;&gt;(); for (E e : this) { idSet.add(e.getId()); } return idSet; } @Override public Set&lt;E&gt; entrySet() { return new HashSet&lt;&gt;(this); } private int modHashCode(int hashCode) { return (hashCode ^ (hashCode &gt;&gt;&gt; 16)) &amp; modCapacity; } private void calculateModCapacity() { modCapacity = capacity - 1; } private void calculateResizeThresholds() { expansionThreshold = capacity; shrinkThreshold = capacity &gt;&gt; 2; } private Identifiable ensureTypeValid(Object o) { if (o instanceof Identifiable) { return (Identifiable) o; } throw new IllegalArgumentException(String.format("Object %s has to be of type idSet.Identifiable.", o)); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FlexSet&lt;?&gt; flexSet = (FlexSet&lt;?&gt;) o; return size == flexSet.size &amp;&amp; containsAll(flexSet); } @Override public int hashCode() { int result = Objects.hash(capacity, size); result = 31 * result + Arrays.hashCode(elements); return result; } @Override public Object getId() { return hashCode(); } @Override public String toString() { return "idSet.FlexSet{" + "elements=" + Arrays.toString(elements) + '}'; } // package private access for test purposes static class IdRef&lt;E extends Identifiable&gt; { int size; E e; IdRef&lt;E&gt; next; int hashCode; private IdRef() { } boolean add(E e, int hashCode) { if (checkFirst(e) &amp;&amp; (setUpIfEmpty(e, hashCode) || setUpAtTheBegginingIfNeeded(e, hashCode) || skipLowerHashCodesAndProceedWithAdding(e, hashCode))) { size++; return true; } return false; } private boolean checkFirst(E e) { return !e.equals(this.e); } private boolean setUpIfEmpty(E e, int hashCode) { if (this.e == null) { setUpAtTheEnd(this, e, hashCode); return true; } return false; } private boolean setUpAtTheBegginingIfNeeded(E e, int hashCode) { if (isHashCodeInRange(hashCode)) { setUpAtTheBeggining(e, hashCode); return true; } return false; } private void setUpAtTheBeggining(E e, int hashCode) { IdRef&lt;E&gt; thisTemp = new IdRef&lt;&gt;(); thisTemp.e = this.e; thisTemp.next = next; thisTemp.hashCode = this.hashCode; this.e = e; next = thisTemp; this.hashCode = hashCode; } private boolean skipLowerHashCodesAndProceedWithAdding(E e, int hashCode) { IdRef&lt;E&gt; current = this; while (current.hashCode &lt; hashCode) { if (setUpAtTheEndIfNeeded(e, hashCode, current)) return true; current = current.next; } while (current.e != null) { Boolean x = setUpInTheMiddleIfNeeded(current, e, hashCode); if (x != null) return x; current = current.next; } setUpAtTheEnd(current, e, hashCode); return true; } private boolean setUpAtTheEndIfNeeded(E e, int hashCode, IdRef&lt;E&gt; current) { if (current.next == null) { setUpAtTheEnd(current, e, hashCode); return true; } return false; } private void setUpAtTheEnd(IdRef&lt;E&gt; current, E e, int hashCode) { current.e = e; current.next = new IdRef&lt;&gt;(); current.hashCode = hashCode; } private Boolean setUpInTheMiddleIfNeeded(IdRef&lt;E&gt; current, E e, int hashCode) { if (current.hashCode != hashCode) { setUpInTheMiddle(current, e, hashCode); return true; } if (current.e.equals(e)) { return false; } return null; } private void setUpInTheMiddle(IdRef&lt;E&gt; current, E e, int hashCode) { IdRef&lt;E&gt; idRef = new IdRef&lt;&gt;(); idRef.e = e; idRef.next = current.next; idRef.hashCode = hashCode; current.next = idRef; } E get(Object id, int hashCode) { if (checkFirst(id)) { return e; } if (isHashCodeInRange(hashCode)) { return null; } return skipLowerHashCodesAndProceedWithGetting(id, hashCode); } private boolean checkFirst(Object id) { return e == null || e.getId().equals(id); } private boolean isHashCodeInRange(int hashCode) { return this.hashCode &gt; hashCode; } private E skipLowerHashCodesAndProceedWithGetting(Object id, int hashCode) { IdRef&lt;E&gt; current = skipLowerHashCodes(hashCode); if (current == null) return null; while (current.e != null &amp;&amp; current.hashCode == hashCode) { if (isFound(current, id)) { return current.e; } current = current.next; } return null; } E removeId(Object id, int hashCode) { if (e == null) return null; if (e.getId().equals(id)) { return getRemovedAndAdjust(this); } return skipLowerHashCodesAndProceedWithRemoving(id, hashCode); } private E skipLowerHashCodesAndProceedWithRemoving(Object id, int hashCode) { IdRef&lt;E&gt; current = skipLowerHashCodes(hashCode); if (current == null) return null; while (current.e != null &amp;&amp; current.hashCode == hashCode) { if (isFound(current, id)) { return getRemovedAndAdjust(current); } current = current.next; } return null; } private void adjustOnRemoval(IdRef&lt;E&gt; current, IdRef&lt;E&gt; next) { current.e = next.e; current.next = next.next; current.hashCode = next.hashCode; } private IdRef&lt;E&gt; skipLowerHashCodes(int hashCode) { IdRef&lt;E&gt; current = next; while (current.hashCode &lt; hashCode) { if (current.e == null) return null; current = current.next; } return current; } private E getRemovedAndAdjust(IdRef&lt;E&gt; current) { IdRef&lt;E&gt; next = current.next; E e = current.e; adjustOnRemoval(current, next); size--; return e; } private boolean isFound(IdRef&lt;E&gt; current, Object id) { return current.e.getId().equals(id); } @Override public String toString() { return "IdRef{" + ", hashCode=" + hashCode + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IdRef&lt;?&gt; idRef = (IdRef&lt;?&gt;) o; return hashCode == idRef.hashCode &amp;&amp; Objects.equals(e, idRef.e); } @Override public int hashCode() { return Objects.hash(e, hashCode); } } // package private access for test purposes static final class TreeIdRef&lt;E extends Identifiable&gt; extends IdRef&lt;E&gt; { private TreeIdRef&lt;E&gt; left; private TreeIdRef&lt;E&gt; right; private IdRef&lt;E&gt; block = new IdRef&lt;&gt;(); private int nodesCount; private TreeIdRef() { } @Override boolean add(E e, int hashCode) { if (addByHashCode(this, null, e, hashCode, 0)) { size++; return true; } return false; } private boolean addByHashCode(TreeIdRef&lt;E&gt; current, TreeIdRef&lt;E&gt; parent, E e, int hashCode, int consecutiveNodesCount) { if (hashCode == current.hashCode) { return handleEqualHashCodes(current, parent, e, hashCode, consecutiveNodesCount); } else if (hashCode &lt; current.hashCode) { return checkLeft(current, e, hashCode, consecutiveNodesCount) || addByHashCode(current.left, current, e, hashCode, consecutiveNodesCount + 1); } else { return checkRight(current, e, hashCode, consecutiveNodesCount) || addByHashCode(current.right, current, e, hashCode, consecutiveNodesCount + 1); } } private boolean handleEqualHashCodes(TreeIdRef&lt;E&gt; current, TreeIdRef&lt;E&gt; parent, E e, int hashCode, int consecutiveNodesCount) { return !checkFirst(current, e) &amp;&amp; (handleNull(current, parent, e, consecutiveNodesCount) || handleBlock(current, e, hashCode)); } private boolean checkFirst(TreeIdRef&lt;E&gt; current, E e) { return e.equals(current.e); } private boolean handleNull(TreeIdRef&lt;E&gt; current, TreeIdRef&lt;E&gt; parent, E e, int consecutiveNodesCount) { if (current.e == null) { current.e = e; parent.next = current; rebuildTreeIdRefIfNeeded(consecutiveNodesCount); return true; } return false; } private boolean handleBlock(TreeIdRef&lt;E&gt; current, E e, int hashCode) { current.next = current.block; return current.block.add(e, hashCode); } private boolean checkLeft(TreeIdRef&lt;E&gt; current, E e, int hashCode, int consecutiveNodesCount) { if (current.left == null) { current.left = createLinkedTreeIdRef(current); current.left.e = e; current.left.hashCode = hashCode; rebuildTreeIdRefIfNeeded(consecutiveNodesCount); return true; } return false; } private boolean checkRight(TreeIdRef&lt;E&gt; current, E e, int hashCode, int consecutiveNodesCount) { if (current.right == null) { current.right = createLinkedTreeIdRef(current); current.right.e = e; current.right.hashCode = hashCode; rebuildTreeIdRefIfNeeded(consecutiveNodesCount); return true; } return false; } private TreeIdRef&lt;E&gt; createLinkedTreeIdRef(TreeIdRef&lt;E&gt; parent) { TreeIdRef&lt;E&gt; treeIdRef = new TreeIdRef&lt;&gt;(); IdRef&lt;E&gt; parentNext = parent.next; parent.next = treeIdRef; treeIdRef.next = parentNext; return treeIdRef; } @Override E get(Object id, int hashCode) { TreeIdRef&lt;E&gt; treeIdRef = findByHashCode(this, hashCode); if (treeIdRef == null) { return null; } E e = treeIdRef.e; if (e == null || e.getId().equals(id)) { return e; } return treeIdRef.block.get(id, hashCode); } private TreeIdRef&lt;E&gt; findByHashCode(TreeIdRef&lt;E&gt; current, int hashCode) { if (hashCode == current.hashCode) { return current; } else { if (hashCode &lt; current.hashCode) { current = current.left; } else { current = current.right; } if (current == null) { return null; } } return findByHashCode(current, hashCode); } @Override E removeId(Object id, int hashCode) { TreeIdRef&lt;E&gt; treeIdRef = findByHashCode(this, hashCode); if (treeIdRef == null) { return null; } E e = treeIdRef.e; if (e == null) { return null; } IdRef&lt;E&gt; block = treeIdRef.block; if (e.getId().equals(id)) { if (block.size == 0) { treeIdRef.e = null; } else { treeIdRef.e = block.removeId(block.e.getId(), hashCode); } size--; return e; } return null; } private void rebuildTreeIdRefIfNeeded(int consecutiveNodesCount) { nodesCount++; if ((28 - Integer.numberOfLeadingZeros(nodesCount) + ID_REF_TREEIFY_THRESHOLD &lt; consecutiveNodesCount)) { rebuildTreeIdRef(); } } private void rebuildTreeIdRef() { TreeIdRef&lt;E&gt;[] temporarySortedTreeIdRefs = createTemporarySortedTreeIdRefs(); TreeIdRef&lt;E&gt; rebuilt = rebuildFromSorted(temporarySortedTreeIdRefs); e = rebuilt.e; hashCode = rebuilt.hashCode; block = rebuilt.block; next = rebuilt.next; left = rebuilt.left; right = rebuilt.right; } @SuppressWarnings("unchecked") private TreeIdRef&lt;E&gt;[] createTemporarySortedTreeIdRefs() { TreeIdRef&lt;E&gt;[] temporarySortedTreeIdRefs = new TreeIdRef[nodesCount]; sortStartingFromLeftmost(temporarySortedTreeIdRefs, this.left, this, 0); return temporarySortedTreeIdRefs; } private int sortStartingFromLeftmost(TreeIdRef&lt;E&gt;[] temporarySortedTreeIdRefs, TreeIdRef&lt;E&gt; current, TreeIdRef&lt;E&gt; parent, int i) { i = sortForCurrent(temporarySortedTreeIdRefs, current, i); i = sortForParent(temporarySortedTreeIdRefs, current, parent, i); return i; } private int sortForParent(TreeIdRef&lt;E&gt;[] temporarySortedTreeIdRefs, TreeIdRef&lt;E&gt; current, TreeIdRef&lt;E&gt; parent, int i) { if (parent.right != current) { if (parent.e != null) { temporarySortedTreeIdRefs[i++] = parent; } if (parent.right != null) { i = sortForCurrent(temporarySortedTreeIdRefs, parent.right, i); } } return i; } private int sortForCurrent(TreeIdRef&lt;E&gt;[] temporarySortedTreeIdRefs, TreeIdRef&lt;E&gt; current, int i) { if (current.left != null) { i = sortStartingFromLeftmost(temporarySortedTreeIdRefs, current.left, current, i); } else { if (current.e != null) { temporarySortedTreeIdRefs[i++] = current; } if (current.right != null) { i = sortStartingFromLeftmost(temporarySortedTreeIdRefs, current.right, current, i); } } return i; } private TreeIdRef&lt;E&gt; rebuildFromSorted(TreeIdRef&lt;E&gt;[] temporarySortedTreeIdRefs) { int index = temporarySortedTreeIdRefs.length &gt;&gt; 1; TreeIdRef&lt;E&gt; midTreeIdRef = temporarySortedTreeIdRefs[index].createStandaloneCopy(); FlexSet&lt;IntegerIdentifiable&gt; usedIndices = new FlexSet&lt;&gt;(nodesCount &lt;&lt; 1); usedIndices.add(new IntegerIdentifiable(index)); midTreeIdRef.nodesCount = rebuildForBoth(temporarySortedTreeIdRefs, midTreeIdRef, 0, index, temporarySortedTreeIdRefs.length, usedIndices); return midTreeIdRef; } private int rebuildForBoth(TreeIdRef&lt;E&gt;[] temporarySortedTreeIdRefs, TreeIdRef&lt;E&gt; midTreeIdRef, int from, int index, int to, FlexSet&lt;IntegerIdentifiable&gt; usedIndices) { int nodesCount = rebuildForLeft(temporarySortedTreeIdRefs, midTreeIdRef, from, index, usedIndices); nodesCount += rebuildForRight(temporarySortedTreeIdRefs, midTreeIdRef, index, to, usedIndices); return nodesCount; } private int rebuildForLeft(TreeIdRef&lt;E&gt;[] temporarySortedTreeIdRefs, TreeIdRef&lt;E&gt; midTreeIdRef, int from, int to, FlexSet&lt;IntegerIdentifiable&gt; usedIndices) { midTreeIdRef.next = null; int diff = to - from; if (diff != 0) { int index = (diff &gt;&gt; 1) + from; if (usedIndices.add(new IntegerIdentifiable(index))) { TreeIdRef&lt;E&gt; treeIdRef = temporarySortedTreeIdRefs[index].createStandaloneCopy(); midTreeIdRef.left = treeIdRef; midTreeIdRef.next = treeIdRef; return rebuildForBoth(temporarySortedTreeIdRefs, midTreeIdRef.left, from, index, to, usedIndices); } } midTreeIdRef.left = null; return 0; } private int rebuildForRight(TreeIdRef&lt;E&gt;[] temporarySortedTreeIdRefs, TreeIdRef&lt;E&gt; midTreeIdRef, int from, int to, FlexSet&lt;IntegerIdentifiable&gt; usedIndices) { int diff = to - from; if (diff != 1) { int index = (diff &gt;&gt; 1) + from; if (usedIndices.add(new IntegerIdentifiable(index))) { TreeIdRef&lt;E&gt; treeIdRef = temporarySortedTreeIdRefs[index].createStandaloneCopy(); midTreeIdRef.right = treeIdRef; getLast(midTreeIdRef).next = treeIdRef; return rebuildForBoth(temporarySortedTreeIdRefs, midTreeIdRef.right, from, index, to, usedIndices); } } midTreeIdRef.right = null; return 0; } private IdRef&lt;E&gt; getLast(IdRef&lt;E&gt; midTreeIdRef) { while (midTreeIdRef.next != null) { midTreeIdRef = midTreeIdRef.next; } return midTreeIdRef; } private TreeIdRef&lt;E&gt; createStandaloneCopy() { TreeIdRef&lt;E&gt; treeIdRef = new TreeIdRef&lt;&gt;(); treeIdRef.e = e; treeIdRef.hashCode = hashCode; treeIdRef.block = block; return treeIdRef; } private static &lt;E extends Identifiable&gt; TreeIdRef&lt;E&gt; fromIdRef(IdRef&lt;E&gt; idRef) { TreeIdRef&lt;E&gt; treeIdRef = new TreeIdRef&lt;&gt;(); treeIdRef.e = idRef.next.next.next.e; treeIdRef.hashCode = idRef.next.next.next.hashCode; treeIdRef.size = 1; treeIdRef.nodesCount = 1; fromIdRefHelp(treeIdRef, idRef.next); fromIdRefHelp(treeIdRef, idRef.next.next.next.next.next); fromIdRefHelp(treeIdRef, idRef); fromIdRefHelp(treeIdRef, idRef.next.next); fromIdRefHelp(treeIdRef, idRef.next.next.next.next); fromIdRefHelp(treeIdRef, idRef.next.next.next.next.next.next); return treeIdRef; } private static &lt;E extends Identifiable&gt; void fromIdRefHelp(TreeIdRef&lt;E&gt; treeIdRef, IdRef&lt;E&gt; idRef) { treeIdRef.add(idRef.e, idRef.hashCode); } private static &lt;E extends Identifiable&gt; IdRef&lt;E&gt; toIdRef(IdRef&lt;E&gt; treeIdRef) { IdRef&lt;E&gt; idRef = new IdRef&lt;&gt;(); while (treeIdRef != null) { if (treeIdRef.e != null) { idRef.add(treeIdRef.e, treeIdRef.hashCode); } treeIdRef = treeIdRef.next; } return idRef; } } private static class IntegerIdentifiable implements Identifiable { private final int integer; private IntegerIdentifiable(int integer) { this.integer = integer; } @Override public Object getId() { return integer; } @Override public boolean equals(Object o) { return o != null &amp;&amp; integer == ((IntegerIdentifiable) o).integer; } @Override public int hashCode() { return integer; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T16:06:56.483", "Id": "409664", "Score": "2", "body": "Welcome to Code Review! Please be sure to include all code that you want reviewed, rather than linking to repositories on third-party sites." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:13:59.427", "Id": "409700", "Score": "0", "body": "Hey Joe, the code i'd like to have reviewed is 1k lines long, should i really post it here? I would like to listen to comments about whole library FlexSet, not only some particular parts of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:36:38.147", "Id": "409710", "Score": "2", "body": "There's a [discussion on meta](https://codereview.meta.stackexchange.com/questions/60/what-is-the-appropriate-length-of-a-code-review-question) on this, which is probably good guidance here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T07:50:13.533", "Id": "409754", "Score": "0", "body": "Thank you Joe, i have edited my question with regard to the discussion you have provided. Please let me know if the question is properly asked now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:33:15.373", "Id": "409833", "Score": "0", "body": "Yes, this looks better to me." } ]
[ { "body": "<h3>Possible Use of Delegation</h3>\n\n<p>I look at this code and see a lot that reminds me of code in the <code>HashMap</code> class. You may be able to simplify this considerably by delegating your methods to a <code>HashMap</code>.</p>\n\n<pre><code>public class FlexSet&lt;E extends Identifiable&gt; implements IdSet&lt;E&gt; {\n private Map&lt;Object, E&gt; backingMap = new HashMap&lt;&gt;();\n\n //example\n @Override\n boolean containsId(Object o) {\n return backingMap.containsKey(o);\n }\n\n //and so on\n}\n</code></pre>\n\n<h3>Use Generic Type for Identifier</h3>\n\n<p>It is highly likely that the ID of your <code>Identifiable</code> will have a type that can be known at compile time. You can use generics to improve the prospects of bugs being found at compile time rather than runtime.</p>\n\n<pre><code>public interface Identifiable&lt;ID&gt; {\n ID getId();\n}\n</code></pre>\n\n<h3>API methods unclear</h3>\n\n<p>The signature of <code>containsAllIds(Collection&lt;?&gt; c)</code> (and other methods along those lines) do not tell me clearly what they accept (IDs? Elements? Mix of both?). Making the <code>Identifiable</code> generic will probably help here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:47:04.317", "Id": "409836", "Score": "1", "body": "Very good points, thank you. I will take a second look later." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:31:29.903", "Id": "211935", "ParentId": "211856", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T13:44:17.663", "Id": "211856", "Score": "0", "Tags": [ "java", "performance", "collections", "hash-map", "set" ], "Title": "java.util.Set extension/implementation" }
211856
<p>I wrote a header only class (actually there is a second one for data bookkeeping and dumping) to measure the execution time of a C++ scope without worrying too much about boilerplates. The idea being to be able to simply instantiate a class at the begining of the scope you want to measure, and do a single call at the end to dump the measure.</p> <p>I rely on the fact that the class instantiation is at the beginning of the scope, and its destruction at the very end. So my main worry is about compile time optimizations that could change the order of execution and bias the measure. Also I'm not satisfy on how I retrieve the type for <code>ScopeTimer::Duration</code> but I couldn't find the type properly :/</p> <p>Here is the code:</p> <p><strong>scope_timer.hpp</strong></p> <pre><code>#ifndef SCOPE_TIMER #define SCOPE_TIMER #include &lt;chrono&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;map&gt; #include &lt;fstream&gt; class ScopeTimer { public: using ScopeSignature = std::string; using DurationType = std::chrono::microseconds; using Duration = decltype(std::chrono::duration_cast&lt;DurationType&gt;(std::chrono::high_resolution_clock::now() - std::chrono::high_resolution_clock::now()).count()); ScopeTimer(const ScopeSignature&amp; scopeName); ~ScopeTimer(); Duration getDurationFromStart() const; private: ScopeTimer(); const ScopeSignature scopeName; const std::chrono::high_resolution_clock::time_point start; }; class ScopeTimerStaticCore { public: static void addTimingToNamedScope(const ScopeTimer::ScopeSignature&amp; scopeName, const ScopeTimer::Duration&amp; duration); static void dumpTimingToFile(const std::string&amp; path); static void clearAllTiming(); static void clearTimingForNamedScope(const ScopeTimer::ScopeSignature&amp; scopeName); private: using TimingVector = std::vector&lt;ScopeTimer::Duration&gt;; using ScopesTiming = std::map&lt;ScopeTimer::ScopeSignature, TimingVector&gt;; static ScopesTiming&amp; getScopesTimingStaticInstance() { static ScopesTiming scopesTimingContainer; return (scopesTimingContainer); }; }; /*******************************************************Implementations*******************************************************/ inline ScopeTimer::ScopeTimer(const ScopeSignature&amp; scopeName) : scopeName(scopeName), start(std::chrono::high_resolution_clock::now()) {}; inline ScopeTimer::~ScopeTimer() { const Duration scopeTimerLifetimeDuration = this-&gt;getDurationFromStart(); ScopeTimerStaticCore::addTimingToNamedScope(this-&gt;scopeName, scopeTimerLifetimeDuration); return ; }; inline ScopeTimer::Duration ScopeTimer::getDurationFromStart() const { using std::chrono::duration_cast; const std::chrono::high_resolution_clock::time_point now = std::chrono::high_resolution_clock::now(); return (duration_cast&lt;DurationType&gt;(now - this-&gt;start).count()); }; inline void ScopeTimerStaticCore::addTimingToNamedScope(const ScopeTimer::ScopeSignature&amp; scopeName, const ScopeTimer::Duration&amp; duration) { ScopesTiming&amp; scopesTimingContainer = ScopeTimerStaticCore::getScopesTimingStaticInstance(); scopesTimingContainer[scopeName].push_back(duration); return ; }; inline void ScopeTimerStaticCore::dumpTimingToFile(const std::string&amp; path) { const ScopesTiming&amp; scopesTimingContainer = ScopeTimerStaticCore::getScopesTimingStaticInstance(); std::ofstream dumpfile; dumpfile.open(path, std::ios::out | std::ios::trunc); for (ScopesTiming::const_iterator it_scopes = scopesTimingContainer.begin(); it_scopes != scopesTimingContainer.end(); ++it_scopes) { const ScopeTimer::ScopeSignature&amp; currentScope = it_scopes-&gt;first; const TimingVector&amp; timings = it_scopes-&gt;second; for (TimingVector::const_iterator it_timings = timings.begin(); it_timings != timings.end(); ++it_timings) dumpfile &lt;&lt; currentScope &lt;&lt; "," &lt;&lt; *it_timings &lt;&lt; std::endl; } dumpfile.close(); return ; }; inline void ScopeTimerStaticCore::clearAllTiming() { ScopesTiming&amp; scopesTimingContainer = ScopeTimerStaticCore::getScopesTimingStaticInstance(); scopesTimingContainer.clear(); return ; }; inline void ScopeTimerStaticCore::clearTimingForNamedScope(const ScopeTimer::ScopeSignature&amp; scopeName) { ScopesTiming&amp; scopesTimingContainer = ScopeTimerStaticCore::getScopesTimingStaticInstance(); ScopesTiming::iterator it_scopes = scopesTimingContainer.find(scopeName); if (it_scopes != scopesTimingContainer.end()) it_scopes-&gt;second.clear(); return ; }; #endif /* SCOPE_TIMER */ </code></pre> <p>And an dummy program that use it</p> <p><strong>main.cpp</strong></p> <pre><code>#include "../include/scope_timer.hpp" void functionA(); void functionB(); int main() { for (size_t i = 0; i &lt; 3; ++i) { functionA(); functionB(); } ScopeTimerStaticCore::dumpTimingToFile("/tmp/scope-timer_dump-dummy-test.csv"); return (0); }; </code></pre> <p><strong>dumb_functions.cpp</strong></p> <pre><code>#include &lt;thread&gt; #include &lt;chrono&gt; #include "../include/scope_timer.hpp" void functionA() { ScopeTimer scopeTimer("functionA"); std::this_thread::sleep_for (std::chrono::milliseconds(500)); return ; }; void functionB() { ScopeTimer scopeTimer("functionB"); std::this_thread::sleep_for (std::chrono::seconds(1)); return ; }; </code></pre> <p>if you want to retrieve the code quickly here is the <a href="https://github.com/TonyRoussel/scope-timer.git" rel="nofollow noreferrer">repo link</a></p>
[]
[ { "body": "<pre><code>using Duration = decltype(std::chrono::duration_cast&lt;DurationType&gt;(std::chrono::high_resolution_clock::now() - std::chrono::high_resolution_clock::now()).count());\n</code></pre>\n\n<p>I'm confused by this line. <code>decltype(std::chrono::duration_cast&lt;DurationType&gt;(expr))</code> is invariably <code>DurationType</code>, isn't it? That's why it's a \"cast\"? So this simplifies down to <code>decltype(std::declval&lt;DurationType&amp;&gt;().count())</code>, which I'm pretty sure <a href=\"https://en.cppreference.com/w/cpp/chrono/duration\" rel=\"nofollow noreferrer\">can be spelled as</a> <code>DurationType::rep</code> unless you're really eager to support non-standard duration types that might not have a <code>rep</code> member. So:</p>\n\n<pre><code>using Duration = typename DurationType::rep;\n</code></pre>\n\n<p>And now it appears that maybe <code>Duration</code> is the wrong name for this typedef, eh?</p>\n\n<p>(EDIT: Oops, the keyword <code>typename</code> is not needed here because <code>DurationType</code> is not dependent. Just <code>using Duration = DurationType::rep;</code> should be sufficient.)</p>\n\n<hr>\n\n<pre><code>static ScopesTiming&amp; getScopesTimingStaticInstance() {\n static ScopesTiming scopesTimingContainer;\n\n return (scopesTimingContainer);\n};\n</code></pre>\n\n<p>Minor nits on whitespace and naming and parentheses and trailing semicolons:</p>\n\n<pre><code>static ScopesTiming&amp; getScopesTimingStaticInstance() {\n static ScopesTiming instance;\n return instance;\n}\n</code></pre>\n\n<p>The defining quality of <code>instance</code> is that it's a static instance of <code>ScopesTiming</code>. If you want to convey the additional information that <code>ScopesTiming</code> is actually a <em>container type</em>, then that information belongs in the name of the <em>type</em>. Personally I'd call it something like <code>TimingVectorMap</code>, because it's a map of <code>TimingVector</code>s.</p>\n\n<hr>\n\n<p>Since the static map is not guarded by any mutex, your function <code>addTimingToNamedScope</code> (which mutates the map) is not safe to call from multiple threads concurrently. This could be a problem for real-world use.</p>\n\n<hr>\n\n<p><code>ScopeTimer</code> has two <code>const</code>-qualified fields. This doesn't do anything except pessimize its implicitly generated move-constructor into a copy-constructor. I recommend removing the <code>const</code>.</p>\n\n<p><code>ScopeTimer</code> also has an implicit conversion from <code>ScopeSignature</code> a.k.a. <code>std::string</code>, so that for example</p>\n\n<pre><code>void f(ScopeTimer timer);\nstd::string hello = \"hello world\";\nf(hello); // compiles without any diagnostic\n</code></pre>\n\n<p>I very strongly suggest that you never enable any implicit conversion unless you have a very good reason for it. This means putting <code>explicit</code> on every constructor and conversion operator.</p>\n\n<pre><code>explicit ScopeTimer(const ScopeSignature&amp; scopeName);\n</code></pre>\n\n<hr>\n\n<pre><code>dumpfile.open(path, std::ios::out | std::ios::trunc);\n</code></pre>\n\n<p>Should you check to see if the open succeeded?</p>\n\n<hr>\n\n<pre><code>inline void ScopeTimerStaticCore::clearTimingForNamedScope(const ScopeTimer::ScopeSignature&amp; scopeName) {\n ScopesTiming&amp; scopesTimingContainer = ScopeTimerStaticCore::getScopesTimingStaticInstance();\n ScopesTiming::iterator it_scopes = scopesTimingContainer.find(scopeName);\n\n if (it_scopes != scopesTimingContainer.end())\n it_scopes-&gt;second.clear();\n return ;\n};\n</code></pre>\n\n<p>This would be a good place to use C++11 <code>auto</code>:</p>\n\n<pre><code>inline void ScopeTimerStaticCore::clearTimingForNamedScope(const ScopeTimer::ScopeSignature&amp; scopeName) {\n ScopesTiming&amp; instance = getScopesTimingStaticInstance();\n auto it = instance.find(scopeName);\n if (it != instance.end()) {\n it-&gt;second.clear();\n }\n}\n</code></pre>\n\n<p>Or, if you don't mind removing the element from the map completely, you could just use <code>erase</code>:</p>\n\n<pre><code>inline void ScopeTimerStaticCore::clearTimingForNamedScope(const ScopeTimer::ScopeSignature&amp; scopeName) {\n ScopesTiming&amp; instance = getScopesTimingStaticInstance();\n instance.erase(scopeName);\n}\n</code></pre>\n\n<p>I also notice that these functions would get a <em>lot</em> shorter and simpler to read if you put their definitions in-line into the class body of <code>ScopeTimerStaticCore</code>. In this case you could omit the keyword <code>inline</code> and the qualification of the parameter type:</p>\n\n<pre><code>void clearTimingForNamedScope(const ScopeSignature&amp; scopeName) {\n ScopesTiming&amp; instance = getScopesTimingStaticInstance();\n instance.erase(scopeName);\n}\n</code></pre>\n\n<p>(Assuming that <code>ScopeTimerStaticCore</code> contains a member typedef <code>using ScopeSignature = ScopeTimer::ScopeSignature;</code>, I guess. It probably should — or vice versa.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:37:46.557", "Id": "409893", "Score": "0", "body": "I cannot compile the example code when I try to use `DurationType::rep` :/\n\nAbout the codestyle I'll add some of your suggestions thanks\n\nTotally agree for the \"open check\" \"full erase\" and \"explicit declaration\" (I didn't know about that last one, so big win for me thanks)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T17:49:39.573", "Id": "409957", "Score": "0", "body": "[Works fine for me](https://wandbox.org/permlink/fLhqTLLWaMtAvhEN), but I admit that the `typename` is not needed, because `DurationType` is not template-dependent. If your compiler is complaining about the `typename` keyword, you can safely remove it. Otherwise, it should work fine." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T16:09:54.423", "Id": "211862", "ParentId": "211857", "Score": "4" } } ]
{ "AcceptedAnswerId": "211862", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T14:32:33.863", "Id": "211857", "Score": "4", "Tags": [ "c++", "performance", "c++11", "benchmarking" ], "Title": "A header only class for C++ time measurement" }
211857
<p>This is SQL Server 2008r2. First, here are some tables and data for test:</p> <pre><code>CREATE TABLE [dbo].[MyOrders] ( [ID] [int] NOT NULL, [ref_type] [nchar](1) NOT NULL, [ref_num] [nvarchar](15) NULL, [req_cert] [nvarchar](255) NULL, CONSTRAINT [PK_MyOrders] PRIMARY KEY CLUSTERED ( [ID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO CREATE TABLE [dbo].[MyJobs] ( [job_id] [nvarchar](15) NOT NULL, [job_message] [nvarchar](255) NULL, CONSTRAINT [PK_MyJobs] PRIMARY KEY CLUSTERED ( [job_id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO CREATE TABLE [dbo].[MyTypes] ( [type] [nvarchar](255) NOT NULL, [value] [nvarchar](255) NOT NULL ) ON [PRIMARY] GO INSERT INTO [dbo].[MyOrders] ([ID], [ref_type], [ref_num], [req_cert]) VALUES (1, 'J', 'Job0001', 'Cert1') GO INSERT INTO [dbo].[MyJobs] ([job_id], [job_message]) VALUES ('Job0001', 'Accepted') GO INSERT INTO [dbo].[MyTypes] ([type], [value]) VALUES ('MyCerts', 'Cert1'), ('MyCerts', 'Cert2') GO </code></pre> <p>Table <code>MyOrders</code> holds my orders, which can reference a job in table <code>MyJobs</code>. <code>MyOrder</code> can specifiy a <code>req_cert</code>, which then will display in <code>job_message</code> field. <code>req_cert</code> will have values from <code>MyTypes</code> table where <code>type == 'MyCert'</code></p> <p>What I am trying to do is create a trigger, which when the column <code>req_cert</code> or <code>ref_num</code> of <code>MyOrders</code> table gets updated, it will do the following:</p> <ol> <li><p>Is one of those 2 fields updated?</p></li> <li><p>Is <code>ref_type == J</code> and <code>ref_num is not null</code>?</p></li> <li><p>Select the existing <code>job_message</code> and check if there is no value from <code>MyTypes</code> table.</p></li> <li><p>If there is, replace it with value from <code>req_cert</code></p></li> <li><p>If there isn't, append <code>req_cert</code></p></li> </ol> <p>I wrote this trigger to do this:</p> <pre><code>ALTER TRIGGER [dbo].[UpdateCert] ON [dbo].[MyOrders] FOR UPDATE AS SET NOCOUNT ON IF (NOT UPDATE ([req_cert]) AND NOT UPDATE ([ref_num])) RETURN DECLARE @ID NVARCHAR(50) DECLARE @Certificate NVARCHAR(255) DECLARE @OldValue NVARCHAR(255) DECLARE @Found TINYINT DECLARE @JobMessage NVARCHAR(2000) DECLARE InsertCursor CURSOR FAST_FORWARD FOR SELECT ref_num, req_cert FROM Inserted OPEN InsertCursor FETCH NEXT FROM InsertCursor INTO @ID, @Certificate WHILE @@FETCH_STATUS = 0 BEGIN IF (NOT EXISTS (SELECT ref_num FROM MyOrders WHERE ref_type = 'J' AND ref_num = @ID)) BEGIN FETCH NEXT FROM InsertCursor INTO @ID, @Certificate CONTINUE END SELECT @JobMessage = job_message FROM MyJobs WHERE job_id = @ID DECLARE CertCursor CURSOR FAST_FORWARD FOR SELECT [Value] FROM MyTypes WHERE [Type] = 'MyCerts' OPEN CertCursor FETCH NEXT FROM CertCursor INTO @OldValue WHILE @@FETCH_STATUS = 0 BEGIN IF (@JobMessage LIKE '%' + @OldValue + '%') BEGIN SET @Found = 1 BREAK END FETCH NEXT FROM CertCursor INTO @OldValue END CLOSE CertCursor DEALLOCATE CertCursor IF (@Found = 1) BEGIN SELECT @JobMessage = REPLACE(@JobMessage, @OldValue, '') END UPDATE MyJobs WITH (ROWLOCK) SET job_message = ISNULL(@Certificate, '') + ISNULL(@JobMessage, '') WHERE MyJobs.job_id = @ID FETCH NEXT FROM InsertCursor INTO @ID, @Certificate END CLOSE InsertCursor DEALLOCATE InsertCursor </code></pre> <p>Expected results (assuming data from above):</p> <pre><code>UPDATE MyOrders SET req_cert = 'Cert1' WHERE ID = 1 </code></pre> <p><code>job_message</code> should be <code>Cert1 Accepted</code></p> <pre><code>UPDATE MyOrders SET req_cert = 'Cert2' WHERE ID = 1 </code></pre> <p><code>job message</code> should be <code>Cert2 Accepted</code></p> <pre><code>UPDATE MyOrders SET ref_num = null WHERE ID = 1 GO UPDATE MyOrders SET req_cert = 'Cert1' WHERE ID = 1 GO UPDATE MyOrders SET ref_num = 'Job0001' WHERE ID = 1 </code></pre> <p><code>job message</code> should be <code>Cert1 Accepted</code></p> <p>My concern: the cursors part. The trigger is not working very well (as in it's slow), but I have no idea how to write it without them.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T11:30:11.107", "Id": "409779", "Score": "1", "body": "Can I know why the downvotes? What else should be added?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T12:59:42.963", "Id": "409785", "Score": "1", "body": "Currently your question is attracting close votes for lack of context, being too broad and the question being unclear. While I'm not sure the question deserves to be closed, it can definitely be improved. Please take a good look at [our FAQ on asking questions](https://codereview.meta.stackexchange.com/q/2436/52915) for quick fixes and general improvements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T13:14:03.753", "Id": "409789", "Score": "1", "body": "I have the example data, test case, actual code, my concern and description. I don't see anything more than I could add about it." } ]
[ { "body": "<p>I'm not sure what is your final goal is, but doing that in triggers usually are not the best solution and they are not recommended to be used. By saying that I mean that there are situation when triggers can help you, but you need to use them with caution as there are quite a lot of troubles that triggers can bring if they are used wrongly.</p>\n\n<p>Once again as I do not know what is the actual goal, I'll ask first before help you with a trigger. If the goal is to show the list with that text on UI, or track some kind of status, then I would suggest to join the tables and get the desired output. Maybe create a view (dbo.vMyOrders or any other name) and get the needed output, for example:</p>\n\n<pre><code>SELECT m.id, \n m.ref_num, \n mj.job_id, \n req_cert \n + IIF(mt.value IS NOT NULL, ' ' + job_message, '') AS cert_status \nFROM dbo.myorders m \n LEFT JOIN dbo.mytypes mt \n ON mt.value = m.req_cert \n AND mt.type = 'MyCerts' \n LEFT JOIN dbo.myjobs mj \n ON mj.job_id = m.ref_num \nWHERE ref_type = 'J' \n AND ref_num IS NOT NULL\n AND job_message NOT LIKE '% %'\n</code></pre>\n\n<p>If you still need trigger then:</p>\n\n<pre><code> CREATE TRIGGER [dbo].[UpdateCert] \n ON [dbo].[MyOrders]\n FOR UPDATE\n AS\n SET NOCOUNT ON\n\n IF (NOT UPDATE ([req_cert])\n AND NOT UPDATE ([ref_num]))\n RETURN\n\n UPDATE j\n SET job_message = req_cert + IIF(mt.value IS NOT NULL,' ' + job_message, '')\n FROM dbo.MyJobs j\n join inserted m on j.job_id = m.ref_num \n LEFT JOIN dbo.MyTypes mt ON mt.value = m.req_cert AND mt.type = 'MyCerts'\n WHERE ref_type = 'J' \n AND ref_num IS NOT NULL\n AND job_message NOT LIKE '% %'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T16:25:50.787", "Id": "410064", "Score": "1", "body": "Which statements are not provided? Also, thank you for the answer, but this fails test case." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:07:06.597", "Id": "410068", "Score": "0", "body": "my bad. copy/paste error. Will review this a bit later" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:17:46.067", "Id": "410127", "Score": "0", "body": "The goal is to get the proper value into the job_message field. This field is bound to a form control in ERP system, and cannot be changed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T05:55:58.133", "Id": "410703", "Score": "0", "body": "After testing the new version, still fails the test cases, sorry :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T08:40:14.130", "Id": "410721", "Score": "0", "body": "updated queries, however it is not clear what to do when the value is updated back to NULL" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:17:05.477", "Id": "212075", "ParentId": "211861", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T15:40:07.200", "Id": "211861", "Score": "0", "Tags": [ "sql", "sql-server" ], "Title": "Modify a column in 2 tables based on trigger" }
211861
<p>Test Case: Input- "I'm hungry!" Output- "!yrgnuh m'I"</p> <p>Approach 1: In this approach, I used a empty string and bind it with the input string reversely.</p> <pre><code>public static class ReverseString { public static string Reverse (string input) { //bind the string to an empty string reversly var reversedString = ""; //check if the input is empty if (input == "") { return ""; } else { for (int i = input.Length - 1; i &gt;= 0; i--) { reversedString += input[i]; } return reversedString; } } } </code></pre> <p>Approach 2: In this approach, I've created an empty char array which has the same length of the string. Then I've copied the value of string's last index to char array's first index and so on.</p> <pre><code>public static class ReverseString { public static string Reverse (string input) { char[] chars = new char[input.Length]; for(int i = 0, j = input.Length -1; i &lt;= j; i++, j--) { chars[i] = input[j]; chars[j] = input[i]; } return new string(chars); } } </code></pre> <p>There are lots of approaches like this(without using built in library). But I wonder which one is the most recommended among programmers preferably C# programmers.Which one do you recommend and why?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T04:01:26.763", "Id": "409736", "Score": "1", "body": "Did you try timing them?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T05:19:24.877", "Id": "409741", "Score": "0", "body": "@SolomonUcko No Sir, I didn't :(" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:34:15.047", "Id": "409761", "Score": "0", "body": "You can reverse a string in-place, without allocating new memory." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:37:16.187", "Id": "409762", "Score": "5", "body": "@allo not in C#/.NET. Strings are immutable objects and to pin memory and _play_ with its internal buffer, while possible, is doomed to break if implementation changes (for example, nothing dictates that a System.String` object cannot _cache_ its hash-code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:41:14.310", "Id": "409763", "Score": "4", "body": "@AKdeBerg first approach is possibly terrible from a performance point of view (N + 1 useless allocations + copies). Approach 2 might be GREATLY simplified or, even better you can use a `StringBuilder`. However the question is: do you have any constraint about **string content**? Because a .NET string is an array of code units which simply cannot be reversed (think about Unicode surrogates) or _characters_ composed by multiple code points (all those emojis and some CJK characters). There are diacritics and so on (like accents, for example). Not to mention RTL languages and much much more..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:42:40.967", "Id": "409764", "Score": "5", "body": "You might take a look to [Split a string into chunks of the same length](https://codereview.stackexchange.com/a/111925/13424) and [How can I perform Unicode aware character by character comparison](https://stackoverflow.com/a/27229590/1207195)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T10:03:52.213", "Id": "409768", "Score": "0", "body": "@AdrianoRepetti Thank you, I did not know this and assumed you are allowed to swap characters in some way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T10:55:18.233", "Id": "409777", "Score": "0", "body": "@AdrianoRepetti Thanks..I am digging into the resources you've shared.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T19:52:33.417", "Id": "409823", "Score": "0", "body": "An example of why you can't meaningfully do this using your first ReverseString code - https://repl.it/repls/ComfortableDeliriousLists - click the \"Run\" button at the top - note that the first string has an accented letter `e` and reverses \"properly\", but the second string looks the same but is made with a plain `e` and a combining accent after it, and when \"reversed\", the combining accent is now placed so it applies to the `z`. For a programming challenge where strings == ascii character code array, string reverse is OK, but it is a toy problem, and for that - use an array of int." } ]
[ { "body": "<h3>Clarity of Approaches</h3>\n\n<p>With the first approach, I look at it and I can tell straight away that you are reversing a string. With the second approach, I need to study it for a minute or two to work out what you're doing.</p>\n\n<h3>Unnecessary Code</h3>\n\n<p>In the first approach, the check for an empty string is not necessary. In this case, your logic will not even enter the for loop, resulting in an empty string being returned anyway.</p>\n\n<h3>Performance</h3>\n\n<p>As you may know, strings are immutable objects in .Net. It is good practice to use a <code>StringBuilder</code> to create strings in this way, like so:</p>\n\n<pre><code>var reversedString = new StringBuilder(input.Length);\nfor (int i = input.Length - 1; i &gt;= 0; i--)\n{\n reversedString.Append(input[i]);\n}\nreturn reversedString.ToString();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T23:08:15.120", "Id": "409731", "Score": "9", "body": "Can't you tell your string builder to expect to hold input.Length characters?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:50:09.660", "Id": "409765", "Score": "3", "body": "Honestly, if I see a method called ReverseString.Reverse(string input) I'd have a fair idea of what it's doing regardless of the method body :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:14:28.770", "Id": "409824", "Score": "0", "body": "@einpoklum Thanks for the suggestion. I've edited accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:35:13.243", "Id": "409834", "Score": "0", "body": "@JoeC: And I don't even know C#.... :-P" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:37:26.023", "Id": "409835", "Score": "0", "body": "@einpoklum I've not used it for half a decade either. I had to look up whether such a thing existed in .Net (I'm normally a Java developer)." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:45:49.247", "Id": "211876", "ParentId": "211873", "Score": "11" } }, { "body": "<p>I like the char[] approach, since it allocates the memory all at once and only makes one string. However using the LINQ extension method(<code>return new string(input.Reverse().ToArray());</code>) seems to do the same job in a fraction of the time according the .net profiler.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T10:31:25.097", "Id": "409773", "Score": "0", "body": "Fast and a _readable_ one-liner? sounds good to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T14:20:31.967", "Id": "409797", "Score": "0", "body": "@VisualMelon's microbenchmark results indicate that this performs *horribly*, like an order of magnitude worse than the OP's version #2 meet-in-the-middle copy into a new array. If that's correct, you'd only want to use this in cases where performance doesn't matter, unfortunately." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T02:57:36.820", "Id": "211889", "ParentId": "211873", "Score": "8" } }, { "body": "<h1>Performance</h1>\n\n<p>I didn't believe that the LINQ method could be faster, and I would never trust a profiler to give an accurate result (for numerous reasons), so I ran a benchmark with BenchmarkDotNet, and got the opposite result from tinstaafl. (<a href=\"https://gist.github.com/VisualMelon/4317c7358807a53dc687462c9b1d6297\" rel=\"noreferrer\"><em>Code in a gist</em></a>)</p>\n\n<p>Here are the results. <code>Linq</code> is as tinstaafl's, <code>StringBuilder</code> is as Joe C's, <code>Char2</code> is as OP's second method, <code>Char1a</code> and <code>Char1b</code> are variations of what I would have suggested off-hand. On this machine (old i7), under .NET Core 2.1, in a dedicated benchmark, the OP's code was significantly faster than the <code>Linq</code> and <code>StringBuilder</code> methods. (Results may be very different under .NET Framework)</p>\n\n<pre><code> Method | TestString | Mean | Error | StdDev |\n---------------------- |---------------------- |-------------:|-----------:|----------:|\n ReverseLinq | | 81.472 ns | 0.1537 ns | 0.1284 ns |\n ReverseChar1a | | 7.946 ns | 0.1156 ns | 0.1081 ns |\n ReverseChar1b | | 7.518 ns | 0.0177 ns | 0.0157 ns |\n ReverseChar2 | | 7.507 ns | 0.0232 ns | 0.0206 ns |\n ReverseStringBuilders | | 12.894 ns | 0.1740 ns | 0.1542 ns |\n ReverseLinq | It's (...)ow it [39] | 671.946 ns | 1.9982 ns | 1.8691 ns |\n ReverseChar1a | It's (...)ow it [39] | 61.711 ns | 0.0774 ns | 0.0604 ns |\n ReverseChar1b | It's (...)ow it [39] | 61.952 ns | 0.2241 ns | 0.1986 ns |\n ReverseChar2 | It's (...)ow it [39] | 48.417 ns | 0.0877 ns | 0.0732 ns |\n ReverseStringBuilders | It's (...)ow it [39] | 203.733 ns | 0.7540 ns | 0.6684 ns |\n ReverseLinq | Magpies | 235.176 ns | 0.5324 ns | 0.4446 ns |\n ReverseChar1a | Magpies | 23.412 ns | 0.0979 ns | 0.0916 ns |\n ReverseChar1b | Magpies | 24.032 ns | 0.0582 ns | 0.0544 ns |\n ReverseChar2 | Magpies | 22.401 ns | 0.1193 ns | 0.0996 ns |\n ReverseStringBuilders | Magpies | 44.056 ns | 0.1313 ns | 0.1097 ns |\n ReverseLinq | ifhia(...) oiha [432] | 4,102.307 ns | 10.4197 ns | 9.2368 ns |\n ReverseChar1a | ifhia(...) oiha [432] | 454.764 ns | 1.0899 ns | 1.0195 ns |\n ReverseChar1b | ifhia(...) oiha [432] | 453.764 ns | 2.3080 ns | 2.0460 ns |\n ReverseChar2 | ifhia(...) oiha [432] | 400.077 ns | 1.0022 ns | 0.7824 ns |\n ReverseStringBuilders | ifhia(...) oiha [432] | 1,630.961 ns | 6.1210 ns | 5.4261 ns |\n</code></pre>\n\n<p><em>Note: never used BenchmarkDotNet before... hopefully I've not misused/misunderstood it in any way (please comment if I have), and hopefully it is good at it's job.</em></p>\n\n<h1>Commentary</h1>\n\n<p>Performance is not everything. The linq method is the most compact, and the hardest to get wrong, which is very good. However, if performance is important, than you need to profile the method as realistically as possible. The results above may not generalise. However, I'd be very surprised if the <code>StringBuilder</code> and <code>Linq</code> methods out-performed any of the char-array based methods ever, because they just incur a fair amount of overhead (i.e. probably a dynamic array, and probably a second copy in the LINQ case (not to mention the general enumeration overhead)).</p>\n\n<p>Personally, I have no issue with your second piece of code. It may not be the most obvious implementation ever, but it doesn't take long to work out, and it's not a method whose job is going to change any time soon, so I'd worry much more about its API than its internals. That said, the API is a problem, as Adriano Repetti has mentioned: the behaviour of this method is going to create problems as soon as you start trying to reverse non-trivial Unicode. Simply, 'reverses a string' is a deficient contract.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T14:09:21.720", "Id": "409794", "Score": "2", "body": "The OP's approach #2 is pretty close to the usual in-place reversal (walk two pointers or indices in from the ends until they cross), just with a new destination instead of doing it in-place. It's probably no more efficient than a single read-backward / write-forward loop (or the reverse), though. It's kind of like unrolling a one-way loop by going both directions at once. For large inputs, hardware prefetching on Intel CPUs can track one forward stream and one backward stream per 4k page for prefetch into L2 cache." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T14:14:49.853", "Id": "409796", "Score": "1", "body": "Of course for performance you'd want it to auto-vectorize with x86 SSSE3 `pshufb`, to load/store 16 bytes at once and reverse them in chunks of 2 bytes (.NET `char`s). That's maybe more likely without the meet-in-the-middle behaviour. (I think I have it right that a `char` in .NET is a fixed-width 16-bit type ([Char size in .net is not as expected?](https://stackoverflow.com/q/10540774)), so even the scalar implementation breaks UTF-16 surrogate pairs forming one Unicode codepoint, as well as strings containing a reverse-text-direction character or whatever.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T14:41:05.993", "Id": "409798", "Score": "1", "body": "@PeterCordes indeed; the other 2 things I tested were a one-way reversal; I thought maybe it would play better with the optimisation, but apparently not. Yeah, `char` is like wchar; one UTF-16 code point. You're right, this is by no means the most aggressive approach for performance (further optimisation will quickly increase complexity), but a factor of 10 is probably worth getting the right way round ;) - I've just had a quick look at the assembly produced, and nothing exciting jumps out at me, so it's not doing anything too smart underneath." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T14:48:08.320", "Id": "409800", "Score": "1", "body": "*code unit; _not_ code point!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T10:46:32.750", "Id": "211908", "ParentId": "211873", "Score": "10" } }, { "body": "<p>I would recommend neither of the approaches. Strings in .NET are a rather unfortunate data structure, they consist of UTF-16 units. This unfortunately exposes the peculiarities of the UTF-16 encoding to the programmer, which will in particular cause problems if your string contains characters from the Unicode astral planes (code points U+10000 and up). These are expressed as pairs of two surrogates, which when reversed will be invalid. There are also issues with combining diacritics: simply reversing the order of code points may result in a combining diacritic being associated with a different letter, or even no letter at all.</p>\n\n<p>Since reversing a sequence of UTF-16 units is not a meaningful operation for textual data, the approach I would take is to use the built-in functionality to slice strings by text elements. This can be done using the <code>System.Globalization.StringInfo</code> class:</p>\n\n<pre><code>public static string Reverse(string source)\n{\n var info = new StringInfo(source);\n var sb = new StringBuilder(source.Length);\n for (var i = info.LengthInTextElements; i-- &gt; 0;)\n {\n sb.Append(info.SubstringByTextElements(i, 1));\n }\n\n return sb.ToString();\n}\n</code></pre>\n\n<p>As noted in the comments, Unicode also supports control structures like bidirectional overrides and interlinear annotations that would end up with their delimiters in the wrong order after this routine. This would require further parsing of the output to switch the start and end characters for these control structures (in particular, the bidirectional characters can represent nested levels of LTR and RTL ordering).</p>\n\n<p>Edit 23.01.19: another thing to note is that some scripts have specific rules about the characters depending on where they are in the word. For example the Greek lowercase letter sigma has a different shape if it is at the end of the word, and is encoded with a different code point in each scenario (U+03C3 GREEK SMALL LETTER SIGMA vs U+03C2 GREEK SMALL LETTER FINAL SIGMA). This will not be taken into account by the above routine, e.g. if you reverse the word \"στάσις\" you will end up with \"ςισάτσ\" not \"σισάτς\". If you require the reversal to take this kind of thing into account you are up for a very large challenge!</p>\n\n<p>Moral of the story: Unicode is hard. This is not Unicode's fault: it is a consequence of the fact that text is hard.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:24:23.343", "Id": "409828", "Score": "2", "body": "That is StringInfo use is cool, I didn't know that was a thing; but even so if the string has a right-to-left-override marker in it - in PowerShell terms `\"first$([char]8238)second\" | Set-Clipboard` to make one (PS strings are .Net strings too), then paste it into a browser, it renders as `firstdnoces` so when reversed it \"should\" look like `secondtsrif` but instead the RTL marker applies to the \"wrong\" thing and it renders as `dnocestsrif`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:28:25.243", "Id": "409831", "Score": "0", "body": "@TessellatingHeckler - good point about the bidirectional overrides. They make things rather more complicated!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:54:24.960", "Id": "409840", "Score": "1", "body": "Welcome to CR! Excellent contribution, thanks for chipping in! So... this reverses unicode astral-plane happy-face emojis into frown-face emojis?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:47:32.333", "Id": "409849", "Score": "0", "body": "@MathieuGuindon - reversing the mood of the emojis would take quite a bit more work! There seems to be an ever-increasing number of them to take care of..." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T18:57:52.610", "Id": "211929", "ParentId": "211873", "Score": "9" } } ]
{ "AcceptedAnswerId": "211908", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:09:00.923", "Id": "211873", "Score": "8", "Tags": [ "c#", "performance", "strings", "programming-challenge", "comparative-review" ], "Title": "Reversing a string - two approaches" }
211873
<p>I created a simple modal that when a user scrolls down a blog post, a modal pops up. If the user wants to sign up for newsletter, then a form pops up. The only external library I used was body-scroll-lock that helps mitigate some issues with modals/forms on iOS.</p> <p>I'm curious about the need to remove event listeners and other pitfalls that I may be overlooking. Should I be using more es6 type conventions? The code is just before the <code>&lt;/body&gt;</code> tag. Here it is in action: <a href="https://develop--tanyamark-prod.netlify.com/blog/do-you-eat-when-youre-hungry-stop-when-youre-full/" rel="nofollow noreferrer">https://develop--tanyamark-prod.netlify.com/blog/do-you-eat-when-youre-hungry-stop-when-youre-full/</a></p> <pre><code>// Wait at least 2s to so CTA var wait = window.setTimeout(showCta, 2000); function showCta() { // Only show CTA on post pages. if (document.querySelector('.post-single') === null) { return; } var screenWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var bodyTag = document.getElementsByTagName('body')[0]; var blogCta = document.getElementById("blog-cta"); var openFormButton = document.getElementById("open-cta"); var closeButtonUnsubmitted = document.getElementById("close-cta"); var submittedCloseButton = document.getElementById("submitted-close"); // Wait to show cta until user scrolls down page. bodyTag.onscroll = function () { if ( window.pageYOffset &gt; (document.body.clientHeight / 4) ) { blogCta.classList.remove("hide"); } }; var openForm = function(e) { if (screenWidth &lt; 901) { blogCta.classList.add("mobile-blog-cta"); bodyScrollLock.disableBodyScroll(blogCta); } // Show the form. document.getElementById("cta-ck-form").style.display = 'block'; // Remove click event from button. openFormButton.removeEventListener('click', openForm); // Hide openFormButton openFormButton.style.display = 'none'; }; var removeCTA = function() { blogCta.classList.remove("mobile-blog-cta"); if (screenWidth &lt; 901) { bodyScrollLock.clearAllBodyScrollLocks(); } // Set inline so it doesn't show more than once. blogCta.style.display = 'none'; }; // Register events openFormButton.addEventListener('click', openForm); closeButtonUnsubmitted.addEventListener('click', removeCTA); submittedCloseButton.addEventListener('click', removeCTA); } </code></pre> <p>/partials/_cta.html (The form itself is a convert kit embed)</p> <pre><code>&lt;div id="blog-cta" class="blog-cta hide"&gt; &lt;div class="cta-content"&gt; &lt;p id="cta-message"&gt;Hi, It's Tanya. Like what you're reading? Get tips once a week on &lt;em&gt;nourishing your whole self.&lt;/em&gt;&lt;/p&gt; &lt;div id="open-cta" class="button pink"&gt;Yes, please!&lt;/div&gt; &lt;div id="cta-ck-form" class="ck_form_container ck_inline" data-ck-version="6"&gt; &lt;div class="ck_form ck_naked"&gt; &lt;div class="ck_form_fields"&gt; &lt;div id="ck_success_msg" style="display:none;"&gt; &lt;p&gt;Success! Check your email to confirm your subscription.&lt;/p&gt; &lt;button id="submitted-close"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;!-- Form starts here --&gt; &lt;form id="ck_subscribe_form" class="ck_subscribe_form" action="https://app.convertkit.com/landing_pages/309440/subscribe" data-remote="true"&gt; &lt;input type="hidden" value="{&amp;quot;form_style&amp;quot;:&amp;quot;naked&amp;quot;}" id="ck_form_options"&gt; &lt;input type="hidden" name="id" value="309440" id="landing_page_id"&gt; &lt;input type="hidden" name="ck_form_recaptcha" value="" id="ck_form_recaptcha"&gt; &lt;div class="ck_errorArea"&gt; &lt;div id="ck_error_msg" style="display:none"&gt; &lt;p&gt;There was an error submitting your subscription. Please try again.&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ck_control_group ck_email_field_group"&gt; &lt;label id="ck-test" class="ck_label" for="ck_emailField" style="display: none"&gt;Email Address&lt;/label&gt; &lt;input type="text" name="first_name" class="ck_first_name" id="ck_firstNameField" placeholder="First Name" required="required"&gt; &lt;input type="email" name="email" class="ck_email_address" id="ck_emailField" placeholder="Email Address" required&gt; &lt;/div&gt; &lt;div class="ck_control_group ck_captcha2_h_field_group ck-captcha2-h" style="position: absolute !important;left: -999em !important;"&gt; &lt;input type="text" name="captcha2_h" class="ck-captcha2-h" id="ck_captcha2_h" placeholder="We use this field to detect spam bots. If you fill this in, you will be marked as a spammer."&gt; &lt;/div&gt; &lt;button class="subscribe_button ck_subscribe_button btn fields" id="ck_subscribe_button"&gt; Subscribe &lt;/button&gt; &lt;/form&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container-author-pic"&gt; &lt;div class="incoming-message"&gt;&lt;span&gt;1&lt;/span&gt;&lt;/div&gt; &lt;img class="article-author-pic" src="/img/tanya-cup-prof.jpg" alt=""/&gt; &lt;div class="mobile-header"&gt;Tanya&lt;/div&gt; &lt;div id="close-cta"&gt;X&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>/partials/_cta.css (Using postcss-cssnext plugin)</p> <pre><code>.blog-cta { display: flex; flex-direction: row; position: fixed; bottom: 80px; right: 30px; z-index: 820; animation: grow .5s ease-in-out; @media all and (max-width: 600px) { right: 0; margin: 15px; } } @keyframes grow { 0% { display: none; opacity: 0; transform: scale(0); } 100% { opacity: 1; transform: scale(1); } } .cta-content { position: relative; display: flex; flex-direction: column; max-width: 300px; background-color: white; box-shadow: 0 0 30px rgba(42, 63, 253, .4); margin-right: 15px; } .cta-content::after { position: absolute; display: block; content: ""; width: 0; height: 0; left: 100%; top: 45px; border-top: 8px solid transparent; border-bottom: 8px solid transparent; border-left: 10px solid #fff; @media all and (max-width: 600px) { top: 30px; } } #cta-message { color: #1c3f55; font-size: 17px; line-height: 22px; padding: 12px; margin: 0; } #open-cta { cursor: pointer; } .mobile-header { /* Will show on mobile */ display: none; } .incoming-message { width: 20px; height: 20px; background-color: red; border-radius: 24px; color: white; font-size: 14px; position: absolute; display: flex; align-items: center; justify-content: center; } #close-cta { display: inline-flex; justify-content: center; align-items: center; position: absolute; top: -15px; right: -15px; font-family: var(--sans-serif-stack); color: #a2a1a1; font-size: 14px; cursor: pointer; height: 16px; width: 16px; padding: 5px; border-radius: 16px; background: #f1f1f5; } #close-cta:hover { color: black; transition: color .2s ease-in-out; transition: font-size .2s ease-in-out; } /********************/ /* Convert Kit Form */ /********************/ #cta-ck-form { display: none; animation: grow .3s ease-in-out; } .ck_form, .ck_form * { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .ck_errorArea { display: none; /* temporary */ } .ck_form input[type="text"]:focus, .ck_form input[type="email"]:focus { outline: none; border-color: #aaa; } .ck_converted_content { display: none; padding: 5%; background: #fff; } .ck_form.ck_naked.width400 .ck_subscribe_button, .ck_form.ck_naked.width400 input[type="text"], .ck_form.ck_naked.width400 input[type="email"] { width: 100%; float: none; margin-top: 5px; } .ck_slide_up, .ck_modal, .ck_slide_up .ck_naked, .ck_modal .ck_naked { min-width: 400px; } .page .ck_form.ck_naked { margin: 50px auto; max-width: 700px; } .ck_slide_up.ck_form_v6, .ck_modal.ck_form_v6, .ck_slide_up.ck_form_v6 .ck_naked, .ck_modal.ck_form_v6 .ck_naked { min-width: 0 !important; } .ck_form_v6 #ck_success_msg { padding: 0px 10px; } @media all and (max-width: 403px) { .ck_form_v6.ck_modal .ck_naked { padding-top: 30px; } } @media all and (max-width: 499px) { .ck_form_v6.ck_modal .ck_naked+.ck_close_link { color: #fff; top: 10px; } } .ck_form_v6.ck_slide_up .ck_naked+.ck_close_link { right: 10px; top: -5px; } @media all and (min-width: 600px) { .ck_form_v6.ck_slide_up .ck_naked+.ck_close_link { right: 35px; } } /************************/ /* ConvertKit overrides */ /************************/ .blog-cta .ck_form.ck_naked p { font-size: 17px; line-height: 20px; } .blog-cta .ck_form.ck_naked .ck_form_fields { padding: 12px; } .blog-cta .ck_form.ck_naked input[type="text"], .blog-cta .ck_form.ck_naked input[type="email"] { padding: 10px 8px; border: 1px solid #d6d6d6; height: 40px; font-size: 18px; } .blog-cta .ck_form.ck_naked .ck_subscribe_button, .blog-cta #ck_success_msg button { color: #fff; font-size: 18px; background: #db65cb; cursor: pointer; border: none; height: 44px; margin-top: 10px } .blog-cta #ck_success_msg button { padding: 0 20px; display: block; margin: 0 auto; } /*************************/ /* Mobile + Small Screen */ /*************************/ .mobile-blog-cta.blog-cta { bottom: initial; flex-direction: column-reverse; justify-content: flex-end; align-items: center; margin: 0; background: #f6f6f6; position: fixed; top: 0; height: 100vh; width: 100%; right: 0; animation: anim .5s ease-in-out; @media (max-height: 370px), (max-width: 320px) { height: 100vh; } } @keyframes anim { 0% { transform: scale(0); } 100% { opacity: 1; transform: scale(1); } } .mobile-blog-cta .cta-content { margin: 10px 10px; max-width: 600px; background-color: white; padding: 30px; box-shadow: 0 2px 20px 0 rgba(0,0,0,.15); @media (max-height: 370px), (max-width: 320px) { background-color: initial; padding: 0; box-shadow: initial; } } .mobile-blog-cta .cta-content #cta-message { padding-top: 0; } .mobile-blog-cta .cta-content::after { display: none; } .mobile-blog-cta .container-author-pic { width: 100%; height: 30px; background: #fff; padding: 10px 0; margin-bottom: 30px; box-shadow: 0 0 20px rgba(0,0,0,.5); display: flex; justify-content: space-around; align-items: center; } .mobile-blog-cta .article-author-pic { margin-top: 30px; border: #fff 5px solid; } .mobile-blog-cta .mobile-header{ display: inline-block; line-height: 50px; font-weight: 600; } .mobile-blog-cta .incoming-message { display: none; } .mobile-blog-cta #close-cta { position: relative; font-size: 20px; color: initial; top: initial; right: initial; height: 22px; width: 22px; } .mobile-blog-cta #ck_firstNameField, .mobile-blog-cta #ck_emailField { width: 100%; margin-bottom: 10px; } .mobile-blog-cta .ck_form.ck_naked .ck_subscribe_button, .mobile-blog-cta #ck_success_msg button { width: 100%; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:37:16.810", "Id": "409711", "Score": "0", "body": "Where's the HTML?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:39:52.310", "Id": "409712", "Score": "0", "body": "I'll add it, though I'm more concerned with the .js. Should I add the css as well?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:40:15.977", "Id": "409713", "Score": "1", "body": "Anything that's code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:42:47.113", "Id": "409714", "Score": "2", "body": "Ok, btw, you can embed code in your post, as opposed to linking it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:47:47.290", "Id": "409719", "Score": "1", "body": "Added the html and css. I linked to the live site only to demonstrate the feel/flow of the modal. And, I should add, of course, feed back on html/css is always nice as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T23:46:01.253", "Id": "409734", "Score": "1", "body": "Where is `bodyScrollLock` defined?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T19:12:30.720", "Id": "211874", "Score": "3", "Tags": [ "javascript", "event-handling", "dom" ], "Title": "Javascript Call To Action Modal" }
211874
<p>I came across a nice <a href="https://www.youtube.com/watch?v=HEfHFsfGXjs" rel="noreferrer">video</a> on 3Blue1Brown's channel that highlights a very indirect way to find the digits in Pi. I'd suggest watching the whole video, but briefly:</p> <p><a href="https://i.stack.imgur.com/Vf8S3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Vf8S3.png" alt="enter image description here"></a></p> <p>The setup is as above. A "small" body of unit mass is at rest on the left and a "large" body on the right is moving towards the left (the initial positions and velocities are irrelevant). Assuming perfectly elastic collisions and that the large body's mass to be the n-th power of 100, where n is a natural number, the total number of collisions is always floor(pi*(10<sup>n</sup>)).</p> <p>The analytical reason for this is discussed <a href="https://www.youtube.com/watch?v=jsYwFizhncE" rel="noreferrer">here</a>, but I've started learning a bit of Python and wanted to simulate this to improve my programming (i.e. I'm a beginner). Here's the code:</p> <pre><code>from fractions import Fraction class Block: # Creating a class since that helps keep track of attributes def __init__(self, mass, velocity, position): self.mass = mass self.velocity = velocity self.position = position # Set initial conditions: the object on the left is at rest at x = 5 and has # unit mass. The one on the right starts off at x = 10, with velocity = # -5 units/s and has mass equal to 100^n, where n is user-specified. # The number of collisions should be floor(Pi*10^n). e.g. n = 2 =&gt; 314, # n = 3 =&gt; 3141, and so on small = Block(1, 0, Fraction(32/10)) large = Block(100**int(input("Which power of 100 is the second mass? ")), -7, Fraction(75,10)) # By "collision", we mean that either the position of both the objects is the # same (both collide against each other) or the position of the small block is # 0 (collision against wall) def updateVelocities(collisions): if(small.position == large.position != 0): # Both blocks collide against each other collisions += 1 temp = small.velocity small.velocity = Fraction(((2*large.mass*large.velocity)+ (small.mass*small.velocity)-(large.mass*small.velocity)), (small.mass + large.mass)) large.velocity = Fraction(((2*small.mass*temp)+(large.mass*large.velocity) -(small.mass*large.velocity)),(small.mass + large.mass)) elif(small.position == 0 != large.position): # The small block gets "reflected" off the wall collisions += 1 small.velocity = -small.velocity elif(small.position == large.position == 0): # The rare instance in which both blocks move towards the wall and # collide with the wall and against each other simultaneously collisions += 2 small.velocity, large.velocity = -small.velocity, -large.velocity else: pass return collisions # Given the current positions and velocities, find the time to next collision # This takes care of all different scenarios def timeToNextCollision(): if(large.velocity &gt;= small.velocity &gt;= 0): # Both blocks move towards right, but the large block is faster and the # small block can't catch up return float("inf") elif(small.velocity &gt;= 0 &gt;= large.velocity): # Both blocks are either moving towards each other, or one of the is at # rest and the other is moving towards it. The wall is obviously ignored # The condition small.velocity == 0 == large.velocity will also be ignored # since if that's true, only the first if statement would be executed. return Fraction(large.position - small.position, small.velocity - large.velocity) elif((large.velocity &gt;= 0 and small.velocity &lt; 0) or (small.velocity &lt;= large.velocity &lt; 0)): # Both blocks move towards left, but the large block can't catch up with # the small block before the latter runs into the wall return Fraction(-small.position, small.velocity) elif(small.position == 0): # Special case for when the small block is currently at the wall if(large.velocity &gt;= abs(small.velocity)): # Small block can no longer catch up with large block return float("inf") else: # Large block is either moving towards left or too slow moving towards # the right. In either case, they will collide return large.position/(abs(small.velocity) - large.velocity) else: # Both blocks move towards left, but large block is faster. If the # distance between blocks is small enough compared to that between the wall # and the small block, they will collide. Otherwise the small block will # reach the wall before the large block has a chance to catch up return min(Fraction(-small.position, small.velocity), Fraction(large.position - small.position), (small.velocity - large.velocity)) collisionCount = 0 while True: t = timeToNextCollision() if(t == float("inf")): # No more collisions break # Update the distances to what they'll be during the next collision small.position += small.velocity*t large.position += large.velocity*t # Update collision count AND velocities to post-collision values collisionCount = updateVelocities(collisionCount) print(collisionCount) </code></pre> <p>The biggest headache was dealing with float's precision issues. For example, for a collision to register, the updated positions of the two blocks should exactly be the same. But with float's rounding issues, there would be a slight difference in the positions and the program would go haywire.</p> <p>Even though this was corrected by using the Fraction data type, the run time of the program is really slow. If n=2, the program finishes within milliseconds, whereas for n=3, it takes a whopping 115 seconds. I'm not really aware of all the nuances of Python nor do I have any computer science knowledge, so I'd be really grateful if I can get some guidance on how I can improve the code.</p> <p>Off the top of my head, perhaps using Fraction affects the run time, or I wrote the if conditions in a clumsy way, or wrote redundant code. I'm confused because there are many possibilities. In the first video I linked to, <a href="https://youtu.be/HEfHFsfGXjs?t=120" rel="noreferrer">at around the 2:00 min mark</a>, there's a simulation of collisions between 1 kg and 100<sup>3</sup> kg, and it's so smooth and quick!</p> <p>P.S. I used the Block class just to improve readability. I've tried using a simple list instead of a Block class object, but that only shaves off around 8 seconds or so. Not much improvement. I also tried using the numpy double data type - again, same rounding issues as with the default float type.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T18:42:38.220", "Id": "409961", "Score": "0", "body": "what version of python are you using?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:31:16.743", "Id": "410219", "Score": "0", "body": "@arnauvivetpares: I'm using 3.7" } ]
[ { "body": "<p>First, <a href=\"https://www.youtube.com/watch?v=jsYwFizhncE\" rel=\"noreferrer\">this is an awesome video!</a> Upvoted for that reason alone. :)</p>\n\n<blockquote>\n <p>If n=2, the program finishes within milliseconds, whereas for n=3, it takes a whopping 115 seconds.</p>\n</blockquote>\n\n<p>Do you know about <a href=\"https://en.wikipedia.org/wiki/Big_O_notation\" rel=\"noreferrer\">big-O notation</a>? Just off the top of my head after watching that video: for <code>n=2</code> you're computing the number of collisions for a 1kg block and a <code>100**2</code> = 10,000kg block, which we know from the video should be 314 collisions. For <code>n=3</code> you're simulating 3141 collisions. That's 10 times as many collisions, simulated one at a time, so it <em>should</em> take 10 times as long. In general your program is going to take O(10<sup>n</sup>) steps to compute its result. So you shouldn't be surprised if it gets real slow real fast.</p>\n\n<p>However, you're saying the difference between <code>n=2</code> and <code>n=3</code> is a factor of more than 100. That's surprising. I think you're right to blame <code>Fraction</code> — that is, you're dealing with much bigger numerators and denominators in the <code>n=3</code> case, and bigger numbers naturally take more time to manipulate.</p>\n\n<hr>\n\n<pre><code>if(large.velocity &gt;= small.velocity &gt;= 0):\n</code></pre>\n\n<p>In general I like your use of chained comparisons... but why did you almost invariably put the biggest number on the <em>left</em> and the smallest on the <em>right</em>? That's backwards from how we usually write number lines.</p>\n\n<p>And then sometimes you don't chain the comparison at all, for no reason I can detect:</p>\n\n<pre><code>elif((large.velocity &gt;= 0 and small.velocity &lt; 0) or\n (small.velocity &lt;= large.velocity &lt; 0)):\n</code></pre>\n\n<p>I'd write this as</p>\n\n<pre><code>elif (small.velocity &lt; 0 &lt;= large.velocity) or (small.velocity &lt;= large.velocity &lt; 0):\n</code></pre>\n\n<p>Notice that you don't need parens around the condition of an <code>if</code> or <code>elif</code> in Python, and so it's not usual to write them.</p>\n\n<pre><code>return large.position/(abs(small.velocity) - large.velocity)\n</code></pre>\n\n<p>You didn't use <code>Fraction</code> here. Was that an oversight? Also, if this is a floating-point division, I <em>might</em> want to blame \"repeated conversion from <code>Fraction</code> to floating-point and back\" for some of your performance problems.</p>\n\n<hr>\n\n<pre><code>large = Block(100**int(input(\"Which power of 100 is the second mass? \")),\n -7, Fraction(75,10))\n</code></pre>\n\n<p>I strongly recommend moving the <code>input</code> onto its own source line. Mixing user input into the middle of an arithmetic expression is just asking for trouble. Plus, this lets you unambiguously name the <code>n</code> that you were trying to talk about in your question:</p>\n\n<pre><code>n = int(input(\"Which power of 100 is the second mass? \"))\nlarge = Block(100**n, -7, Fraction(75,10))\n</code></pre>\n\n<p>Actually, hang on; back up!</p>\n\n<pre><code># Set initial conditions: the object on the left is at rest at x = 5 and has\n# unit mass. The one on the right starts off at x = 10, with velocity =\n# -5 units/s and has mass equal to 100^n, where n is user-specified.\n# The number of collisions should be floor(Pi*10^n). e.g. n = 2 =&gt; 314,\n# n = 3 =&gt; 3141, and so on\n\nsmall = Block(1, 0, Fraction(32/10))\nlarge = Block(100**int(input(\"Which power of 100 is the second mass? \")),\n -7, Fraction(75,10))\n</code></pre>\n\n<p>That comment is <em>ridiculously</em> untrue! The object on the left is at rest at <code>x = 3.2</code> (or <code>x = 3</code> if you're in Python 2), and the object on the right starts off at <code>x = 7.5</code> with velocity <code>-7</code> units per second, not -5. So the comment is <em>completely</em> wrong. Besides, starting the big block with anything other than \"velocity -1\" is just wasting bits and CPU cycles. Who wants to multiply anything by <code>32/10</code> when you could be multiplying it by <code>1</code>?</p>\n\n<hr>\n\n<p>Also, all of that initial setup should be encapsulated into a <code>__main__</code> block:</p>\n\n<pre><code>if __name__ == '__main__':\n n = int(input(\"Which power of 100 is the second mass? \"))\n small = Block(1, 0, 1)\n large = Block(100**n, -1, 2)\n collisionCount = 0\n\n while True:\n t = timeToNextCollision(small, large)\n if t == float(\"inf\"):\n # No more collisions\n break\n # Update the distances to what they'll be during the next collision\n small.position += small.velocity * t\n large.position += large.velocity * t\n # Update collision count AND velocities to post-collision values\n collisionCount = updateVelocities(small, large, collisionCount)\n print(collisionCount)\n</code></pre>\n\n<p>I changed your <code>timeToNextCollision()</code> to <code>timeToNextCollision(small, large)</code>, passing the blocks to it as parameters, since it needs to look at the blocks in order to know what to do.</p>\n\n<hr>\n\n<pre><code># Both blocks move towards left, but large block is faster. If the\n# distance between blocks is small enough compared to that between the wall\n# and the small block, they will collide. Otherwise the small block will\n# reach the wall before the large block has a chance to catch up\nreturn min(Fraction(-small.position, small.velocity),\n Fraction(large.position - small.position), \n (small.velocity - large.velocity))\n</code></pre>\n\n<p>I strongly recommend running your whole program through <code>pylint</code> or <code>pyflakes</code> and fixing all the style issues. Here specifically, I think it would benefit from the usual Python indentation style, which looks like this:</p>\n\n<pre><code>return min(\n Fraction(-small.position, small.velocity),\n Fraction(large.position - small.position), \n (small.velocity - large.velocity)\n)\n</code></pre>\n\n<p>This makes it very clear that you're taking the <code>min</code> of <em>three</em> things, not the usual two — and also you're constructing a <code>Fraction</code> from <em>one</em> argument, not the usual two. If this is intentional behavior, then the indentation is important because it communicates to your reader, \"Hey, I know what I'm typing, don't worry\" — and if this is <em>unintentional</em> behavior, then hey, you just found one of your bugs!</p>\n\n<hr>\n\n<p>Finally, let's fix your performance issue.</p>\n\n<p>As I said, I assume that your program takes so long because you're manipulating gigantic numerators and denominators. Above about <code>2**64</code> (or maybe <code>2**32</code>, I'm not sure), Python is going to switch from native integer representation to bignum representation, and get super slow. <a href=\"https://docs.python.org/2/library/fractions.html\" rel=\"noreferrer\">Reading the <code>fractions</code> docs</a> tells me that there's a <code>limit_denominator</code> method that's used precisely to keep the numerator and denominator small. So let's use it!</p>\n\n<pre><code>while True:\n t = timeToNextCollision(small, large)\n if t == float(\"inf\"):\n # No more collisions\n break\n # Update the distances to what they'll be during the next collision\n small.position += small.velocity * t\n large.position += large.velocity * t\n collisionCount = updateVelocities(collisionCount, small, large)\n\n # Here's the new code!\n small.position = small.position.limit_denominator(2**32)\n large.position = large.position.limit_denominator(2**32)\n small.velocity = small.velocity.limit_denominator(2**32)\n large.velocity = large.velocity.limit_denominator(2**32)\n</code></pre>\n\n<p>With just this change (and the cleanups mentioned in this review, including fixing that bug that pyflakes would have found), I see your program taking the O(10<sup>n</sup>) that we expect it to:</p>\n\n<pre><code>$ time echo '2' | python x.py\nWhich power of 100 is the second mass? 314\n\nreal 0m0.240s\nuser 0m0.196s\nsys 0m0.018s\n\n$ time echo '3' | python x.py\nWhich power of 100 is the second mass? 3141\n\nreal 0m1.721s\nuser 0m1.697s\nsys 0m0.015s\n\n$ time echo '4' | python x.py\nWhich power of 100 is the second mass? 31415\n\nreal 0m22.497s\nuser 0m20.226s\nsys 0m0.160s\n</code></pre>\n\n<p>Problem solved!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T06:43:00.970", "Id": "409746", "Score": "0", "body": "Thanks so much for the detailed feedback! Regarding the min formula with nested fractions, it's indeed technically incorrect but it runs fine and gives the correct answer, which is strange. I corrected that though. Regarding the comment, I'd actually updated the program with new values just for more testing and forgot to update the comment. Also, I want to upload this thing to Github (though it may seem like a trivial toy program to experienced programmers). Are you okay with me crediting you (because you made a big improvement to the performance)? Let me know!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T07:12:27.607", "Id": "409749", "Score": "0", "body": "@ShirishKulhari: Sure, I don't mind. Re the typo not mattering: Consider whether that branch of the code is ever even reached. (You could put an `assert False` in there to see what happens.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T07:17:32.693", "Id": "409751", "Score": "0", "body": "Okay, I'll credit you by your username in the program comment - hopefully that's the right protocol. One more thing, you restricted the numerator and denominator of the positions to 32 bits. Couldn't I do the same for the velocities as well? Or would that start causing inaccurate results? I noticed when I changed the 2^32 in your newly added lines to 2^16, it gives the result 3.14169 for n=100^5. 2**32 is totally okay, but should the same limiting be done for all the rest of fraction calculations too?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T14:44:55.557", "Id": "409799", "Score": "1", "body": "@ShirishKulhari: All user content here is licensed under [CC-BY-SA 3.0](https://creativecommons.org/licenses/by-sa/3.0/) with [attribution required](https://stackoverflow.blog/2009/06/25/attribution-required/) as mentioned in the page footer. As you can read in that second link you should mention that it is from SO, add a [link to this answer](https://codereview.stackexchange.com/a/211885/98493), mention the author by name and add a link to the [author's profile](https://codereview.stackexchange.com/users/16369/quuxplusone) if you want to use it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T15:17:08.523", "Id": "409801", "Score": "0", "body": "\"One more thing, you restricted the numerator and denominator of the positions to 32 bits. Couldn't I do the same for the velocities as well? Or would that start causing inaccurate results?\" — My code in the answer restricts both the positions (first 2 lines) and the velocities (second 2 lines). Restricting the denominator of a fraction automatically restricts the numerator (unless the absolute value of the fraction is very large, of course). And yes, what I wrote *does* cause inaccurate results, just like your version that used `float`. We're trading off accuracy for speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T17:52:59.183", "Id": "409816", "Score": "1", "body": "@Graipher: Yeah I wrote all that in the comments, providing a link to this question and his profile and all. Hopefully that's enough? https://github.com/Shirish-Kulhari/numerical-methods/blob/master/TwoBodyCollision/TwoBodyCollision.py" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T01:36:22.297", "Id": "211885", "ParentId": "211882", "Score": "11" } }, { "body": "<p>I would like to explain why my code has a better implementation of the problem. one thing to understand is that all possible collisions will be over when the right side block is moving right and the left block is also moving right with a lower velocity. this situation will continue till infinity.</p>\n\n<p>Also, we dont need the position parameter at all as we only need to check velocity change to know a collision. The case when the left block is moving towards the wall has also been considered in the last if statement where i reverse its velocity. I am new in this forum and if any changes are needed, just leave a note and will do the same.</p>\n\n<p>I am a beginner to programming and can code only in MATLAB. I found this problem interesting and hence tried solving it.</p>\n\n<pre><code>%Written by Shubham Wani, Mechanical Undergrad at NIT Trichy.\n%Set the mb(stands for Mass B) variable to powers of 100\n%COLLIDING BLOCKS COMPUTE PI\n%3BLUE1BROWN @ YOUTUBE\n%Takes about 0.043737 seconds for calculations for 100000000 kg Mass B\ntic\nclearvars;\nclear ;\nclear clc;\nma = 1;\n%set mb to various powers of 100\nmb = 10000000000; \nva(1)= double(0);\nvb(1)= double(-10);\nn=1;\nwhile (true)\n **%check if it is the last possible collision**\n if (vb(n)&gt;0 &amp;&amp; va(n)&lt;vb(n))\n break;\n end\n **%Calculate new velocities after the collision**\n va(n+1)=(ma*va(n)+mb*vb(n)+mb*(vb(n)-va(n)))/(ma+mb);\n va(n+1);\n vb(n+1)=(ma*va(n)+mb*vb(n)+ma*(va(n)-vb(n)))/(ma+mb);\n vb(n+1);\n n=n+1;\n **%if mass A is moving towards left, invert its speed.**\n if (va(n)&lt;0)\n va(n+1)=-va(n);\n vb(n+1)=vb(n);\n n=n+1;\n end\nend\n**%Number of collisions=n-1 as indexing starts from 1**\ndisp(n-1);\ntoc\n</code></pre>\n\n<p>the comments are self explanatory.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T15:10:23.340", "Id": "410623", "Score": "0", "body": "@shirish-kulhari this code is also available on my github handle shubhamwani376" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:51:33.150", "Id": "410942", "Score": "0", "body": "That's very nice! +1 for the faster code, though I think I may have seen another similar implementation in a different programming language. Either would work much faster than my code. I guess vectorizing the velocity update would also speed things up a bit - not entirely sure though.." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T15:04:02.607", "Id": "212329", "ParentId": "211882", "Score": "1" } } ]
{ "AcceptedAnswerId": "211885", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-20T23:58:50.560", "Id": "211882", "Score": "16", "Tags": [ "python", "performance", "simulation", "numerical-methods", "physics" ], "Title": "Simulating a two-body collision problem to find digits of Pi" }
211882
<p>I have implemented the <a href="http://www.rosettacode.org/wiki/Rock-paper-scissors" rel="noreferrer">Rosetta Code Rock Paper Scissors game</a> in Red, but I'm sure that there are better ways to do every thing that I did. I would appreciate any feedback on this code, which does work according to spec:</p> <blockquote> <p>Implement the classic children's game Rock-Paper-Scissors, as well as a simple predictive AI (artificial intelligence) player.</p> <p>Rock Paper Scissors is a two player game.</p> <p>Each player chooses one of rock, paper or scissors, without knowing the other player's choice.</p> <p>The winner is decided by a set of rules:</p> <ul> <li>Rock beats scissors</li> <li>Scissors beat paper</li> <li>Paper beats rock</li> </ul> <p>If both players choose the same thing, there is no winner for that round.</p> <p>For this task, the computer will be one of the players.</p> <p>The operator will select Rock, Paper or Scissors and the computer will keep a record of the choice frequency, and use that information to make a weighted random choice in an attempt to defeat its opponent.</p> </blockquote> <pre><code>Red [ Problem: %http://www.rosettacode.org/wiki/Rock-paper-scissors Code: %https://github.com/metaperl/red-rosetta/blob/master/rock-paper-scissors.red ] help1: %https://stackoverflow.com/questions/54272942/how-to-find-the-first-element-of-a-block-of-strings-whose-first-character-matche help2: %https://stackoverflow.com/questions/54272956/how-to-increment-element-of-block-after-found-element help3: %https://stackoverflow.com/questions/54273057/two-dimensional-dispatch-table-with-templated-response help4: %https://stackoverflow.com/questions/54273161/in-red-how-do-i-search-through-a-block-for-a-string-matching-a-pattern/54275072#54275072 games-played: 0 weapons: ["rock" "scissors" "paper"] matching-weapon: func [abbrev][ foreach weapon weapons [ if (first weapon) = first abbrev [ return weapon ] ] ] player-choices: ["rock" 0 "scissors" 0 "paper" 0 ] player-choice-tally: func [choice][player-choices/(choice): player-choices/(choice) + 1] player-choice: "x" valid-choice: func [c][find "rpsq" c] player-wins: [ ["rock" "scissors"] "breaks" ["paper" "rock"] "covers" ["scissors" "paper"] "cut" ] player-wins?: function [player1 player2] [ game: reduce [player1 player2] winning: player-wins/(game) ] report-win: func [player1 player2][rejoin [player1 " " (player-wins? player1 player2) " " player2]] draw: func [player computer][player = computer] update-stats: func [player-choice][ player-choice-tally player-choice games-played: games-played + 1 ] make-computer-choice: func [][ either games-played &gt;= 3 [ tmp: random games-played tally: select "rock" player-choices either tmp &lt;= tally [return "rock"][ tally: tally + select "scissors" player-choices either tmp &lt;= tally [return "scissors"][ return "paper" ] ] ][random/only weapons] ] while [not player-choice = "q"][ player-choice: ask "(r)ock, (s)cissors, (p)aper or (q)uit? " either (player-choice = "q") [][ if (valid-choice player-choice) [ computer-choice: random/only weapons player-choice: matching-weapon player-choice update-stats player-choice print rejoin ["Player choice: " player-choice "tally" player-choices "Computer choice:" computer-choice] either draw player-choice computer-choice [print "Draw"][ tmp: player-wins? player-choice computer-choice print either tmp [rejoin ["Player wins: " report-win player-choice computer-choice]] [rejoin ["Computer wins: " report-win computer-choice player-choice]] ] ] ] ] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T12:49:37.357", "Id": "409783", "Score": "3", "body": "This looks like a really interesting language. Welcome to Code Review and well done on your first question. Should anything be unclear about how we handle questions (Code Review works a bit differently from Stack Overflow), most of it is explained [here](https://codereview.meta.stackexchange.com/q/2436/52915). Feel free to ask if anything is unclear." } ]
[ { "body": "<p>Looks an interesting first project! Some thoughts:</p>\n\n<ul>\n<li><p>The URL! type does not need a <code>%</code> prefix (they would be interpreted as FILE! and would behave incorrectly were you to operate upon them).</p></li>\n<li><p>In Red, you can use the WORD! type in place of strings. You can use a LIT-WORD! to get a word without evaluating it. Takes a little getting used to, but is more efficient and expressive:</p>\n\n<pre><code>weapons: [rock paper scissors]\nplayer-choices: [rock 0 scissors 0 paper 0]\n\nplayer-wins: [\n [rock scissors] \"breaks\"\n [paper rock] \"covers\"\n [scissors paper] \"cut\"\n]\n\nselect player-choices 'rock\n</code></pre></li>\n<li><p>Instead of VALID-CHOICE, you could use SWITCH to drive things:</p>\n\n<pre><code>until [\n switch player-choice: ask \"(r)ock, (s)cissors, (p)aper or (q)uit? \" [\n \"q\" [true]\n \"r\" \"s\" \"p\" [\n play-round player-choice\n false\n ]\n ]\n]\n</code></pre></li>\n<li><p>You can use CASE in place of nested EITHER statements—breaks the choices out a bit:</p>\n\n<pre><code>make-computer-choice: func [\n /local tmp tally\n][\n case [\n games-played &lt; 3 [\n random/only weapons\n ]\n\n (\n tmp: random games-played\n tmp &lt;= tally: select player-choices 'rock\n ) [\n 'rock\n ]\n\n tmp &lt;= tally: tally + select player-choices 'scissors [\n 'scissors\n ]\n\n true [ ; or else\n 'paper\n ]\n ]\n]\n</code></pre></li>\n<li><p>If you want to somewhat keep the game logic separate from the interface, I'd recommend a <code>play-round</code> function called in the same fashion as above. <code>play-round</code> could return <code>false</code> (continues) or <code>true</code> (ends loop when someone wins a certain amount of games).</p></li>\n<li><p>I notice you define the function <code>make-computer-choice</code> but don't invoke it.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T05:23:02.337", "Id": "211969", "ParentId": "211884", "Score": "4" } }, { "body": "<p>Your code seemingly follows <a href=\"https://doc.red-lang.org/en/style-guide.html\" rel=\"nofollow noreferrer\">official style guide</a>, so that's a plus. \nNot all of it is properly formatted though.</p>\n\n<p>In terms of implementation: textual interface is tightly coupled with game logic, which makes refactoring and code support particularly hard. I would suggest to keep all functionally related modules separately and consider usage of <a href=\"https://doc.red-lang.org/en/reactivity.html\" rel=\"nofollow noreferrer\">reactive programming</a> - all of it will make your code more general and declarative.</p>\n\n<hr>\n\n<p>Now, the main points:</p>\n\n<ol>\n<li>Red has a literal <code>url!</code> datatype, but for some reason you are using <code>file!</code>... and it certainly doesn't mean exactly what you want it to:</li>\n</ol>\n\n<pre><code>&gt;&gt; [%http://www.rosettacode.org/wiki/Rock-paper-scissors]\n== [%http :/ /www.rosettacode.org /wiki /Rock-paper-scissors]\n</code></pre>\n\n<p>That's one <code>file!</code>, one <code>get-word!</code> and 3 <code>refinement!</code>s. Instead you can just write:</p>\n\n<pre><code>&gt;&gt; type? http://www.rosettacode.org/wiki/Rock-paper-scissors\n== url!\n</code></pre>\n\n<ol start=\"2\">\n<li><p>Using <code>help*</code> words as indices is a code smell. Even if you really need to keep these URLs as values, you should put them in a block and index them by their positions. However, I would suggest to omit cluttering source code with various cross-references. It belongs either to readme file or script header.</p></li>\n<li><p><code>player-choice: \"x\"</code> - another code smell. Red has a <code>none</code> value, typically used to represent the \"absence\" of something. You should use that instead of an arbitrarily selected string.</p></li>\n<li><p>Redefeniton of pre-defined words. Your <code>draw: ...</code> overwrites <a href=\"https://doc.red-lang.org/en/draw.html\" rel=\"nofollow noreferrer\">Draw dialect</a> function. To avoid that, either pick a different name or use contexts for encapsulation. <code>draw</code> definition itself is just an alias for <code>equal?</code> - there's no need to reinvent the wheel.</p></li>\n<li><p>Zero argument function <code>func [][...]</code> has an idiomatic <code>does [...]</code> form.</p></li>\n<li><p><code>either condition [][...]</code> -> <code>unless condition [...]</code>.</p></li>\n<li><p>Redundant usages of <code>rejoin</code>. <code>print</code> already <code>reduce</code>s its argument and preserves spaces between elements.</p></li>\n<li><p>Redundant usages of parenthesis. It is preferred to omit them entirely.</p></li>\n<li><p><code>not x = y</code> -> <code>x &lt;&gt; y</code>.</p></li>\n<li><p><a href=\"https://doc.red-lang.org/en/style-guide.html#_naming_conventions\" rel=\"nofollow noreferrer\">Naming could be better</a>. As a rule of thumb, try to pick 5-8 letter words, and avoid verbosity. Function that return boolean values should be posfixed with <code>?</code> mark. </p></li>\n<li><p>You say that your code works according to a spec. However, implementation of weighted random choice contains two related bugs: in particular, <code>tally: select \"rock\" player-choices</code> and <code>select \"scissors\" player-choices</code> - this expressions always return <code>none</code>, because you mixed up the order of arguments. Because of that, only <code>random/only</code> branch is picked at any time. Moreso, <code>make-computer-choice</code> itself is never used in the main loop.</p></li>\n<li><p>Poor input checks - you consider only the first input character, but don't impose any restrictions on input length. What happens if I input, say, <code>\"rp\"</code>? Your implementation interprets it as \"rock\", whereas to me it looks like a typo.</p></li>\n<li><p>Refactor deeply nested conditionals using <code>case</code> and <code>switch</code>. Consider usage of dispatch tables.</p></li>\n</ol>\n\n<p>With that said, take more time to <a href=\"https://github.com/red/red/wiki/[LINKS]-Learning-resources\" rel=\"nofollow noreferrer\">learn the language</a>, as your code clearly indicates the lack of knowledge about available datatypes and functions, common idioms and leverage points.</p>\n\n<p>You certainly wrote it having a typical scripting language in mind, without paying homage to Red's key strengths (dialects, data-orientation and homoiconicity) - and that's not a bad thing per se by any means. However, if you deem your code worthy of showcasing on Rosettacode, then you should spend some time on triaging all the bugs and making it idiomatic - as of now, it doesn't strike me as anything special.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T06:15:33.557", "Id": "211972", "ParentId": "211884", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T01:12:01.713", "Id": "211884", "Score": "6", "Tags": [ "rock-paper-scissors", "red-lang" ], "Title": "Red implementation of Rock, Scissors, Paper" }
211884
<p>I want to get two distinct sets of schema from a database without having to create multiple <code>Connection</code>/<code>PreparedStatement</code>/<code>ResultSet</code> objects.</p> <p>Currently, I have a helper method that queries the database, gets each individual schema, and then returns them together in one <code>ArrayList</code> - please refer to the code below.</p> <pre><code>private ArrayList&lt;ArrayList&lt;?&gt;&gt; getAttributesAndGroups() { ArrayList&lt;ArrayList&lt;?&gt;&gt; retList = new ArrayList&lt;ArrayList&lt;?&gt;&gt;(); Connection conn = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(jdbcUrl, userId, password); ArrayList&lt;Attribute&gt; listAttrs = new ArrayList&lt;Attribute&gt;(); String query = "select aid, aname from tbl_attributes order by aid"; PreparedStatement ps = conn.prepareStatement(query); ResultSet rs = ps.executeQuery(); while (rs.next()) { int aid = rs.getInt(1); String aname = rs.getString(2); Attribute attr = new Attribute(aid, aname); listAttrs.add(attr); } retList.add(listAttrs); ArrayList&lt;Group&gt; listGroups = new ArrayList&lt;Group&gt;(); query = "select gid, gname from tbl_groups order by gid"; ps = conn.prepareStatement(query); rs = ps.executeQuery(); while (rs.next()) { int gid = rs.getInt(1); String gname = rs.getString(2); Group grp = new Group(gid, gname); listGroups.add(grp); } retList.add(listGroups); rs.close(); ps.close(); } catch (Exception e) { log.error("Exception", e); } finally { if (conn != null) { try { conn.close(); } catch (Exception e) { // } } } return retList; } </code></pre> <p>Where I call my helper method, I do the following:</p> <pre><code> ArrayList&lt;ArrayList&lt;?&gt;&gt; lists = getAttributesAndGroups(); ArrayList&lt;Attribute&gt; listAttrs = (ArrayList&lt;Attribute&gt;) lists.get(ATTRIBUTES); request.setAttribute("listAttrs", listAttrs); ArrayList&lt;Group&gt; listGroups = (ArrayList&lt;Group&gt;) lists.get(GROUPS); request.setAttribute("listGroups", listGroups); request.getRequestDispatcher("addUser.jsp").forward(request, response); </code></pre> <p>(<code>ATTRIBUTES</code> and <code>GROUPS</code> are simple integer constants representing 0 and 1 respectively.)</p> <p>However, my code is giving me warnings of <code>Type safety: Unchecked cast from ArrayList&lt;capture#1-of ?&gt; to ArrayList&lt;Attribute&gt;</code> (ditto for the other line).</p> <p>Is there a better approach for what I want to do?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T08:09:10.583", "Id": "409755", "Score": "0", "body": "For future reference, if you had provided more context (specifically the class definition for `Request`), I could have written out another alternative solution." } ]
[ { "body": "<h3>Generics</h3>\n\n<p>When you say, <code>ArrayList&lt;ArrayList&lt;?&gt;&gt;</code>, you are saying that there is a type but that you don't know what it is. So you write it as a <code>?</code>. </p>\n\n<p>But in your code, you are putting <code>ArrayList&lt;Attribute&gt;</code> and <code>ArrayList&lt;Group&gt;</code> into the larger list. These are not one type. So it has to find a type that covers both <code>Attribute</code> and <code>Group</code>. Absent both extending or implementing some common class or interface, that will be <code>Object</code>. So <code>?</code> is actually <code>Object</code> in your code. </p>\n\n<p>It is natural to think that <code>?</code> is a wildcard that can match multiple things simultaneously. But it is not. It represents exactly one type at a time. You just avoid having to say which type. As such, I don't think that it is what you want to use here. </p>\n\n<h3>Cast by element not collection</h3>\n\n<p>The general way to fix this warning on something like </p>\n\n<blockquote>\n<pre><code> ArrayList&lt;Attribute&gt; listAttrs = (ArrayList&lt;Attribute&gt;) lists.get(ATTRIBUTES);\n</code></pre>\n</blockquote>\n\n<p>would be something like </p>\n\n<pre><code> List&lt;Attribute&gt; listAttrs = new ArrayList&lt;&gt;();\n for (Object attr : lists.get(ATTRIBUTES)) {\n if (attr instanceof Attribute) {\n listAttrs.add((Attribute) attr);\n }\n }\n</code></pre>\n\n<p>You can often leave off the <code>instanceof</code> check because you know what the result should be. </p>\n\n<p>I changed from the implementation (<code>ArrayList</code>) to the interface (<code>List</code>), as is customary in Java when you aren't using implementation specific methods unavailable to the interface. </p>\n\n<p>But I wouldn't recommend that code for this specific problem. You don't really need to cast here. You control the code at both ends and in between. Just write it without casts. </p>\n\n<h3>Custom return type</h3>\n\n<p>The most direct way to fix this specific problem is to replace your return value with a custom class. </p>\n\n<pre><code>class AttributesAndGroups {\n\n private List&lt;Attribute&gt; attributes;\n\n private List&lt;Group&gt; groups;\n\n public void setAttributes(List&lt;Attribute&gt; attributes) {\n this.attributes = attributes;\n }\n\n public List&lt;Attribute&gt; getAttributes() {\n return attributes;\n }\n\n public void setGroups(List&lt;Group&gt; groups) {\n this.groups = groups;\n }\n\n public List&lt;Group&gt; getGroups() {\n return groups;\n }\n\n}\n</code></pre>\n\n<p>You can use this like </p>\n\n<pre><code> AttributesAndGroups result = new AttributesAndGroups();\n result.setAttributes(listAttrs);\n result.setGroups(listGroups);\n return result;\n</code></pre>\n\n<p>and in the caller </p>\n\n<pre><code> AttributesAndGroups lists = getAttributesAndGroups();\n List&lt;Attribute&gt; listAttrs = lists.getAttributes();\n List&lt;Group&gt; listGroups = lists.getGroups();\n</code></pre>\n\n<p>No casts (unchecked or otherwise). </p>\n\n<p>There's a lot of boilerplate code in the class. It's possible to avoid that here. </p>\n\n<h3>Pass to the method</h3>\n\n<p>Another alternative would be to pass the lists into the helper method rather than have the method initialize them. </p>\n\n<pre><code> List&lt;Attribute&gt; listAttrs = new ArrayList&lt;&gt;();\n List&lt;Group&gt; listGroups = new ArrayList&lt;&gt;();\n fillAttributesAndGroups(listAttrs, listGroups);\n request.setAttribute(\"listAttrs\", listAttrs);\n request.setAttribute(\"listGroups\", listGroups);\n</code></pre>\n\n<p>I changed the name to be more representative of the revised implementation. </p>\n\n<p>And then the method signature would be </p>\n\n<pre><code>private void fillAttributesAndGroups(List&lt;Attribute&gt; listAttrs, List&lt;Group&gt; listGroups) {\n</code></pre>\n\n<p>Now just delete </p>\n\n<blockquote>\n<pre><code> ArrayList&lt;ArrayList&lt;?&gt;&gt; retList = new ArrayList&lt;ArrayList&lt;?&gt;&gt;();\n ArrayList&lt;Attribute&gt; listAttrs = new ArrayList&lt;Attribute&gt;();\n retList.add(listAttrs);\n ArrayList&lt;Group&gt; listGroups = new ArrayList&lt;Group&gt;();\n retList.add(listGroups);\n return retList;\n</code></pre>\n</blockquote>\n\n<p>And the remainder of your code should function normally. </p>\n\n<p>Again, no casts needed. And this code is much terser, particularly if this is the only time you call it. </p>\n\n<p>Another alternative would be to pass <code>request</code> into the method, but I won't try to implement that here. That would allow you to make the lists inside the method again. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T06:00:47.947", "Id": "409994", "Score": "1", "body": "In the end I reorganized my code, so that instead of having one helper method do all the work, I call two methods in two separate DAO objects. Thanks for the concise answer though, great reference." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T08:06:35.413", "Id": "211893", "ParentId": "211890", "Score": "0" } } ]
{ "AcceptedAnswerId": "211893", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T04:02:54.717", "Id": "211890", "Score": "1", "Tags": [ "java" ], "Title": "Getting multiple table schema and returning them, using one helper method" }
211890
<p>Now, there is a company list in which an element is an employee list in every company. I calculate the salary of employees in every company with a RESTful API one by one,. This is very slow, so I join 1000 elements to one list and post it to the service.</p> <pre><code>import requests def _calculate_employee_salaries(employees): response = requests.post(url, json={"input": employees}) salaries = parse_response(response) return salaries def get_calculate_employee_salaries(company_employees_lis): begin, step = 0, 1000 company_employee_salaries_lis = [] while begin &lt; len(company_employees_lis): employees = [] employee_num_lis = [] for comp_employees in company_employees_lis[begin:(begin+step)]: employees.extend(comp_employees) employee_num_lis.append(len(comp_employees)) salaries = _calculate_employee_salaries(employees) idx = 0 for num in employee_num_lis: company_employee_salaries_lis.append(salaries[idx:(idx + num)]) idx += num begin += step return company_employee_salaries_lis if __name__ == "__main__": company_employees_lis = [["employees_id_1", "employees_id_2", "employees_id_3"], ["employees_id_4"], ["employees_id_5", "employees_id_6"]] company_employee_salaries_lis = get_calculate_employee_salaries(company_employees_lis) </code></pre> <p>I think my code is bad, because I use a variable <code>employee_num_lis</code> to remember the number of employees in every company. And there must be clean, artful and pythonic code. This code is just a sample, not what I should do.</p>
[]
[ { "body": "<p>Yes, you can simplify this. Let's break down the algorithm needed for this:</p>\n\n<ol>\n<li>Chain all employees into one stream</li>\n<li>Chunk this stream into 1000 employees\n\n<ul>\n<li>For each chunk get the salaries</li>\n</ul></li>\n<li>Distribute the salaries back again into the different companies</li>\n</ol>\n\n<p>The first part can be done using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.chain.from_iterable\" rel=\"nofollow noreferrer\"><code>itertools.chain.from_iterable</code></a>. The second one can use e.g. <a href=\"https://stackoverflow.com/a/12186183/4042267\">this <code>grouper</code> recipe</a>. And the final part can be easily done with <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a> if we keep everything before as generators.</p>\n\n<pre><code>from itertools import chain, islice\n</code></pre>\n\n<blockquote>\n<pre><code>def grouper(iterable, n):\n it = iter(iterable)\n return iter(lambda: tuple(islice(it, n)), ())\n</code></pre>\n</blockquote>\n\n<pre><code>def get_salaries(employees):\n respone = requests.post(url, json={\"input\": employees})\n return parse_respone(respone)\n\ndef employee_salaries_per_company(company_employees):\n all_employees = chain.from_iterable(company_employees) \n salaries = chain.from_iterable(get_salaries(employees)\n for employees in grouper(all_employees, 1000))\n return [list(islice(salaries, n)) for n in map(len, company_employees)]\n</code></pre>\n\n<hr>\n\n<p>Note that in english the plural of employee is employees and not emploices; and the plural of salary is salaries and not salarices.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:15:17.540", "Id": "211900", "ParentId": "211891", "Score": "3" } } ]
{ "AcceptedAnswerId": "211900", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T04:43:56.833", "Id": "211891", "Score": "1", "Tags": [ "python", "multithreading", "asynchronous" ], "Title": "Processing a company list in which every element is an employee list" }
211891
<p>I have to do a Bruteforce script, so mine is working, but is also very very low. My teacher gave me a small Shadow file and from the shadow file I have to find the original password (MD5 used here). I know that my code is working but I'm looking for tips and tricks to improve it.</p> <pre><code>import hashlib import itertools #possible characters in user password Alphabet = ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.;#@") #minimum password value CharLength = 6 #getting passwords and username from shadow file with open("shadow_test", "r") as ins: array = [] users = [] passwd = [] #getting everyline from shadow file into an array for line in ins: array.append(line) #saving only username and passwords for pw in array: str(pw) r= pw.split(":") users.append(r[0]) passwd.append(r[1]) # print(users) # print(passwd) list = [] #removing passowrd with * or ! for mdp in passwd: if mdp != '*' and mdp != '!': str(mdp) list.append(mdp) # trying to Bruteforce for _ in range(12): passwords = (''.join(word) for word in itertools.product(Alphabet, repeat=CharLength)) #print(*passwords) for pswd in passwords: hash_object = hashlib.md5(str.encode(pswd)).hexdigest() # hash_object.update(*passwords.encode('utf-8')) generatedpassword = '$1$' + hash_object # print(generatedpassword) for compare in list: for user in users: #print('on cherche le Mot de passe : ' + compare +' pour ' +user) #print('mot de passe MD5 généré : ' +generatedpassword) #print('mot de passe clair généré : ' +pswd) if generatedpassword == compare: print('Le Mot de passe pour' + user + ' est : ' + pswd) </code></pre>
[]
[ { "body": "<ol>\n<li>Use capital letters with underscores for constants <a href=\"https://pep8.org/#constants\" rel=\"nofollow noreferrer\">https://pep8.org/#constants</a>\nThere is no need to wrap alphabet string into parentheses:</li>\n</ol>\n\n<pre><code>ALPHABET = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.;#@\"\nLENGTH = 6\n</code></pre>\n\n<ol start=\"2\">\n<li><p>Expression <code>str(pw)</code> does nothing so you can remove it. You probably meant <code>pw = str(pw)</code> but it is redundant since <code>pw</code> already is <code>str</code></p></li>\n<li><p>You do not need <code>array</code> variable at all, just iterate over input file line by line. Also, unpacking is more readable:</p></li>\n</ol>\n\n<pre><code> for line in ins:\n user, password, *rest = line.split(\":\")\n users.append(user)\n passwd.append(password)\n</code></pre>\n\n<ol start=\"4\">\n<li><p>Since you ignore passwords <code>\"*\"</code> and <code>\"!\"</code> it is better to filter them out when reading from file.</p></li>\n<li><p>Since <code>ins</code> is not used after generating <code>users</code> and <code>passwd</code> lists you do not need to place rest of code inside <code>with</code> block. Actually, the first block may look like:</p></li>\n</ol>\n\n<pre><code>#getting passwords and username from shadow file\nwith open(\"shadow_test\", \"r\") as ins:\n users = [] \n passwd = []\n for line in ins:\n user, password, *rest = line.split(\":\")\n if password not in ('*', '!'):\n users.append(user)\n passwd.append(password)\n</code></pre>\n\n<ol start=\"6\">\n<li><p>Why do you need <code>for _ in range(12)</code> loop? Just to make the program 12 times slower? Remove it.</p></li>\n<li><p>Do not use names of built-in funciton names for variables, like <code>list</code>. BTW, why do you need it at all? Just iterate over all possible words and look for their hash in <code>passwd</code>:</p></li>\n</ol>\n\n<pre><code>passwords = (''.join(word) for word in itertools.product(ALPHABET, repeat=LENGTH))\nfor pswd in passwords:\n # calculate hash of pswd and if it is equal to one in passwd print it\n</code></pre>\n\n<ol start=\"8\">\n<li>When you compare generated hash with elements of passwd you do not need to iterate over all usernames and print them all! Actually it is better to make \"password hash\" -> \"username\" dictionary so you can check if <code>generatedpassword</code> is one of given password hashes faster (because checking that <code>dict</code> has a key generally is faster than checking each element of array):</li>\n</ol>\n\n<pre><code>with open(\"shadow_test\", \"r\") as ins:\n data = dict()\n for line in ins:\n username, password, *rest = line.split(\":\")\n if password not in ('*', '!'):\n data[password] = username\n\npassword_hash = md5hash(\"qwerty\") # assume it is a function for calculating md5\nif passwod_hash in data:\n print(\"qwerty is password of\", data[password_hash])\n</code></pre>\n\n<ol start=\"9\">\n<li>It is probably better to remove <code>\"$1$\"</code> from stored records rather than add it to each calculated hash:</li>\n</ol>\n\n<pre><code>if password not in ('*', '!'):\n assert password.startswith(\"$1$\"), \"Expect password records to begin with $1$\"\n data[password[3:]] = username # remove $1$ \n</code></pre>\n\n<p>So the whole solution may look like:</p>\n\n<pre><code>import hashlib\nimport itertools\n\n\ndef md5hash(char_sequence):\n string = ''.join(char_sequence)\n hash_object = hashlib.md5(string.encode())\n return hash_object.hexdigest()\n\n\n# possible characters in user password\nALPHABET = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-_.;#@\"\n# password length\nLENGTH = 6\n\n# getting passwords and username from shadow file\nwith open(\"shadow_test\", \"r\") as ins:\n data = dict() # hash -&gt; username mapping from shadow file\n for line in ins:\n username, password, *rest = line.split(\":\")\n if password not in ('*', '!'):\n data[password[3:]] = username # remove $1$\n\n# bruteforce\nfor word in itertools.product(ALPHABET, repeat=LENGTH):\n generated_hash = md5hash(word)\n if generated_hash in data:\n print('The password of user', data[generated_hash], 'is:', word)\n```\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T19:52:45.980", "Id": "211932", "ParentId": "211897", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T08:57:04.917", "Id": "211897", "Score": "0", "Tags": [ "python", "python-3.x" ], "Title": "Python BruteForce Script" }
211897
<p>I would like to know if there is any pre-existing implementation of my solution so I don't have to reinvent the wheel.</p> <p>What I'm trying to create is an utility which allows me to create critical section around given object. Can you check my code if there are any errors in my implementation?</p> <pre><code>import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.locks.ReentrantLock; public class MultiCriticalSection { private final ConcurrentHashMap&lt;Object, ExtendReentrantLock&gt; locks = new ConcurrentHashMap&lt;&gt;(); private final Object globalLock = new Object(); /** * Run critical section guarded by given object. It is potentionally blocking code! */ public &lt;T&gt; T doWithLock(final Object key, Callable&lt;T&gt; fce) throws Exception { ExtendReentrantLock lock = getLock(key); try { return fce.call(); } finally { freeLock(key, lock); } } /** * Run critical section guarded by given object. It is potentionally blocking code! */ public void doWithLock(final Object key, Runnable fce) { ExtendReentrantLock lock = getLock(key); try { fce.run(); } finally { freeLock(key, lock); } } /** * Release the lock. If there are no threads waiting and the lock is marked for removal it will be removed. */ private void freeLock(final Object key, final ExtendReentrantLock lock) { synchronized (globalLock) { if (!lock.hasQueuedThreads() &amp;&amp; lock.remove) { locks.remove(key); } lock.remove = true; lock.unlock(); } } /** * Acquire lock. If there are no locks for given object it is created. * If there is a lock for given object and it is locked the removal flag is cleared. This way the currently running thread will not * remove the lock from memory. */ private ExtendReentrantLock getLock(final Object key) { ExtendReentrantLock lock; synchronized (globalLock) { lock = locks.computeIfAbsent(key, o -&gt; new ExtendReentrantLock()); if (lock.isLocked()) { lock.remove = false; } } lock.lock(); return lock; } /** * Utility class adding a flag to ReentrantLock. */ private class ExtendReentrantLock extends ReentrantLock { boolean remove = true; } } </code></pre> <p>The goal is not to allow 2 concurrent threads to operate on the same data. That is, only one object can operate on given object at same time. The other thread will be blocked, until the working thread is finished. The locks are automatically cleared when there are no threads running.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:12:29.117", "Id": "410256", "Score": "0", "body": "Multithreading is always tricky. My gut feeling is that the globalLock might be a local copy on each thread and doesn't really have to prevent both threads to wait for each other. Why not use the applicable concurrent lock/semaphore/... specific to each case where you need mutual exclusion? Hiding thread safety in a new class doesn't really make the issue go away, it only becomes harder to reason about why it doesn't work in certain specific situations that are inherently hard to reproduce." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T09:17:08.427", "Id": "211901", "Score": "1", "Tags": [ "java", "concurrency", "locking" ], "Title": "Critical section around given key" }
211901
<p>I'm looking to create a wrapper for an API, mainly for learning purposes at work as "The IT guy". I've been trying to follow the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow noreferrer">PEP 8 styling guide</a> and make my docstring as detailed as possible.</p> <p>I believe my code looks quite sluggish. I've tried to avoid duplicate code and multiple line sets of logic.</p> <p>Here's my class initialization:</p> <pre><code>class API: def __init__(self, environment, client_code, api_key): """ __init__() Instantiate an instance of API. Parameters: environment(string): The runtime environment. Acceptable arguements [sandbox] [live] client_code(string): Your client code, found the settings page of your account api_key(string): The API key found in the settings page of your account """ self.base_url = 'https://%s.apiprovider.co.uk/api/v3/client/%s/' %\ (environment, client_code) self.header = { 'Accept': 'json', 'apiKey': api_key, 'Content-Type': 'json', 'Content-Length': '0' } # Pythonic names | API names self.customer_arguments = { 'customer_ref': 'customerRef', 'email': 'email', 'title': 'title', 'first_name': 'firstName', 'surname': 'surname', 'post_code': 'postCode', 'line1': 'line1', 'line2': 'line2', 'account_number': 'accountNumber', 'sort_code': 'bankSortCode', 'account_name': 'accountHolderName', 'date_of_birth': 'dateOfBirth', 'company_name': 'companyName', 'home_phone': 'homePhone', 'work_phone': 'workPhone', 'mobile_phone': 'mobilePhone', 'line3': 'line3', 'line4': 'line4', 'initials': 'initials' } self.session = requests.Session() </code></pre> <p>And an example class definition:</p> <pre><code>def create_customer(self, customer_ref, email, first_name, surname, post_code, line1, account_number, sort_code, account_name, **keyword_arguments): """ create_customer() Create a new customer in API. parameters: customer_ref(string): A unique reference number for the customer set by the client. email(string): A contact email address for the new customer first_name(string): The first name of the new customer surname(string): The surname of the new customer post_code(string): The postal code of the new customer line1(string): The first line of the customers postal address line2(string): The second line of the customers postal address account_number(string): The payment bank account number for the new customer sort_code(string): The payment sort code for the new customer account_name(string): The customers name as it appears on the bank account **parameters date_of_birth(datetime): The customers date of birth company_name(string): The company the customer represents home_phone(string): The customers home telephone number mobile_phone(string): The customers mobile telephone number work_phone(string): The customers work telephone number line3(string): The third line of the customers postal address line4(string): The fourth line of the customers postal address initials(string): The customers initials usage: It is possible to create a new customer using only the required parameters. It is also possible to use any number of the non-required parameters when creating a customer. Creating a customer using only the required parameters works like so create_customer('NEW-001', 'first@test.account', 'Mr', 'First', 'Test', 'GL514AA', 'Test road', '14785236', '698741', 'Mr First Test') Creating a customer using the optional parameters works like so create_customer('NEW-002', 'second@test.account', 'Mrs', 'Second', 'Test', 'GL514AA', 'Test road', '36985214', '784512', 'Mrs Second Test', company_name='Test company', date_of_birth='1990-01-01') """ arguments = self.customer_arguments parameters = {'customerRef': customer_ref, 'email': email, 'fistName': first_name, 'surname': surname, 'postCode': post_code, 'line1': line1, 'accountNumber': account_number, 'bankSortCode': sort_code, 'accountHolderName': account_name} existing_cref_error = 'There is an existing Customer with the same ' \ 'Client and Customer ref in the database ' \ 'already.' object_not_set_error = 'Object reference not set to an instance of ' \ 'an object.' invalid_email_address_error = 'The provided Email is not a valid ' \ 'Email address.' post_code_empty = 'Post code cannot be empty.' invalid_post_code = 'Invalid Postcode. The postcode must have 5, ' \ '6 or 7 characters only' account_number_invalid = 'AccountNumber can only be 8 characters ' \ 'long and only numbers.' sort_code_invalid = 'BankSortCode can only be 6 characters long ' \ 'and only numbers' sort_code_empty = 'Secure bank sort code cannot be empty.' line_1_empty = 'Address Line 1 cannot be empty' try: for key, value in keyword_arguments.items(): if key in arguments: parameters.update({arguments[key]: value}) else: raise InvalidSearchTerm header = self.header request_url = self.base_url + 'customer' request = self.session.post(request_url, headers=header, params=parameters) print(request.content) try: if request.json()['Detail'] == existing_cref_error: raise ExistingCustomer elif request.json()['Detail'] == object_not_set_error: raise MissingParameter elif request.json()['Detail'] == invalid_email_address_error: raise InvalidParameter elif request.json()['Detail'] == post_code_empty: raise InvalidParameter elif request.json()['Detail'] == invalid_post_code: raise InvalidParameter elif request.json()['Detail'] == account_number_invalid: raise InvalidParameter elif request.json()['Detail'] == sort_code_invalid: raise InvalidParameter elif request.json()['Detail'] == line_1_empty: raise InvalidParameter elif request.json()['Detail'] == sort_code_empty: raise InvalidParameter else: pass # Detail will not be present if an error is not generated. except TypeError: pass except KeyError: pass except InvalidSearchTerm: print(key + ' is not a valid argument. Make sure to check the ' 'spelling. You can also refer to the docstring by ' 'calling help(create_customer) for more assistance.') except MissingParameter: print('It looks like one or more of the required parameters is ' 'not present. Please double check this, and if needed, ' 'refer to the documentation.') except ExistingCustomer: print('The reference (' + customer_ref + ') is not unique.Please ' 'double check the reference. You are also able to ' 'cross-reference this by using query_customers()') except InvalidParameter: print('At least one of the parameters you have entered are ' 'invalid. Error details: ' + request.json()['Detail']) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T12:57:38.407", "Id": "409784", "Score": "1", "body": "Most of it looks good, some oddities here and there. What is your problem description? As in, it's an API wrapper of sorts, but why is it required and are there any particular requirements for it that your code happens to cover adequately that make it easier to use than the original non-wrapped version?" } ]
[ { "body": "<p>Some Python notes, else i have some difficulty wrapping my head around how the API is used.</p>\n\n<h2>String Formatting</h2>\n\n<p>Sometimes, string formatting simplifies things.</p>\n\n<p>this</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.base_url = 'https://%s.apiprovider.co.uk/api/v3/client/%s/' %\\\n (environment, client_code)\n</code></pre>\n\n<p>can be made more readable:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>self.base_url = 'https://{}.apiprovider.co.uk/api/v3/client/{}/'.format(\n environment, client_code)\n</code></pre>\n\n<p>this too can be formatted:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print('The reference (' + customer_ref + ') is not unique.Please '\n 'double check the reference. You are also able to '\n 'cross-reference this by using query_customers()')\n</code></pre>\n\n<p>so that you don't have to worry about ++ each time</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print('The reference ({}) is not unique.Please '\n 'double check the reference. You are also able to '\n 'cross-reference this by using query_customers()'.format(customer_ref))\n</code></pre>\n\n<p>and in py3.6+</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>print(f'The reference ({customer_ref}) is not unique.Please '\n 'double check the reference. You are also able to '\n 'cross-reference this by using query_customers()')\n</code></pre>\n\n<h2>Adding Strings Together</h2>\n\n<p>For concatenating strings, adding <code>()</code> simplifies lots of <code>\\</code>s</p>\n\n<p>From this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>existing_cref_error = 'There is an existing Customer with the same ' \\\n 'Client and Customer ref in the database ' \\\n 'already.'\n</code></pre>\n\n<p>to this:</p>\n\n<pre class=\"lang-py prettyprint-override\"><code>existing_cref_error = ('There is an existing Customer with the same '\n 'Client and Customer ref in the database '\n 'already.')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-14T14:32:56.190", "Id": "439270", "Score": "1", "body": "Thanks for taking the time to answer this after it went unseen for months. I've already began implementing a lot of what you've suggested, though it's definitely great advice to avoid code smells." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-14T05:10:35.263", "Id": "226087", "ParentId": "211907", "Score": "2" } } ]
{ "AcceptedAnswerId": "226087", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T10:32:02.727", "Id": "211907", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Creating an object using an API call" }
211907
<p>Red is a paradigm-neutral <a href="http://en.wikipedia.org/wiki/Homoiconicity" rel="nofollow noreferrer">homoiconic</a> language.</p> <p>Red has a low memory footprint, and has a <a href="http://www.red-lang.org/p/download.html" rel="nofollow noreferrer">low disk footprint (&lt; 1MB)</a>. Red seeks to be a "full-stack" language whose methodology is independent of any other toolchain. It's goal is to compile that which can be known ahead of time, JIT-compile that which cannot, and embeds a small interpreter into its executables to handle constructions which are not amenable to any compilation.</p> <p>As an intermediate language (IL) Red uses a C-like language called <a href="/questions/tagged/red-system" class="post-tag" title="show questions tagged &#39;red-system&#39;" rel="tag">red-system</a>. Red/System's parser is reused from Red itself...and for which it has its own code generators. The Red executable is able to build Red/System files directly (<code>*.reds</code>) as well as Red files (<code>*.red</code>), and Red/System code may be embedded freely in Red code.</p> <ul> <li><a href="http://www.red-lang.org" rel="nofollow noreferrer">Red Language Website</a></li> <li><a href="https://twitter.com/red_lang" rel="nofollow noreferrer">@red_lang</a> on Twitter.</li> <li><a href="https://gitter.im/red/red" rel="nofollow noreferrer">Red community chat</a> on Gitter.</li> <li><a href="http://groups.google.com/group/red-lang?hl=en" rel="nofollow noreferrer">Mailing-List</a></li> <li><a href="http://webchat.freenode.net/?channels=red-lang&amp;uio=d4#" rel="nofollow noreferrer">IRC channel</a> on Freenode</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T12:45:04.943", "Id": "211910", "Score": "0", "Tags": null, "Title": null }
211910
Red language, inspired by the interpreted language Rebol, but compiled.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T12:45:04.943", "Id": "211911", "Score": "0", "Tags": null, "Title": null }
211911
<p>I have substantially revised my <a href="https://codereview.stackexchange.com/questions/210757/rfc-1951-deflate-compression">earlier implementation</a>, it now seems to be competitive with the standard C# ZLib implementation, increasing compression while being faster for moderate length inputs, and slightly slower for large inputs ( data dependent ) - see long initial comment below for details. </p> <p>It may also be competitive with google's <a href="https://en.wikipedia.org/wiki/Zopfli" rel="noreferrer">Zopfli</a>, which is much slower but which aims to maximise compression with a sophisticated algorithm to divide the input into blocks.</p> <p>The code below chooses a blocksize ( for each individual block ) according to whether a larger blocksize improves compression. </p> <p>After a fair bit of consideration, I decided against using _ for private field names, except if there is a clash with a property name ( as in the Heap class below ). I also opened a <a href="https://github.com/georgebarwood/pdf" rel="noreferrer">github account</a> with my C# code for writing PDF files, which is my use for the code below.</p> <p>I don't have specific questions for review, but would be interested in alternative ideas for dividing the input into blocks. </p> <pre><code>namespace Pdf { /* RFC 1951 compression ( https://www.ietf.org/rfc/rfc1951.txt ) aims to compress a stream of bytes using : (1) LZ77 matching, where if an input sequences of at least 3 bytes re-occurs, it may be coded as a &lt;length,distance&gt; pointer. (2) Huffman coding, where variable length codes are used, with more frequently used symbols encoded in less bits. The input may be split into blocks, a new block introduces a new set of Huffman codes. The choice of block boundaries can affect compression. The method used to determine the block size is as follows: (1) The size of the next block to be output is set to an initial value. (2) A comparison is made between encoding two blocks of this size, or a double-length block. (3) If the double-length encoding is better, that becomes the block size, and the process repeats. LZ77 compression is implemented as suggested in the standard, although no attempt is made to truncate searches ( except searches terminate when the distance limit of 32k bytes is reached ). Only dynamic huffman blocks are used, no attempt is made to use Fixed or Copy blocks. Deflator ( this code) typically achieves better compression than ZLib ( http://www.componentace.com/zlib_.NET.htm via https://zlib.net/, default settings ) by a few percent, and is faster on small inputs, but slower on large inputs ( perhaps due to searches not being truncated ). For example, compressing a font file FreeSans.ttf ( 264,072 bytes ), Zlib output is 148,324 bytes in 44 milliseconds, whereas Deflator output is 144,289 bytes, 4,035 bytes smaller, in 59 milliseconds. Compressing a C# source file of 19,483 bytes, Zlib output size was 5,965 bytes in 27 milliseconds, whereas Deflator output was 5,890 bytes, 75 bytes smaller, in 16 milliseconds. Sample usage: byte [] data = { 1, 2, 3, 4 }; var mbs = new MemoryBitStream(); Deflator.Deflate( data, mbs, 1 ); byte [] deflated_data = mbs.ToArray(); The MemoryBitStream may alternatively be copied to a stream, this may be useful when writing PDF files ( the intended use case ). Auxiliary top level classes/structs ( included in this file ): * OutBitStream. * MemoryBitStream : an implementation of OutBitStream. * HuffmanCoding calculates Huffman codes. * Heap : used to implemnt HuffmanCoding. */ sealed class Deflator { public static void Deflate( byte [] input, OutBitStream output, int format ) { Deflator d = new Deflator( input, output ); if ( format == 1 ) output.WriteBits( 16, 0x9c78 ); // RFC 1950 bytes. d.FindMatches( input ); d.Buffered = input.Length; while ( !d.OutputBlock( true ) ); if ( format == 1 ) { output.Pad( 8 ); output.WriteBits( 32, Adler32( input ) ); // RFC 1950 checksum. } } // Private constants. // RFC 1951 limits. private const int MinMatch = 3; private const int MaxMatch = 258; private const int MaxDistance = 0x8000; private const int StartBlockSize = 0x1000; // Initial blocksize, actual may be larger or smaller. Need not be power of two. private const bool DynamicBlockSize = true; private const int MaxBufferSize = 0x8000; // Must be power of 2. // Instead of initialising LZ77 hashTable and link arrays to -(MaxDistance+1), EncodePosition // is added when storing a value and subtracted when retrieving a value. // This means a default value of 0 will always be more distant than MaxDistance. private const int EncodePosition = MaxDistance + 1; // Private fields. private byte [] Input; private OutBitStream Output; private int Buffered; // How many Input bytes have been processed to intermediate buffer. private int Finished; // How many Input bytes have been written to Output. // Intermediate circular buffer for storing LZ77 matches. private int [] PositionBuffer; private ushort [] LengthBuffer; private ushort [] DistanceBuffer; private int BufferMask; private int BufferWrite, BufferRead; // Indexes for writing and reading. // Private functions and classes. private Deflator( byte [] input, OutBitStream output ) { Input = input; Output = output; int bufferSize = CalcBufferSize( input.Length / 3, MaxBufferSize ); PositionBuffer = new int[ bufferSize ]; LengthBuffer = new ushort[ bufferSize ]; DistanceBuffer = new ushort[ bufferSize ]; BufferMask = bufferSize - 1; } public static int CalcBufferSize( int n, int max ) // Calculates a power of 2 &gt;= n, but not more than max. { if ( n &gt;= max ) return max; int result = 1; while ( result &lt; n ) result = result &lt;&lt; 1; return result; } private void FindMatches( byte [] input ) // LZ77 compression. { if ( input.Length &lt; MinMatch ) return; int limit = input.Length - 2; int hashShift = CalcHashShift( limit * 2 ); uint hashMask = ( 1u &lt;&lt; ( MinMatch * hashShift ) ) - 1; int [] hashTable = new int[ hashMask + 1 ]; int [] link = new int[ limit ]; int position = 0; // position in input. uint hash = ( (uint)input[ 0 ] &lt;&lt; hashShift ) + input[ 1 ]; while ( position &lt; limit ) { hash = ( ( hash &lt;&lt; hashShift ) + input[ position + 2 ] ) &amp; hashMask; int hashEntry = hashTable[ hash ]; hashTable[ hash ] = position + EncodePosition; if ( position &gt;= hashEntry ) // Equivalent to position - ( hashEntry - EncodePosition ) &gt; MaxDistance. { position += 1; continue; } link[ position ] = hashEntry; int distance, match = BestMatch( input, link, hashEntry - EncodePosition, position, out distance ); position += 1; if ( match &lt; MinMatch ) continue; // "Lazy matching" RFC 1951 p.15 : if there are overlapping matches, there is a choice over which of the match to use. // Example: "abc012bc345.... abc345". Here abc345 can be encoded as either [abc][345] or as a[bc345]. // Since a range typically needs more bits to encode than a single literal, choose the latter. while ( position &lt; limit ) { hash = ( ( hash &lt;&lt; hashShift ) + input[ position + 2 ] ) &amp; hashMask; hashEntry = hashTable[ hash ]; hashTable[ hash ] = position + EncodePosition; if ( position &gt;= hashEntry ) break; link[ position ] = hashEntry; int distance2, match2 = BestMatch( input, link, hashEntry - EncodePosition, position, out distance2 ); if ( match2 &gt; match || match2 == match &amp;&amp; distance2 &lt; distance ) { match = match2; distance = distance2; position += 1; } else break; } int copyEnd = SaveMatch( position - 1, match, distance ); if ( copyEnd &gt; limit ) copyEnd = limit; position += 1; // Advance to end of copied section. while ( position &lt; copyEnd ) { hash = ( ( hash &lt;&lt; hashShift ) + input[ position + 2 ] ) &amp; hashMask; link[ position ] = hashTable[ hash ]; hashTable[ hash ] = position + EncodePosition; position += 1; } } } private static int BestMatch( byte [] input, int [] link, int oldPosition, int position, out int distance ) { int avail = input.Length - position; if ( avail &gt; MaxMatch ) avail = MaxMatch; int bestMatch = 0, bestDistance = 0; while ( true ) { if ( input[ position + bestMatch ] == input[ oldPosition + bestMatch ] ) { int match = MatchLength( input, position, oldPosition ); if ( match &gt; bestMatch ) { bestMatch = match; bestDistance = position - oldPosition; if ( bestMatch == avail ) break; } } oldPosition = link[ oldPosition ]; if ( position &gt;= oldPosition ) break; oldPosition -= EncodePosition; } distance = bestDistance; return bestMatch; } private static int MatchLength( byte [] input, int p, int q ) { int end = input.Length; if ( end &gt; p + MaxMatch ) end = p + MaxMatch; int pstart = p; while ( p &lt; end &amp;&amp; input[ p ] == input [ q ] ) { p += 1; q += 1; } return p - pstart; } private static int CalcHashShift( int n ) { int p = 1; int result = 0; while ( n &gt; p ) { p = p &lt;&lt; MinMatch; result += 1; if ( result == 6 ) break; } return result; } private int SaveMatch ( int position, int length, int distance ) // Called from FindMatches to save a &lt;length,distance&gt; match. Returns position + length. { // System.Console.WriteLine( "SaveMatch at " + position + " length=" + length + " distance=" + distance ); int i = BufferWrite; PositionBuffer[ i ] = position; LengthBuffer[ i ] = (ushort) length; DistanceBuffer[ i ] = (ushort) distance; i = ( i + 1 ) &amp; BufferMask; if ( i == BufferRead ) OutputBlock( false ); BufferWrite = i; position += length; Buffered = position; return position; } private bool OutputBlock( bool last ) { int blockSize = Buffered - Finished; // Uncompressed size in bytes. if ( blockSize &gt; StartBlockSize ) { blockSize = ( last &amp;&amp; blockSize &lt; StartBlockSize*2 ) ? blockSize &gt;&gt; 1 : StartBlockSize; } Block b; int bits; // Compressed size in bits. // While block construction fails, reduce blockSize. while ( true ) { b = new Block( this, blockSize, null, out bits ); if ( bits &gt;= 0 ) break; blockSize -= blockSize / 3; } // Investigate larger block size. while ( b.End &lt; Buffered &amp;&amp; DynamicBlockSize ) { // b2 is a block which starts just after b. int bits2; Block b2 = new Block( this, blockSize, b, out bits2 ); if ( bits2 &lt; 0 ) break; // b3 is the block which encodes b and b2 together. int bits3; Block b3 = new Block( this, b2.End - b.Start, null, out bits3 ); if ( bits3 &lt; 0 ) break; if ( bits3 &gt; bits + bits2 ) break; bits = bits3; b = b3; blockSize += blockSize; } // Output the block. if ( b.End &lt; Buffered ) last = false; b.WriteBlock( this, last ); return last; } public static uint Adler32( byte [] b ) // Checksum function per RFC 1950. { uint s1 = 1, s2 = 0; for ( int i = 0; i &lt; b.Length; i += 1 ) { s1 = ( s1 + b[ i ] ) % 65521; s2 = ( s2 + s1 ) % 65521; } return s2 * 65536 + s1; } private class Block { public readonly int Start, End; // Range of input encoded. public Block( Deflator d, int blockSize, Block previous, out int bits ) // The block is not immediately output, to allow caller to try different block sizes. // Instead, the number of bits neeed to encoded the block is returned ( excluding "extra" bits ). { Output = d.Output; bits = -1; if ( previous == null ) { Start = d.Finished; BufferStart = d.BufferRead; } else { Start = previous.End; BufferStart = previous.BufferEnd; } int avail = d.Buffered - Start; if ( blockSize &gt; avail ) blockSize = avail; End = TallyFrequencies( d, blockSize ); Lit.Used[ 256 ] += 1; // End of block code. if ( Lit.ComputeCodes() || Dist.ComputeCodes() ) return; if ( Dist.Count == 0 ) Dist.Count = 1; // Compute length encoding. DoLengthPass( 1 ); if ( Len.ComputeCodes() ) return; // The length codes are permuted before being stored ( so that # of trailing zeroes is likely to be more ). Len.Count = 19; while ( Len.Count &gt; 4 &amp;&amp; Len.Bits[ ClenAlphabet[ Len.Count - 1 ] ] == 0 ) Len.Count -= 1; bits = 17 + 3 * Len.Count + Len.Total() + Lit.Total() + Dist.Total(); } public void WriteBlock( Deflator d, bool last ) { OutBitStream output = Output; output.WriteBits( 1, last ? 1u : 0u ); output.WriteBits( 2, 2 ); output.WriteBits( 5, (uint)( Lit.Count - 257 ) ); output.WriteBits( 5, (uint)( Dist.Count - 1 ) ); output.WriteBits( 4, (uint)( Len.Count - 4 ) ); for ( int i = 0; i &lt; Len.Count; i += 1 ) output.WriteBits( 3, Len.Bits[ ClenAlphabet[ i ] ] ); DoLengthPass( 2 ); PutCodes( d ); output.WriteBits( Lit.Bits[ 256 ], Lit.Codes[ 256 ] ); // End of block code } // Block private fields and constants. private OutBitStream Output; private int BufferStart, BufferEnd; // Huffman codings : Lit = Literal or Match Code, Dist = Distance code, Len = Length code. HuffmanCoding Lit = new HuffmanCoding(15,288), Dist = new HuffmanCoding(15,32), Len = new HuffmanCoding(7,19); // Counts for code length encoding. private int LengthPass, PreviousLength, ZeroRun, Repeat; // RFC 1951 constants. private readonly static byte [] ClenAlphabet = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; private readonly static byte [] MatchExtra = { 0,0,0,0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 5,5,5,5, 0 }; private readonly static ushort [] MatchOff = { 3,4,5,6, 7,8,9,10, 11,13,15,17, 19,23,27,31, 35,43,51,59, 67,83,99,115, 131,163,195,227, 258, 0xffff }; private readonly static byte [] DistExtra = { 0,0,0,0, 1,1,2,2, 3,3,4,4, 5,5,6,6, 7,7,8,8, 9,9,10,10, 11,11,12,12, 13,13 }; private readonly static ushort [] DistOff = { 1,2,3,4, 5,7,9,13, 17,25,33,49, 65,97,129,193, 257,385,513,769, 1025,1537,2049,3073, 4097,6145,8193,12289, 16385,24577, 0xffff }; // Block private functions. private int TallyFrequencies( Deflator d, int blockSize ) { int position = Start; int end = position + blockSize; int bufferRead = BufferStart; while ( position &lt; end &amp;&amp; bufferRead != d.BufferWrite ) { int matchPosition = d.PositionBuffer[ bufferRead ]; if ( matchPosition &gt;= end ) break; int length = d.LengthBuffer[ bufferRead ]; int distance = d.DistanceBuffer[ bufferRead ]; bufferRead = ( bufferRead + 1 ) &amp; d.BufferMask; byte [] input = d.Input; while ( position &lt; matchPosition ) { Lit.Used[ input[ position ] ] += 1; position += 1; } position += length; // Compute match and distance codes. int mc = 0; while ( length &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1; int dc = 29; while ( distance &lt; DistOff[ dc ] ) dc -= 1; Lit.Used[ 257 + mc ] += 1; Dist.Used[ dc ] += 1; } while ( position &lt; end ) { Lit.Used[ d.Input[ position ] ] += 1; position += 1; } BufferEnd = bufferRead; return position; } private void PutCodes( Deflator d ) { byte [] input = d.Input; OutBitStream output = d.Output; int position = Start; int bufferRead = BufferStart; while ( position &lt; End &amp;&amp; bufferRead != d.BufferWrite ) { int matchPosition = d.PositionBuffer[ bufferRead ]; if ( matchPosition &gt;= End ) break; int length = d.LengthBuffer[ bufferRead ]; int distance = d.DistanceBuffer[ bufferRead ]; bufferRead = ( bufferRead + 1 ) &amp; d.BufferMask; while ( position &lt; matchPosition ) { byte b = d.Input[ position ]; output.WriteBits( Lit.Bits[ b ], Lit.Codes[ b ] ); position += 1; } position += length; // Compute match and distance codes. int mc = 0; while ( length &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1; int dc = 29; while ( distance &lt; DistOff[ dc ] ) dc -= 1; output.WriteBits( Lit.Bits[ 257 + mc ], Lit.Codes[ 257 + mc ] ); output.WriteBits( MatchExtra[ mc ], (uint)(length-MatchOff[ mc ] ) ); output.WriteBits( Dist.Bits[ dc ], Dist.Codes[ dc ] ); output.WriteBits( DistExtra[ dc ], (uint)(distance-DistOff[ dc ] ) ); } while ( position &lt; End ) { byte b = input[ position ]; output.WriteBits( Lit.Bits[ b ], Lit.Codes[ b ] ); position += 1; } d.BufferRead = bufferRead; d.Finished = position; } // Run length encoding of code lengths - RFC 1951, page 13. private void DoLengthPass( int pass ) { LengthPass = pass; EncodeLengths( Lit.Count, Lit.Bits, true ); EncodeLengths( Dist.Count, Dist.Bits, false ); } private void PutLength( int code ) { if ( LengthPass == 1 ) Len.Used[ code ] += 1; else Output.WriteBits( Len.Bits[ code ], Len.Codes[ code ] ); } private void EncodeLengths( int n, byte [] lengths, bool isLit ) { if ( isLit ) { PreviousLength = 0; ZeroRun = 0; Repeat = 0; } for ( int i = 0; i &lt; n; i += 1 ) { int length = lengths[ i ]; if ( length == 0 ) { EncodeRepeat(); ZeroRun += 1; PreviousLength = 0; } else if ( length == PreviousLength ) { Repeat += 1; } else { EncodeZeroRun(); EncodeRepeat(); PutLength( length ); PreviousLength = length; } } if ( !isLit ) { EncodeZeroRun(); EncodeRepeat(); } } private void EncodeRepeat() { while ( Repeat &gt; 0 ) { if ( Repeat &lt; 3 ) { PutLength( PreviousLength ); Repeat -= 1; } else { int x = Repeat; if ( x &gt; 6 ) x = 6; PutLength( 16 ); if ( LengthPass == 2 ) { Output.WriteBits( 2, (uint)( x - 3 ) ); } Repeat -= x; } } } private void EncodeZeroRun() { while ( ZeroRun &gt; 0 ) { if ( ZeroRun &lt; 3 ) { PutLength( 0 ); ZeroRun -= 1; } else if ( ZeroRun &lt; 11 ) { PutLength( 17 ); if ( LengthPass == 2 ) Output.WriteBits( 3, (uint)( ZeroRun - 3 ) ); ZeroRun = 0; } else { int x = ZeroRun; if ( x &gt; 138 ) x = 138; PutLength( 18 ); if ( LengthPass == 2 ) Output.WriteBits( 7, (uint)( x - 11 ) ); ZeroRun -= x; } } } } // end class Block } // end class Deflator // ****************************************************************************** struct HuffmanCoding // Variable length coding. { public int Count; // Number of used symbols. public int [] Used; // Count of how many times a symbol is used in the block being encoded. public byte [] Bits; // Number of bits used to encode a symbol. public ushort [] Codes; // Huffman code for a symbol ( bit 0 is most significant ). private int Limit; // Maxiumum number of bits for a code. public HuffmanCoding( int limit, int symbols ) { Limit = limit; Count = symbols; Used = new int[ symbols ]; Bits = new byte[ symbols ]; Codes = new ushort[ symbols ]; } public int Total() { int result = 0, count = Count; for ( int i = 0; i &lt; count; i += 1 ) result += Used[i] * Bits[i]; return result; } public bool ComputeCodes() // returns true if Limit is exceeded. { int count = Count; Heap&lt;TreeNode&gt; heap = new Heap&lt;TreeNode&gt;( count, TreeNode.LessThan ); for ( int i = 0; i &lt; Count; i += 1 ) { int used = Used[ i ]; if ( used &gt; 0 ) heap.Insert( new Leaf( (ushort)i, used ) ); } int maxBits = 0; if ( heap.Count == 1 ) { heap.Remove().GetBits( Bits, 1 ); maxBits = 1; } else if ( heap.Count &gt; 1 ) { do // Keep pairing the lowest frequency TreeNodes. { heap.Insert( new Branch( heap.Remove(), heap.Remove() ) ); } while ( heap.Count &gt; 1 ); TreeNode root = heap.Remove(); maxBits = root.Depth; if ( maxBits &gt; Limit ) return true; root.GetBits( Bits, 0 ); // Walk the tree to find the code lengths (Bits). } // Compute codes, code below is from RFC 1951 page 7. int [] bl_count = new int[ maxBits + 1 ]; for ( int i = 0; i &lt; count; i += 1 ) bl_count[ Bits[ i ] ] += 1; int [] next_code = new int[ maxBits + 1 ]; int code = 0; bl_count[ 0 ] = 0; for ( int i = 0; i &lt; maxBits; i += 1 ) { code = ( code + bl_count[ i ] ) &lt;&lt; 1; next_code[ i+1 ] = code; } for ( int i = 0; i &lt; count; i += 1 ) { int length = Bits[ i ]; if ( length != 0 ) { Codes[ i ] = (ushort)Reverse( next_code[ length ], length ); next_code[ length ] += 1; } } // Reduce count if there are unused symbols. while ( count &gt; 0 &amp;&amp; Bits[ count - 1 ] == 0 ) count -= 1; Count = count; //System.Console.WriteLine( "HuffEncoder.ComputeCodes" ); // for ( int i = 0; i &lt; count; i += 1 ) if ( Bits[ i ] &gt; 0 ) // System.Console.WriteLine( "i=" + i + " len=" + Bits[ i ] + " tc=" + Codes[ i ].ToString("X") + " freq=" + Used[ i ] ); return false; } private static int Reverse( int x, int bits ) // Reverse a string of bits ( ready to be output as Huffman code ). { int result = 0; for ( int i = 0; i &lt; bits; i += 1 ) { result &lt;&lt;= 1; result |= x &amp; 1; x &gt;&gt;= 1; } return result; } private abstract class TreeNode { public int Used; public byte Depth; public static bool LessThan( TreeNode a, TreeNode b ) { return a.Used &lt; b.Used || a.Used == b.Used &amp;&amp; a.Depth &lt; b.Depth; } public abstract void GetBits( byte [] nbits, int length ); } private class Leaf : TreeNode { public ushort Code; public Leaf( ushort code, int used ) { Code = code; Used = used; } public override void GetBits( byte [] nbits, int length ) { nbits[ Code ] = (byte)length; } } // end class Leaf private class Branch : TreeNode { TreeNode Left, Right; public Branch( TreeNode left, TreeNode right ) { Left = left; Right = right; Used = left.Used + right.Used; Depth = (byte)( 1 + ( left.Depth &gt; right.Depth ? left.Depth : right.Depth ) ); } public override void GetBits( byte [] nbits, int length ) { Left.GetBits( nbits, length + 1 ); Right.GetBits( nbits, length + 1 ); } } // end class Branch } // end struct HuffmanCoding // ****************************************************************************** sealed class Heap&lt;T&gt; // An array organised so the smallest element can be efficiently removed. { public delegate bool DLessThan( T a, T b ); public int Count { get{ return _Count; } } private int _Count; private T [] Array; private DLessThan LessThan; public Heap ( int capacity, DLessThan lessThan ) { Array = new T[ capacity ]; LessThan = lessThan; } public void Insert( T e ) { int j = _Count++; while ( j &gt; 0 ) { int p = ( j - 1 ) / 2; // Index of parent. T pe = Array[ p ]; if ( !LessThan( e, pe ) ) break; Array[ j ] = pe; // Demote parent. j = p; } Array[ j ] = e; } public T Remove() // Returns the smallest element. { T result = Array[ 0 ]; _Count -= 1; T e = Array[ _Count ]; Array[ _Count ] = default(T); int j = 0; while ( true ) { int c = j * 2 + 1; if ( c &gt;= _Count ) break; T ce = Array[ c ]; if ( c + 1 &lt; _Count ) { T ce2 = Array[ c + 1 ]; if ( LessThan( ce2, ce ) ) { c += 1; ce = ce2; } } if ( !LessThan( ce, e ) ) break; Array[ j ] = ce; j = c; } Array[ j ] = e; return result; } } // end class Heap // ****************************************************************************** abstract class OutBitStream { public void WriteBits( int n, ulong value ) // Write first n ( 0 &lt;= n &lt;= 64 ) bits of value to stream, least significant bit is written first. // Unused bits of value must be zero, i.e. value must be in range 0 .. 2^n-1. { if ( n + BitsInWord &gt;= WordCapacity ) { Save( Word | value &lt;&lt; BitsInWord ); int space = WordCapacity - BitsInWord; value &gt;&gt;= space; n -= space; Word = 0; BitsInWord = 0; } Word |= value &lt;&lt; BitsInWord; BitsInWord += n; } public void Pad( int n ) // Pad with zero bits to n bit boundary where n is power of 2 in range 1,2,4..64, typically n=8. { int w = BitsInWord % n; if ( w &gt; 0 ) WriteBits( n - w, 0 ); } public abstract void Save( ulong word ); protected const int WordSize = sizeof(ulong); // Size of Word in bytes. protected const int WordCapacity = WordSize * 8; // Number of bits that can be stored Word protected ulong Word; // Bits are first stored in Word, when full, Word is saved. protected int BitsInWord; // Number of bits currently stored in Word. } // ****************************************************************************** sealed class MemoryBitStream : OutBitStream { // ByteSize returns the current size in bytes. // CopyTo copies the contents to a Stream. // ToArray returns the contents as an array of bytes. public int ByteSize() { return ( CompleteChunks * Chunk.Capacity + WordsInCurrentChunk ) * WordSize + ( BitsInWord + 7 ) / 8; } public void CopyTo( System.IO.Stream s ) { byte [] buffer = new byte [ WordSize ]; for ( Chunk c = FirstChunk; c != null; c = c.Next ) { int n = ( c == CurrentChunk ) ? WordsInCurrentChunk : Chunk.Capacity; for ( int j = 0; j &lt; n; j += 1 ) { ulong w = c.Words[ j ]; unchecked { buffer[0] = (byte) w; buffer[1] = (byte)( w &gt;&gt; 8 ); buffer[2] = (byte)( w &gt;&gt; 16 ); buffer[3] = (byte)( w &gt;&gt; 24 ); buffer[4] = (byte)( w &gt;&gt; 32 ); buffer[5] = (byte)( w &gt;&gt; 40 ); buffer[6] = (byte)( w &gt;&gt; 48 ); buffer[7] = (byte)( w &gt;&gt; 56 ); } s.Write( buffer, 0, 8 ); } } int biw = BitsInWord; ulong word = Word; while ( biw &gt; 0 ) { s.WriteByte( unchecked( (byte) word ) ); word &gt;&gt;= 8; biw -= 8; } } public byte [] ToArray() { byte [] buffer = new byte[ ByteSize() ]; int i = 0; for ( Chunk c = FirstChunk; c != null; c = c.Next ) { int n = ( c == CurrentChunk ) ? WordsInCurrentChunk : Chunk.Capacity; for ( int j = 0; j &lt; n; j += 1 ) { ulong w = c.Words[ j ]; unchecked { buffer[i++] = (byte) w; buffer[i++] = (byte)( w &gt;&gt; 8 ); buffer[i++] = (byte)( w &gt;&gt; 16 ); buffer[i++] = (byte)( w &gt;&gt; 24 ); buffer[i++] = (byte)( w &gt;&gt; 32 ); buffer[i++] = (byte)( w &gt;&gt; 40 ); buffer[i++] = (byte)( w &gt;&gt; 48 ); buffer[i++] = (byte)( w &gt;&gt; 56 ); } } } int biw = BitsInWord; ulong word = Word; while ( biw &gt; 0 ) { buffer[ i++ ] = unchecked( (byte) word ); word &gt;&gt;= 8; biw -= 8; } return buffer; } public MemoryBitStream() { FirstChunk = new Chunk(); CurrentChunk = FirstChunk; } public override void Save( ulong word ) { if ( WordsInCurrentChunk == Chunk.Capacity ) { Chunk nc = new Chunk(); CurrentChunk.Next = nc; CurrentChunk = nc; CompleteChunks += 1; WordsInCurrentChunk = 0; } CurrentChunk.Words[ WordsInCurrentChunk++ ] = word; } private int WordsInCurrentChunk; // Number of words stored in CurrentChunk. private int CompleteChunks; // Number of complete Chunks. private Chunk FirstChunk, CurrentChunk; private class Chunk { public const int Capacity = 256; public ulong [] Words = new ulong[ Capacity ]; public Chunk Next; } } // end class MemoryBitStream } // namespace </code></pre>
[]
[ { "body": "<p>On the question of alternative ideas for dividing the input into blocks, I have now implemented a fairly simple extension : the code now checks whether moving data into the previous block improves compression (with the current encodings), before making a decision about doubling the block size. </p>\n\n<p>The search terminates if a code is encountered which doesn't occur in the previous block ( this seems a reasonable heuristic, I guess it could assign a fairly large penalty and continue the search instead ).</p>\n\n<p>Here's a copy of the revised code, the new function is <code>TuneBoundary</code>. The code incorporates various other improvements as well.</p>\n\n<pre><code>using System.Threading.Tasks;\nusing System.Collections.Generic;\n\nnamespace Pdf {\n\n/* RFC 1951 compression ( https://www.ietf.org/rfc/rfc1951.txt ) aims to compress a stream of bytes using :\n\n (1) LZ77 matching, where if an input sequences of at least 3 bytes re-occurs, it may be coded \n as a &lt;length,distance&gt; pointer.\n\n (2) Huffman coding, where variable length codes are used, with more frequently used symbols encoded in less bits.\n\n The input may be split into blocks, a new block introduces a new set of Huffman codes. The choice of block \n boundaries can affect compression. The method used to determine the block size is as follows:\n\n (1) The size of the next block to be output is set to an initial value.\n\n (2) A comparison is made between encoding two blocks of this size, or a double-length block.\n\n (3) If the double-length encoding is better, that becomes the block size, and the process repeats.\n\n LZ77 compression is implemented as suggested in the standard, although no attempt is made to\n truncate searches ( except searches terminate when the distance limit of 32k bytes is reached ).\n\n Only dynamic huffman blocks are used, no attempt is made to use Fixed or Copy blocks.\n\n Deflator ( this code) typically achieves better compression than ZLib ( http://www.componentace.com/zlib_.NET.htm \n via https://zlib.net/, default settings ) by a few percent, and is faster on small inputs, but slower \n on large inputs.\n\n For example, compressing a font file FreeSans.ttf ( 264,072 bytes ), Zlib output is 148,324 bytes\n in 50 milliseconds, whereas Deflator output is 143,666 bytes in 58 milliseconds. If dynamic block sizing\n is disabled, the output is 146,892 bytes and the time is the same as ZLib.\n\n Compressing a C# source file of 19,483 bytes, Zlib output size is 5,965 bytes in 27 milliseconds, \n whereas Deflator output is 5,890 bytes, 75 bytes smaller, in 16 milliseconds.\n\n Sample usage:\n\n byte [] data = { 1, 2, 3, 4 };\n var mbs = new MemoryBitStream();\n Deflator.Deflate( data, mbs, 1 );\n byte [] deflated_data = mbs.ToArray();\n\n The MemoryBitStream may alternatively be copied to a stream, this may be useful when writing PDF files ( the intended use case ).\n\n Auxiliary top level classes/structs ( included in this file ): \n * OutBitStream.\n * MemoryBitStream : an implementation of OutBitStream.\n * HuffmanCoding calculates Huffman codes.\n * UlongHeap : used to implemnt HuffmanCoding.\n*/ \n\nsealed class Deflator \n{\n\n public static void Deflate( byte [] input, OutBitStream output ) // Deflate with default options.\n {\n Deflator d = new Deflator( input, output );\n d.Go();\n }\n\n // Options : to amend these use new Deflator( input, output ) and set before calling Go().\n public int StartBlockSize = 0x1000; // Increase to go faster ( with less compression ), reduce to try for more compression.\n public int MaxBufferSize = 0x8000; // Must be power of 2, increase to try for slightly more compression on large inputs.\n public bool RFC1950 = true; // Set false to suppress RFC 1950 fields.\n public bool LZ77 = true; // Set false to go much faster ( with much less compression ).\n public bool DynamicBlockSize = true; // Set false to go faster ( with less compression ).\n public bool TuneBlockSize = true; // Set false to go faster ( with less compression ).\n\n public Deflator( byte [] input, OutBitStream output )\n { \n Input = input; \n Output = output; \n }\n\n public void Go()\n {\n int bufferSize = CalcBufferSize( Input.Length / 3, MaxBufferSize );\n PositionBuffer = new int[ bufferSize ];\n LengthBuffer = new byte[ bufferSize ];\n DistanceBuffer = new ushort[ bufferSize ]; \n BufferMask = bufferSize - 1; \n\n if ( RFC1950 ) Output.WriteBits( 16, 0x9c78 );\n if ( LZ77 ) FindMatches( Input );\n Buffered = Input.Length;\n while ( !OutputBlock( true ) );\n if ( RFC1950 )\n { \n Output.Pad( 8 );\n Output.WriteBits( 32, Adler32( Input ) );\n } \n }\n\n // Private constants.\n\n // RFC 1951 limits.\n private const int MinMatch = 3;\n private const int MaxMatch = 258;\n private const int MaxDistance = 0x8000;\n\n // Instead of initialising LZ77 hashTable and link arrays to -(MaxDistance+1), EncodePosition \n // is added when storing a value and subtracted when retrieving a value.\n // This means a default value of 0 will always be more distant than MaxDistance.\n private const int EncodePosition = MaxDistance + 1;\n\n // Private fields.\n\n private byte [] Input;\n private OutBitStream Output;\n\n private int Buffered; // How many Input bytes have been processed to intermediate buffer.\n private int Finished; // How many Input bytes have been written to Output.\n\n // Intermediate circular buffer for storing LZ77 matches.\n private int [] PositionBuffer;\n private byte [] LengthBuffer;\n private ushort [] DistanceBuffer;\n private int BufferMask;\n private int BufferWrite, BufferRead; // Indexes for writing and reading.\n\n // Private functions and classes.\n\n private static int CalcBufferSize( int n, int max )\n // Calculates a power of 2 &gt;= n, but not more than max.\n {\n if ( n &gt;= max ) return max;\n int result = 1;\n while ( result &lt; n ) result = result &lt;&lt; 1;\n return result;\n }\n\n private void FindMatches( byte [] input ) // LZ77 compression.\n {\n if ( input.Length &lt; MinMatch ) return;\n int limit = input.Length - 2;\n\n int hashShift = CalcHashShift( limit * 2 );\n uint hashMask = ( 1u &lt;&lt; ( MinMatch * hashShift ) ) - 1;\n\n int [] hashTable = new int[ hashMask + 1 ];\n int [] link = new int[ limit ];\n\n int position = 0; // position in input.\n uint hash = ( (uint)input[ 0 ] &lt;&lt; hashShift ) + input[ 1 ];\n\n while ( position &lt; limit )\n {\n hash = ( ( hash &lt;&lt; hashShift ) + input[ position + 2 ] ) &amp; hashMask; \n int hashEntry = hashTable[ hash ];\n hashTable[ hash ] = position + EncodePosition;\n if ( position &gt;= hashEntry ) // Equivalent to position - ( hashEntry - EncodePosition ) &gt; MaxDistance.\n {\n position += 1;\n continue;\n }\n link[ position ] = hashEntry;\n\n int distance, match = BestMatch( input, link, hashEntry - EncodePosition, position, out distance );\n position += 1;\n if ( match &lt; MinMatch ) continue;\n\n // \"Lazy matching\" RFC 1951 p.15 : if there are overlapping matches, there is a choice over which of the match to use.\n // Example: \"abc012bc345.... abc345\". Here abc345 can be encoded as either [abc][345] or as a[bc345].\n // Since a range typically needs more bits to encode than a single literal, choose the latter.\n while ( position &lt; limit ) \n {\n hash = ( ( hash &lt;&lt; hashShift ) + input[ position + 2 ] ) &amp; hashMask; \n hashEntry = hashTable[ hash ];\n hashTable[ hash ] = position + EncodePosition;\n if ( position &gt;= hashEntry ) break;\n link[ position ] = hashEntry;\n\n int distance2, match2 = BestMatch( input, link, hashEntry - EncodePosition, position, out distance2 );\n if ( match2 &gt; match || match2 == match &amp;&amp; distance2 &lt; distance )\n {\n match = match2;\n distance = distance2;\n position += 1;\n }\n else break;\n }\n\n int copyEnd = SaveMatch( position - 1, match, distance );\n if ( copyEnd &gt; limit ) copyEnd = limit;\n\n position += 1;\n\n // Advance to end of copied section.\n while ( position &lt; copyEnd )\n { \n hash = ( ( hash &lt;&lt; hashShift ) + input[ position + 2 ] ) &amp; hashMask;\n link[ position ] = hashTable[ hash ];\n hashTable[ hash ] = position + EncodePosition;\n position += 1;\n }\n }\n }\n\n private static int BestMatch( byte [] input, int [] link, int oldPosition, int position, out int distance )\n { \n int avail = input.Length - position;\n if ( avail &gt; MaxMatch ) avail = MaxMatch;\n\n int bestMatch = 0, bestDistance = 0;\n\n while ( true )\n { \n if ( input[ position + bestMatch ] == input[ oldPosition + bestMatch ] )\n {\n int match = 0; \n while ( match &lt; avail &amp;&amp; input[ position + match ] == input[ oldPosition + match ] ) \n match += 1;\n\n if ( match &gt; bestMatch )\n {\n bestMatch = match;\n bestDistance = position - oldPosition;\n if ( bestMatch == avail ) break;\n }\n }\n oldPosition = link[ oldPosition ];\n if ( position &gt;= oldPosition ) break;\n oldPosition -= EncodePosition;\n }\n distance = bestDistance;\n return bestMatch;\n }\n\n private static int CalcHashShift( int n )\n {\n int p = 1;\n int result = 0;\n while ( n &gt; p ) \n {\n p = p &lt;&lt; MinMatch;\n result += 1;\n if ( result == 6 ) break;\n }\n return result;\n } \n\n private int SaveMatch ( int position, int length, int distance )\n // Called from FindMatches to save a &lt;length,distance&gt; match. Returns position + length.\n {\n // System.Console.WriteLine( \"SaveMatch at \" + position + \" length=\" + length + \" distance=\" + distance );\n int i = BufferWrite;\n PositionBuffer[ i ] = position;\n LengthBuffer[ i ] = (byte) (length - MinMatch);\n DistanceBuffer[ i ] = (ushort) distance;\n i = ( i + 1 ) &amp; BufferMask;\n if ( i == BufferRead ) OutputBlock( false );\n BufferWrite = i;\n position += length;\n Buffered = position;\n return position;\n }\n\n private bool OutputBlock( bool last )\n {\n int blockSize = Buffered - Finished; // Uncompressed size in bytes.\n\n if ( blockSize &gt; StartBlockSize ) \n {\n blockSize = ( last &amp;&amp; blockSize &lt; StartBlockSize*2 ) ? blockSize &gt;&gt; 1 : StartBlockSize;\n }\n\n Block b = new Block( this, blockSize, null );\n int bits = b.GetBits(); // Compressed size in bits.\n int finalBlockSize = blockSize;\n\n // Investigate larger block size.\n while ( b.End &lt; Buffered &amp;&amp; DynamicBlockSize ) \n {\n // b2 is a block which starts just after b.\n Block b2 = new Block( this, blockSize, b );\n\n // b3 covers b and b2 exactly as one block.\n Block b3 = new Block( this, b2.End - b.Start, null );\n\n int bits2 = b2.GetBits();\n int bits3 = b3.GetBits(); \n\n int delta = TuneBlockSize ? b2.TuneBoundary( this, b, blockSize / 4, out finalBlockSize ) : 0;\n\n if ( bits3 &gt; bits + bits2 + delta ) break;\n\n bits = bits3;\n b = b3;\n blockSize += blockSize; \n finalBlockSize = blockSize;\n } \n\n if ( finalBlockSize &gt; blockSize )\n {\n b = new Block( this, finalBlockSize, null ); \n b.GetBits();\n }\n\n // Output the block.\n if ( b.End &lt; Buffered ) last = false;\n b.WriteBlock( this, last ); \n return last;\n }\n\n public static uint Adler32( byte [] b ) // Checksum function per RFC 1950.\n {\n uint s1 = 1, s2 = 0;\n for ( int i = 0; i &lt; b.Length; i += 1 )\n {\n s1 = ( s1 + b[ i ] ) % 65521;\n s2 = ( s2 + s1 ) % 65521;\n }\n return s2 * 65536 + s1; \n }\n\n private class Block\n {\n public readonly int Start, End; // Range of input encoded.\n\n public Block( Deflator d, int blockSize, Block previous )\n // The block is not immediately output, to allow caller to try different block sizes.\n // Instead, the number of bits neeed to encoded the block is returned by GetBits ( excluding \"extra\" bits ).\n {\n Output = d.Output;\n\n if ( previous == null )\n {\n Start = d.Finished;\n BufferStart = d.BufferRead;\n }\n else\n {\n Start = previous.End;\n BufferStart = previous.BufferEnd;\n }\n\n int avail = d.Buffered - Start;\n if ( blockSize &gt; avail ) blockSize = avail;\n\n End = TallyFrequencies( d, blockSize );\n Lit.Used[ 256 ] += 1; // End of block code.\n }\n\n public int GetBits()\n {\n Lit.ComputeCodes();\n Dist.ComputeCodes();\n\n if ( Dist.Count == 0 ) Dist.Count = 1;\n\n // Compute length encoding.\n DoLengthPass( 1 );\n Len.ComputeCodes();\n\n // The length codes are permuted before being stored ( so that # of trailing zeroes is likely to be more ).\n Len.Count = 19; while ( Len.Count &gt; 4 &amp;&amp; Len.Bits[ ClenAlphabet[ Len.Count - 1 ] ] == 0 ) Len.Count -= 1;\n\n return 17 + 3 * Len.Count + Len.Total() + Lit.Total() + Dist.Total();\n }\n\n public void WriteBlock( Deflator d, bool last )\n {\n OutBitStream output = Output;\n output.WriteBits( 1, last ? 1u : 0u );\n output.WriteBits( 2, 2 );\n output.WriteBits( 5, (uint)( Lit.Count - 257 ) ); \n output.WriteBits( 5, (uint)( Dist.Count - 1 ) ); \n output.WriteBits( 4, (uint)( Len.Count - 4 ) );\n\n for ( int i = 0; i &lt; Len.Count; i += 1 ) \n output.WriteBits( 3, Len.Bits[ ClenAlphabet[ i ] ] );\n\n DoLengthPass( 2 );\n PutCodes( d );\n output.WriteBits( Lit.Bits[ 256 ], Lit.Codes[ 256 ] ); // End of block code\n }\n\n // Block private fields and constants.\n\n private OutBitStream Output;\n private int BufferStart, BufferEnd;\n\n // Huffman codings : Lit = Literal or Match Code, Dist = Distance code, Len = Length code.\n HuffmanCoding Lit = new HuffmanCoding(15,288), Dist = new HuffmanCoding(15,32), Len = new HuffmanCoding(7,19);\n\n // Counts for code length encoding.\n private int LengthPass, PreviousLength, ZeroRun, Repeat;\n\n // RFC 1951 constants.\n private readonly static byte [] ClenAlphabet = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };\n private readonly static byte [] MatchExtra = { 0,0,0,0, 0,0,0,0, 1,1,1,1, 2,2,2,2, 3,3,3,3, 4,4,4,4, 5,5,5,5, 0 };\n private readonly static ushort [] MatchOff = { 3,4,5,6, 7,8,9,10, 11,13,15,17, 19,23,27,31, 35,43,51,59, 67,83,99,115, \n 131,163,195,227, 258, 0xffff };\n private readonly static byte [] DistExtra = { 0,0,0,0, 1,1,2,2, 3,3,4,4, 5,5,6,6, 7,7,8,8, 9,9,10,10, 11,11,12,12, 13,13 };\n private readonly static ushort [] DistOff = { 1,2,3,4, 5,7,9,13, 17,25,33,49, 65,97,129,193, 257,385,513,769, \n 1025,1537,2049,3073, 4097,6145,8193,12289, 16385,24577, 0xffff };\n\n // Block private functions.\n\n private int TallyFrequencies( Deflator d, int blockSize )\n {\n int position = Start;\n int end = position + blockSize;\n\n int bufferRead = BufferStart;\n while ( position &lt; end &amp;&amp; bufferRead != d.BufferWrite )\n {\n int matchPosition = d.PositionBuffer[ bufferRead ];\n if ( matchPosition &gt;= end ) break;\n\n int length = d.LengthBuffer[ bufferRead ] + MinMatch;\n int distance = d.DistanceBuffer[ bufferRead ];\n bufferRead = ( bufferRead + 1 ) &amp; d.BufferMask;\n\n byte [] input = d.Input;\n while ( position &lt; matchPosition ) \n {\n Lit.Used[ input[ position ] ] += 1;\n position += 1;\n }\n\n position += length;\n\n // Compute match and distance codes.\n int mc = 0; while ( length &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1;\n int dc = 29; while ( distance &lt; DistOff[ dc ] ) dc -= 1;\n\n Lit.Used[ 257 + mc ] += 1;\n Dist.Used[ dc ] += 1; \n }\n\n while ( position &lt; end ) \n {\n Lit.Used[ d.Input[ position ] ] += 1;\n position += 1;\n }\n\n BufferEnd = bufferRead;\n return position;\n }\n\n public int TuneBoundary( Deflator d, Block prev, int howfar, out int blockSize )\n {\n // Investigate whether moving data into the previous block uses fewer bits,\n // using the current encodings. If a symbol with no encoding in the \n // previous block is found, terminate the search ( goto EndSearch ).\n\n int position = Start;\n int bufferRead = BufferStart;\n int end = position + howfar;\n if ( end &gt; End ) end = End;\n\n int delta = 0, bestDelta = 0, bestPosition = position;\n\n while ( position &lt; End &amp;&amp; bufferRead != d.BufferWrite )\n {\n int matchPosition = d.PositionBuffer[ bufferRead ];\n\n if ( matchPosition &gt;= End ) break;\n\n int length = d.LengthBuffer[ bufferRead ] + MinMatch;\n int distance = d.DistanceBuffer[ bufferRead ]; \n\n bufferRead = ( bufferRead + 1 ) &amp; d.BufferMask;\n\n while ( position &lt; matchPosition ) \n {\n byte b = d.Input[ position ];\n\n if ( prev.Lit.Bits[ b ] == 0 ) goto EndSearch;\n delta += prev.Lit.Bits[ b ] - Lit.Bits[ b ];\n if ( delta &lt; bestDelta ) { bestDelta = delta; bestPosition = position; }\n position += 1;\n } \n position += length;\n\n // Compute match and distance codes.\n int mc = 0; while ( length &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1;\n int dc = 29; while ( distance &lt; DistOff[ dc ] ) dc -= 1;\n\n if ( prev.Lit.Bits[ 257 + mc ] == 0 || prev.Dist.Bits[ dc ] == 0 ) goto EndSearch;\n delta += prev.Lit.Bits[ 257 + mc ] - Lit.Bits[ 257 + mc ];\n delta += prev.Dist.Bits[ dc ] - Dist.Bits[ dc ];\n\n if ( delta &lt; bestDelta ) { bestDelta = delta; bestPosition = position; }\n position += 1;\n }\n\n while ( position &lt; end ) \n {\n byte b = d.Input[ position ];\n if ( prev.Lit.Bits[ b ] == 0 ) goto EndSearch;\n delta += prev.Lit.Bits[ b ] - Lit.Bits[ b ];\n if ( delta &lt; bestDelta ) { bestDelta = delta; bestPosition = position; }\n position += 1;\n } \n\n EndSearch:\n\n blockSize = bestPosition - prev.Start;\n return bestDelta;\n }\n\n\n private void PutCodes( Deflator d )\n {\n byte [] input = d.Input;\n OutBitStream output = d.Output;\n\n int position = Start;\n int bufferRead = BufferStart;\n\n while ( position &lt; End &amp;&amp; bufferRead != d.BufferWrite )\n {\n int matchPosition = d.PositionBuffer[ bufferRead ];\n\n if ( matchPosition &gt;= End ) break;\n\n int length = d.LengthBuffer[ bufferRead ] + MinMatch;\n int distance = d.DistanceBuffer[ bufferRead ]; \n\n bufferRead = ( bufferRead + 1 ) &amp; d.BufferMask;\n\n while ( position &lt; matchPosition ) \n {\n byte b = d.Input[ position ];\n output.WriteBits( Lit.Bits[ b ], Lit.Codes[ b ] );\n position += 1;\n } \n position += length;\n\n // Compute match and distance codes.\n int mc = 0; while ( length &gt;= MatchOff[ mc ] ) mc += 1; mc -= 1;\n int dc = 29; while ( distance &lt; DistOff[ dc ] ) dc -= 1;\n\n output.WriteBits( Lit.Bits[ 257 + mc ], Lit.Codes[ 257 + mc ] );\n output.WriteBits( MatchExtra[ mc ], (uint)(length-MatchOff[ mc ] ) );\n output.WriteBits( Dist.Bits[ dc ], Dist.Codes[ dc ] );\n output.WriteBits( DistExtra[ dc ], (uint)(distance-DistOff[ dc ] ) ); \n }\n\n while ( position &lt; End ) \n {\n byte b = input[ position ];\n output.WriteBits( Lit.Bits[ b ], Lit.Codes[ b ] );\n position += 1;\n } \n\n d.BufferRead = bufferRead;\n d.Finished = position;\n }\n\n // Run length encoding of code lengths - RFC 1951, page 13.\n\n private void DoLengthPass( int pass )\n {\n LengthPass = pass; \n EncodeLengths( Lit.Count, Lit.Bits, true ); \n EncodeLengths( Dist.Count, Dist.Bits, false );\n }\n\n private void PutLength( int code ) \n { \n if ( LengthPass == 1 ) \n Len.Used[ code ] += 1; \n else \n Output.WriteBits( Len.Bits[ code ], Len.Codes[ code ] ); \n }\n\n private void EncodeLengths( int n, byte [] lengths, bool isLit )\n {\n if ( isLit ) \n { \n PreviousLength = 0; \n ZeroRun = 0; \n Repeat = 0; \n }\n for ( int i = 0; i &lt; n; i += 1 )\n {\n int length = lengths[ i ];\n if ( length == 0 )\n { \n EncodeRepeat(); \n ZeroRun += 1; \n PreviousLength = 0; \n }\n else if ( length == PreviousLength ) \n {\n Repeat += 1;\n }\n else \n { \n EncodeZeroRun(); \n EncodeRepeat(); \n PutLength( length ); \n PreviousLength = length; \n }\n } \n if ( !isLit ) \n { \n EncodeZeroRun(); \n EncodeRepeat();\n }\n }\n\n private void EncodeRepeat()\n {\n while ( Repeat &gt; 0 )\n {\n if ( Repeat &lt; 3 ) \n { \n PutLength( PreviousLength ); \n Repeat -= 1; \n }\n else \n { \n int x = Repeat; \n if ( x &gt; 6 ) x = 6; \n PutLength( 16 ); \n if ( LengthPass == 2 )\n { \n Output.WriteBits( 2, (uint)( x - 3 ) ); \n }\n Repeat -= x; \n }\n }\n }\n\n private void EncodeZeroRun()\n {\n while ( ZeroRun &gt; 0 )\n {\n if ( ZeroRun &lt; 3 ) \n { \n PutLength( 0 ); \n ZeroRun -= 1; \n }\n else if ( ZeroRun &lt; 11 ) \n { \n PutLength( 17 ); \n if ( LengthPass == 2 ) Output.WriteBits( 3, (uint)( ZeroRun - 3 ) ); \n ZeroRun = 0; \n }\n else \n { \n int x = ZeroRun; \n if ( x &gt; 138 ) x = 138; \n PutLength( 18 ); \n if ( LengthPass == 2 ) Output.WriteBits( 7, (uint)( x - 11 ) ); \n ZeroRun -= x; \n }\n }\n }\n } // end class Block\n\n} // end class Deflator\n\n\n// ******************************************************************************\n\nstruct HuffmanCoding // Variable length coding.\n{\n public ushort Count; // Number of symbols.\n public byte [] Bits; // Number of bits used to encode a symbol ( code length ).\n public ushort [] Codes; // Huffman code for a symbol ( bit 0 is most significant ).\n public int [] Used; // Count of how many times a symbol is used in the block being encoded.\n\n private int Limit; // Limit on code length ( 15 or 7 for RFC 1951 ).\n private ushort [] Left, Right; // Tree storage.\n\n public HuffmanCoding( int limit, ushort symbols )\n {\n Limit = limit;\n Count = symbols;\n Bits = new byte[ symbols ];\n Codes = new ushort[ symbols ];\n Used = new int[ symbols ];\n Left = new ushort[ symbols ];\n Right = new ushort[ symbols ];\n }\n\n public int Total()\n {\n int result = 0;\n for ( int i = 0; i &lt; Count; i += 1 ) \n result += Used[i] * Bits[i];\n return result;\n }\n\n public void ComputeCodes()\n {\n // Tree nodes are encoded in a ulong using 16 bits for the id, 8 bits for the tree depth, 32 bits for Used.\n const int IdBits = 16, DepthBits = 8, UsedBits = 32;\n const uint IdMask = ( 1u &lt;&lt; IdBits ) - 1;\n const uint DepthOne = 1u &lt;&lt; IdBits;\n const uint DepthMask = ( ( 1u &lt;&lt; DepthBits ) - 1 ) &lt;&lt; IdBits;\n const ulong UsedMask = ( ( 1ul &lt;&lt; UsedBits ) - 1 ) &lt;&lt; ( IdBits + DepthBits );\n\n // First compute the number of bits to encode each symbol (Bits).\n UlongHeap heap = new UlongHeap( Count );\n\n for ( ushort i = 0; i &lt; Count; i += 1 )\n {\n int used = Used[ i ];\n if ( used &gt; 0 )\n heap.Insert( ( (ulong)used &lt;&lt; ( IdBits + DepthBits ) ) | i );\n }\n\n int maxBits = 0;\n\n if ( heap.Count == 1 )\n { \n GetBits( unchecked( (ushort) heap.Remove() ), 1 );\n maxBits = 1;\n }\n else if ( heap.Count &gt; 1 ) unchecked\n {\n ulong treeNode = Count;\n\n do // Keep pairing the lowest frequency TreeNodes.\n {\n ulong left = heap.Remove(); \n Left[ treeNode - Count ] = (ushort) left;\n\n ulong right = heap.Remove(); \n Right[ treeNode - Count ] = (ushort) right;\n\n // Extract depth of left and right nodes ( still shifted though ).\n uint depthLeft = (uint)left &amp; DepthMask, depthRight = (uint)right &amp; DepthMask; \n\n // New node depth is 1 + larger of depthLeft and depthRight.\n uint depth = ( depthLeft &gt; depthRight ? depthLeft : depthRight ) + DepthOne;\n\n heap.Insert( ( ( left + right ) &amp; UsedMask ) | depth | treeNode );\n\n treeNode += 1;\n } while ( heap.Count &gt; 1 );\n\n uint root = ( (uint) heap.Remove() ) &amp; ( DepthMask | IdMask );\n maxBits = (int)( root &gt;&gt; IdBits );\n if ( maxBits &lt;= Limit )\n GetBits( (ushort)root, 0 );\n else\n {\n maxBits = Limit;\n PackageMerge();\n }\n }\n\n // Computation of code lengths (Bits) is complete.\n // Now compute Codes, code below is from RFC 1951 page 7.\n\n int [] bl_count = new int[ maxBits + 1 ];\n for ( int i = 0; i &lt; Count; i += 1 ) \n bl_count[ Bits[ i ] ] += 1; \n\n int [] next_code = new int[ maxBits + 1 ];\n int code = 0; bl_count[ 0 ] = 0;\n for ( int i = 0; i &lt; maxBits; i += 1 ) \n {\n code = ( code + bl_count[ i ] ) &lt;&lt; 1;\n next_code[ i + 1 ] = code;\n }\n\n for ( int i = 0; i &lt; Count; i += 1 ) \n {\n int length = Bits[ i ];\n if ( length != 0 ) \n {\n Codes[ i ] = (ushort) Reverse( next_code[ length ], length );\n next_code[ length ] += 1;\n }\n }\n\n // Reduce Count if there are unused trailing symbols.\n while ( Count &gt; 0 &amp;&amp; Bits[ Count - 1 ] == 0 ) Count -= 1;\n\n // System.Console.WriteLine( \"HuffmanCoding.ComputeCodes\" );\n // for ( int i = 0; i &lt; Count; i += 1 ) if ( Bits[ i ] &gt; 0 )\n // System.Console.WriteLine( \"symbol=\" + i + \" len=\" + Bits[ i ] + \" code=\" + Codes[ i ].ToString(\"X\") + \" used=\" + Used[ i ] );\n\n }\n\n private void GetBits( ushort treeNode, int length )\n {\n if ( treeNode &lt; Count ) // treeNode is a leaf.\n {\n Bits[ treeNode ] = (byte)length;\n }\n else \n {\n treeNode -= Count;\n length += 1;\n GetBits( Left[ treeNode ], length );\n GetBits( Right[ treeNode ], length );\n }\n }\n\n private static int Reverse( int x, int bits )\n // Reverse a string of bits ( ready to be output as Huffman code ).\n { \n int result = 0; \n for ( int i = 0; i &lt; bits; i += 1 ) \n {\n result &lt;&lt;= 1; \n result |= x &amp; 1; \n x &gt;&gt;= 1; \n } \n return result; \n } \n\n // PackageMerge is used if the Limit code length limit is exceeded.\n // The result is technically not a Huffman code in this case ( due to the imposed limit ).\n // See https://en.wikipedia.org/wiki/Package-merge_algorithm for a description of the algorithm.\n\n private void PackageMerge()\n {\n // Tree nodes are encoded in a ulong using 16 bits for the id, 32 bits for Used.\n const int IdBits = 16, UsedBits = 32;\n const ulong UsedMask = ( ( 1ul &lt;&lt; UsedBits ) - 1 ) &lt;&lt; IdBits;\n\n Left = new ushort[ Count * Limit ];\n Right = new ushort[ Count * Limit ];\n\n // First sort using Heapsort.\n UlongHeap heap = new UlongHeap( Count );\n for ( uint i = 0; i &lt; Count; i += 1 ) \n {\n if ( Used[ i ] != 0 ) \n {\n heap.Insert( (ulong)Used[ i ] &lt;&lt; IdBits | i );\n }\n }\n int n = heap.Count; \n ulong [] sorted = new ulong[ n ];\n for ( int i = 0; i &lt; n; i += 1 ) sorted[ i ] = heap.Remove();\n\n // Sort is complete.\n\n // List class is from System.Collections.Generic.\n List&lt;ulong&gt; merged = new List&lt;ulong&gt;( Count ), \n next = new List&lt;ulong&gt;( Count );\n\n uint package = (uint) Count; // Allocator for package ids.\n\n for ( int i = 0; i &lt; Limit; i += 1 ) \n {\n int j = 0, k = 0; // Indexes into the lists being merged.\n next.Clear();\n for ( int total = ( sorted.Length + merged.Count ) / 2; total &gt; 0; total -= 1 ) \n {\n ulong left, right; // The tree nodes to be packaged.\n\n if ( k &lt; merged.Count )\n {\n left = merged[ k ];\n if ( j &lt; sorted.Length )\n {\n ulong sj = sorted[ j ];\n if ( left &lt; sj ) k += 1;\n else { left = sj; j += 1; }\n }\n else k += 1;\n }\n else left = sorted[ j++ ];\n\n if ( k &lt; merged.Count )\n {\n right = merged[ k ];\n if ( j &lt; sorted.Length )\n {\n ulong sj = sorted[ j ];\n if ( right &lt; sj ) k += 1;\n else { right = sj; j += 1; }\n }\n else k += 1;\n }\n else right = sorted[ j++ ];\n\n Left[ package ] = unchecked( (ushort) left );\n Right[ package ] = unchecked( (ushort) right );\n next.Add( ( left + right ) &amp; UsedMask | package ); \n package += 1;\n }\n\n // Swap merged and next.\n List&lt;ulong&gt; tmp = merged; merged = next; next = tmp;\n }\n\n for ( int i = 0; i &lt; merged.Count; i += 1 )\n MergeGetBits( unchecked( (ushort) merged[i] ) );\n }\n\n private void MergeGetBits( ushort node )\n {\n if ( node &lt; Count )\n Bits[ node ] += 1;\n else\n {\n MergeGetBits( Left[ node ] );\n MergeGetBits( Right[ node ] );\n }\n }\n\n} // end struct HuffmanCoding\n\n\n// ******************************************************************************\n\n\nstruct UlongHeap // An array organised so the smallest element can be efficiently removed.\n{\n public int Count { get{ return _Count; } }\n private int _Count;\n private ulong [] Array;\n\n public UlongHeap ( int capacity )\n {\n _Count = 0;\n Array = new ulong[ capacity ];\n }\n\n public void Insert( ulong e )\n {\n int j = _Count++;\n while ( j &gt; 0 )\n {\n int p = ( j - 1 ) &gt;&gt; 1; // Index of parent.\n ulong pe = Array[ p ];\n if ( e &gt;= pe ) break;\n Array[ j ] = pe; // Demote parent.\n j = p;\n } \n Array[ j ] = e;\n }\n\n public ulong Remove() // Returns the smallest element.\n {\n ulong result = Array[ 0 ];\n _Count -= 1;\n ulong e = Array[ _Count ];\n int j = 0;\n while ( true )\n {\n int c = ( j + j ) + 1; if ( c &gt;= _Count ) break;\n ulong ce = Array[ c ];\n if ( c + 1 &lt; _Count )\n {\n ulong ce2 = Array[ c + 1 ];\n if ( ce2 &lt; ce ) { c += 1; ce = ce2; }\n } \n if ( ce &gt;= e ) break;\n Array[ j ] = ce; j = c; \n }\n Array[ j ] = e;\n return result;\n }\n\n} // end struct UlongHeap\n\n\n// ******************************************************************************\n\n\nabstract class OutBitStream\n{\n public void WriteBits( int n, ulong value )\n // Write first n ( 0 &lt;= n &lt;= 64 ) bits of value to stream, least significant bit is written first.\n // Unused bits of value must be zero, i.e. value must be in range 0 .. 2^n-1.\n {\n if ( n + BitsInWord &gt;= WordCapacity )\n {\n Save( Word | value &lt;&lt; BitsInWord );\n int space = WordCapacity - BitsInWord;\n value &gt;&gt;= space;\n n -= space;\n Word = 0;\n BitsInWord = 0;\n }\n Word |= value &lt;&lt; BitsInWord;\n BitsInWord += n;\n }\n\n public void Pad( int n )\n // Pad with zero bits to n bit boundary where n is power of 2 in range 1,2,4..64, typically n=8.\n {\n int w = BitsInWord % n; \n if ( w &gt; 0 ) WriteBits( n - w, 0 );\n }\n\n public abstract void Save( ulong word );\n\n protected const int WordSize = sizeof(ulong); // Size of Word in bytes.\n protected const int WordCapacity = WordSize * 8; // Number of bits that can be stored Word\n\n protected ulong Word; // Bits are first stored in Word, when full, Word is saved.\n protected int BitsInWord; // Number of bits currently stored in Word.\n}\n\n\n// ******************************************************************************\n\n\nsealed class MemoryBitStream : OutBitStream\n{\n // ByteSize returns the current size in bytes.\n // CopyTo copies the contents to a Stream.\n // ToArray returns the contents as an array of bytes.\n\n public int ByteSize() \n {\n return CompleteChunks * Chunk.Capacity + BytesInCurrentChunk + ( BitsInWord + 7 ) / 8;\n }\n\n public void CopyTo( System.IO.Stream s ) \n {\n byte [] buffer = new byte [ WordSize ];\n for ( Chunk c = FirstChunk; c != null; c = c.Next )\n { \n int n = ( c == CurrentChunk ) ? BytesInCurrentChunk : Chunk.Capacity;\n s.Write( c.Bytes, 0, n ); \n }\n\n int biw = BitsInWord;\n ulong word = Word;\n while ( biw &gt; 0 )\n {\n s.WriteByte( unchecked( (byte) word ) );\n word &gt;&gt;= 8;\n biw -= 8;\n }\n }\n\n public byte [] ToArray()\n {\n byte [] buffer = new byte[ ByteSize() ];\n int i = 0;\n\n for ( Chunk c = FirstChunk; c != null; c = c.Next )\n { \n int n = ( c == CurrentChunk ) ? BytesInCurrentChunk : Chunk.Capacity;\n System.Array.Copy( c.Bytes, 0, buffer, i, n ); \n i += n;\n }\n\n int biw = BitsInWord;\n ulong word = Word;\n while ( biw &gt; 0 )\n {\n buffer[ i++ ] = unchecked( (byte) word );\n word &gt;&gt;= 8;\n biw -= 8;\n }\n return buffer;\n }\n\n public MemoryBitStream()\n {\n FirstChunk = new Chunk();\n CurrentChunk = FirstChunk;\n }\n\n public override void Save( ulong w )\n {\n if ( BytesInCurrentChunk == Chunk.Capacity )\n {\n Chunk nc = new Chunk();\n CurrentChunk.Next = nc;\n CurrentChunk = nc;\n CompleteChunks += 1;\n BytesInCurrentChunk = 0;\n }\n int i = BytesInCurrentChunk;\n byte [] bytes = CurrentChunk.Bytes;\n unchecked\n {\n bytes[ i++ ] = (byte) w; w &gt;&gt;= 8;\n bytes[ i++ ] = (byte) w; w &gt;&gt;= 8;\n bytes[ i++ ] = (byte) w; w &gt;&gt;= 8;\n bytes[ i++ ] = (byte) w; w &gt;&gt;= 8;\n bytes[ i++ ] = (byte) w; w &gt;&gt;= 8;\n bytes[ i++ ] = (byte) w; w &gt;&gt;= 8;\n bytes[ i++ ] = (byte) w; w &gt;&gt;= 8;\n bytes[ i++ ] = (byte) w;\n }\n BytesInCurrentChunk = i;\n }\n\n private int BytesInCurrentChunk; // Number of bytes stored in CurrentChunk.\n private int CompleteChunks; // Number of complete Chunks.\n private Chunk FirstChunk, CurrentChunk;\n\n private class Chunk\n {\n public const int Capacity = 0x800;\n public byte [] Bytes = new byte[ Capacity ];\n public Chunk Next;\n }\n\n} // end class MemoryBitStream\n\n} // namespace\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T23:20:21.190", "Id": "212351", "ParentId": "211912", "Score": "0" } }, { "body": "<p>I found a new trick which speeds up the LZ77 search. </p>\n\n<p>After finding a match, it's possible to check the hash table for the last 3 bytes of the next largest possible match. If the hash entry is zero ( or earlier than the 32k window ), the search can be terminated. Here's the affected code, the new function is <code>MatchPossible</code>.</p>\n\n<pre><code> private int BestMatch( byte [] input, int position, out int distance, int oldPosition, int [] link )\n { \n int avail = input.Length - position;\n if ( avail &gt; MaxMatch ) avail = MaxMatch;\n\n int bestMatch = 0, bestDistance = 0;\n\n while ( true )\n { \n if ( input[ position + bestMatch ] == input[ oldPosition + bestMatch ] )\n {\n int match = 0; \n while ( match &lt; avail &amp;&amp; input[ position + match ] == input[ oldPosition + match ] ) \n {\n match += 1;\n }\n if ( match &gt; bestMatch )\n {\n bestMatch = match;\n bestDistance = position - oldPosition;\n if ( bestMatch == avail ) break;\n if ( ! MatchPossible( position, bestMatch+1 ) ) break;\n }\n }\n oldPosition = link[ oldPosition ];\n if ( position &gt;= oldPosition ) break;\n oldPosition -= EncodePosition;\n }\n distance = bestDistance;\n return bestMatch;\n }\n\n // MatchPossible is used to try and shorten the BestMatch search by checking whether \n // there is a hash entry for the last 3 bytes of the next longest possible match.\n\n private bool MatchPossible( int position, int matchLength )\n {\n int end = position + matchLength - 3;\n uint hash = ( (uint)Input[ end+0 ] &lt;&lt; HashShift ) + Input[ end+1 ];\n hash = ( ( hash &lt;&lt; HashShift ) + Input[ end + 2 ] ) &amp; HashMask; \n int hashEntry = HashTable[ hash ];\n if ( end &gt;= hashEntry ) return false;\n return true;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T17:50:23.010", "Id": "212478", "ParentId": "211912", "Score": "0" } }, { "body": "<p>Not looked in detail at the interesting stuff, but a couple of tiny things jumped out at me:</p>\n\n<h1><code>CalcBufferSize</code></h1>\n\n<p>This method looks wrong:</p>\n\n<pre><code>public static int CalcBufferSize( int n, int max )\n// Calculates a power of 2 &gt;= n, but not more than max.\n{\n if ( n &gt;= max ) return max;\n int result = 1;\n while ( result &lt; n ) result = result &lt;&lt; 1;\n return result;\n}\n</code></pre>\n\n<p>The comment (or inline documentation) should probably explain here that you assume <code>max</code> is a power of two (because it doesn't work otherwise); this might cause confusion in the future otherwise. I see that you've made this method private in later revisions, so that's good.</p>\n\n<h1>Heap Sort</h1>\n\n<p>I think your heap-sort in <code>PackageMerge</code> can be better. Repeated insertion is <code>O(n log(n))</code>, but you can build a heap from a known set of elements in linear time (<a href=\"https://en.wikipedia.org/wiki/Binary_heap#Building_a_heap\" rel=\"nofollow noreferrer\">lazy Wikipedia reference</a>), which is an option there (and I'm assuming you've benchmarked your own heap-sort against <code>Array.Sort</code> and such if this matters). I'd also feel compelled to add parentheses into <code>(ulong)Used[ i ] &lt;&lt; IdBits | i )</code>, since both <code>&lt;&lt;</code> and <code>|</code> are uncommon operations and the order of operations may not be clear.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T02:18:50.790", "Id": "411036", "Score": "0", "body": "Yes, it was a mistake that CalcBufferSize was public. On the sort, I used heapsort as I had it handy, I didn't know about Array.Sort ( which apparently uses heapsort or quicksort ). I will try that. I have done the linear heap build, which I didn't know about either." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T20:15:53.487", "Id": "212482", "ParentId": "211912", "Score": "1" } } ]
{ "AcceptedAnswerId": "212482", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T13:04:47.227", "Id": "211912", "Score": "7", "Tags": [ "c#", "compression", "pdf" ], "Title": "Improved RFC 1951 Deflate compression" }
211912
<p>I'm writing a program that adds all network interfaces with multiple parameters to a list. </p> <p>I have written the following code, which should work out of the box on any Linux system with Python and ethtool installed:</p> <pre><code>import imp import os import subprocess import re from enum import Enum class interface_type(Enum): OPTIC = 1 TWISTED_PAIR = 2 class NetworkInterface: def set_indentifier(self, id): self.id = id def set_mac_address(self, mac): self.mac = mac def set_interface_type(self, interface_type): self.interface_type = interface_type def findNetworkInterfaces(ignoredInterface): filteredList = netifaces.interfaces() network_interfaces = [] for interface in filteredList: for regex in ignoredInterface: if re.search(regex, interface): break else: nwi = NetworkInterface() nwi.set_indentifier(interface) nwi.set_mac_address(setMAC(interface)) nwi.set_interface_type(setInterfaceType(interface)) network_interfaces.append(nwi) filteredList.remove(interface) break return network_interfaces def setMAC(identifier): addrs = netifaces.ifaddresses(identifier) mac_address = addrs[netifaces.AF_LINK][0].get("addr") return mac_address def setInterfaceType(identifier): bashCommand1 = "ethtool " + identifier bashCommand2 = "grep ports" try: process1 = subprocess.Popen(bashCommand1.split(), stdout=subprocess.PIPE) process2 = subprocess.Popen(bashCommand2.split(), stdin=process1.stdout, stdout=subprocess.PIPE) output, error = process2.communicate() except: print ("Error determining interface type: " + error + "\n") print ("Interface will be treated as Optical \n") if "TP" in output: return interface_type.TWISTED_PAIR else: return interface_type.OPTIC if __name__ == "__main__": ignored_interface = ["lo", "wlp2s0"] try: imp.find_module("netifaces") netifaces_status = True import netifaces except ImportError as e: print ("netifaces not found: " + str(e)) os.sys.exit(-1) network_identifiers = findNetworkInterfaces(ignored_interface) #print network_identifiers for iface in network_identifiers: print iface.id print iface.mac print iface.interface_type </code></pre> <p>I'm mainly concerned with the <code>findNetworkInterfaces</code> function, as I feel I'm doing this in a very ineffecient way (basically copying the list and removing interfaces as to not have doubles). In this special case, <strong>I'm not concerned with PEP8</strong> - this is something I'll do later. Any other suggestions to improve the code are very welcome.</p>
[]
[ { "body": "<ul>\n<li><p>Start writing in <a href=\"/questions/tagged/python3.x\" class=\"post-tag\" title=\"show questions tagged &#39;python3.x&#39;\" rel=\"tag\">python3.x</a> ;)</p>\n\n<p>End of Life for <a href=\"/questions/tagged/python2.x\" class=\"post-tag\" title=\"show questions tagged &#39;python2.x&#39;\" rel=\"tag\">python2.x</a> will happen pretty soon <a href=\"https://pythonclock.org/\" rel=\"nofollow noreferrer\">1</a></p></li>\n<li><p>One regex to rule them all</p>\n\n<p>Instead of looping over a the list to create a regex, </p>\n\n<p>you could use the <code>|</code> char which will work as an <code>or</code> so it can handle multiple outputs</p>\n\n<p><code>REGEX_FILTER = re.conmpile('lo|wlp2s0')</code></p></li>\n<li><p>If you only need the parameters, a simple namedtuple will suffice</p>\n\n<p>You could create a <code>namedtuple</code> that will get rid of the empty looking class</p></li>\n<li><p>IMHO setting the variables outside of the init is bad style</p>\n\n<p>I would get the different variables needed before, and only then create the <code>NetworkInterface</code> object.</p></li>\n</ul>\n\n<p><em>Note I will not review getting the interface type, since I am nowhere near a linux atm</em></p>\n\n<h1>Code</h1>\n\n<pre><code>from collections import namedtuple\nimport re\n\nimport netifaces\n\nFILTER_REGEX = re.compile(r'lo|wlp2s0')\nNetworkInterface = namedtuple('NetworkInterface', ['iface', 'mac', 'type'])\n\ndef get_mac(iface):\n addresses = netifaces.ifaddresses(iface)\n return addresses[netifaces.AF_LINK][0].get(\"addr\")\n\ndef get_type(iface):\n \"\"\"Just return TP for testing\"\"\"\n return \"TP\"\n\ndef find_network_interfaces():\n for iface in netifaces.interfaces():\n if FILTER_REGEX.search(iface):\n continue\n yield NetworkInterface(iface, get_mac(iface), get_type(iface))\n\nif __name__ == '__main__':\n for nwi in find_network_interfaces():\n print(nwi.iface)\n print(nwi.mac)\n print(nwi.type)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T18:58:17.123", "Id": "409821", "Score": "1", "body": "Since you saved the compiled regexes to a variable, you could do `FILTER_REGEX.search(iface)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T16:20:48.583", "Id": "211919", "ParentId": "211915", "Score": "5" } } ]
{ "AcceptedAnswerId": "211919", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T15:31:26.930", "Id": "211915", "Score": "4", "Tags": [ "python", "python-2.x", "linux", "networking" ], "Title": "Looping through multiple regex efficiently" }
211915
<p>I am rendering a list from an array of objects. I want to check the correctness of the array before rendering. For that I am using typeof and null.</p> <p>In real situation the list comes from the API. </p> <p>Is it the correct way? and is there any better way to do it?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const activeEvents = [{ id: '1', title: 'event 1' }, { id: '2', title: 'event 2' }] function App() { return ( &lt;div &gt; &lt;h4&gt; List &lt;/h4&gt; { typeof activeEvents === 'object' &amp;&amp; activeEvents !== null &amp;&amp; activeEvents.map(event =&gt; ( &lt;li key = { event.id } value = { event.id } &gt; { event.title } &lt;/li&gt; ))} &lt;/div&gt; ); } ReactDOM.render( &lt; App / &gt; , document.getElementById('root') );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"&gt;&lt;/script&gt; &lt;div id="root" /&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p><code>typeof activeEvents === 'object' &amp;&amp; activeEvents !== null</code> can be <code>true</code> for both <code>Array</code> and <code>Object</code> :</p>\n\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 array = [];\nconst obj = {};\n\nconsole.log(typeof array === 'object' &amp;&amp; array !== null)\nconsole.log(typeof obj === 'object' &amp;&amp; obj !== null)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>you can use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray\" rel=\"nofollow noreferrer\">Array.isArray</a></p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const activeEvents = [{\n id: '1',\n title: 'event 1'\n}, {\n id: '2',\n title: 'event 2'\n}]\n\nfunction App() {\n return ( \n &lt;div &gt;\n &lt;h4&gt; List &lt;/h4&gt; \n { Array.isArray(activeEvents) &amp;&amp; \n activeEvents.map(event =&gt; ( \n &lt;li key = { event.id } value = { event.id } &gt; { event.title } &lt;/li&gt;\n ))\n } \n &lt;/div&gt;\n );\n}\n\nReactDOM.render( &lt;\n App / &gt; ,\n document.getElementById('root')\n);</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js\"&gt;&lt;/script&gt;\n\n&lt;div id=\"root\" /&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": "2019-01-21T16:29:06.877", "Id": "211920", "ParentId": "211917", "Score": "4" } } ]
{ "AcceptedAnswerId": "211920", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T15:47:10.460", "Id": "211917", "Score": "2", "Tags": [ "javascript", "react.js", "jsx" ], "Title": "Validating Array before rendering" }
211917
<p>I recently wrote a full implementation of a <code>range()</code> operator with floating point values in Python, and I'm not sure if I've followed the standard pythonic patterns. From what I can tell, it works. I've written a few test cases, but they don't cover <em>everything</em> yet. I've also published this in a <a href="https://gist.github.com/AndroxxTraxxon/eeb788811a8b481326cd5f6a8cd2e090" rel="nofollow noreferrer">gist</a> on github as well</p> <p>This was written in Python 3.6.4, though I think it should work in most 3.x flavors. Here's <code>FloatRange.py</code></p> <pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*- from numbers import Real class FloatRange: """ step/precision used as the tolerance in __contains__ method. Defaults to 1/(10**10). This is used to attempt to mitigate some of the floating point rounding error, but scales with the step size so that smaller step sizes are not susceptible to catching more than they ought. Basically, there's a 2 in &lt;precision&gt; chance that a number will randomly """ _precision = 10**10 _start, _step = 0, 1 # stop must be defined by user. No use putting it in here. """ Here we set up our constraints as the user passes their values: - You can pass the values as follows: - stop (start defaults to 0, step defaults to 1) - start, stop (step again defaults to 1) - start, stop, step - start, step, and stop must be Real numbers - The step must be non-zero - The step must be in the same direction as the difference between stop and start """ def __init__(self, *args, **kwargs): self.start = self._start self.step = self._step self.precision = self._precision self.counter = 0 if len(args) == 1: (self.stop, ) = args # FloatRange elif len(args) == 2: (self.start, self.stop) = args elif len(args) == 3: (self.start, self.stop, self.step) = args else: raise TypeError("FloatRange accepts 1, 2, or 3 arguments. ({0} given)".format(len(args))) for num in self.start, self.step, self.stop: if not isinstance(num, Real): raise TypeError("FloatRange only accepts Real number arguments. ({0} : {1} given)".format(type(num), str(num))) if self.step == 0: raise ValueError("FloatRange step cannot be 0") if (self.stop-self.start)/self.step &lt; 0: raise ValueError("FloatRange value must be in the same direction as the start-&gt;stop") self.set_precision(self._precision) # x in FloatRange will return True for values within 0.1% of step size if len(kwargs) &gt; 0: for key, value in kwargs.items(): if key == "precision": if value &lt; 0: raise ValueError("FloatRange precision must be positive") self.tolerance = self.step/self.precision else: raise ValueError("Unknown kwargs key: {0}".format(key)) """ Returns the next value in the iterator, or it stops the iteration and resets. """ def __next__(self): output = self.start + (self.counter * self.step) if ((self.step &gt; 0 and output &gt;= self.stop) or (self.step &lt; 0 and output &lt;= self.stop)) : self.counter = 0 raise StopIteration self.counter += 1 return output """ The class already implements __next__(), so it is its own iterable """ def __iter__(self): return self def set_precision(self, precision=None): if precision is None: self.precision = self._precision elif isinstance(precision, Real): if precision &lt; 0: raise ValueError("FloatRange precision cannot be a negative number.") self.precision = precision else: raise ValueError("FloatRange precision must be a Real number.") self.tolerance = abs(self.step/self.precision) """ len(my_FloatRange) """ def __len__(self): # we have to do this minute addition here so that floating point rounding does not fail. return int((self.stop - self.start + self.step/10**13) / self.step) """ x in my_FloatRange Evaluates whether a given number is contained in the range, in constant time. Non-exact values will return True if they are within the provided tolerance. Use set_precision(precision) to define the precision:step ratio (the tolerance) """ def __contains__(self, item): diff = (item - self.start) % self.step # if we're dealing with exact cases (not recommended, but okay.) if (self.step &gt; 0 and item &gt;= self.start-self.tolerance and item &lt; self.stop): return (min(diff, self.step-diff) &lt; self.tolerance) elif (self.step &lt; 0 and item &lt;= self.start+self.tolerance and item &gt; self.stop ): return (min(abs(diff), abs(self.step-diff)) &lt; self.tolerance) return False def __str__(self): return self.__repr__() def __repr__(self): ext = "" if not self.step == 1: ext += ", {0}".format(self.step) if self.precision != self._precision: ext += ", precision={0}, tolerance={1}".format( self.precision, self.tolerance ) return "FloatRange({0}, {1}{2})".format( self.start, self.stop, ext ) </code></pre> <p>Here are my current preliminary test cases<code>test_FloatRange.py</code></p> <pre class="lang-py prettyprint-override"><code># -*- coding: utf-8 -*- import unittest from FloatRange import FloatRange class TestCase_FloatRange(unittest.TestCase): def test_compare_basic(self, start=None, stop=1, step=None, verbose=False): my_range = None my_FloatRange = None if step is None: if start is None: my_range = range(stop) my_FloatRange = FloatRange(stop) else: my_range = range(start, stop) my_FloatRange = FloatRange(start, stop) else: my_range = range(start, stop, step) my_FloatRange = FloatRange(start, stop, step) if verbose: print("Validating:[{0}] == [{1}]".format( my_range, my_FloatRange)) for x,y in zip(my_range, my_FloatRange): try: self.assertEqual(x,y) except: print("{0} and {1} failed to produce the same values.".format( my_range, my_FloatRange )) raise def test_compare_range_functionality(self): _length = 10 # arbitrary number for adequate length _step = 2 _start = 5 self.test_compare_basic(stop = _length) self.test_compare_basic(start =_start, stop = _length) self.test_compare_basic(start=_start, stop= _start+_length) self.test_compare_basic(start=_start, stop= _start+_length*_step, step= _step) def test_correct_length(self): for _divisor in range(1, 100): for _step_base in range(1, 100): for _length in range(1, 100): _step = _step_base / _divisor _start = 1 / _divisor + 1 _stop = _start + _length*_step my_FloatRange = FloatRange(_start, _stop, _step) try: self.assertEqual(len(my_FloatRange), _length) except Exception: print("Length test failed with parameters:\n\tstart:{0}\n\tstop :{1}\n\tstep: {2}\n\tvalue: {2}".format( _start, _stop, _step, len(my_FloatRange) )) raise def test_value_set(self, subject=FloatRange(1), values=[0], verbose=False): if verbose: print("Validating {0} produces {1}".format(subject, values)) try: self.assertEqual(len(subject), len(values)) except: print("{0} and {1} do not have the same length!".format(subject, values)) raise for f, v in zip(subject, values): try: self.assertAlmostEqual(f, v) # floating point rounding doesn't allow for exact equality. except: print("{0} does not produce {1}".format(subject, values)) raise def test_values(self): self.test_value_set(FloatRange(0, 10, 1/3), [(x/3) for x in range(30)]) self.test_value_set(FloatRange(5, 15, 1/3), [(5+(x/3)) for x in range(30)]) self.test_value_set(FloatRange(1, 11, 1/7), [(1+(x/7)) for x in range(70)]) self.test_value_set(FloatRange(8, 18, 1/7), [(8+(x/7)) for x in range(70)]) if __name__ == '__main__': unittest.main() </code></pre> <p>My initial test cases pass, and it seems to work alright. Is there anything else that I should be doing? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T22:42:37.310", "Id": "409859", "Score": "0", "body": "Why do you use `_start` and `_step` names instead of just `start` and `step` for class attributes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T14:51:39.667", "Id": "409932", "Score": "1", "body": "I’m surprised by the \"(stop - start) and step must have the same sign\" condition. `list(range(0, 10, -1))` is the empty list, not an error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T15:00:42.330", "Id": "409935", "Score": "0", "body": "hmmm... I suppose that could be fixed with a similar condition in the __next__ implementation" } ]
[ { "body": "<p>You probably should replace <code>**kwargs</code> in <code>__init__</code> with <code>precision=10**10</code>:</p>\n\n<pre><code>def __init__(self, *args, precision=10**10):\n self.precision = precision\n self.set_precision(precision) # not self._precision\n</code></pre>\n\n<p>and remove last huge block of <code>__init__</code> that validates <code>kwargs</code></p>\n\n<p>The way you implement <code>__iter__</code> has following disadvantage:</p>\n\n<pre><code>r = FloatRange(1., 2., 0.3)\niterator1 = iter(r)\niterator2 = iter(r)\nassert next(iterator1) == 1.0\nassert next(iterator2) == 1.3\niterator3 = iter(r)\nassert next(iterator3) == 1.6\n</code></pre>\n\n<p>If you run the same code with built-in python <code>range</code> iterator2 and iterator3 will produce original sequence, not empty. You probably should remove <code>__next__</code> method and return generator in <code>__iter__</code>:</p>\n\n<pre><code>def __iter__(self):\n output = self.start\n while (self.step &gt; 0) == (output &lt; self.stop) and output != self.stop:\n yield output\n output += self.step\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T13:57:38.210", "Id": "409923", "Score": "0", "body": "What version of Python are you using? when I ran your code, it failed on `assert list(iterator2) == [] --- AssertionError` That is where it is supposed to fail, yes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T17:45:59.683", "Id": "410639", "Score": "0", "body": "It's my mistake. I wanted to point out that consuming one iterators have side effect on other iterator because all iterators are the same object. The assertion error happen because consuming iterator1 resets its state so it is possible to iterate with it again. Updated the answer" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T22:40:37.473", "Id": "211951", "ParentId": "211918", "Score": "0" } }, { "body": "<p>Let's start with comments about the code you've submitted, before we discuss some more important overlying concepts and design decisions.</p>\n\n<p>Good</p>\n\n<ul>\n<li>Docstrings for each method (some could be more helpful though, like <code>__len__</code>)</li>\n<li>Some comments for perhaps unclear lines</li>\n<li>Python 3 style classes (didn't inherit from <code>object</code>)</li>\n<li>You have unit tests!</li>\n<li>Good use of <code>ValueError</code></li>\n</ul>\n\n<p>Improvements</p>\n\n<ul>\n<li>You don't need <code># -*- coding: utf-8 -*-</code> with Python 3</li>\n<li>You formatting is pretty inconsistent. Try <a href=\"https://pypi.org/project/pycodestyle/\" rel=\"nofollow noreferrer\">PEP8</a> (it's the standard formatting that most projects adhere to)</li>\n<li>You seem to prefix a lot of variables with <code>_</code>. It seems like you may be confused about kwargs. If you do <code>foo(bar=1)</code>, <code>bar</code> is not a variable. So if you had <code>bar = 1</code>, it's perfectly legal (and encouraged) to do <code>foo(bar=bar)</code>. Although, consider if it really is unclear what the param means. Perhaps a positional arg works just fine. If that's not the case, we basically exclusively use <code>_</code> for private instance properties (like <code>self._start</code>)</li>\n<li>Your <code>test_compare_basic</code> isn't actually a test case. Methods starting with <code>test_</code> should exercise a specific test case or group of test cases. <code>test_compare_basic</code> is actually a generic way of testing any range. Writing it was a fantastic idea, because it makes writing the later tests much more succinct and clear. However, naming it <code>test_</code> means that it is run by the test harness (and it shouldn't be run alone). I usually call these functions <code>assert*</code> to match the unittest framework (camelCase unfortunately, as this is what <code>unittest</code> does, but you could break this if you wanted). Eg. name it <code>assertFloatRangeCorrect</code>. Then your tests look like:</li>\n</ul>\n\n\n\n<pre><code> def test_simple_float_ranges(self):\n # These reads much more like sentences now...\n self.assertFloatRangeCorrect(0.5, 5.0, 0.5)\n self.assertFloatRangeCorrect(1, 2, 0.25)\n</code></pre>\n\n<ul>\n<li>I see you have <code>try</code>/<code>except</code> in your tests to print a message. You shouldn't be doing this. For one, the message won't be grouped with the error (or it's stack trace). You can just pass the extra optional <code>msg</code> argument to <code>assertEqual</code>: <code>self.assertEqual(len(actual), len(expected), f'len({actual}) != len({expected})')</code> (notice my use of f-strings, they're definitely cleaner here). By doing this, your tests become a lot shorter and you avoid the <code>try</code>/<code>except</code>/<code>raise</code> dance.</li>\n<li>For testing exact equality, instead of <code>zip</code>ing two iterables just use <code>self.assertEqual(iterable_a, iterable_b)</code>. This will also produce a nice error message automatically.</li>\n<li>Your check against <code>Real</code> is strange (more on this later)</li>\n<li>What is going on with the <code>_precision</code>, <code>_start</code>, and <code>_step</code>? You shouldn't have those.</li>\n<li>Don't use <code>*args</code> like this in <code>__init__</code>. Use arg defaults. Eg. <code>def __init__(self, start=0, stop=1, step=1)</code> (I know this doesn't work perfectly with your current argument scheme, but later I'll argue you should change it)</li>\n<li>In tuple unpacking (<code>(self.stop, ) = args</code>) you don't need the parens'</li>\n<li>Your <code>__iter__</code> docstring should be a comment. It doesn't explain to a user of <code>FloatRange</code> how to use the class. But you can eliminate it, because that's obvious from the fact you <code>return self</code>.</li>\n<li>Having the range be it's own iterator is strange (and uncommon). And I'll argue against it later.</li>\n<li>Minor nit but in <code>__str__</code> use <code>repr(self)</code>. We usually don't call dunder methods (with the prominent exception being <code>super().__init__(...)</code>).</li>\n<li>In <code>__repr__</code> use <a href=\"https://cito.github.io/blog/f-strings/\" rel=\"nofollow noreferrer\">f-strings</a>. They much easier to construct and they give a better idea of the output format.</li>\n<li>You should put <code>FloatRange</code> in <code>float_range.py</code> instead of <code>FloatRange.py</code></li>\n<li>Comparing floats with <code>0</code> is usually not what you want. Rarely will the result of arithmetic be exactly 0. You want <code>math.isclose</code></li>\n</ul>\n\n<p>Now, let's talk about the big concept here. Python's builtin range doesn't support <code>float</code>s as you likely know. There is good reason for this. Floating point math does not always work as pen and paper decimal math due to representation issues. A similar problem would be adding 1/3 as a decimal by hand 3 times. You expect 1, but since you only have a finite number of decimals, it won't be exactly 1 (it'll be <code>0.99...</code>).</p>\n\n<p>What does this have to do with your float range? It poses two interesting problems for the user of <code>FloatRange</code> if they're used to <code>range()</code>.</p>\n\n<p>The upper bound may not produce the range that you expect due to representation errors alluded to above. Where we can know that <code>range(5)</code> will always have 5 numbers, we can't really be so sure about the length of <code>range(0, 10, 0.1)</code> (that is, unless the start, stop, and step are <strong>exactly</strong> 0, 10, and 0,1--floats are deterministic given the same operations in the same order) because of floating point inaccuracies. Sure, we can divide like you did. However, with your precision factor, I suspect that length won't always be right. The trouble here is we need to decide what <code>stop</code> means. For <code>range</code>, it's much easier to say because integers are exact. <code>range</code> can be thought of as filling in the number line between <code>start</code> and <code>stop</code> (excluding <code>stop</code>). We probably want to exclude <code>stop</code> too for consistency, but <code>FloatRange</code> is more of a finite set of points between <code>start</code> and <code>stop</code> exclusive. Because of this, membership is a little more tricky. You could define membership as being within the range or being an explicit member from the iteration of the range. For <code>range()</code>, these two are equivalent because integers are countable.</p>\n\n<p>You seem to have chosen the later definition of <code>__contains__</code>. But, it does beg the question: is this actually meaningful? Is there a context where you'd need to check floating point within a tolerance of some number of (finite-representable) discrete points in some range.</p>\n\n<p>As a result of these issues, this <code>FloatRange</code> is way more complicated than it needs to be. You also make some common mistakes with comparing floating point numbers that will fail for extrema.</p>\n\n<p>As an aside, let's also take a look at your constructor parameters. You allow for 1, 2, or 3 arguments (excluding precision), like <code>range</code>. I think the only really meaningful constructors are the 2 and 3 argument ones. The single argument assumes a start of <code>0</code> and step of <code>1</code>. But, then this is precisely just <code>range</code> (so why not use <code>range</code>?). It seems like it's really only meaningful to define a floating point stop and step (with a start of 0) or all 3. But, if you really feel strongly about the 1 argument case, you can of course keep it.</p>\n\n<p>Now that we've discussed the problems, let's take a stab at some solutions. I see two solutions.</p>\n\n<p>You want a range starting at <code>start</code> that adds <code>step</code> until the number is <code>&gt;= stop</code>. This is more like what you've implemented (and similar to <code>range</code> in some regards, except its length is not constant-time computable). I'd recommend not defining <code>__len__</code>. If you do, you may want to warn that it is not constant time. Why is this? Well you could do <code>(stop - start) / step</code>, but as you likely found, this has accuracy issues. These are the same representation issues we mentioned above. Furthermore, it is difficult to account for fancier bounds checking (ie. if you want to keep producing numbers until one is less than or \"close to\" <code>stop</code> for some definition of close to--like within some <code>threshold</code>).</p>\n\n<pre><code>from itertools import count, takewhile\n\nclass FloatRange:\n def __init__(self, start, stop=None, step=1):\n # No to handle # of arguments manually\n if stop is None:\n stop = start\n start = 0\n\n if any(not isinstance(x, float) for x in (start, stop, step)):\n raise ValueError('start, stop, step must be floats')\n if (start &lt; stop and step &lt; 0) or (start &gt; stop and step &gt; 0):\n raise ValueError('step sign must match (stop - start)')\n\n self.start = start\n self.stop = stop\n self.step = step\n\n def __iter__(self):\n return takewhile(lambda x: x &lt; self.stop, (self.start + i * self.step\n for i in count(0)))\n</code></pre>\n\n<p>Note we need no custom iterator or lots of logic. <code>itertools</code> can do most of the heavy lifting. Furthermore, we can update the predicate <code>lambda x:</code> to also include some definition of less than or close to like so: <code>lambda x: x &lt; self.stop and not math.isclose(x, self.stop, ...)</code>. Look at <a href=\"https://docs.python.org/3/library/math.html#math.isclose\" rel=\"nofollow noreferrer\"><code>math.isclose</code></a> to see what you need to pass (you need two params, not just tolerance). If you really need <code>__len__</code>:</p>\n\n<pre><code>def __len__(self):\n count = 0\n for x in self:\n count += 1\n return count\n</code></pre>\n\n<p>I'd recommend against <code>__contains__</code> here because determining the index count have precision issues for extrema. Eg. <code>self.step * round((x - self.start) / self.step)</code> could be unstable.</p>\n\n<p>You want a range that takes some pre-determinted number of <code>steps</code> of size <code>step</code> from <code>start</code>. Notice there is no stop here. <code>__len__</code> is immediately obvious. I'd recommend maybe not defining <code>__contains__</code> for now.</p>\n\n<p>This case is very straightfoward:</p>\n\n<pre><code>class FloatRange:\n def __init__(self, start, *, step=1, steps=0): # here I require step and steps to be kwargs for clarity\n if any(not isinstance(x, float) for x in (start, step)):\n raise ValueError('start and step must be floats')\n if not isinstance(steps, int) or x &lt; 0:\n raise ValueError('steps must be a positive integer')\n\n self.start = start\n self.step = step\n self.steps = steps\n\n def __iter__(self):\n return (self[i] for i in range(self.steps))\n\n def __getitem__(self, i):\n if not 0 &lt;= i &lt; self.steps:\n raise IndexError('FloatRange index out of range')\n return self.start + i * self.step\n\n def __len__(self):\n return self.steps\n</code></pre>\n\n<p>Here we can easily define <code>__len__</code>. <code>__contains__</code> is still tricky, because determining the index of a potential member of the range could be unstable. Here, though, because we can compute the end of the range in constant time (it's exactly <code>start + steps * step</code>), we can do some sort of clever binary search. More specifically, we can search for numbers close to the desired numbers (for some metric of closeness that you determine) and stop once the numbers we find are less than the desired number and decreasing (negative step) OR greater than the desired number and increasing (positive step). This comes nearly for free because we were able to define <code>__getitem__</code> (which we couldn't before because we couldn't bound the indices). We note that in this way, this <code>FloatRange</code> behaves much more like <code>range()</code> even though the constructor parameters are different.</p>\n\n<p>You may argue that since <code>steps</code> must be an integer, if you placed some sane limits on it then it would be impossible to construct a member whose index calculation is unstable. Unfortunately, because the index calculation involves a multiply/divide this is just not the case. By reading the IEEE 754 spec you can construct a degenerate case. Specifically, for large indices (which would initially be a float when resulting from the index computation) the floating point resolution is so wide that converting to an <code>int</code> does not produce the correct index. This is especially true for Python because <code>int</code> is arbitrary precision. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T14:10:19.567", "Id": "409928", "Score": "0", "body": "Wow, that's quite detailed. Thank you for your time... I'm gonna have to read through this a few times to pick it apart. You mentioned that my comparison against `Real` was strange... could you expand on that? Obviously, I thought it was a reasonable comparison." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T14:53:09.287", "Id": "409933", "Score": "1", "body": "You may want to test `isinstance(x, (float, int))` to allow calls like `FloatRange(3, 9, .1)` without error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T08:41:55.893", "Id": "410010", "Score": "0", "body": "Also, as regard to your discussion on the number of arguments, I find the use-case of a single argument perfectly valid and not necessarily replaceable by `range`. Think of `FloatRange(9.3)` for instance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T00:29:21.687", "Id": "410165", "Score": "0", "body": "@DavidCulbreth For one, `isinstance` is used pretty sparingly. Although, it's definitely appropriate in this context. Checking against `Real` is appropriate depending on the kind of numbers you'd want to accept. Perhaps in this context it's appropriate, but that depends. @MathiasEttinger has a good point that you should allow both `float`s and `int`s." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T00:31:04.000", "Id": "410166", "Score": "1", "body": "@MathiasEttinger Yes, I had considered that case. I see your point, but that's equivalent to `map(float, range(ceil(x))` or preferably `range(ceil(x))`. The latter gives you more operations (since `range` is more featured with better performance). Although, in my sample implementations I did support this 1-arg constructor." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T10:05:54.723", "Id": "211986", "ParentId": "211918", "Score": "4" } } ]
{ "AcceptedAnswerId": "211986", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T16:19:49.977", "Id": "211918", "Score": "4", "Tags": [ "python", "python-3.x", "interval" ], "Title": "Python Float point range() operator implementation" }
211918
<p>I've completed my first Python project. I created a basic guessing game first, with no extra features other than guessing and random number generation. Afterwards, I've watched python courses on Udemy and slowly I began implementing what I've learned. I have a name system, welcome screen, fully functional betting system, a score system with prizes depending on amount of guesses, etc etc.</p> <p>I'm super proud of this, and would like it reviewed. Any tips, tricks, etc. is very welcome, same with constructive criticism!</p> <pre><code> #pylint:disable=W0621 #pylint:disable=W0621 #pylint:disable=W0613 #pylint:disable=W0312 #pylint:disable=W0611 from random import randint import math ######### NUMBER GUESSING GAME ########## START_BALANCE = 500 POSITIVES = ["yes", "yeah", "y", "yep", "roger", "yea", "positive", "play"] NEGATIVES = ["no", "nope", "n", "nah", "negative"] game_state = [True, START_BALANCE] guess_list = [] choice = ("\nPlay again? Y/N: ").upper() userName = input(" Welcome to NumGuess! What is your name?\n") userName = userName.title() #### INTRO MENU #### def menu(): print(''' \n Hello {}!\n * The rules are very simple * -- The AI generates a number from 1 - 100. -- -- You will have to make a bet and enter your guess. -- -- You have 10x tries. If you fail, you lose your bet. -- -- The AI will let say if you guessed 'low' or 'high' -- -- Correct guess = prize. Wrong guess = lost bet. -- - Good Luck! - '''.format(userName)) #### MENU SCREEN #### def menuPlay(): try: menuPlay = input(" Press any key to start the game.\n") except TypeError: return menuPlay() else: if menuPlay.upper() != "": return #### NUMBER GENERATION FUNCTION #### def xNumbers(): number = randint(1,100) return number #### TRIES FUNCTION #### def xTries(): tries = 10 return tries #### BETTING FUNCTION #### def xBets(balance): try: print("--------------------------------") bet = int(input("Enter your bet: ")) if (bet &lt;= balance and bet &gt;= 0): return int(bet) else: print(f"Your bet of {bet}$ has to be less than your balance of {balance}$. Try again.\n") return xBets(balance) except ValueError: return xBets(balance) #### GUESSING FUNCTION #### def xGuesses(): try: guess = int(input("Enter your guess: ")) if (guess &gt;= 0 and guess &lt;= 100): guess_list.append(guess) return int(guess) else: print("Your guess has to be from 0 to 100. Try again.") return xGuesses() except ValueError: xGuesses() ####################### ##### MAIN FUNCTION ##### def main(number, tries, balance, gameWon, guess_list, bet): print(f"\nYou have {tries}x tries left.\n") scoreFactor = { '10':5.0, '9':3.00, '8':2.50, '7':2.00, '6':1.75, '5':1.50, '4':1.35, '3':1.25, '2':1.25, '1':1.25 } guess = int(xGuesses()) gameEnds = False if gameWon == True: number = int(xNumbers()) if tries ==0: balance -= bet print(f"\nGAME OVER! - YOU ARE OUT OF TRIES!\n- The number was: {number}.\n- Your balance is now: {balance}$") print(guess_list) gameEnds = True elif guess == number: gameEnds = True prize = bet * scoreFactor[str(tries)] prize = math.ceil(prize) balance += prize print(f"Congratulations, {userName}! 'You win: {prize}$") print(f"Your new balance is: {balance}$\n") print(guess_list) elif guess &lt; number: print(f"--------------------------------\nWrong guess\nYour guess is too LOW!\nPrevious guesses: {guess_list}\n--------------------------------") tries -= 1 return main(number, tries, balance, False, guess_list, bet) elif guess &gt; number: print(f"--------------------------------\nWrong guess\nYour guess is too HIGH!\nPrevious guesses: {guess_list}\n--------------------------------") tries -= 1 return main(number, tries, balance, False, guess_list, bet) if gameEnds is True: playerChoice = input(choice).lower() if playerChoice in POSITIVES: print(f"New round started!\nYour balance is: {balance}$") return [True, balance] elif playerChoice in NEGATIVES: print(f"\nThanks for playing, {userName}!\n") return [False, balance] menu() menuPlay() tries = xTries() print("Your balance is: "+str(game_state[1])+"$") while game_state[0]: guess_list = [] game_state = main(0, tries, game_state[1], True, guess_list, xBets(game_state[1])) ## BY KEYANAB </code></pre>
[]
[ { "body": "<p>Good job on your first Python project! :)</p>\n\n<p>But there are improvements to be made,</p>\n\n<ul>\n<li><p>Instead of the block-comments use docstrings</p>\n\n<blockquote>\n<pre><code>#### INTRO MENU ####\ndef menu():\n</code></pre>\n</blockquote>\n\n<p>You could do</p>\n\n<pre><code>def menu():\n \"This function will print the intro banner\"\n</code></pre>\n\n<ul>\n<li>Avoid working in the global namespace</li>\n</ul>\n\n<p>When you work in the global namespace, it becomes really hard to track that one bug.</p>\n\n<p>Because when something changes, it's hard to see what part of the program changes that variable</p></li>\n<li><p>Instead of recursive functions start writing iterative functions</p>\n\n<p>Python doesn't really suit itself for recursion</p>\n\n<p>There is an recursion limit, say your function will be called a 1000 times, it will break, you can see this behavior with </p>\n\n<pre><code>&gt;&gt;&gt; print(sys.getrecursionlimit())\n1000\n</code></pre></li>\n<li><p>Don't Repeat yourself</p>\n\n<p>Notice how the function where you get an input from the user are mostly similar. You can refactor those into one (iterative) function</p>\n\n<pre><code>def get_user_input(lower_bound, upper_bound, message):\n while True:\n try:\n guess = int(input(message)\n if lower_bound &lt;= guess &lt;= upper_bound:\n return guess\n print(f\"Your guess has to be from {lower_bound} to {upper_bound}. Try again.\")\n except ValueError:\n pass\n</code></pre></li>\n<li><p><code>if gameWon == True:</code> the <code>== ...</code> part is redundent</p>\n\n<p>Just <code>if True:</code> will suffice</p></li>\n<li><p>You only have to check for positives</p>\n\n<p>When you ask the user for a restart, a negative is the same as False. So there is no need to check for it. Just check for a positive, else <code>game_ended</code></p></li>\n<li><p>I advice to check PEP8</p>\n\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">The Python style guide</a> with many good point regarding style</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:03:07.820", "Id": "211939", "ParentId": "211922", "Score": "3" } }, { "body": "<p><code>xTries</code> doesn't need to be a function. All it's doing is returning <code>10</code>. Just make it a variable defining the starting number of tries:</p>\n\n<pre><code>STARTING_TRIES = 10\n\n. . .\n\ntries = STARTING_TRIES\n</code></pre>\n\n<p>Just like what you did with <code>START_BALANCE</code>.</p>\n\n<hr>\n\n<p><code>POSITIVES</code>, and similar collections should arguably be sets, not lists. Since you're using them to check for membership in the collection using <code>in</code>, sets will be much faster than lists. In your case here, it doesn't matter. It's a good thing to think about though. Change it to:</p>\n\n<pre><code># Just change to curly braces to make it a set\nPOSITIVES = {\"yes\", \"yeah\", \"y\", \"yep\", \"roger\", \"yea\", \"positive\", \"play\"}\n</code></pre>\n\n<p>When using lists, <code>in</code> will have to search potentially the entire list to see if the element is in it. With sets though, <code>in</code> only has to search a small fraction of the list. Once you're dealing with large amounts of data, this can make a significant difference.</p>\n\n<hr>\n\n<p>Your current way with <code>POSITIVES</code> is more complicated than it needs to be anyway. Unless you want input validation to be super strict, it seems like the only requirement for being classified as \"positive\" or \"negative\" is that positive inputs begin with <code>'y'</code> or <code>'p'</code>, and that negative inputs start with <code>'n'</code>.</p>\n\n<p>You could just make these quick functions:</p>\n\n<pre><code>def is_positive(s):\n # s is truthy if non-empty\n return s and s[0] in {'y', 'p'} \n\ndef is_negative(s):\n return s and s[0] == 'n'\n</code></pre>\n\n<p>This is a little more forgiving.</p>\n\n<p>If you could guarantee that the input is non-negative, the <code>s and</code> check would be unnecessary. It's needed here though so <code>s[0]</code> doesn't throw on an empty input. You could also using slicing to avoid the exception:</p>\n\n<pre><code>def is_positive(s):\n # s[0:1] also gets the first character, but returns \"\" if s is empty\n return s[0:1] in {'y', 'p'} \n\ndef is_negative(s):\n return s[0:1] == 'n'\n</code></pre>\n\n<p>Although I'm not sure if that's clearer.</p>\n\n<hr>\n\n<p><code>menuPlay</code> is very jarring to read. The function is called <code>menuPlay</code>, then you create a local variable called <code>menuPlay</code>. You also try to catch a <code>TypeError</code>, although you appear to be using Python 3. I'm not aware of a case where <code>input</code> would throw a <code>TypeError</code>. And if this is actually Python 2, then a much better solution is just to use <code>raw_input</code> instead.</p>\n\n<p>This is a case where a <code>while True</code> loop (or a do...while if Python had them) is handy. I'd just write this as:</p>\n\n<pre><code>def menu_play():\n while True:\n inp = input(\"...\")\n\n # Return if the input is non-empty\n if inp:\n return\n</code></pre>\n\n<p>If you think about it though, is this even necessary? The prompt is <code>\"Press any key to start the game\"</code>. The \"enter\" key is a valid key though, but pressing just that is rejected by your program. It might make more sense to get rid of that function and just write:</p>\n\n<pre><code>menu()\n\n# We don't care about what key was pressed, just that one (+ enter) was\ninput(\"Press any key and enter to continue\")\n\ntries = STARTING_TRIES\n</code></pre>\n\n<hr>\n\n<p>Python uses snake_case, not camelCase (unless you're working with other code that already uses camelCase). You use it in a few places, but are inconsistent. Just remember, <em>Python</em> uses <em>snake_case</em> (<code>a_b</code>).</p>\n\n<hr>\n\n<pre><code>bet &lt;= balance and bet &gt;= 0\n</code></pre>\n\n<p>can be more clearly written as</p>\n\n<pre><code>0 &lt;= bet &lt;= balance\n</code></pre>\n\n<p>Python, unlike most languages, allows for \"chaining\" of the comparison operators.</p>\n\n<hr>\n\n<p>Your design of <code>game_state</code> isn't optimal. Say you leave this code for awhile, and come back. Are you going to be able to accurately remember what <code>game_state[1]</code> represents?</p>\n\n<p>I would use a simple dictionary:</p>\n\n<pre><code>game_state = {\"continue?\":True, \"balance\":START_BALANCE}\n\n. . .\n\nprint(\"Your balance is: \"+str(game_state[\"balance\"])+\"$\")\n\n. . .\n\nwhile game_state[\"continue?\"]:\n</code></pre>\n\n<p>Which I feel reads better. Using Strings here has the disadvantage though that a typo in the String key when accessing <code>game_state</code> will cause a <code>KeyError</code> to be thrown at runtime. <code>game_state[2]</code> will still cause an exception in your code, but it's arguably easier to typo a String than it is a single digit number.</p>\n\n<p>You could also make this a full class, then your IDE could assist using auto-completion. You're likely only ever going to need a single instance of the class though (with the current design), so I'm not sure it's worth it here.</p>\n\n<p>Your design still has problems though:</p>\n\n<ul>\n<li><p>Really, grouping these two bits of data into a state isn't massively advantageous. You have them grouped inside a global variable, so instead of having two smaller global variables, you have one larger one. Grouping them slightly complicates accessing/reading (since you need to index the global using either a numeric or String key). As long as these are global variables, I don't see much point in grouping them together. If you made them locals that are being passed around, it might make a little more sense, but even then...</p></li>\n<li><p>Does it make much sense to <em>store</em> in the state whether or not a player wants to continue? You only use the first boolean part of the state in two places: returning it from <code>main</code>, and checking for it at <code>while game_state[0]:</code>. It makes sense as a return value from <code>main</code>*, but why is it part of the state? It's only ever needed at the call-site of <code>main</code>. Note how you don't pass their decisions between recursive calls. There doesn't seem to be any reason to store it. I'd make the entire state just the balance.</p></li>\n</ul>\n\n<p><code>main</code> can still return whether or not the player wants to continue though:</p>\n\n<pre><code>if playerChoice in POSITIVES: \n print(f\"New round started!\\nYour balance is: {balance}$\")\n return True, balance # A tuple instead, although a list would still work\n\nelif playerChoice in NEGATIVES:\n print(f\"\\nThanks for playing, {userName}!\\n\")\n return False, balance\n</code></pre>\n\n<p>Then, do something like:</p>\n\n<pre><code>keep_playing = True\nwhile keep_playing:\n guess_list = []\n keep_playing, balance = main(0, tries, global_balance, True, guess_list, xBets(global_balance))\n</code></pre>\n\n<p><code>*</code> Arguably, <code>main</code> should be responsible for the looping, and everything you currently have in <code>main</code> should go into a function called <code>play_round</code> or something. In most designs, the <code>main</code> is the central function that ties everything together, and in many languages, it's the obligatory entry point to the program that the user never manually calls. In my opinion, in Python, <code>main</code> should really only be called from an \"import guard\". It's more inline with the conventions of other languages, and just makes more sense.</p>\n\n<hr>\n\n<p>As the other answer notes, you're using far too much recursion here. I like recursion, I think it gets too much flak. You're using it here though for cases where simple iteration would be simpler. The major downside of recursion in a language like Python where recursion isn't optimized away is that it can lead to Stack Overflows. With how your code is now, if your user fails a validation check too many times (in say, <code>xBets</code>), you'll recurse too many times, and get a Stack Overflow. I'd write <code>xBets</code> as:</p>\n\n<pre><code>def ask_for_bet(current_balance):\n while True:\n try:\n print(\"--------------------------------\")\n bet = int(input(\"Enter your bet: \"))\n if (0 &lt;= bet &lt;= current_balance):\n return bet # Bet is already an int, no need for \"int\" again here\n\n else:\n print(f\"Your bet of {bet}$ has to be less than your balance of {current_balance}$. Try again.\")\n # Let it loop again instead of recursing\n\n except ValueError:\n print(\"Please enter a valid number\")\n</code></pre>\n\n<p>If you like recursion and want to be \"\"allowed\"\" or even encouraged to use it, I'd look into functional languages. Recursion is the main (or arguably the only) way to loop in Haskell, and many other functional languages allow for optimization that prevent Stack Overflows. Scala supports optimization and a <code>@tail-call</code> annotation that warns you if it can't be optimized. Clojure has the <code>recur</code> special form that emulates Tail-Call Optimization. Python's a great language, but there may be others out there that are more in-line with how you approach problems.</p>\n\n<hr>\n\n<hr>\n\n<p>Those are the major things I saw. This isn't awful code, but there are a few things that can be improved. Good luck!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T23:27:25.113", "Id": "211952", "ParentId": "211922", "Score": "2" } } ]
{ "AcceptedAnswerId": "211952", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T16:45:48.553", "Id": "211922", "Score": "4", "Tags": [ "python", "game" ], "Title": "First Project - Guessing game with various features" }
211922
<p>A <a href="https://en.wikipedia.org/wiki/Lexical_analysis" rel="nofollow noreferrer">lexer</a> is a program whose purpose is the conversion of a sequence of characters into a sequence of tokens. It is also often referred to as a scanner or tokenizer. </p> <p>A lexer often exists as a single function, which is called by a parser or another function. In a compiler, the lexing phase is usually after preprocessing and before parsing.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T17:42:55.143", "Id": "211924", "Score": "0", "Tags": null, "Title": null }
211924
A program converting a sequence of characters into a sequence of tokens.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T17:42:55.143", "Id": "211925", "Score": "0", "Tags": null, "Title": null }
211925
<p>I've written a method to render a polygon in <code>C#</code> using the <code>SharpDX</code> libraries and would like a review of my code's maintainability and the documentation around it. The method works fine as is, but I feel that perhaps the documentation could be improved, or that there could be simpler and more maintainable method of executing the algorithm.</p> <pre><code>/// &lt;summary&gt; /// Render an n-sided polygon from a list of allowed polygons. /// &lt;/summary&gt; /// &lt;param name="context2D"&gt;The 2D context used to render the polygon.&lt;/param&gt; /// &lt;param name="polygon"&gt;The n-sided polygon to render.&lt;/param&gt; /// &lt;param name="center"&gt;The central position of the polygon in 2D space&lt;/param&gt; /// &lt;param name="radius"&gt;The radius of the polygon.&lt;/param&gt; /// &lt;param name="rotation"&gt;The global rotation of the polygon (in degrees).&lt;/param&gt; public void RenderPolygon(DeviceContext context2D, PolygonType polygon, Vector2 center, float radius, float rotation) { float numberOfPoints = (float)polygon; Vector2? firstPoint = null, previousPoint = null, currentPoint = null; for (int n = 0; n &lt; numberOfPoints; n++) { float theta = ((360.0f / numberOfPoints) * n + rotation) * (float)Math.PI / 180.0f; currentPoint = center + new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * radius; if (previousPoint != null &amp;&amp; currentPoint != null) context2D.DrawLine((Vector2)previousPoint, (Vector2)currentPoint, brush); previousPoint = currentPoint; if (firstPoint == null) firstPoint = currentPoint; } if (firstPoint != null &amp;&amp; currentPoint != null) context2D.DrawLine((Vector2)currentPoint, (Vector2)firstPoint, brush); } </code></pre> <hr> <p>With regards to the <code>PolygonType</code> argument, this is an <code>enum</code> with <code>int</code> values for each type; for example:</p> <pre><code>public enum PolygonType { Trigon = 3, Tetragon = 4, Pentagon = 5 } </code></pre> <p>There are a total of 30 polygon types offered stopping at <code>Chiliagon</code> which has <code>1000</code> sides.</p> <hr> <p>The things I am most interested in are:</p> <ul> <li>Ensuring documentation provides as much detail as possible (while remaining concise).</li> <li>Ensuring that the algorithm is easy to follow and maintain.</li> </ul> <p>The one thing I don't currently like about the algorithm:</p> <ul> <li>Casting from <code>Vector2?</code> to <code>Vector2</code> seems redundant (though required in the current case).</li> </ul> <p>Since <code>Vector2</code>'s default value is <code>0, 0</code>, I'm not sure I should use it and have chosen to use null; but since <code>Vector2</code> is not a nullable type, I have to cast back to the normal <code>Vector2</code> prior to using my variables.</p>
[]
[ { "body": "<p>The most confusing thing in your code is names of arguments and variables and their types.</p>\n\n<blockquote>\n<pre><code>DeviceContext context2D\n</code></pre>\n</blockquote>\n\n<p>Why not <code>deviceContext</code>?</p>\n\n<blockquote>\n<pre><code>PolygonType polygon\n</code></pre>\n</blockquote>\n\n<p>It's not polygon (which is collection of points as I expect), it's polygon type, so name it <code>polygonType</code></p>\n\n<blockquote>\n<pre><code>float numberOfPoints = (float)polygon;\n</code></pre>\n</blockquote>\n\n<p>Why are you casting to <code>float</code>? Number of points can be non-integer? Also in my opinion it's not good to give another meanings to enum values except what they mean by their names. Your enum defines polygons types, not numbers of points. I recommend to create dictionary:</p>\n\n<pre><code>private static readonly Dictionary&lt;PolygonType, int&gt; NumberOfPoints =\n new Dictionary&lt;PolygonType, int&gt;\n {\n [PolygonType.Trigon] = 3,\n // ...\n };\n</code></pre>\n\n<p>and use it:</p>\n\n<pre><code>var numberOfPoints = NumberOfPoints[polygonType];\n</code></pre>\n\n<p>Why are you using for polygon types such strange names and not <em>Triangle</em> and <em>Square</em>?</p>\n\n<p>If it's public API method, add arguments checking using appropriate exceptions (<code>ArgumentOutOfRangeException</code>, <code>InvalidEnumArgumentException</code> and so on). All possible exceptions should be documented via <code>&lt;exception&gt;</code> tags.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:45:16.483", "Id": "409848", "Score": "0", "body": "Thank you for the feedback; the reason for `context2D` has been made redundant by making that particular parameter a field in the class, however since `DeviceContext` is the same in the 2D and 3D namespaces calling it `context2D` seems to be pretty common across the board. Casting to `float` was to prevent casting down the line as part of division; and in regards to the `PolygonType` names within the `enum` I used the mathematical names to add clarity since a square is not a diamond, but they are both tetragons." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:14:30.930", "Id": "211940", "ParentId": "211927", "Score": "5" } } ]
{ "AcceptedAnswerId": "211940", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T18:43:35.957", "Id": "211927", "Score": "3", "Tags": [ "c#" ], "Title": "Render Polygon Method (Documentation)" }
211927
<p>I'm trying to parse data into a csv prior to a bulk transaction into Neo4j. I'm using vast amounts of data in the relationships and wondered if anyone could help in speeding up the transactions below. It's genomic data, with 2,000 samples, each with up to 3.5m variants per chromosome probably equating to about 40m variants, up to two rows per sample, so ~120,000,000,000 rows in total. Currently it's taking me about 20 minutes per sample. Does anyone have any suggestions on how to improve this:</p> <pre><code>import sys import time import datetime import numpy as np import allel import zarr import numcodecs import os import pandas import csv import math import dask.array as da vcf_directory = '/media/user/Seagate Backup Plus Drive/uk_alspac/' zarr_path = vcf_directory + 'chroms.zarr' callset = zarr.open_group(zarr_path, mode='r') samples_fn = '/media/user/Seagate Backup Plus Drive/uk_alspac/phenotype_data/EGAZ00001016605_UK10K_ALSPAC_Phenotype_Data_August_2013_1867samples.txt' panel = pandas.DataFrame.from_csv(samples_fn, sep='\t') chrom_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,'X'] i = 0 j = 0 seq_tech = 'Illumina HiSeq 2000 (ILLUMINA)' with open('/media/user/Seagate Backup Plus Drive/uk_alspac/Import_files/sample_variants.csv', 'w') as csvfile: filewriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) filewriter.writerow([':START_ID(Sample)','type', 'hapA', 'hapB','genotype', 'seqtech', 'read_depth', 'phase_set','GP0','GP1','GP2','PL0','PL1','PL2', ':END_ID(Variant)']) for chrom in chrom_list: print(chrom) datetime_object = datetime.datetime.now() print(datetime_object) sampledata = callset[chrom]['samples'] samples = list(sampledata) variants = allel.VariantChunkedTable(callset[chrom]['variants'], names=['AC','AF_AFR', 'AF_AMR', 'AF_ASN', 'AF_EUR', 'AF_MAX', 'CGT', 'CLR', 'CSQ', 'DP', 'DP4', 'ESP_MAF', 'FILTER_LowQual', 'FILTER_MinHWE', 'FILTER_MinVQSLOD', 'FILTER_PASS', 'HWE', 'ICF', 'ID', 'IS', 'PC2', 'PCHI2', 'POS', 'PR', 'QCHI2', 'QUAL', 'REF', 'ALT', 'INDEL', 'SHAPEIT', 'SNP_ID', 'TYPE', 'UGT', 'VQSLOD', 'dbSNPmismatch', 'is_snp', 'numalt', 'svlen'], index='POS') pos = variants['POS'][:] SNPid = variants['ID'][:] ref = variants['REF'][:] alt = variants['ALT'][:] dp = variants['DP'][:] ac = variants['AC'][:] vartype = variants['TYPE'][:] svlen = variants['svlen'][:] qual = variants['QUAL'][:] vq = variants['VQSLOD'][:] numalt = variants['numalt'][:] csq = variants['CSQ'][:] vcfv = 'VCFv4.1' refv = 'https://www.ncbi.nlm.nih.gov/assembly/GCF_000001405.13/' calldata = callset[chrom]['calldata'] dpz = calldata['DP'] psz = calldata['PS'] plz = calldata['PL'] gpz = calldata['GP'] gtz = calldata['GT'] i = 0 j = 0 seq_tech = 'Illumina HiSeq 2000 (ILLUMINA)' for i in range(50): print("Chrom " + str(chrom) + "sample" + str(i)) print(datetime_object) gt = gtz[:,i].tolist() hap1, hap2 = zip(*gt) dp = dpz[:, i] ps = psz[:, i] pl = plz[:, i] gp = gpz[:, i] subject = samples[i] for j in range(len(pos)): h1 = int(hap1[j]) h2 = int(hap2[j]) read_depth = int(dp[j]) ps1 = int(ps[j]) PL0 = int(pl[j][0]) PL1 = int(pl[j][1]) PL2 = int(pl[j][2]) GP0 = float(gp[j][0]) GP1 = float(gp[j][1]) GP2 = float(gp[j][2]) if h1 == 0 and h2 == 0: filewriter.writerow([subject,"Homozygous",h1 ,h2, str(h1) + '|' + str(h2), seq_tech, read_depth, ps1, GP0, GP1, GP2, PL0, PL1, PL2, str(chrom) + '-' + str(pos[j]) + ref[j]]) elif h1 == 0 and h2 &gt; 0: filewriter.writerow([subject,"Heterozygous - Haplotype A",h1 ,'', str(h1) + '|' + str(h2), seq_tech, read_depth, ps1, GP0, GP1, GP2, PL0, PL1, PL2, str(chrom) + '-' + str(pos[j]) + ref[j]]) filewriter.writerow([subject,"Heterozygous - Haplotype B",'',h2, str(h1) + '|' + str(h2), seq_tech, read_depth, ps1, GP0, GP1, GP2, PL0, PL1, PL2, str(chrom) + '-' + str(pos[j]) + alt[j][h2-1]]) elif h1 &gt; 0 and h2 == 0: filewriter.writerow([subject,"Heterozygous - Haplotype A",h1, '', str(h1) + '|' + str(h2), seq_tech, read_depth, ps1, GP0, GP1, GP2, PL0, PL1, PL2, str(chrom) + '-' + str(pos[j]) + alt[j][h1-1]]) filewriter.writerow([subject,"Heterozygous - Haplotype B",'' ,h2, str(h1) + '|' + str(h2), seq_tech, read_depth, ps1, GP0, GP1, GP2, PL0, PL1, PL2, str(chrom) + '-' + str(pos[j]) + ref[j]]) elif h1 == h2 and h1 &gt; 0: filewriter.writerow([subject,"Homozygous",h1, h2, str(h1) + '|' + str(h2), seq_tech, read_depth, ps1, GP0, GP1, GP2, PL0, PL1, PL2, str(chrom) + '-' + str(pos[j]) + alt[j][h1-1]]) else: filewriter.writerow([subject,"Heterozygous - Haplotype A",h1,'', str(h1) + '|' + str(h2), seq_tech, read_depth, ps1, GP0, GP1, GP2, PL0, PL1, PL2, str(chrom) + '-' + str(pos[j]) + alt[j][h1-1]]) filewriter.writerow([subject,"Heterozygous - Haplotype B",'',h2, str(h1) + '|' + str(h2), seq_tech, read_depth, ps1, GP0, GP1, GP2, PL0, PL1, PL2, str(chrom) + '-' + str(pos[j]) + alt[j][h2-1]]) </code></pre> <p>It was all done a bit ad-hoc and I'm still new to python, so any tips would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:19:49.820", "Id": "409827", "Score": "0", "body": "Thanks @Ludisposed. Can you tell me what difference it will be making here? The results seem to come out as anticipated and I'm hesitant to stop the loop as I'll have to start over again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:33:04.470", "Id": "409832", "Score": "0", "body": "Ah yes, sorry @Ludisposed that was just a formatting error when writing the question. I've corrected it now. It's running at the moment, I just wondered if there was any way to speed up the loop." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T19:02:35.510", "Id": "211930", "Score": "2", "Tags": [ "python", "performance", "csv", "iteration" ], "Title": "Speed up iteration for large dataset in python" }
211930
<p>I've got an XML file with some info about hosts connected to my home network and I would like to create objects containing that info in a neat way, so that I can make some nice front-end application with that data later on.</p> <p>This is how I do it:</p> <ul> <li>Loading the XML</li> <li>Encoding it into JSON</li> <li>Making an array from the JSON</li> <li>Making a simpler array from the last array</li> <li>Creates objects from the array</li> <li>Done!</li> </ul> <p>My question to you is: Is this the way to do it, or is there some better way? Am I missing something obvious? Is this the way to do it the "OOP" way? I'm trying to learn this, so all constructive feedback is welcome!</p> <pre><code>class Host { public $ipv4, $mac; public function __construct($ipv4, $mac){ $this-&gt;ipv4 = $ipv4; $this-&gt;mac = $mac; } } class PagesController extends Controller { public function index(){ // Get xml with hosts that are connected to local network $xml = file_get_contents("C:/test.xml"); $xml = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA); $json = json_encode($xml); $array = json_decode($json,TRUE); // put all hosts in separate array (to make it easier to work with when creating an object further down) foreach ($array['host'] as $hostKey =&gt; $hostValue) { foreach ($hostValue['address'] as $addressKey =&gt; $addressValue) { foreach ($addressValue['@attributes'] as $attributeKey =&gt; $attributeValue) { $hosts['host'.$hostKey]['address'.$addressKey][$attributeKey] = $attributeValue; } } } // Create object from array created earlier foreach ($hosts as $hostKey =&gt; $hostValue) { if(isset($hostValue)){ foreach ($hostValue as $addressKey =&gt; $addressValue) { if(isset($addressValue)){ if(isset($addressValue['addrtype'])){ // ipv4 ? if($addressValue['addrtype'] == 'ipv4'){ $ipv4 = $addressValue['addr']; // or mac-address? } elseif($addressValue['addrtype'] == 'mac'){ $mac = $addressValue['addr']; } } } } } // Skapa ett objekt som heter host+$hostKey $hosts[$hostKey] = new Host($ipv4, $mac); } </code></pre> <p>Note: The reason for the <code>PagesController</code> class and the <code>index()</code> method is because I'm using the Laravel framework.</p> <p>The xml-file is generated from nmap which I plan to run every five minutes or so. This is what the xml looks like:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;!DOCTYPE nmaprun&gt; &lt;?xml-stylesheet href="file:///usr/bin/../share/nmap/nmap.xsl" type="text/xsl"?&gt; &lt;!-- Nmap 7.70 scan initiated Fri Jan 18 19:54:05 2019 as: nmap -sP -oX test.xml 192.168.1.1/24 --&gt; &lt;nmaprun scanner="nmap" args="nmap -sP -oX test.xml 192.168.1.1/24" start="1547837645" startstr="Fri Jan 18 19:54:05 2019" version="7.70" xmloutputversion="1.04"&gt; &lt;verbose level="0"/&gt; &lt;debugging level="0"/&gt; &lt;host&gt; &lt;status state="up" reason="arp-response" reason_ttl="0"/&gt; &lt;address addr="192.168.1.1" addrtype="ipv4"/&gt; &lt;address addr="E8:FC:AF:7B:42:46" addrtype="mac" vendor="Netgear"/&gt; &lt;hostnames&gt; &lt;/hostnames&gt; &lt;times srtt="597" rttvar="5000" to="100000"/&gt; &lt;/host&gt; &lt;host&gt; &lt;status state="up" reason="arp-response" reason_ttl="0"/&gt; &lt;address addr="192.168.1.2" addrtype="ipv4"/&gt; &lt;address addr="6C:AD:F8:C5:BB:65" addrtype="mac" vendor="AzureWave Technology"/&gt; &lt;hostnames&gt; &lt;/hostnames&gt; &lt;times srtt="47811" rttvar="47811" to="239055"/&gt; &lt;/host&gt; &lt;host&gt; &lt;status state="up" reason="arp-response" reason_ttl="0"/&gt; &lt;address addr="192.168.1.4" addrtype="ipv4"/&gt; &lt;address addr="04:69:F8:9C:F5:1F" addrtype="mac" vendor="Apple"/&gt; &lt;hostnames&gt; &lt;/hostnames&gt; &lt;times srtt="50599" rttvar="50599" to="252995"/&gt; &lt;/host&gt; &lt;host&gt; &lt;status state="up" reason="arp-response" reason_ttl="0"/&gt; &lt;address addr="192.168.1.5" addrtype="ipv4"/&gt; &lt;address addr="C8:69:CD:C8:44:A7" addrtype="mac" vendor="Apple"/&gt; &lt;hostnames&gt; &lt;/hostnames&gt; &lt;times srtt="55214" rttvar="55214" to="276070"/&gt; &lt;/host&gt; &lt;host&gt; &lt;status state="up" reason="arp-response" reason_ttl="0"/&gt; &lt;address addr="192.168.1.7" addrtype="ipv4"/&gt; &lt;address addr="68:D9:3C:CC:FA:1D" addrtype="mac" vendor="Apple"/&gt; &lt;hostnames&gt; &lt;/hostnames&gt; &lt;times srtt="78890" rttvar="73429" to="372606"/&gt; &lt;/host&gt; &lt;host&gt; &lt;status state="up" reason="arp-response" reason_ttl="0"/&gt; &lt;address addr="192.168.1.9" addrtype="ipv4"/&gt; &lt;address addr="14:DA:E9:51:3F:CC" addrtype="mac" vendor="Asustek Computer"/&gt; &lt;hostnames&gt; &lt;/hostnames&gt; &lt;times srtt="467" rttvar="5000" to="100000"/&gt; &lt;/host&gt; &lt;host&gt; &lt;status state="up" reason="arp-response" reason_ttl="0"/&gt; &lt;address addr="192.168.1.200" addrtype="ipv4"/&gt; &lt;address addr="00:15:5D:01:05:00" addrtype="mac" vendor="Microsoft"/&gt; &lt;hostnames&gt; &lt;/hostnames&gt; &lt;times srtt="453" rttvar="5000" to="100000"/&gt; &lt;/host&gt; &lt;runstats&gt; &lt;finished time="1547837648" timestr="Fri Jan 18 19:54:08 2019" elapsed="3.12" summary="Nmap done at Fri Jan 18 19:54:08 2019; 256 IP addresses (8 hosts up) scanned in 3.12 seconds" exit="success"/&gt; &lt;hosts up="8" down="248" total="256"/&gt; &lt;/runstats&gt; &lt;/nmaprun&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T22:03:55.013", "Id": "409851", "Score": "0", "body": "Welcome to Code Review! Where does the XML file come from? Is it generated by a service/product? Would it be possible for you to [edit] your post to include a sample (with names/addresses altered to protect sensitive values, if necessary)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T11:42:29.900", "Id": "409909", "Score": "0", "body": "Thank you! I've added the xml and some info about its origin in the original post. I've used nmap to generate the file and for now it is static, but I'm planning on putting it to run on a schedule. Heard that there is something called cron-jobs, so thats probably what I'm going to use. You think that is a good idea or should I use something else?" } ]
[ { "body": "<h2>Addressing your questions</h2>\n\n<blockquote>\n <p>Is this the way to do it, or is there some better way? Am I missing something obvious? </p>\n</blockquote>\n\n<p>I'm reminded of <a href=\"https://stackoverflow.com/a/3577662/1575353\">this highly upvoted SO answer</a> to <a href=\"https://stackoverflow.com/q/3577641/1575353\"><em>How do you parse and process HTML/XML in PHP?</em></a>. Based on the information there, you could choose a different tactic, like using the <a href=\"http://php.net/manual/en/book.dom.php\" rel=\"nofollow noreferrer\">DOM</a> API by utilizing thr <a href=\"http://php.net/manual/en/class.domdocument.php\" rel=\"nofollow noreferrer\">DOMDocument</a> class. This would allow you to do the following:</p>\n\n<ul>\n<li>remove the steps that encode and decode the data as JSON</li>\n<li>simplify access of node attributes</li>\n</ul>\n\n<p>And the step \"<em>Making a simpler array from the last array</em>\" seems excessive as well - why not just create the hosts as soon as the appropriate data is parsed/found?</p>\n\n<p>The code below has one less level of <code>foreach</code> loops because it simply checks if the <code>address</code> node has attributes for <code>addrtype</code> and <code>addr</code>. It also eliminates the second set of <code>foreach</code> statements and creates the host objects as soon as the information is available.</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>libxml_use_internal_errors(true); //ignore invalid HTML tag warnings\n$dom = new DOMDocument();\n$dom-&gt;loadHTMLFile('C:/test.xml');\nforeach($dom-&gt;getElementsByTagName('host') as $hostKey =&gt; $host) {\n $hostAttributes = array();\n foreach($host-&gt;getElementsByTagName('address') as $adressKey =&gt; $addressValue) {\n if ($addressValue-&gt;getAttribute('addrtype') &amp;&amp; $addressValue-&gt;getAttribute('addr')) {\n $hostAttributes[$addressValue-&gt;getAttribute('addrtype')] = $addressValue-&gt;getAttribute('addr');\n }\n }\n if (array_key_exists('ipv4', $hostAttributes) || array_key_exists('mac', $hostAttributes) {\n $hosts[$hostKey] = new Host($hostAttributes['ipv4'], $hostAttributes['mac']);\n } \n}\n</code></pre>\n\n<blockquote>\n <p>Is this the way to do it the \"OOP\" way?</p>\n</blockquote>\n\n<p>If you mean the parsing techniques, one might say that your approach is to parse JSON objects with arrays of nested children and then create Host objects - seems fine. </p>\n\n<hr>\n\n<h2>General review points</h2>\n\n<p>If you don't decide to simplify the code with an approach like above, consider these critiques of your existing code.</p>\n\n<p>The value of the variables <code>$ipv4</code> and <code>$mac</code> persist across iterations of the <code>foreach</code> loops, which means that if a host had only one type of address, then a previous value may be used unintentionally...</p>\n\n<hr>\n\n<p>The following lines can be simplified:</p>\n\n<blockquote>\n<pre><code>if(isset($addressValue)){\n if(isset($addressValue['addrtype'])){\n</code></pre>\n</blockquote>\n\n<p>Why not combine those into a single line combined with the logical AND operator (i.e. <code>&amp;&amp;</code>)? I could see a reason not to do so if there was an <code>else</code> case defined immediately after one of those but that is not the case.</p>\n\n<pre><code>if(isset($addressValue) &amp;&amp; isset($addressValue['addrtype'])){\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:33:40.540", "Id": "410101", "Score": "0", "body": "Thanks alot for a your answer! I tried your way with the DOMDocument and I think it looks alot better. I also think that it will make it easier for me later on when I'm about to add more properties to the objects. Your answer was spot on!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:34:49.843", "Id": "410103", "Score": "1", "body": "P.S would give an upvote, but I've got too low reputation for that" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:37:57.090", "Id": "410104", "Score": "0", "body": "Okay thanks - if you earn that vote up privilege then it would be appreciated if you come back to this :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:49:00.500", "Id": "410106", "Score": "0", "body": "I sure will! :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T18:41:18.697", "Id": "212013", "ParentId": "211931", "Score": "2" } } ]
{ "AcceptedAnswerId": "212013", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T19:09:35.040", "Id": "211931", "Score": "2", "Tags": [ "php", "object-oriented", "parsing", "xml", "iteration" ], "Title": "Creating objects from xml-data" }
211931
<p>I wrote a (max) heap in Haskell which is balanced after every (public) operation. Not based on any documentation. Focus is on:</p> <ul> <li>speed, that is the right time-complexities (not necessarily optimal);</li> <li>easy to understand, so no Maybe's, Monads or symbols a beginner is unfamiliar with.</li> </ul> <blockquote> <pre><code> ******* 4 * ******* 6 * * * ******* 2 * 8 * * ******* 3 * * ******* 7 * * ******* * * ******* 5 * ******* 1 </code></pre> </blockquote> <p>Would like it to be reviewed. </p> <pre><code>module Heap (insert, size, deleteMax, getMax, fromList, toList, isEmpty, empty, singleton, member) where data Heap a = Empty | Node a Int (Heap a) (Heap a) -- Insert an element to the heap. insert :: Ord a =&gt; a -&gt; Heap a -&gt; Heap a insert x Empty = Node x 1 Empty Empty insert x (Node t n l r) | x &gt; t &amp;&amp; size l &gt; size r = Node x (n + 1) l (insert t r) | x &gt; t = Node x (n + 1) (insert t l) r | x &lt;= t &amp;&amp; size l &gt; size r = Node t (n + 1) l (insert x r) | x &lt;= t = Node t (n + 1) (insert x l) r -- Checks if a heap is empty. isEmpty :: Ord a =&gt; Heap a -&gt; Bool isEmpty Empty = True isEmpty _ = False -- Gives the empty heap. empty :: Ord a =&gt; Heap a empty = Empty -- Creates a heap from a list. fromList :: Ord a =&gt; [a] -&gt; Heap a fromList ls = foldr insert Empty ls -- Checks if an element is a member of the heap. member :: Ord a =&gt; a -&gt; Heap a -&gt; Bool member x Empty = False member x (Node t _ l r) | x &gt;= t = x == t | otherwise = member x l || member x r -- Turns the heap into a list. toList :: Ord a =&gt; Heap a -&gt; [a] toList Empty = [] toList (Node t _ l r) = (t : toList l) ++ (toList r) -- Deletes an element from a heap which doesn't have any -- smaller elements in a left or right heap. The mentioned -- element together with the new heap are returned. deleteBottom :: Ord a =&gt; Heap a -&gt; (a, Heap a) deleteBottom (Node t _ Empty Empty) = (t, Empty) deleteBottom (Node t n l r) | size l &lt; size r = (x1, Node t (n - 1) l r') | otherwise = (x2, Node t (n - 1) l' r) where (x1, r') = deleteBottom r (x2, l') = deleteBottom l -- Delete the largest element in the heap. The largest element -- together with the new heap are returned. -- Doesn't check for non-emptiness, therefore unsafe. deleteMax :: Ord a =&gt; Heap a -&gt; (a, Heap a) deleteMax (Node t _ Empty Empty) = (t, Empty) deleteMax (Node t n l r) = (t, merge x l' r') where (x, Node _ _ l' r') = deleteBottom (Node t n l r) -- Create a heap from a single element. singleton :: Ord a =&gt; a -&gt; Heap a singleton x = insert x Empty -- An element x and two heaps A and B for which holds: -- |size A - size B| &lt;= 1. -- Returns a new heap where x, A and B are glued together. merge :: Ord a =&gt; a -&gt; Heap a -&gt; Heap a -&gt; Heap a merge x Empty Empty = singleton x merge x (Node t _ Empty Empty) Empty | x &lt; t = Node t 2 (singleton x) Empty | otherwise = Node x 2 (singleton t) Empty merge x Empty (Node t _ Empty Empty) | x &lt; t = Node t 2 Empty (singleton x) | otherwise = Node x 2 Empty (singleton t) merge x (Node t n l r) (Node t' n' l' r') | x &gt;= t &amp;&amp; x &gt;= t' = Node x new_n (Node t n l r) (Node t' n' l' r') | t &gt;= x &amp;&amp; t &gt;= t' = Node t new_n (merge x l r) (Node t' n' l' r') | otherwise = Node t' new_n (Node t n l r) (merge x l' r') where new_n = 1 + n + n' -- Returns the number of elements in a heap. size :: Ord a =&gt; Heap a -&gt; Int size Empty = 0 size (Node _ n _ _) = n -- Get the largest element in a non-empty heap. -- Doesn't check for non-emptiness, therefore unsafe. getMax :: Ord a =&gt; Heap a -&gt; a getMax (Node t _ _ _) = t instance (Show a) =&gt; Show (Heap a) where show tr = ((++) "\n" . unlines . snd . toLines) tr where toLines :: (Show a) =&gt; Heap a -&gt; (Int, [String]) toLines Empty = (0, [""]) toLines (Node t _ Empty Empty) = (0, [" " ++ show t]) toLines (Node t _ l r) = (ln + 1, lv_new ++ [" *"] ++ [" " ++ show t] ++ [" *"] ++ rv_new) where (il, lv) = toLines l (ir, rv) = toLines r ln = length lv rn = length rv lv_sub = (replicate il " ") ++ [" *******"] ++ (replicate (ln - il) " * ") rv_sub = (replicate ir " * ") ++ [" *******"] ++ (replicate (rn - ir) " ") lv_new = zipWith (++) lv_sub lv rv_new = zipWith (++) rv_sub rv </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T22:19:26.367", "Id": "409855", "Score": "1", "body": "Welcome to Code Review. Is there a specific reason why you don't want to use `Maybe` and therefore get partial functions? Also, is that `Show` instance intended?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:14:56.993", "Id": "211934", "Score": "1", "Tags": [ "haskell", "functional-programming", "heap", "immutability" ], "Title": "Max heap in Haskell" }
211934
<p>An isogram (also known as a "nonpattern word") is a word or phrase without a repeating letter, however spaces and hyphens are allowed to appear multiple times.</p> <p>The <code>IsIsogram()</code> method takes a string and returns boolean value. </p> <ol> <li>INPUT: anik OUTPUT: true</li> <li>INPUT: A nika OUTPUT: false</li> </ol> <p>Approach 01: <code>Using Dictionary&lt;TKey, TValue&gt;</code></p> <pre><code>static bool IsIsogram(string str) { //create a dictionary with 26 keys and assign false as default value var storeOccurance = new Dictionary&lt;int, bool&gt;(); for (int i = 0; i &lt;= 25; i++) { storeOccurance[i] = false; } str = Regex.Replace(str, "[ -]", ""); //ignore whitespace and dash //iterate over each character of the string foreach (var ch in str.ToLower()) { //(ch - 'a') is used to calculate the key. Check if the character key has false as it's value, //meaning they were never stored if (!storeOccurance[ch - 'a']) { storeOccurance[ch - 'a'] = true; //assign true when they are stored in the dictionary } else //otherwise, if a character key has true as it's value then it means that it exists in the dictionary { return false; //return false and exits the iteration..Multiple occurance in dictionary //means the string has repeating character so it's not Isogram } } return true; } </code></pre> <p>Approach 02: <code>Using HashSet&lt;T&gt;</code></p> <pre><code>static bool IsIsogram(string str) { //TRICK: HashSet&lt;T&gt;.Add(T) returns false if an item already exists in HashSet&lt;T&gt;, //otherwise returns true and add the character to the datastructure var charHash = new HashSet&lt;char&gt;(); foreach (var ch in str.ToLower()) { //check if the charHash.Add() returns false, if it does then terminate //as it means the character already exists if (!charHash.Add(ch) &amp;&amp; char.IsLetter(ch)) return false; } return true; //otherwise return true } </code></pre> <p>Approach 03: Using LINQ</p> <pre><code>static bool IsIsogram(string str) { //Suppose "anik a" is a given string return str.Where(char.IsLetter) //filter only the letters ||here- only a, n, i, k, a will be taken .GroupBy(char.ToLower) //create group by characters(and transform them to lowercase) || here, there will be a group for each character a, n, i, k .All(g =&gt; g.Count() == 1); //for every group, count the number of it's element and check if it's 1 //|| here, 'a' group has 2 elements so it return false though other groups has only one element in their group } </code></pre> <p>Given those above approaches:</p> <ol> <li>Which approach would you recommend regarding readability, clean code and performance?</li> <li>Is there any scope for improvement in the existing approaches?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T11:24:50.093", "Id": "409905", "Score": "1", "body": "4th solution (after deleting authorized multiple characters) : `return str.Count() == str.distinct().count();`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T20:43:45.523", "Id": "409969", "Score": "1", "body": "Along the same lines, if you're OK with using side effects of HashSet.Add: `var uniques = new HashSet<char>(); return str.Where(char.IsLetter).Select(char.ToLower).All(uniques.Add);`" } ]
[ { "body": "<h3>Choice of Map Key</h3>\n\n<p>Ultimately, as you are querying your map based upon the character, you should really make your key as the character. This makes your regular subtraction of <code>'a'</code> unnecessary.</p>\n\n<pre><code> var storeOccurance = new Dictionary&lt;char, bool&gt;();\n for (char c = 'a'; c &lt;= 'z'; c++)\n {\n storeOccurance[c] = false;\n }\n</code></pre>\n\n<h3>Inconsistent behaviour for non-letter characters</h3>\n\n<p>Given a string such as <code>anik00</code>, the first approach will produce a <code>false</code> response, as the duplicate 0s are detected like any other letter. The other two approaches will produce <code>true</code>, as 0s are ignored.</p>\n\n<h3>Comments</h3>\n\n<p>I don't think these comments are necessary, as the code is clear enough on its own. If you feel the need to add comments to explain what something is doing, you should extract methods instead to make these intentions clear.</p>\n\n<h3>Which approach would I choose?</h3>\n\n<p>The litmus test is how easy it is to understand. I've not seen any serious LINQ for a number of years, and despite that I can understand your LINQ query without difficulty. If you can create understandable code in fewer lines, it's a good thing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:21:56.727", "Id": "211943", "ParentId": "211936", "Score": "5" } }, { "body": "<p>I like the second approach since it allows you to exit as soon as a false condition is reached and is simpler than the first. I would offer one minor optimization, keep the check for isletter separate and only check for duplicate if isletter is true:</p>\n\n<pre><code>static bool IsIsogram(string str)\n{\n //TRICK: HashSet&lt;T&gt;.Add(T) returns false if an item already exists in HashSet&lt;T&gt;,\n //otherwise returns true and add the character to the datastructure\n\n var charHash = new HashSet&lt;char&gt;();\n\n foreach (var ch in str.ToLower())\n { \n //check if the charHash.Add() returns false, if it does then terminate\n //as it means the character already exists\n if(char.IsLetter(ch))\n {\n if (!charHash.Add(ch))\n return false; \n }\n\n }\n return true; //otherwise return true\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T12:51:42.190", "Id": "409918", "Score": "0", "body": "Or you could just swap those two inside the same `if`, it will [short-circuit](https://en.wikipedia.org/wiki/Short-circuit_evaluation) if the first evaluates to `false`, no need to unnecessary nesting IMO." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:24:15.770", "Id": "211945", "ParentId": "211936", "Score": "6" } }, { "body": "<p>I suggest using an array of boolean, so instead of</p>\n\n<pre><code>var storeOccurance = new Dictionary&lt;int, bool&gt;();\n</code></pre>\n\n<p>use simply</p>\n\n<pre><code>var storeOccurance = new bool[26];\n</code></pre>\n\n<p>Although if you want to allow a large character set instead of just a-z, say the whole of unicode, the HashSet approach may be appropriate, although in that case you would have to consider surrogates ( the situation where a character is represented by two chars ).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T23:27:35.373", "Id": "211953", "ParentId": "211936", "Score": "2" } }, { "body": "<p>I think i would go for LINQ approach. For this simple operation, it is short and easy to understand. Don't reinvent the wheel, use LINQ.</p>\n\n<p>Here is another shorter version of LINQ : </p>\n\n<pre><code>public static bool IsIsogram(string input)\n{\n var preprocessedInput = Regex.Replace (input.ToLower(), \"[ -]\", \"\").Dump();\n return preprocessedInput.Length == preprocessedInput.Distinct().Count();\n}\n</code></pre>\n\n<p>But i would like to introduce another approach which is recursive. There is no need to use HashSets or Dictionaries within the implementation. </p>\n\n<pre><code>public static bool IsIsogram( string input){\n if (string.IsNullOrEmpty(input))\n {\n throw new ArgumentNullException(nameof(input));\n //or we can return true , no character, no repeated character :) \n }\n var preprocessedInput = Regex.Replace(input.ToLower(), \"[ -]\", \"\");\n if (input.Length==1)\n {\n return true;\n }\n var firstHalf = preprocessedInput.Substring(0,preprocessedInput.Length/2);\n var secondHalf = preprocessedInput.Remove(0,preprocessedInput.Length/2);\n\n if (firstHalf.Intersect(secondHalf).Any())\n {\n return false;\n }\n\n return IsIsogram(firstHalf) &amp;&amp; IsIsogram(secondHalf);\n}\n</code></pre>\n\n<p>The input string is divided into two string and checked for any intersected characters. If there is an intersecting character then, returns false.\n If there is not any intersected character then, each string divided into two substrings and called the method for each recursively. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T23:39:03.897", "Id": "211955", "ParentId": "211936", "Score": "3" } }, { "body": "<p>The <strong>third approach</strong> is definitely the one to start with. It's the simplest one and unless you don't have to analyze an entire library of texts it would probably be sufficient in 99.99% use-cases.</p>\n\n<p>Without measuring/benchmarking every presented approach it's not possible to say which one would be the fastest one. It also rarely matters. Don't overengineer it if you don't have a good explanation for doing so.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T10:21:20.827", "Id": "409899", "Score": "2", "body": "Both `Any` and `All` will return as soon as they find a match/mismatch." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T10:23:11.390", "Id": "409900", "Score": "0", "body": "@PieterWitvoet oops, you're so right ;-]" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T10:09:07.823", "Id": "211987", "ParentId": "211936", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:37:11.280", "Id": "211936", "Score": "3", "Tags": [ "c#", "programming-challenge", "comparative-review", "linq", "hash-map" ], "Title": "Finding Isogram Word" }
211936
<p>As a 'trying to learn Python' project, I am using ffmpy to stitch together a timelapse from a series of still images. I'd like the script to output a couple of formats for web use.</p> <p>This is what I have:</p> <pre><code>#!/usr/bin/env python3 import datetime import ffmpy import os now = datetime.datetime.now() ydr = now.strftime('%Y') mdr = now.strftime('%m') ddr = now.strftime('%d') ipath = str(os.path.dirname(os.path.abspath(__file__))) + '/images/' + ydr + '/' + mdr + '/*/*.jpg' opath1 = str(os.path.dirname(os.path.abspath(__file__))) + '/videos/' + ydr + mdr + '.mp4' opath2 = str(os.path.dirname(os.path.abspath(__file__))) + '/videos/' + ydr + mdr + '.webm' ff = ffmpy.FFmpeg( inputs={ipath: '-loglevel info -pattern_type glob -framerate 18 '}, outputs={opath1: '-c:v libx264 -vf "scale=1280:-1,hqdn3d=luma_spatial=1" -pix_fmt yuv420p'} ) ff.run() ff = ffmpy.FFmpeg( inputs={ipath: '-loglevel info -pattern_type glob -framerate 18 '}, outputs={opath2: '-c:v libvpx -vf "scale=1280:-1,hqdn3d=luma_spatial=1" -b:v 1M -c:a libvorbis'} ) ff.run() </code></pre> <p>It works, but it's kinda ugly and I'm pretty sure there's a more efficient and 'Pythonic' way of doing this. Any pointers?</p>
[]
[ { "body": "<ul>\n<li><p>Use <code>path.join()</code> instead of manually concatenating file paths</p>\n\n<p>This will make sure that it will work on different OS's, windows uses <code>\\</code> backslashes for instance</p></li>\n<li><p>No need to convert with <code>strftime</code></p>\n\n<p>A <code>datetime</code> has years, months and days as properties, if you want them in <code>str</code> format you could:</p>\n\n<p><code>map(str, iterable)</code> to convert them into strings</p></li>\n</ul>\n\n<h1>Code</h1>\n\n<pre><code>import datetime\nimport os.path\n\nnow = datetime.datetime.now()\ny, m = map(str, (now.year, now.month))\n\nlocation = os.path.dirname(os.path.abspath(__file__))\nipath = os.path.join(location, 'images', y, m + '.jpeg')\nvideo_path_mp4 = os.path.join(location, 'videos', y, m + '.mp4')\nvideo_path_webm = os.path.join(location, 'videos', y, m + '.webm')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:15:51.640", "Id": "211941", "ParentId": "211937", "Score": "2" } } ]
{ "AcceptedAnswerId": "211941", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:55:57.070", "Id": "211937", "Score": "3", "Tags": [ "python", "beginner", "image", "video" ], "Title": "Building a timelapse with ffmpy" }
211937
<p>I have more than 20 sheets in Excel and one main sheet (all programs with 200 names). Each sheet has a column with names and 24 months (Jan 18 to Dec 18, Jan 19 to Dec 20). Each sheet names is a subset of the main sheet.</p> <p>Main sheet (all programs) has 200 names and 24 months (values to be calculated based on other sheets). The other sheet has names and values for each month respective to the main sheet. I need to take each name in main sheet and search the name in all other sheets, and if present sum all same column values and insert in the main sheet.</p> <p>For 1 name I need to do calculation on 34 cells (for 200 names * 34 cells = 6800 cells). It's taking almost 20 minutes with my code. Is there any other way I can do it or any modification which improves the performance?</p> <p>Main Sheet has name "employee1"</p> <p><a href="https://i.stack.imgur.com/H9YhO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/H9YhO.png" alt="enter image description here"></a></p> <p>Sheet1</p> <p><a href="https://i.stack.imgur.com/Qvvq9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qvvq9.png" alt="enter image description here"></a></p> <p>Sheet2</p> <p><a href="https://i.stack.imgur.com/aqzzb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aqzzb.png" alt="enter image description here"></a></p> <p>Value on the main sheet should be calculated respect to months</p> <p><a href="https://i.stack.imgur.com/oEkU8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oEkU8.png" alt="enter image description here"></a></p> <pre><code>Dim sheetCount As Integer Dim datatoFind Private Sub CommandButton1_Click() Dim mainSheet As String: mainSheet = "All Programs" Dim nameColumnStart As String: nameColumnStart = "A" Dim namesStart As Integer: namesStart = 1 Dim namesEnd As Integer: namesEnd = 200 Dim startColumn As Integer: startColumn = 10 'J Column' Dim EndColumn As Integer: EndColumn = 33 'AG Column' namesStart = InputBox("Please enter start value") namesEnd = InputBox("Please enter end value") Dim temp_str As String Dim total As Single On Error Resume Next Sheets(mainSheet).Activate lastRow_main = ActiveCell.SpecialCells(xlLastCell).Row lastCol_main = 34 For vRow = namesStart To namesEnd temp_str = Sheets(mainSheet).Cells(vRow, "A").Text datatoFind = StrConv(temp_str, vbLowerCase) For vCol = startColumn To EndColumn total = Find_Data(vCol) Worksheets(mainSheet).Cells(vRow, vCol).Value = total Next vCol Next vRow Sheets(mainSheet).Activate 'MsgBox ("Calculated all values")' End Sub Private Function Find_Data(ByVal ColumnName As Integer) As Single Dim counter As Integer Dim currentSheet As Integer Dim sheetCount As Integer Dim str As String Dim lastRow As Long Dim lastCol As Long Dim val As Single Find_Data = 0 currentSheet = ActiveSheet.Index If datatoFind = "" Then Exit Function sheetCount = ActiveWorkbook.Sheets.Count For counter = 2 To sheetCount Sheets(counter).Activate lastRow = ActiveCell.SpecialCells(xlLastCell).Row lastCol = ActiveCell.SpecialCells(xlLastCell).Column For vRow = 1 To lastRow str = Sheets(counter).Cells(vRow, "A").Text If InStr(1, StrConv(str, vbLowerCase), datatoFind) Then val = Sheets(counter).Cells(vRow, ColumnName).Value Find_Data = Find_Data + val End If Next vRow Next counter End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:02:46.540", "Id": "409841", "Score": "3", "body": "Welcome to Code Review! 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 [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:14:47.600", "Id": "409842", "Score": "2", "body": "I've removed the VBScript tag, since this is obviously VBA - and VBScript is a different language. What Toby means is that as it stands, the post's title is essentially \"my code runs too slow, how do I make it faster\" - which is a title that's applicable to pretty much 90% of the VBA questions on this site. So in order to avoid having a [tag:vba] page filled with nearly-identical titles, we ask that you make your title a short description of what your code does, i.e. it's purpose. As the watermark says: \"state the purpose of the code\". Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:21:35.813", "Id": "409844", "Score": "0", "body": "i changed the title for easy filtering . Thank you @m" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:33:06.947", "Id": "409846", "Score": "2", "body": "That's.... literally the opposite of what I said." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T03:47:29.207", "Id": "409869", "Score": "0", "body": "Got it , I will change lol" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T20:23:44.777", "Id": "409965", "Score": "0", "body": "Not an answer: but (based on your description of the problem) I would first think of creating a union of all the data and creating a pivot table or some simple data structure first. This is using the native Excel functionality rather than trying to duplicate it in VBA." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T21:17:05.463", "Id": "409971", "Score": "0", "body": "Why not use Python?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T08:54:30.803", "Id": "410015", "Score": "0", "body": "@Elmex80s what is the advantage of using Python?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T18:34:58.557", "Id": "410092", "Score": "0", "body": "@TinMan It is a good alternative to VBA." } ]
[ { "body": "<h2>Global Variables</h2>\n\n<blockquote>\n<pre><code>Dim sheetCount As Integer\nDim datatoFind\n</code></pre>\n</blockquote>\n\n<p>Global variables make the code harder to maintain, modify, and debug. It would be better to pass the data as parameters between the sub routines. This makes it easier to determine exactly what data is being passed into your subroutines.</p>\n\n<p><code>Private</code> or <code>Public</code> modifiers should be used instead of <code>Dim</code> when declaring a global variable. </p>\n\n<h2>Constant Expressions</h2>\n\n<blockquote>\n<pre><code>Dim mainSheet As String: mainSheet = \"All Programs\"\nDim nameColumnStart As String: nameColumnStart = \"A\"\nDim startColumn As Integer: startColumn = 10 'J Column'\nDim EndColumn As Integer: EndColumn = 33 'AG Column'\n</code></pre>\n</blockquote>\n\n<p>The variables above should be declared as constants.</p>\n\n<blockquote>\n<pre><code>Const mainSheet As String = \"All Programs\"\nConst nameColumnStart As String = \"A\"\nConst startColumn As Integer = 10 'J Column'\nConst EndColumn As Integer = 33 'AG Column'\n</code></pre>\n</blockquote>\n\n<h2>namesStart and namesEnd</h2>\n\n<p>Why initiate the values below if you are not going to use the initial values?</p>\n\n<blockquote>\n<pre><code>Dim namesStart As Integer: namesStart = 1\nDim namesEnd As Integer: namesEnd = 200\n\n\nnamesStart = InputBox(\"Please enter start value\")\nnamesEnd = InputBox(\"Please enter end value\")\n</code></pre>\n</blockquote>\n\n<p>Consider using <a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.application.inputbox\" rel=\"nofollow noreferrer\">Application.InputBox</a> because you can specify the type of data it returns.</p>\n\n<blockquote>\n<pre><code>Dim namesStart As Integer\nDim namesEnd As Integer\nConst namesStartDefault As Integer = 1\nConst namesEndDefault As Integer = 200\n\nnamesStart = Application.InputBox(Prompt:=\"Please enter start value\", Default:=namesStartDefault, Type:=1)\nnamesEnd = Application.InputBox(Prompt:=\"Please enter end value\", Default:=namesEndDefault, Type:=1)\n\nIf namesStart &lt; namesStartDefault Then\n MsgBox \"Start vaule must be greater than or equal to \" &amp; namesStartDefault, vbCritical\n Exit Sub\nEnd If\n</code></pre>\n</blockquote>\n\n<h2>Selecting and Activating Objects</h2>\n\n<p>Selecting and Activating Objects should be avoided unless absolutely necessary, watch <a href=\"https://www.youtube.com//watch?v=c8reU-H1PKQ&amp;index=5&amp;list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)</a>. I would wager to bet that of the 20 minutes that it takes to run your code 19+ minutes are spent needlessly activating worksheets. </p>\n\n<p>Using <code>Application.ScreenUpdating = False</code> would probably cut the time in half.</p>\n\n<h2>Function Find_Data</h2>\n\n<p><code>SpecialCells(xlLastCell)</code> should only be used when you don't know the data structure. </p>\n\n<p><code>lastCol</code> isn't used.</p>\n\n<blockquote>\n<pre><code> lastCol = ActiveCell.SpecialCells(xlLastCell).Column\n</code></pre>\n</blockquote>\n\n<p><code>vRow</code> is never declared. The <code>v</code> prefix implies a variant when it should clearly be long.</p>\n\n<p><code>ColumnName</code> implies a string value. I would use <code>CoumnIndex</code> instead.</p>\n\n<h2>Refactored Code</h2>\n\n<pre><code>Private Const mainSheet As String = \"All Programs\"\n\nPrivate Sub CommandButton1_Click()\n Application.ScreenUpdating = False\n Const LastColumn = 34\n Dim namesStart As Integer\n Dim namesEnd As Integer\n Const namesStartDefault As Integer = 1\n Const namesEndDefault As Integer = 200\n\n namesStart = Application.InputBox(Prompt:=\"Please enter start value\", Default:=namesStartDefault, Type:=1)\n namesEnd = Application.InputBox(Prompt:=\"Please enter end value\", Default:=namesEndDefault, Type:=1)\n\n If namesStart &lt; namesStartDefault Then\n MsgBox \"Start vaule must be greater than or equal to \" &amp; namesStartDefault, vbCritical\n Exit Sub\n End If\n\n Dim r As Long, c As Long\n With ThisWorkbook.Worksheets(mainSheet)\n For r = namesStartDefault To namesEndDefault\n For c = 2 To LastColumn\n .Cells(r, c).Value = Find_Data(.Cells(r, 1).Value, c)\n Next\n Next\n End With\n\nEnd Sub\n\nPrivate Function Find_Data(ByVal EmployeeName As String, ByVal ColumnIndex As Integer) As Single\n Dim result As Single\n Dim ws As Worksheet\n Dim r As Long\n For Each ws In ThisWorkbook.Worksheets\n With ws\n If Not .Name = mainSheet Then\n For r = 2 To .Range(\"A\" &amp; .Rows.Count).End(xlUp).Row\n If InStr(1, .Cells(r, 1).Value, EmployeeName, vbTextCompare) &gt; 0 Then\n result = result + .Cells(r, ColumnIndex).Value\n End If\n Next\n End If\n End With\n Next\n Find_Data = result\nEnd Function\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T08:53:32.190", "Id": "212050", "ParentId": "211938", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T20:58:02.063", "Id": "211938", "Score": "0", "Tags": [ "performance", "vba", "excel" ], "Title": "Excel sheets with employees and dates" }
211938
<p>I could not find a compile time counter/accumulator to achieve something like the following:</p> <blockquote> <pre><code>#define DECLARE_VAR(type, varName) \ type varName; \ ADD_TO_ACCUMULATOR(sizeof(type)); DECLARE_VAR(float, var1); DECLARE_VAR(bool, var2); constexpr int total = GET_ACCU_AND_ADD(0); static_assert(total == 5); </code></pre> </blockquote> <p>So I came up with the following:</p> <pre><code>#define GET_ACCU_AND_ADD_IMPL(number, counterIndex) \ summer&lt;counterIndex&gt;::get(); \ template&lt;&gt; \ struct summer&lt;counterIndex+1&gt; { \ constexpr static int get() { \ return summer&lt;counterIndex&gt;::get() + (number); \ } \ }; #define ADD_TO_ACCUMULATOR_IMPL(number, counterIndex) \ template&lt;&gt; \ struct summer&lt;counterIndex+1&gt; { \ constexpr static int get() { \ return summer&lt;counterIndex&gt;::get() + (number); \ } \ }; #define GET_ACCU_AND_ADD(number) \ GET_ACCU_AND_ADD_IMPL(number, __COUNTER__) #define ADD_TO_ACCUMULATOR(number) \ ADD_TO_ACCUMULATOR_IMPL(number, __COUNTER__) template&lt;int tIndex&gt; struct summer { constexpr static int get() { static_assert(tIndex == 0, "should not be called/instantiated"); return 0; } }; template&lt;&gt; struct summer&lt;0&gt; { constexpr static int get() { return 0; } }; </code></pre> <p>Downsides: </p> <ul> <li>Relies on <code>__ COUNTER __</code></li> <li>?</li> </ul> <p>Feedback is appreciated, maybe there are already better solutions out here?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T04:38:26.727", "Id": "409873", "Score": "1", "body": "I'm not sure I fully understand what you want to do, but are you looking for [Simon Brand's \"`integral_variable`: A compile-time assignable variable\"](https://blog.tartanllama.xyz/integral_variable/)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T08:03:03.570", "Id": "409878", "Score": "1", "body": "It would be nice to know what you want to achieve with this: how will `total`be used?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:19:07.683", "Id": "211942", "Score": "3", "Tags": [ "c++", "constant-expression" ], "Title": "C++ compile time counter/accumulator" }
211942
<p>From what I've read, I should use abstract classes when I want to define behavior for a superclass, and I don't want to instantiate the superclass. So, I'm making a Blackjack game in Java, and I want a <code>BlackjackDealer</code> class and a <code>BlackjackPlayer</code> class. Would it be okay to make these children of a <code>BlackjackPerson</code> class, since some of the behavior should be the same? An example of behavior that should be the same:</p> <pre><code>abstract class BlackjackPerson { protected Card[] cards; public void hit(Card c) { // add c to cards } public abstract void displayHand(); // print out hand } </code></pre> <p>An example of a <code>BlackjackDealer</code> class, with its own implementation of the <code>displayHand</code> method (since a dealer has 1 card hidden):</p> <pre><code>class BlackjackDealer extends BlackjackPerson { public void displayHand() { for (Card c : cards) { System.out.println(c); } } } </code></pre> <p>This is my first time using inheritance, I just want to know if I'm on the right track.</p>
[]
[ { "body": "<h3>Look for common functionality</h3>\n\n<p>The real power of inheritance comes from the existence of common functionality. In this case, the dealing of cards and the calculation of totals will be common to both players and dealers, and so having both of these in the parent class would be a good choice.</p>\n\n<h3>Look for differing functionality</h3>\n\n<p>A dealer will have rules on when they hit and when they stay. A player will likely have an amount bet and a chip balance. These would be candidates for inclusion in the child classes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:36:25.967", "Id": "211947", "ParentId": "211946", "Score": "2" } }, { "body": "<p>Congratulations on taking class inheritance with a pinch of salt. This is a tricky part of OOP due to the strong dependency created between the parent and child classes and yet out of an urge for classification many people apply it badly, myself included.</p>\n\n<p>As I understand, you have Blackjack players and one of them is the Dealer. So I would have this simple specialization: <code>BlackjackDealer extends BlackjackPlayer</code>. None of them would be abstract, so sorry if you wanted to put abstract classes to use.</p>\n\n<p>You employ abstract classes when you want to provide partial functionality in a class but it seems that you don't have any to belong to the parent class. This is why I recommend the previous simpler design.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T22:05:08.893", "Id": "409852", "Score": "0", "body": "I do see what you mean about just regular inheritance, but aren't there some behaviors that the player needs that the dealer cannot have (like betting per Joe C's example)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T22:12:55.813", "Id": "409854", "Score": "0", "body": "Having a `BlackjackPerson` class doesn't make much sense to me. At least in the naming it should be renamed to `BlackjackPlayer`. Everyone involved are playing a game anyway. Of course, if you have special functionality to a Dealer subclass and some other special to a Player subclass then go ahead and create the abstract class. I'm not familiar with the game so I cannot proceed further. One other thing, don't forget you can have interface inheritance." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:51:47.563", "Id": "211948", "ParentId": "211946", "Score": "1" } }, { "body": "<h2>When using inheritance, always answer the 'Sub <code>is a</code> Super?'</h2>\n\n<blockquote>\n <p>Would it be okay to make these children of a BlackjackPerson class,\n since some of the behavior should be the same? </p>\n</blockquote>\n\n<p>or </p>\n\n<blockquote>\n <p>Look for common functionality</p>\n</blockquote>\n\n<p>This is a thing that often goes wrong. Just because there is a bit of similar behavior does not necessarily mean there is a 'is-a' relation.</p>\n\n<p>For example, both a Human and a Car can <code>moveForward()</code>. Does this mean a Human is a Car or a Car is a Human. Surely not :) </p>\n\n<p>Let's think about the common behaviour of a BlackJackPlayer and a BlackJackDealer. It is <code>displayHand()</code>. Can a <code>BlackJackDealer</code> be seen as a <code>BlackJackPlayer</code>? I would say yes, it <strong>is a</strong> special kind of player which have some specialized behavior. So I think, in your case, it would be fine to have </p>\n\n<pre><code>BlackJackDealer extends BlackJackPlayer \n</code></pre>\n\n<p>No need for abstract supertypes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T17:03:54.480", "Id": "409954", "Score": "0", "body": "I see your point, this is similar to what Piovezan said. However, what do I do about behavior specific to the player? For instance, a player can split, bet, etc. If I make the dealer inherit player, then the dealer will be able to bet, which it should not be." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:54:05.983", "Id": "410007", "Score": "0", "body": "Well, then it becomes different :) The player and dealer obviously have some similarity; like displayHand(). But there is no **real** supertype (as in, there does not exist a 'blackjackperson' who is neither a player or dealer, so we need an `AbstractBlackjackPlayer`, which can never be instantiated." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T10:21:23.367", "Id": "211988", "ParentId": "211946", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T21:27:51.620", "Id": "211946", "Score": "4", "Tags": [ "java", "beginner", "inheritance" ], "Title": "Abstract classes in Blackjack game" }
211946
<p>As if this isn't extremely obvious, I am a new coder. </p> <p>My code works, but is quite far from ideal. I'm also not sure if there are unnecessary bits, since I've been trying to get this to work for a few days on and off, so I've started and stopped multiple times.</p> <p>The goal is to have cleaner code, with a #comment on each line (unless extremely basic) so as to improve my annotation habits. Please let me know what you would do to improve it overall.</p> <pre><code>import urllib.request as ur from bs4 import BeautifulSoup url = str(input('Enter URL- ')) #convert input to string html = ur.urlopen(url).read() #read html soup = BeautifulSoup(html, "html.parser") #retrieve all of the anchor tags Count_ = int(input('Enter count: ')) #convert input to integer pos_1 = int(input('Enter position: ')) #convert input to integer tags = soup('a') final = '' #url of name list before break curpos = '' print('Retrieving: ', url) #prints starting point/url count = int(Count_) + 1 while count &gt; 1 : #starting a definite loop that goes until count is smaller than 1 pos = 0 for tag in tags : if pos == int(pos_1) - 1 : #conditional statement regarding position curpos = tag.get('href', None) break pos = pos + 1 #increases value of pos for each tag final = curpos # url = str(curpos) # html = ur.urlopen(url).read() soup = BeautifulSoup(html, "html.parser") tags = soup('a') count = count - 1 #for every iteration in the loop, subtract 1 from the value of count print('Retrieving: ', final) </code></pre>
[]
[ { "body": "<h3>General Observations</h3>\n\n<ul>\n<li><p>instead of manually looking for a tag a desired position and handling <code>pos</code> increment in the loop, I think you could just simply get the value by index:</p>\n\n<pre><code>curpos = tags[int(pos_1) - 1].get('href', None)\n</code></pre></li>\n<li><p><code>count = count - 1</code> could be simplified as <code>count -= 1</code></p></li>\n<li>follow the <a href=\"https://www.python.org/dev/peps/pep-0008/#id36\" rel=\"nofollow noreferrer\">PEP8 <code>lower_case_with_underscores</code> variable naming guideline</a></li>\n<li>what if you prefix the variable names containing user-defined values with <code>input_</code> (see below)? </li>\n<li><p>and, I think a \"for\" loop with a <em>negative step</em> would be a simpler solution that the while loop here:</p>\n\n<pre><code>for count in range(int(Count_) + 1, 1, -1):\n # ...\n</code></pre></li>\n<li>Or, to bring it one step further, what if we apply a generally easier to follow recursive flow instead of the iterative approach you currently have. The base condition for the recursion could be the input count reaching 1. And, we'll improve on <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> with that function as well. </li>\n</ul>\n\n<h3>Web-Scraping</h3>\n\n<ul>\n<li><p>you don't have to call <code>.read()</code> on the result of <code>.urlopen()</code> as <code>BeautifulSoup</code> also accepts file-like objects:</p>\n\n<pre><code>soup = BeautifulSoup(ur.urlopen(url), \"html.parser\")\n</code></pre></li>\n<li><p>switching from <code>html.parser</code> to <code>lxml</code> may help drastically improve HTML-parsing performance</p></li>\n<li>instead of using <code>urllib()</code>, you could <a href=\"http://docs.python-requests.org/en/master/user/advanced/#session-objects\" rel=\"nofollow noreferrer\">switch to <code>requests</code> and re-use a session</a> which would help avoid an overhead of re-establishing network connection to the host on every request</li>\n<li>you could use <a href=\"https://beautiful-soup-4.readthedocs.io/en/latest/#parsing-only-part-of-a-document\" rel=\"nofollow noreferrer\"><code>SoupStrainer</code></a> to let <code>BeautifulSoup</code> parse only the <code>a</code> elements</li>\n<li>you should also account for relative links and use <a href=\"https://docs.python.org/3/library/urllib.parse.html#urllib.parse.urljoin\" rel=\"nofollow noreferrer\"><code>urljoin()</code></a> to combine base urls and relative links</li>\n</ul>\n\n<hr>\n\n<p>The code with the above and other improvements applied:</p>\n\n<pre><code>from urllib.parse import urljoin\n\nimport requests\nfrom bs4 import BeautifulSoup, SoupStrainer\n\n\nonly_links = SoupStrainer('a')\n\n\ndef follow_link(session, url, position, count):\n \"\"\"Follows a link at a given \"position\" \"count\" number of times.\"\"\"\n if count &lt;= 1:\n return\n\n print('Retrieving: ', url)\n response = session.get(url)\n\n soup = BeautifulSoup(response.content, \"lxml\", parse_only=only_links)\n links = soup('a')\n next_url = links[position - 1].get('href', None)\n\n return follow_link(session, urljoin(url, next_url), position, count - 1)\n\n\nif __name__ == '__main__':\n input_url = str(input('Enter URL- '))\n input_count = int(input('Enter count: '))\n input_position = int(input('Enter position: '))\n\n with requests.Session() as session:\n follow_link(session, input_url, input_position, input_count)\n</code></pre>\n\n<hr>\n\n<h3>Afterthoughts</h3>\n\n<ul>\n<li>what if there is no link at the desired position available on some page?</li>\n<li>if we once get a link which links itself, this code in this state would get stuck on this page alone until the <code>count</code> is exchausted </li>\n</ul>\n\n<hr>\n\n<blockquote>\n <p>The goal is to have cleaner code, with a #comment on each line (unless extremely basic) so as to improve my annotation habits.</p>\n</blockquote>\n\n<p>Comments on each line could overall decrease readability of the code and they are, in essence, extra information and weight you need to make sure stay <em>up to date with the actual code</em>. <em>Self-documented code</em> is something you should strive to achieve, using comments as an extra measure used to explain the \"why\" some decisions were made and not the \"how\". </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T16:33:34.197", "Id": "410634", "Score": "0", "body": "\"Self-documented code is something you should strive to achieve, using comments as an extra measure used to explain the \"why\" some decisions were made and not the \"how\".\" This is very helpful in my process, thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T03:44:13.217", "Id": "211962", "ParentId": "211949", "Score": "3" } } ]
{ "AcceptedAnswerId": "211962", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T22:15:25.593", "Id": "211949", "Score": "3", "Tags": [ "python", "beginner", "web-scraping", "beautifulsoup" ], "Title": "Pulls href tags using BeautifulSoup with Python" }
211949
<p>This solution surpassed 100% of submissions for efficiency! My method was to recursively check surrounding values and change any contiguous "land" to "water". Is there a better way to write what I wrote?</p> <blockquote> <p>Given a 2d grid map of '1's (land) and '0's (water), count 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.</p> </blockquote> <pre><code>class Solution { public int numIslands(char[][] grid) { int islands = 0; for (int i = 0; i &lt; grid.length; i++) { for (int j = 0; j &lt; grid[i].length; j++) { if (grid[i][j] == '1') { islands++; destroyIsland(grid, i, j); } } } return islands; } public void destroyIsland(char[][] grid, int i, int j) { grid[i][j] = '0'; if (i &lt; grid.length - 1 &amp;&amp; grid[i+1][j] == '1') { destroyIsland(grid, i+1, j); } if (i &gt; 0 &amp;&amp; grid[i-1][j] == '1') { destroyIsland(grid, i-1, j); } if (j &lt; grid[i].length - 1 &amp;&amp; grid[i][j+1] == '1') { destroyIsland(grid, i, j+1); } if (j &gt; 0 &amp;&amp; grid[i][j-1] == '1') { destroyIsland(grid, i, j-1); } } } </code></pre>
[]
[ { "body": "<p>The code seems correct. The only missing part is</p>\n\n<blockquote>\n <p>You may assume all four edges of the grid are all surrounded by water.</p>\n</blockquote>\n\n<p>which means that <code>numIslands</code> may iterate</p>\n\n<pre><code> for (int i = 1; i &lt; grid.length - 1; i++) {\n for (int j = 1; j &lt; grid[i].length - 1; j++) {\n</code></pre>\n\n<p>and do not bother <code>destroyIsland</code> with validating the surroundings.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T09:46:50.917", "Id": "410487", "Score": "1", "body": "I interpreted that as \"all cells outside the bounds should be interpreted as water\", which makes the original correct and yours faulty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T03:08:40.773", "Id": "411478", "Score": "0", "body": "@MarkJeronimus, you are correct. This solution would not pass the test." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T02:39:34.573", "Id": "211960", "ParentId": "211954", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-21T23:29:00.923", "Id": "211954", "Score": "2", "Tags": [ "java", "algorithm" ], "Title": "Counts \"islands\" of 1s in sea of 0s (2d array matrix)" }
211954
<p>I've been programming for what is a probably a little bit and made a very simple logging system for my personal projects. While it works out fairly well so far, I would like advice on how to make it perform better and stuff I can do to make it more usable in general.</p> <p>Main questions include:</p> <ol> <li><p>Is my code thread safe? If not, how do I make it thread safe?</p></li> <li><p>Is there a way to make the interface a bit cleaner for use? Right now <code>#define</code> feels a bit hacky.</p></li> <li><p>Is there a way to avoid the use of a global <code>unique_ptr</code>?</p></li> <li><p>Should I just make it a header only library? Is there any benefits in doing so?</p></li> </ol> <p>.hpp:</p> <pre><code>#pragma once /* Use it by including this header in every file required, and in your main function start a new log. Logger::startLog("Log.txt"); Use the various error levels by naming them and simply passing the info and what you want to output. Logger::log(ERROR, "Something went wrong."); */ // For the unique pointers. #include &lt;memory&gt; // Filestream. #include &lt;fstream&gt; // String class for names and parameters passed around. #include &lt;string&gt; #define FATAL Logger::Level::Fatal #define ERROR Logger::Level::Error #define WARNING Logger::Level::Warning #define INFO Logger::Level::Info #define DEBUG Logger::Level::Debug namespace Logger { // Severity level enum. enum class Level { Fatal, Error, Warning, Info, Debug }; // Initialize the log. void startLog(const std::string&amp; filepath); // Log a message. void log(Level s, const std::string&amp; msg); // Logging class. class Log { public: Log(const std::string&amp; filepath); void addLog(Level s, const std::string&amp; msg); ~Log(); private: // File for logging. std::ofstream m_logfile; std::string levels[5] = {"Fatal", "Error", "Warning", "Info", "Debug"}; }; } </code></pre> <p>.cpp: </p> <pre><code>#include "Log.hpp" namespace Logger { // Global Logging Object. std::unique_ptr&lt;Log&gt; g_log; // Initalize our logging object. void startLog(const std::string&amp; filepath) { g_log = std::make_unique&lt;Log&gt;(filepath); Logger::log(Level::Info, "Started logging system."); } // Method which logs. void log(Level s, const std::string&amp; msg) { g_log-&gt;addLog(s, msg); } // Create our global logging object. Log::Log(const std::string&amp; filepath) : m_logfile{} { m_logfile.open(filepath); } // Add a message to our log. void Log::addLog(Level s, const std::string&amp; msg) { if (m_logfile.is_open()) { m_logfile &lt;&lt; levels[static_cast&lt;int&gt;(s)] &lt;&lt; ": " &lt;&lt; msg &lt;&lt; std::endl; } } Log::~Log() { addLog(Level::Info, "Stopped logging system."); m_logfile.close(); } } </code></pre>
[]
[ { "body": "<blockquote>\n <ol>\n <li>Is my code thread safe? If not, how do I make it thread safe?</li>\n </ol>\n</blockquote>\n\n<p>No, of course it's not thread-safe. You don't do anything to make it thread-safe.</p>\n\n<p>A more nuanced answer would be: It's thread-safe as long as you don't use it in an unsafe way. For example, calling <code>Logger::log(FATAL, \"hello world\")</code> from two different threads concurrently would of course be unsafe. But if your program <em>has</em> only one thread... :)</p>\n\n<p>If you want to allow calling <code>Logger::log</code> from two threads concurrently, you'll have to do something to eliminate the data race on <code>m_logfile</code> which is caused by the two threads' both calling <code>m_logfile &lt;&lt; levels[static_cast&lt;int&gt;(s)]</code> at the same time. For example, you could throw a mutex lock around <code>addLog</code>.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>Is there a way to make the interface a bit cleaner for use? Right now <code>#define</code> feels a bit hacky.</li>\n </ol>\n</blockquote>\n\n<p>The only place you use <code>#define</code> is in <code>#define FATAL Logger::Level::Fatal</code> and so on. (By the way, technically <code>#define ERROR ...</code> triggers undefined behavior, because all macros of the form <code>EXXXX</code> are reserved for use by POSIX error codes.) My question is, if you wanted these values to be referred to as <code>FATAL</code>, <code>ERROR</code>, etc., why didn't you just declare them that way?</p>\n\n<pre><code>inline constexpr int FATAL = 0;\ninline constexpr int ERROR = 1;\ninline constexpr int WARNING = 2;\n// ...\n</code></pre>\n\n<p>Or, probably better:</p>\n\n<pre><code>namespace Logger {\n enum Level {\n FATAL, ERROR, WARNING, // ...\n };\n}\n</code></pre>\n\n<p>Making this an <code>enum</code> (rather than an <code>enum class</code>) allows your user to refer to the enumerators without needing to redundantly name the enum type: just <code>Logger::FATAL</code>, <code>Logger::ERROR</code>, et cetera.</p>\n\n<p>Personally, I would consider writing convenience functions to eliminate the boilerplate:</p>\n\n<pre><code>namespace Logger {\n void log_fatal(const std::string&amp; msg) { log(FATAL, msg); }\n void log_error(const std::string&amp; msg) { log(ERROR, msg); }\n // ...\n}\n</code></pre>\n\n<hr>\n\n<p>By the way, I think your numbering scheme is backwards. \"Level\" represents the <em>severity of the message</em>, right? Some messages have higher severity than others? So how would I <em>test</em> whether one message had a higher severity than another? Well, I think I'd write:</p>\n\n<pre><code>if (one_severity &gt; another_severity) ...\n</code></pre>\n\n<p>But with the values you gave your enumeration, this is actually going to be completely backwards! And so my code for testing severity levels is going to have a bug (or else I'll catch the bug, but then have to write unintuitive code that uses <code>&lt;</code> to mean \"greater than\"). So, I recommend switching the values around.</p>\n\n<hr>\n\n<blockquote>\n <ol start=\"3\">\n <li>Is there a way to avoid the use of a global <code>unique_ptr</code>?</li>\n </ol>\n</blockquote>\n\n<p>Sure; declare it <code>static</code>! And to make it really non-global, stick it in a function. It'll still have static lifetime, though. There's not much getting around that.</p>\n\n<pre><code>inline Log *get_glog() {\n static std::unique_ptr&lt;Log&gt; glog = std::make_unique&lt;Log&gt;();\n return glog.get();\n}\n\nvoid startLog(const std::string&amp; filepath) {\n Log *glog = get_glog();\n glog-&gt;set_filepath_and_open(filepath);\n}\n</code></pre>\n\n<hr>\n\n<blockquote>\n <ol start=\"4\">\n <li>Should I just make it a header only library? Is there any benefits in doing so?</li>\n </ol>\n</blockquote>\n\n<p>The big benefit of a header-only library is that it's super easy to incorporate into another project — the user just drops the header file into his <code>include/</code> directory and he's good to go.</p>\n\n<p><em>Single</em>-header libraries are particularly nice because they can easily be dropped into <a href=\"https://godbolt.org\" rel=\"noreferrer\">Godbolt</a> or <a href=\"https://wandbox.org\" rel=\"noreferrer\">Wandbox</a>.</p>\n\n<p>In your case, the tradeoff is that presumably this header is going to get included all over the place (because logging is ubiquitous), and so the bigger you make it, the more work you're forcing the compiler to do <em>in every translation unit.</em></p>\n\n<hr>\n\n<p>Since you said \"C++17\", consider rewriting all your <code>void foo(const std::string&amp; s)</code> signatures into <code>void foo(std::string_view sv)</code> signatures. (Yes, <a href=\"https://quuxplusone.github.io/blog/2018/03/27/string-view-is-a-borrow-type/\" rel=\"noreferrer\">pass <code>string_view</code> by value.</a>)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T16:47:23.957", "Id": "409952", "Score": "0", "body": "Thank you for the insight. I think I managed to resolve most of my concerns and update the code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T03:45:12.743", "Id": "211963", "ParentId": "211957", "Score": "11" } }, { "body": "<p>A couple of things. You can avoid the #defines with a using directive . You don't need to give the caller any knowledge of the Log class. It does not need to be in the header at all. What happens if I call start log more than once? There's no protection against that. Also, I know it probably works as is, but the static cast in add log scares me because you never defined an integer value for the enum class. It seems to be begging for a segfault.</p>\n\n<p>Beyond that, how to improve the interface depends in what you want. Currently the code is not thread safe. You could use lock guards in your methods to accomplish this. </p>\n\n<p>Do you want to have one central log? Or do you want each instantiation of the log to be isolated?</p>\n\n<p>If you want one central, consider the singleton pattern and give out shared or weak pointers via a static factory, and make the ctor private. Then instead of having the function interface, you can keep a shared pointer to the logging object and give it references to it, people can then call the functions on the class. </p>\n\n<p>If you want each installation of the log to be separate, just have the user construct a log class. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T06:36:26.033", "Id": "409875", "Score": "4", "body": "Welcome to Code Review. You didn't use any `<code>yourcode</code>` tags (with Markdown: \\`yourcode`), so you might be interested in [the formatting section of our help center](https://codereview.stackexchange.com/help/formatting)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T04:16:42.327", "Id": "211965", "ParentId": "211957", "Score": "2" } }, { "body": "<p>I know that this already has an excepted answer but I will demonstrate the current <code>Logger</code> that I am using and what it looks like. Mind you though; it inherits from a <code>Singleton</code> class so that only one <code>Logger</code> can be constructed per a single application instance. It also relies on a few other classes in which I can not show here. </p>\n\n<p>There was some functionality to make it thread safe in the original design, however I am currently in the process of updating this class from using <code>Windows</code> headers for <code>CRITICAL_SECTION</code> and replacing them with <code>mutex</code> and <code>lock_guard</code>. </p>\n\n<p>There is also an <code>ExceptionHandler</code> class where the two work together in an integrated manner, however, no exceptions can be thrown from within the <code>Logger</code> since the <code>ExceptionHandler</code> itself uses the <code>Logger</code>. This way if an exception is thrown and caught; it will write that exception both to the console and the log file. </p>\n\n<hr>\n\n<p>The declaration of the <code>Logger</code> class looks like this:</p>\n\n<p><em>-Logger.h-</em></p>\n\n<pre><code>#pragma once\n\n#include \"Singleton.h\"\n\n#include &lt;array&gt;\n#include &lt;string&gt;\n#include &lt;sstream&gt;\n\nnamespace util {\n\n class Logger final : public Singleton {\n public:\n enum Type {\n INFO = 0,\n WARNING,\n ERROR\n };\n\n private:\n std::string filename_;\n unsigned maxCharLength_;\n\n std::array&lt;std::string, 3&gt; logTypes_;\n const std::string unknownLogType_;\n\n // CRICTICAL_SECTION // replace with mutex and lockguard...\n\n public:\n explicit Logger(const std::string&amp; filename);\n virtual ~Logger();\n\n Logger(const Logger&amp; c) = delete;\n Logger&amp; operator=(const Logger&amp; c) = delete;\n\n static void log(const std::string&amp; text, Type type = INFO);\n static void log(const std::ostringstream&amp; stream, Type type = INFO);\n static void log(const char* text, Type type = INFO);\n };\n\n} // namespace util\n</code></pre>\n\n<p>And it's implementation looks like this:</p>\n\n<p><em>-Logger.cpp-</em></p>\n\n<pre><code>#include \"Logger.h\"\n\n#include \"TextFileWriter.h\"\n\n#include &lt;conio.h&gt;\n#include &lt;iomanip&gt;\n#include &lt;iostream&gt;\n\n// include mutex - thread\n\nnamespace util {\n static Logger* spLogger_ = nullptr;\n} // namespace util\n\nusing namespace util;\n\nLogger::Logger(const std::string &amp; filename) :\nSingleton( LOGGER ),\nfilename_( filename ),\nmaxCharLength_( 0 ),\nunknownLogType_( \"UNKNOWN\" ) {\n // Order MUST MATCH Types in Logger::Type\n logTypes_[0] = \"Info\";\n logTypes_[1] = \"Warning\";\n logTypes_[2] = \"Error\";\n\n // Find widest log type string\n maxCharLength_ = static_cast&lt;unsigned int&gt;( unknownLogType_.size() );\n for( const std::string&amp; logType : logTypes_) {\n if (maxCharLength_ &lt; logType.size()) {\n maxCharLength_ = static_cast&lt;unsigned int&gt;( logType.size() );\n }\n }\n\n // critical section - mutex - thread lock\n\n\n // Start Log File\n TextFileWriter file(filename, false, false);\n\n spLogger_ = this;\n}\n\nLogger::~Logger() {\n spLogger_ = nullptr;\n\n // remove critical section or destroy mutex - lockguard, thread etc.\n}\n\nvoid Logger::log(const std::string &amp; text, Type type) {\n log(text.c_str(), type);\n}\n\nvoid Logger::log(const std::ostringstream &amp; stream, Type type) {\n log(stream.str().c_str(), type);\n}\n\n#include &lt;Windows.h&gt;\n\nvoid Logger::log(const char * text, Type type) {\n if (nullptr == spLogger_) {\n std::cout &lt;&lt; \"Logger has not been initialized, can not log \" &lt;&lt; text &lt;&lt; std::endl;\n }\n\n // block thread\n\n\n // Choose Log Type text string, display \"UNKNOWN\" if Type is out of range.\n std::ostringstream stream;\n stream &lt;&lt; std::setfill(' ') &lt;&lt; std::setw(spLogger_-&gt;maxCharLength_);\n\n try {\n stream &lt;&lt; spLogger_-&gt;logTypes_.at(type);\n } catch (...) {\n stream &lt;&lt; spLogger_-&gt;unknownLogType_;\n }\n\n // I am currently in the process of removing Windows specific code:\n // I am trying to do something similar to the date &amp; time code below\n // but in a more generic, portable and cross - platform way using\n // only stand library code.\n\n // Date &amp; Time\n SYSTEMTIME time;\n GetLocalTime(&amp;time);\n\n stream &lt;&lt; \" [\" &lt;&lt; time.wYear &lt;&lt; '.'\n &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; time.wMonth &lt;&lt; '.'\n &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; time.wDay &lt;&lt; ' '\n &lt;&lt; std::setfill(' ') &lt;&lt; std::setw(2) &lt;&lt; time.wHour &lt;&lt; ':'\n &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; time.wMinute &lt;&lt; ':'\n &lt;&lt; std::setfill('0') &lt;&lt; std::setw(2) &lt;&lt; time.wSecond &lt;&lt; '.'\n &lt;&lt; std::setfill('0') &lt;&lt; std::setw(3) &lt;&lt; time.wMilliseconds &lt;&lt; \"] \";\n\n stream &lt;&lt; text &lt;&lt; std::endl;\n\n std::cout &lt;&lt; stream.str();\n\n // Save message to log file\n try {\n TextFileWriter file(spLogger_-&gt;filename_, true, false);\n file.write(stream.str());\n } catch (...) {\n // Not saved in log file, write message to console\n std::cout &lt;&lt; __FUNCTION__ &lt;&lt; \" failed to write to file: \" &lt;&lt; stream.str() &lt;&lt; std::endl;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>A few things to be aware of with this class is that this depends on a <code>TextFileWriter</code> class which I can not disclose. </p>\n\n<p>I am also in the process of replacing the <code>Date &amp; Time</code> section to be something more portable and standard instead of using <code>Windows</code> headers. </p>\n\n<p>If you look closely at the design above, You can see that the <code>Logger</code> class contains an <code>enum</code> for basic types of errors. Their severity is already in order: {<code>INFO</code>, <code>WARNING</code>, <code>ERROR</code> }. I can easily expand this class to have different types of errors. The class stores a <code>string</code> for its filename, simple enough. There is an <code>array</code> of strings where the size of the array matches the types of errors. </p>\n\n<p>The constructor simply takes a string as a filename. It initializes the names of the error types with a string value. The <code>maxCharLength</code> is currently used for formatting the output to the console and written text file. I use the <code>TextFileWriter</code> class to create a file instead of having this responsibility within the <code>Logger</code>. This way I can have many different things read and write to files through the <code>FileHandler</code> classes. There is also a static pointer to this class that gets set as the last operation being done within the constructor. </p>\n\n<p>The destructor set's the pointer back to null, and will eventually remove or destroy any mutexes or locks. </p>\n\n<p>There are 3 overloaded <code>log</code> functions that all get passed to the one that takes a <code>const char*</code>. They have a second parameter which allows the user or caller to specify the type of error and it has a default value of <code>INFO</code> just incase you want to quickly write something to the console that isn't an error. The <code>log</code> function will also write the same message with the same format to a log file. </p>\n\n<p>Also <code>Logger</code> must be the first thing created because there is a stipulation in its parent class <code>Singleton</code> that <code>Logger</code> must be created before any other <code>Singleton</code> type. It was originally designed this way because there are several <code>Manager</code> type classes where you only ever want a single <code>Manager</code> class. So the <code>Logger</code>, <code>Settings</code> and various <code>Manager - classes</code> not shown here other than the <code>Logger</code> all inherit from <code>Singleton</code>. Once they are constructed an error will be thrown if you try to construct another per run of application.</p>\n\n<hr>\n\n<p>Here is what a sample application would look like while using the <code>Logger</code> class:</p>\n\n<p><em>-main.cpp-</em></p>\n\n<pre><code>#include \"Logger.h\"\n#include \"ExceptionHandler.h\"\n\nint main() {\n try {\n Logger log( \"log.txt\" );\n\n Logger::log( \"Hello World!\" ); // Default Info Type\n Logger::log( \"Hello World!, Logger::INFO ); // Explicitly Stating Info Type\n Logger::log( \"Hello World!, Logger::WARNING ); // Warning Type\n Logger::log( \"Hello World!, Logger::ERROR ); // Error Type\n\n // And since my ExceptionHandler also uses the Logger\n\n ExceptionHandler( \"Good Bye Cruel World!\" );\n\n } catch( ExceptionHandler&amp; e ) {\n std::cout &lt;&lt; \"Exception Thrown: \" &lt;&lt; e.getMessage() &lt;&lt; std::endl;\n return EXIT_FAILURE;\n } catch( ... ) {\n // Mind you I believe __FUNCTION__ is Windows or Visual Studio specific.\n // I've tried using __PRETTY_FUNCTION__ but for my purposes the formatting\n // wasn't quite right. You can use your desired choice. \n std::cout &lt;&lt; __FUNCTION__ &lt;&lt; \" Caught Unknown Exception\" &lt;&lt; std::endl;\n } \n}\n</code></pre>\n\n<p>My output to the console and text file would look like this from the above main.cpp.</p>\n\n<p><em>-Output-</em></p>\n\n<pre><code> Info [2019.02.20 6:54:17.282] Hello World!\n Info [2019.02.20 6:54:17.283] Hello World!\nWarning [2019.02.20 6:54:17.284] Hello World!\n Error [2019.02.20 6:54:17.285] Hello World!\n Error [2019.02.20 6:54:17.285] Good Bye Cruel World!\n</code></pre>\n\n<hr>\n\n<p>Another thing that was also incorporated but is Window's specific is that the code works with the standard console and it's property settings. When the logger writes to the console depending on what kind of text is being printed, basic <code>cout</code> will always white text against a black background, but as for the <code>Logger</code> types, each different type of error has a different set of parameters for the console's text color and background color. This way while debugging an application and some error is generated and or thrown; I can easily tell what type of error I'm reading just by the color of the text and background. </p>\n\n<hr>\n\n<p><em>-Disclosure-</em></p>\n\n<p>I hope that this gives you some insight towards a design of a versatile Logger. Now this code is not 100% mine as I did not fully write this. The overall structure and implementation has come from <code>Marek A. Krzeminski</code> as the original code is <code>(c)</code>. You can find the full source material <a href=\"https://www.marekknows.com/about.php\" rel=\"nofollow noreferrer\">here</a>. </p>\n\n<p>He has given me permission to share parts of his code in situations like this provided that: I do not show fully compliable source code and that I give him credit when I do so. I am free to use his original code for my own personal uses since I have subscribed to his content in that past as long as I don't use any of it for commercial purposes. I do however, like to use parts of his code when applicable when someone needs some advice towards specific algorithms, functionality or just overall code design. I like to take what I have learned from him and to share that learning experience. I am also in the process of redesigning his original class to be my own that is fully generic, portable, cross-platform capable while using modern C++ standards and techniques. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-20T12:21:19.557", "Id": "213878", "ParentId": "211957", "Score": "1" } } ]
{ "AcceptedAnswerId": "211963", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T00:22:50.930", "Id": "211957", "Score": "11", "Tags": [ "c++", "logging", "c++17" ], "Title": "Implementing a logging system in C++17" }
211957
<p>I needed to make a freight calculator and had to solve a bin packing problem. I utilized a <a href="https://github.com/skjolber/3d-bin-container-packing" rel="nofollow noreferrer">github package</a>.</p> <p>Basically with the help of <a href="https://stackoverflow.com/questions/54222030/how-to-create-an-algorithm-that-will-continue-running-an-algorithm-until-success">my stack overflow question</a> I made a class Method that</p> <ul> <li>Splits an array of packable items into the number of largest boxes that those items can fit into</li> <li>Splits the the item array into that number of items,</li> <li>Goes through each large box and tries to fit it into smaller boxes, if it does it will repack into the smaller container and the container will be in the results Container array</li> </ul> <hr> <pre><code>public class PackingService { private List&lt;Product&gt; productsRequest; private ArrayList&lt;BoxItem&gt; productsToPack; private Map&lt;Integer,ArrayList&lt;BoxItem&gt;&gt; productSetsMap; private Map&lt;Integer,Container&gt; packedContainerMap; public PackingService(List&lt;Product&gt; products) { //containers = SetContainers(); this.productsRequest = products; this.productSetsMap = new HashMap&lt;Integer, ArrayList&lt;BoxItem&gt;&gt;(); this.packedContainerMap = new HashMap&lt;Integer, Container&gt;(); } public ArrayList&lt;Container&gt; PackItems() { ArrayList&lt;Container&gt; packingResults = new ArrayList&lt;Container&gt;(); PrepareProductsToPack(this.productsRequest); ArrayList&lt;ArrayList&lt;BoxItem&gt;&gt; productSetsToPack = splitProductSet(productsToPack, getInitBoxCount(productsToPack)); int hashMapId = 0; for(int i = productSetsToPack.size()-1; i &gt;= 0; i--) { ArrayList&lt;BoxItem&gt; itemsToPack = productSetsToPack.get(i); productSetsMap.put(hashMapId, itemsToPack); pack(itemsToPack, hashMapId, 5); //pack largest sized box ++hashMapId; }; for (Map.Entry&lt;Integer, Container&gt; entry : packedContainerMap.entrySet()) { int containerKey = entry.getKey(); Container packedContainer = entry.getValue(); int smallestBoxSize = getSmallestBox(productSetsMap.get(containerKey), Integer.parseInt(packedContainer.getName())); packingResults.add(pack(productSetsMap.get(containerKey), smallestBoxSize)); } return packingResults; } private int getInitBoxCount(ArrayList&lt;BoxItem&gt; itemsToPack) { if(doProductsFit(itemsToPack, 5) == false) { ArrayList&lt;BoxItem&gt; temp1 = new ArrayList&lt;BoxItem&gt;(); ArrayList&lt;BoxItem&gt; temp2 = new ArrayList&lt;BoxItem&gt;(); for(int x = 0; x &lt; itemsToPack.size(); x++) { if(x &gt; itemsToPack.size() / 2) { temp1.add(itemsToPack.get(x)); } else { temp2.add(itemsToPack.get(x)); } } return getInitBoxCount(temp1) + getInitBoxCount(temp2); } return 1; } private int getSmallestBox(ArrayList&lt;BoxItem&gt; items, int boxsize) { if(doProductsFit(items, boxsize -1) != false) { if(boxsize == 1) return boxsize; return getSmallestBox(items, boxsize -1); } else return boxsize; } private boolean doProductsFit(ArrayList&lt;BoxItem&gt; products, int boxsize) { try { ArrayList&lt;Container&gt; testContainers = new ArrayList&lt;Container&gt;(); testContainers.add(GetContainer(boxsize)); Packager testPacker = new LargestAreaFitFirstPackager(testContainers); Container results = testPacker.pack(products); if(results==null) return false; else return true; } catch(Exception e) { return false; } } private void pack(ArrayList&lt;BoxItem&gt; products, int hashId ,int boxsize) { ArrayList&lt;Container&gt; testContainers = new ArrayList&lt;Container&gt;(); testContainers.add(GetContainer(boxsize)); Packager packer = new LargestAreaFitFirstPackager(testContainers); Container results = packer.pack(products); packedContainerMap.put(hashId, results); return; //results; } private Container pack(ArrayList&lt;BoxItem&gt; products , int boxsize) { ArrayList&lt;Container&gt; testContainers = new ArrayList&lt;Container&gt;(); testContainers.add(GetContainer(boxsize)); Packager packer = new LargestAreaFitFirstPackager(testContainers); Container results = packer.pack(products); return results; } private void PrepareProductsToPack(List&lt;Product&gt; products) { productsToPack = new ArrayList&lt;BoxItem&gt;(); for(Product product : products) { for(int i = 1; i &lt; product.getQuantity(); i++) { productsToPack.add(new BoxItem(new Box(product.getSku(), product.getProductDimensions().getRoundedWidth(), product.getProductDimensions().getRoundedDepth(), product.getProductDimensions().getRoundedHeight(), product.getProductDimensions().getRoundedWeight()))); } } } private Container GetContainer(int boxsize) { switch(boxsize) { case 1: return new Container("1", 10, 16, 6, 1000); case 2: return new Container("2", 11, 17, 11, 1000); case 3: return new Container("3", 12, 18, 15, 1000); case 4: return new Container("4", 13, 21, 16, 1000); case 5: return new Container("5", 17, 28, 17, 1000); default: return null; } //return null; } private static ArrayList&lt;ArrayList&lt;BoxItem&gt;&gt; splitProductSet (ArrayList&lt;BoxItem&gt; list, final int L) { ArrayList&lt;ArrayList&lt;BoxItem&gt;&gt; results = new ArrayList&lt;ArrayList&lt;BoxItem&gt;&gt;(); for (int i = 0; i &lt; L; i++) { ArrayList&lt;BoxItem&gt; items = new ArrayList&lt;BoxItem&gt;(); items.addAll(list.subList(i * list.size() / L, (i + 1) * list.size() / L)); results.add(items); System.out.println(items); } return results; } </code></pre> <p>I guess my biggest concern is that since I learned java in literally 1 month ('learned' I know C# as you can tell from the brackets being on new lines I'm sure) I'm not sure if I am following any best practices. For example my <code>hashmapId</code> feels insecure in the sense that the Id in the <code>productSetsMap</code> is not the same <code>Object</code> but instead the value is the same in <code>packContainerMap</code>.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T00:39:43.103", "Id": "211958", "Score": "1", "Tags": [ "java", "algorithm", "recursion" ], "Title": "Bin-packing-problem solution using recursion" }
211958
<p>I have been studying Haskell by myself for about a little over a year. And I have been stuck at monad/monad transformers for quite a while until recently some examples I read online enlightened me. So I decided to try on the following problem with writing monadic Haskell code. </p> <p>The problem is to evaluate a string that contains only 0-9, +, - and *, which represents addition, subtraction and multiplication separately. The string itself should represent a valid math expression and starts with a number always. </p> <pre><code>"3+5" -&gt; 8 "3+25*4" -&gt; 103 "1-2*2*2+7" -&gt; 0 </code></pre> <p>The goal of the exercise is not to write a perfect parsing engine to evaluate any math expression but to try to learn to use monad as a tool to write program that could be relatively straight forward in an imperative language such as C++. </p> <p>It is a linear algorithm and the main the idea is to use two stacks to track numbers and operators.</p> <ul> <li>On a new digit, update the current on-the-run number</li> <li>On any operator, push the on-the-run number to the number stack. Update the stacks if the existing operator on the top of the stack is '*'. If this new operator is a '+' or '-', update the stacks if only the existing operator is '+' or '-'. Once the update is done, push the new operator to the stack</li> <li>repeat the process until there is one number left.</li> </ul> <p>This algorithm is used to develop the solutions in both C++ and Haskell. </p> <p>C++ solution:</p> <pre class="lang-cpp prettyprint-override"><code> #include &lt;stack&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;stdexcept&gt; using namespace std; int calc(char c, int n1, int n2) { // cout &lt;&lt; c &lt;&lt; "--&gt;" &lt;&lt; n1 &lt;&lt; " and " &lt;&lt; n2 &lt;&lt; endl; if (c == '+') return n1+n2; else if (c == '-') return n1-n2; else if (c == '*') return n1*n2; else throw runtime_error("bad operator"); } void update(stack&lt;int&gt;&amp; numbers, stack&lt;char&gt;&amp; operators) { if (operators.size() + 1 != numbers.size()) throw runtime_error("bad"); char op = operators.top(); operators.pop(); int n2 = numbers.top(); numbers.pop(); int n1 = numbers.top(); numbers.pop(); numbers.push(calc(op, n1, n2)); } int processMath(const string&amp; input) { int num = 0; stack&lt;int&gt; numbers; stack&lt;char&gt; operators; for (char c : input) { if (c == '+' || c == '-' || c == '*') { numbers.push(num); num = 0; // reset number if (c == '*' &amp;&amp; !operators.empty() &amp;&amp; operators.top() == '*') { update(numbers, operators); } else if (c == '+' || c == '-') { // c is + or - while (!operators.empty()) update(numbers, operators); } operators.push(c); } else { num = num*10+(c-'0'); // cout &lt;&lt; "num=" &lt;&lt; num &lt;&lt; endl; } } numbers.push(num); while (!operators.empty()) update(numbers, operators); return numbers.top(); } // To execute C++, please define "int main()" int main() { string exp1 = "13+15"; string exp2 = "3+25*4"; string exp3 = "1-2*2*2+7"; cout &lt;&lt; exp1 &lt;&lt; endl &lt;&lt; processMath(exp1) &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; exp2 &lt;&lt; endl &lt;&lt; processMath(exp2) &lt;&lt; endl &lt;&lt; endl; cout &lt;&lt; exp3 &lt;&lt; endl &lt;&lt; processMath(exp3) &lt;&lt; endl &lt;&lt; endl; return 0; } </code></pre> <p>The following part is the Haskell program I came up with, without using anything specific for parsing or math evaluation.</p> <pre class="lang-hs prettyprint-override"><code>import Control.Monad.State import Data.Char data MathStacks = MathStacks { numbers :: [Int] , operators :: [Char] , current :: Int } deriving Show data EvalErr = ParseErr { position :: Int, reason :: String } | StackErr String | OpErr String deriving Show collapseOn :: MathStacks -&gt; [Char] -&gt; Either EvalErr MathStacks collapseOn ms@(MathStacks ns ops _) permittedOps | null ops = return ms | length ns &lt; 2 = Left $ StackErr ("numbers length &lt; 2:" ++ show ns) | not $ op `elem` "+-*" = Left $ OpErr ("invalid op=" ++ [op]) | not $ op `elem` permittedOps = return ms | otherwise = do n &lt;- calc op n1 n2 return $ ms { numbers=(n:nrest), operators=oprest } where (n2:n1:nrest) = ns (op:oprest) = ops calc :: Char -&gt; Int -&gt; Int -&gt; Either EvalErr Int calc c n1 n2 | c == '+' = return $ n1 + n2 | c == '-' = return $ n1 - n2 | c == '*' = return $ n1 * n2 | otherwise = Left $ OpErr ("invalid op=" ++ [c]) exec :: MathStacks -&gt; Either EvalErr MathStacks exec ms@(MathStacks ns ops curr) | nlen /= olen + 1 = Left $ StackErr ("inconsistent stacks") | olen == 0 = Right ms | otherwise = do let (n2:n1:nrest) = ns (op:oprest) = ops n &lt;- calc op n1 n2 return $ MathStacks (n:nrest) oprest curr where nlen = length ns olen = length ops exec' :: MathStacks -&gt; Either EvalErr MathStacks exec' ms@(MathStacks ns ops _) | null ops = return ms | otherwise = (exec ms) &gt;&gt;= exec' eval :: MathStacks -&gt; Either EvalErr Int eval (MathStacks ns ops curr) | nlen /= 1 || olen /= 0 = Left $ StackErr ("inconsistent stacks") | otherwise = Right $ head ns where nlen = length ns olen = length ops horner :: Int -&gt; Int -&gt; Int horner digit num = num * 10 + digit updateCurr :: Int -&gt; MathStacks -&gt; MathStacks updateCurr digit ms@(MathStacks _ _ curr) = ms { current=horner digit curr } updateOps :: Char -&gt; MathStacks -&gt; Either EvalErr MathStacks updateOps op ms@(MathStacks _ ops _) | op `elem` ['+', '-', '*'] = return $ ms { operators=(op:ops) } | otherwise = Left $ OpErr ("invalid op=" ++ [op]) updateNum :: MathStacks -&gt; MathStacks updateNum ms@(MathStacks ns _ curr) = ms { numbers=(curr:ns), current=0 } parse :: (Char, Int) -&gt; MathStacks -&gt; Either EvalErr MathStacks parse (c, idx) ms@(MathStacks ns ops curr) | c `elem` ['+', '-', '*'] = do -- current number run is done let ms0 = updateNum ms -- if there is existing multiplication on top. collapse it ms1 &lt;- collapseOn ms0 "*" ms2 &lt;- if c == '+' || c == '-' -- if there is existing addition or subtraction, do it then collapseOn ms1 "+-" else return ms1 updateOps c ms2 | isDigit c = Right $ updateCurr (digitToInt c) ms | otherwise = Left $ ParseErr idx ("err char at pos=" ++ show idx ++ " char:" ++ [c]) where nlen = length ns olen = length ops updateOnceT :: StateT MathStacks (Either EvalErr) () updateOnceT = do -- in side of StateT MathStacks (Either EvalErr) monad ms &lt;- get ms' &lt;- lift $ exec ms put ms' evalCharT :: (Char, Int) -&gt; StateT MathStacks (Either EvalErr) () evalCharT (c, idx) = do ms &lt;- get -- ms :: MathStacks -- promotes from Either EvalErr MathStacks type to StateT monad ms' &lt;- lift $ parse (c, idx) ms put ms' evalStringT :: String -&gt; StateT MathStacks (Either EvalErr) () evalStringT s = mapM_ evalCharT $ zip s [1..] evalStringE :: String -&gt; Either EvalErr MathStacks evalStringE s = foldM (flip parse) emptyStack $ zip s [1..] calcStringE :: String -&gt; Either EvalErr MathStacks calcStringE s = do (_, ms) &lt;- (runStateT $ evalStringT s) emptyStack return ms top :: MathStacks -&gt; Either EvalErr Int top ms = do let ns = numbers ms if null ns then Left $ StackErr "no value left" else return $ head ns calcString :: String -&gt; Either EvalErr Int calcString s = do ms &lt;- evalStringE s -- or use ms &lt;- calcStringE s ms' &lt;- exec' $ updateNum ms top ms' emptyStack = MathStacks [] [] 0 main :: IO () main = do print $ calcString "13+15" print $ calcString "3+25*4" print $ calcString "1-2*2*2+7" </code></pre> <p>The solution is a much longer program than the C++ counterpart, which is not the impression I got with Haskell program. The part that I used <code>StateT</code> monad transformer is probably not necessary (function <code>evalStringT</code> and function <code>calcStringE</code>), however even without these functions I don't think my solution will get much shorter. I thought using <code>State</code> monad could be a natural solution as it involves quite some state updates in the whole process but it looks like <code>foldM</code> over <code>Either</code> monad seems doable. Overall I am not even sure my solution is Haskellish enough so please point out anything that I can improve on my code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T11:29:10.187", "Id": "409908", "Score": "0", "body": "Can you explain why `\"1-2*2*2+7\"` yields `\"7\"` and not `0` (\\$1-8+7\\$)? You should probably add more detail on the grammar behind your math expressions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T12:27:23.997", "Id": "409913", "Score": "0", "body": "Sorry that was a typo. Fixed." } ]
[ { "body": "<p><strong>Update:</strong> <em>Zeta suggested that what I gave was not really a review. So I present a review first:</em></p>\n\n<ul>\n<li><p>The data type <code>EvalErr</code> has both <code>ParseErr</code>, <code>StackErr</code> and <code>OpErr</code>. A common error type for your entire pipeline seems like an OK idea, since the individual parts (parser, evaluator) will not be used independently.</p></li>\n<li><p>Your error values are all parameterised with a <code>String</code>, which can be super useful as you write the parser, but this makes testing negative cases more difficult. A <code>StackErr</code> may be parameterised with the actual stack that broke. This also makes negative testing easier; a good sign of code quality is testability. You can always produce meaningful error messages based on <code>StackErr ns</code> (and whatever remaining context that makes for a good message; what was the operator that failed?).</p>\n\n<p>Similarly, <code>OpErr</code> could take a single <code>Char</code>.</p></li>\n<li><p>You perform unsafe pattern matching in the <code>where</code> of <code>collapseOn</code>:</p>\n\n<pre><code>where (n2:n1:nrest) = ns\n (op:oprest) = ops\n</code></pre>\n\n<p>You justify this by guarding against too short lists.</p>\n\n<p>But this creates a dependency between multiple lines.</p>\n\n<p>You can avoid this either by using pattern matching to <em>restrict access</em> to executing code: A function body that will only execute once a pattern matches is safe. Or you can extract values monadically, providing for more abstraction (including implicit error handling). For example, a monadic stack may work like:</p>\n\n<pre><code>eval Add = do\n v1 &lt;- pop\n v2 &lt;- pop\n push (v1 + v2)\n</code></pre></li>\n<li><p>I'm not sure exactly what <code>collapseOn</code> does. It handles a bunch of types of errors that are at different levels of abstraction. And then it calls <code>eval</code>, pushes the result to the stack, and removes an operator from a list of operators for some reason or other.</p>\n\n<p>Is <em>collapse</em> a metaphor for error handling? Or for reducing the stack?</p>\n\n<p>So I'd say it does too many things.</p></li>\n<li><p>You can check that there are enough elements via pattern matching or monadic popping from the stack without calculating the entire length (a full traversal of the stack) every time you handle a new element.</p></li>\n<li><p>Your list of supported operators is repeated many times. This makes adding new ones difficult and error-prone. The precedence and associativity of your operators is embedded in the ordering of your code and makes it hard to derive, extend or verify that they're right.</p></li>\n<li><p>The following <code>StateT</code> functions seem a little off:</p>\n\n<pre><code>updateOnceT :: StateT MathStacks (Either EvalErr) ()\nupdateOnceT = do\n ms &lt;- get\n ms' &lt;- lift $ exec ms\n put ms'\n\nevalCharT :: (Char, Int) -&gt; StateT MathStacks (Either EvalErr) ()\nevalCharT (c, idx) = do\n ms &lt;- get -- ms :: MathStacks\n ms' &lt;- lift $ parse (c, idx) ms \n put ms'\n</code></pre>\n\n<p>There is a <a href=\"https://hackage.haskell.org/package/mtl-2.2.2/docs/Control-Monad-State-Lazy.html#v:modify\" rel=\"nofollow noreferrer\"><code>modify</code></a> combinator. But I would probably ditch the <code>StateT</code> altogether to begin with and either</p>\n\n<ol>\n<li><p>Build a non-monadic stack-based parser from scratch, simplify it and extend it. (You'll eventually end up with something that is somewhat equivalent to parser combinators, since they're also recursive descent parsers, but not explicitly recursive.)</p></li>\n<li><p>Build a parser using parser combinators (see below) and either construct a syntax tree or make the parser produce the evaluator directly.</p></li>\n</ol></li>\n<li><p>I'd recommend reading up on <a href=\"https://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow noreferrer\"><em>separation of concerns</em></a>.</p></li>\n</ul>\n\n<hr>\n\n<p><strong>Previous:</strong> <em>I wrote this suggestion to solve the problem by dividing the problem into parsing and evaluation, and to use other abstractions than a stack-based algorithm.</em></p>\n\n<p>What you can do is convert the expression into a syntax tree using a parser combinator library like <a href=\"http://akashagrawal.me/beginners-guide-to-megaparsec/\" rel=\"nofollow noreferrer\">Megaparsec</a> and evaluate that syntax tree. The author of Megaparsec, Mark Karpov, wrote a tutorial called <a href=\"https://markkarpov.com/megaparsec/parsing-simple-imperative-language.html\" rel=\"nofollow noreferrer\">Parsing a simple imperative language</a>. It has a section called <a href=\"https://markkarpov.com/megaparsec/parsing-simple-imperative-language.html#expressions\" rel=\"nofollow noreferrer\">Expressions</a> where he demonstrates the <code>makeExprParser</code> combinator:</p>\n\n<pre><code>aExpr :: Parser AExpr\naExpr = makeExprParser aTerm aOperators\n\naOperators :: [[Operator Parser AExpr]]\naOperators =\n [ [ Prefix (Neg &lt;$ symbol \"-\") ]\n , [ InfixL (ABinary Multiply &lt;$ symbol \"*\")\n , InfixL (ABinary Divide &lt;$ symbol \"/\") ]\n , [ InfixL (ABinary Add &lt;$ symbol \"+\")\n , InfixL (ABinary Subtract &lt;$ symbol \"-\") ]\n ]\n</code></pre>\n\n<p>As for building a monadic evaluator, I'd read <a href=\"https://wiki.haskell.org/The_Monadic_Way/Part_I\" rel=\"nofollow noreferrer\">The Monadic Way</a> on the Haskell Wiki. It starts by building a regular evaluator and then adds features that are greatly complicated by the lack of monads, and then it introduces them.</p>\n\n<p>It seems that your examples do not mention division, which is a pretty good example of something that may fail during evaluation because of division by zero. If you had the following syntax tree,</p>\n\n<pre><code>data AExpr\n = IntConst Integer\n | Neg AExpr\n | ABinary ABinOp AExpr AExpr\n deriving (Show)\n\ndata ABinOp\n = Add\n | Subtract\n | Multiply\n | Divide\n deriving (Show, Eq)\n\ndata Error\n = DivisionByZero\n deriving (Show, Eq)\n</code></pre>\n\n<p>you could write something like,</p>\n\n<pre><code>eval :: AExpr -&gt; Either Error Integer\neval (IntConst i) = return i\neval (Neg e) = negate &lt;$&gt; eval e\neval (ABinary op e1 e2) = do\n i1 &lt;- eval e1\n i2 &lt;- eval e2\n if op == Divide &amp;&amp; i2 == 0 then Left DivisionByZero else\n return $ binop op i1 i2\n\nbinop :: ABinOp -&gt; (Integer -&gt; Integer -&gt; Integer)\nbinop Add = (+)\nbinop Subtract = (-)\nbinop Multiply = (*)\nbinop Divide = quot\n</code></pre>\n\n<p>This separates the concerns of syntax analysis and evaluation. This also means that different kinds of errors are handled at different layers of abstraction. And it means you get a declarative, high-level way of expressing the precedence and associativity of your operators.</p>\n\n<hr>\n\n<p><strong>More:</strong> <em>I added this after to suggest a middle ground.</em></p>\n\n<p>If you think <code>makeExprParser</code> feels like cheating, and you think the intermediate syntax-tree representation is redundant, you can</p>\n\n<ol>\n<li><p>Make your life harder by writing your expression parser using the <a href=\"http://dev.stephendiehl.com/fun/002_parsers.html\" rel=\"nofollow noreferrer\"><code>chainl</code>, <code>chainr</code> etc.</a> combinators, or write your own hierarchy of nested combinators (makes precedence and associativity slightly more obscure, but much less so than an explicitly recursive function would).</p></li>\n<li><p>Make the program simpler by writing a parser that generates a function that evaluates:</p>\n\n<pre><code>evalP :: Parser (String -&gt; Integer)\nevalP = ...\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T09:02:51.263", "Id": "410207", "Score": "1", "body": "Hm. You have presented a well-thought alternative solution, but haven't reviewed the code. Please explain your reasoning (why it is better than the original) so that the author and other readers can learn from your thought process. I'd start with the saparation of concerns first, as it is the most prominent issue of the original code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T08:04:50.480", "Id": "212123", "ParentId": "211966", "Score": "3" } } ]
{ "AcceptedAnswerId": "212123", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T04:27:17.570", "Id": "211966", "Score": "6", "Tags": [ "haskell", "math-expression-eval", "monads" ], "Title": "Writing monadic Haskell to evaluate arithmetic expression" }
211966
<h3>TLDR</h3> <p>Python developer; first project in Go; looking for feedback :)</p> <p><a href="https://github.com/gtalarico/pm" rel="nofollow noreferrer">Repo</a></p> <h3>Overview</h3> <p>I just started learning Go (need to use it at work). As a fan of project-based learning, I put together a small program to practice writing Go and setting up a project from scratch.</p> <p>As a Python developer, many of Go's elements are new to me (structs, interfaces, etc) - not to mention static typing and compilation.</p> <p>I was hoping someone could review the code &amp; project organization and share some constructive feedback. Thanks in advance!</p> <p><strong>What I am interested in:</strong></p> <ul> <li>Improvements to overall program structure</li> <li>Improvements to non-idiomatic uses of the language</li> <li>Improvements to usage of types</li> <li>Error handling?</li> <li>Any other feedback you might have!</li> </ul> <p><strong>Not interested in:</strong></p> <ul> <li>Replacing code with libraries - I know there some libraries that help with CLI interface, args parsing etc. but I wanted to build this the hard way since this is primarily a learning exercise :)</li> </ul> <hr> <h1>The Program</h1> <p>A simple CLI tool to help you manage and jump around your local projects.</p> <h3>Usage</h3> <p><strong>Create Projects</strong></p> <pre><code>$ pm add newproject ~/code/repos/newproject $ pm add another ~/code/go/src/github.com/username/another </code></pre> <p><strong>Remove project</strong></p> <pre><code>$ pm remove newproject </code></pre> <p><code>pm add</code> and <code>pm remove</code> is used to implicitly manage a json file with those configs. This config file is used by other commands to track "projects".</p> <p><code>~/.pm.json</code></p> <pre><code>{ "projects": [ { "path": "~/code/repos/newproject", "name": "newproject" }, { "path": "~/code/go/src/github.com/username/another", "name": "another" } ] } </code></pre> <p><strong>Go to project</strong> (finds project in config and starts new shell at config location</p> <pre><code>$ pm go newproject Starting Shell... ~/code/repos/newproject $ $ pm go another Starting Shell... ~/code/go/src/github.com/username/another $ </code></pre> <p><strong>List project</strong> (shows list of projects)</p> <pre><code>$ pm list newproject another </code></pre> <hr> <h1>Code</h1> <p>The full program is <a href="https://github.com/gtalarico/pm" rel="nofollow noreferrer">on this repo</a> but I copied all relevant files below.</p> <h3>Package Structure</h3> <pre><code>pm/ + main.go + cmd/ + main.go + internal/ + commands/ + cli/ + config/ </code></pre> <h3>Entry Point</h3> <pre><code>// main.go package main import ( "github.com/gtalarico/pm/cmd" ) func main() { cmd.Run() } </code></pre> <h3>Cmd Entry Point</h3> <pre><code>// cmd/main.go package cmd import ( "os" "github.com/gtalarico/pm/internal/cli" "github.com/gtalarico/pm/internal/commands" "github.com/gtalarico/pm/internal/config" ) func Run() { // Get all args, excluding binary name var args []string = os.Args[1:] cmdName, posArgs, err := cli.ValidateArgs(args) // No Args if err != nil { cli.ShowUsage() os.Exit(1) } // Checks for invalid command name // and number of args for a given command cmd, err := commands.GetCommand(cmdName) if err != nil { cli.Abort(err) } if cmd.NumArgs != len(posArgs) { cli.ShowCmdUsage(cmd.UsageMsg) } // Get Config config, err := config.ReadConfig() if err != nil { cli.Abort(err) } // Run Command cmd.Run(posArgs, config) } </code></pre> <h3>Commands Module</h3> <p>Types, command functions and definitions</p> <p>Command Type</p> <pre><code>// internal/commands/types.go package commands import "github.com/gtalarico/pm/internal/config" type Command struct { Name string NumArgs int UsageMsg string Run func([]string, config.Config) } </code></pre> <p>Commands Main</p> <pre><code>// internal/commands/commands.go package commands import ( "fmt" "os" "path/filepath" "github.com/gtalarico/pm/internal/cli" "github.com/gtalarico/pm/internal/config" "github.com/pkg/errors" ) func GetCommand(cmdName string) (command Command, err error) { for _, cmd := range Commands { if cmd.Name == cmdName { command = cmd return } } err = errors.New("invalid command") return } func CommandList(args []string, config config.Config) { cli.PrintProjects(config.Projects) } func CommandGo(args []string, cfg config.Config) { projectName := args[0] project, err := config.GetOneProject(projectName, cfg) if err != nil { cli.Abort(errors.Wrap(err, projectName)) } else { cli.Shell(project.Path) } } func CommandAdd(args []string, cfg config.Config) { projectName := args[0] projectPath := args[1] absPath, err := filepath.Abs(projectPath) if err != nil { cli.Abort(errors.Wrap(err, "invalid path")) } newProject := config.Project{ Name: projectName, Path: absPath, } projects := config.SearchProjects(projectName, cfg) if len(projects) == 0 { cfg.Projects = append(cfg.Projects, newProject) } else { for i, project := range cfg.Projects { if project.Name == newProject.Name { cfg.Projects[i] = newProject } } } writeError := config.WriteConfig(cfg) if writeError != nil { cli.Abort(writeError) } cli.PrintProjects(cfg.Projects) } func CommandRemove(args []string, cfg config.Config) { var projectToKeep []config.Project projectName := args[0] matchedProject, err := config.GetOneProject(projectName, cfg) if err != nil { cli.Abort(errors.Wrap(err, projectName)) } else { for _, project := range cfg.Projects { if project.Name != matchedProject.Name { projectToKeep = append(projectToKeep, project) } } cfg.Projects = projectToKeep promptMsg := fmt.Sprintf("Delete '%s' [Y/n]? ", matchedProject.Name) confirm := cli.ConfirmPrompt(promptMsg, true) if confirm == false { os.Exit(0) } writeError := config.WriteConfig(cfg) if writeError != nil { cli.Abort(writeError) } cli.PrintProjects(projectToKeep) } } var Commands = [...]Command{ Command{ Name: "list", NumArgs: 0, // pm list UsageMsg: "list", Run: CommandList, }, Command{ Name: "add", NumArgs: 2, // pm add &lt;name&gt; &lt;path&gt; UsageMsg: "add &lt;project-name&gt; &lt;path&gt;", Run: CommandAdd, }, Command{ Name: "remove", NumArgs: 1, // pm remove &lt;query&gt; UsageMsg: "remove &lt;project-name&gt;", Run: CommandRemove, }, Command{ Name: "go", NumArgs: 1, // pm go &lt;project-name&gt; UsageMsg: "go &lt;project-name&gt;", Run: CommandGo, }, } </code></pre> <h3>Cli Module</h3> <p>Usage</p> <pre><code>// internal/commands/usage.go package cli import ( "fmt" "os" ) // Shows usage of all available commands and exits func ShowUsage() { usage := `Usage: pm list pm go &lt;project-name&gt; pm add &lt;project-name&gt; &lt;project-path&gt; pm remove &lt;project-name&gt;` fmt.Fprintln(os.Stderr, usage) } // Shows usage of a command and exits func ShowCmdUsage(usageMsg string) { fmt.Fprint(os.Stderr, fmt.Sprintf("Usage: pm %s", usageMsg)) os.Exit(1) } </code></pre> <p>Args</p> <pre><code>// internal/commands/args.go package cli import "github.com/pkg/errors" func ValidateArgs(args []string) (cmdName string, posArgs []string, err error) { if len(args) == 0 { err = errors.New("missing command name") return } if len(args) &gt; 1 { posArgs = args[1:] } cmdName = args[0] return } </code></pre> <p>Output</p> <pre><code>// internal/cli/output.go // Poorly named file... package cli import ( "fmt" "log" "os" "strings" "github.com/gtalarico/pm/internal/config" ) func Abort(err error) { // Show error message and exit with error fmt.Fprint(os.Stderr, err.Error()) os.Exit(1) } // Prompts user to confirm a "y" or "n" and returns as boolean func ConfirmPrompt(promptMsg string, default_ bool) bool { fmt.Print(promptMsg) var response string _, err := fmt.Scanln(&amp;response) if err != nil { log.Fatal(err) } if response == "" { return default_ } r := (strings.ToLower(response) == "y") return r } func PrintProjects(projects []config.Project) { for _, project := range projects { fmt.Println(project.Name) } } </code></pre> <p>Shell Handles New Shell Process Spawning</p> <pre><code>// internal/cli/shell.go package cli import ( "fmt" "os" "os/user" "github.com/pkg/errors" ) func handleShellError() { shellError := recover() if shellError != nil { err := errors.New("shell error") Abort(err) } } func Shell(cwd string) { //technosophos.com/2014/07/11/start-an-interactive-shell-from-within-go.html defer handleShellError() fmt.Println("Starting new shell") fmt.Println("Use 'CTRL + C' or '$ exit' to terminate child shell") // Get the current user. me, err := user.Current() if err != nil { panic(err) } // If needed: sets env vars // os.Setenv("SOME_VAR", "1") // Transfer stdin, stdout, and stderr to the new process // and also set target directory for the shell to start in. pa := os.ProcAttr{ Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}, Dir: cwd, } // Start up a new shell. // Note that we supply "login" twice. // -fpl means "don't prompt for PW and pass through environment." // fmt.Print("&gt;&gt; Starting a new interactive shell") proc, err := os.StartProcess("/usr/bin/login", []string{"login", "-fpl", me.Username}, &amp;pa) if err != nil { panic(err) } // Wait until user exits the shell state, err := proc.Wait() if err != nil { panic(err) } fmt.Printf("Exited Go Sub Shell\n %s\n", state.String()) } </code></pre> <h3>Config Module</h3> <p>Handles reading and writing of config file, including types for json encoding/decoding.</p> <p>Types</p> <pre><code>// internal/config/types.go package config type Config struct { Projects []Project `json:"projects"` } type Project struct { Path string `json:"path"` Name string `json:"name"` } </code></pre> <p>Config - Main config functions</p> <pre><code>// internal/config/config.go package config import ( "encoding/json" "fmt" "io/ioutil" "os" "github.com/pkg/errors" ) const CFG_FILENAME = ".pm.json" func WriteConfig(config Config) (err error) { path := ConfigFilepath() configJson, _ := json.MarshalIndent(config, "", " ") writeErr := ioutil.WriteFile(path, configJson, 0644) err = errors.Wrap(writeErr, path) return } func CreateConfig(path string) (cfg Config, err error) { projects := []Project{} cfg = Config{projects} err = WriteConfig(cfg) return } func ReadConfig() (cfg Config, err error) { path := ConfigFilepath() configBytes, readErr := ioutil.ReadFile(path) if readErr != nil { // Try creating new file in case of read error (eg. file not found) cfg, err = CreateConfig(path) return } parsingError := json.Unmarshal(configBytes, &amp;cfg) if parsingError != nil { err = errors.Wrap(parsingError, path) return } return } // Gets user home path using environment variable '$HOME' func UserHomePath() (path string) { path = os.Getenv("HOME") if path == "" { err, _ := fmt.Printf("Could not get home directory") panic(err) } return } // Gets the full config filepath func ConfigFilepath() string { return UserHomePath() + fmt.Sprintf("/%s", CFG_FILENAME) } </code></pre> <p>Search</p> <pre><code>// internal/config/search.go package config import ( "errors" "fmt" "strings" ) func SearchProjects(query string, config Config) []Project { var projects []Project for _, project := range config.Projects { if strings.Contains(project.Name, query) { projects = append(projects, project) } } return projects } func GetOneProject(query string, config Config) (project Project, err error) { projects := SearchProjects(query, config) numProjects := len(projects) if numProjects == 1 { project = projects[0] } if numProjects == 0 { err = errors.New("no match") } if numProjects &gt; 1 { for _, project := range projects { fmt.Println(project.Name) } err = errors.New("multiple matches") } return } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T05:10:51.010", "Id": "211967", "Score": "5", "Tags": [ "go" ], "Title": "CLI Utility Go - First Go Program" }
211967
<p>I implemented a very simple blocking uart interface. Most of the serial instruments I interface with are master/slave and I have to wait on data to proceed forward. I am contemplating add some template code to accept any container iterator, but for now I will probably use array or vector. Also, I open the serial port immediately in the constructor and only close it in the destructor. If I don't keep it open some of the other calls will not perform their intended function. </p> <p>Things I implemented that I'm working on understanding better</p> <ol> <li>Pimpl Idiom</li> <li>Exception Handling</li> <li>RAII (close handle on destruction)</li> <li>Constructor defaults</li> </ol> <p>Any comments/improvements are welcome. </p> <p>SerialPort.h</p> <pre><code>#pragma once #include &lt;memory&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;chrono&gt; namespace Lite { class SerialPort { public: enum class PARITY { NONE, ODD, EVEN, MARK, SPACE }; enum class STOPBITS { ONE, ONEPT5, TWO }; enum class FLOWCONTROL { SW, HW, NONE }; SerialPort(const std::string port = "COM1", const uint32_t baudRate = 9600, const PARITY parity = PARITY::NONE, const STOPBITS stopBit = STOPBITS::ONE, const FLOWCONTROL flowControl = FLOWCONTROL::NONE, const uint8_t databits = 8); ~SerialPort(); SerialPort(const SerialPort&amp;) = delete; SerialPort(SerialPort&amp;&amp;) = delete; SerialPort&amp; operator=(const SerialPort&amp;) = delete; SerialPort&amp; operator=(SerialPort&amp;&amp;) = delete; size_t ReadBytes(uint8_t* data, const size_t bytesToRead); size_t SendBytes(const uint8_t* data, const size_t bytesToSend); // thinking of adding a container template version of read and send void SetRxTimeouts(const std::chrono::milliseconds&amp; timeOut, const std::chrono::milliseconds&amp; readIntervalTimeout); void FlushRx(); void FlushTx(); size_t CurrentRxQueueSize(); size_t CurrentTxQueueSize(); size_t CurrentRxInQueue(); size_t CurrentTxInQueue(); private: struct Impl; std::unique_ptr&lt;Impl&gt; m_impl; }; class SerialPortRuntimeException : public std::runtime_error { public: SerialPortRuntimeException(const char *message) : std::runtime_error(message) {} }; class SerialPortRangeError : public std::range_error { public: SerialPortRangeError(const char *message) : std::range_error(message) {} }; } </code></pre> <p>SerialPort.cpp</p> <pre><code>#if defined(_WIN32) #include &lt;Windows.h&gt; #include &lt;CommCtrl.h&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;stdexcept&gt; #include "SerialPort.h" struct Lite::SerialPort::Impl { BYTE ParityValue(const SerialPort::PARITY parity); BYTE StopBitsValue(const SerialPort::STOPBITS stopBits); DCB&amp; FlowControlValue(const SerialPort::FLOWCONTROL, DCB&amp; dcb); std::string GetCommError(); HANDLE m_hCommPort; }; std::string Lite::SerialPort::Impl::GetCommError() { LPSTR lpMsgBuf; DWORD errCode = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, errCode, 0, // Default language (LPTSTR)&amp;lpMsgBuf, 0, NULL ); std::stringstream temp; temp &lt;&lt; lpMsgBuf; return temp.str(); } Lite::SerialPort::SerialPort(const std::string name, const uint32_t baudRate, const PARITY parity, const STOPBITS stopBit, const FLOWCONTROL flowControl, const uint8_t databits) : m_impl(std::make_unique &lt;Impl&gt;()) { m_impl-&gt;m_hCommPort = CreateFile(name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING, 0, 0 ); if(m_impl-&gt;m_hCommPort == INVALID_HANDLE_VALUE) { throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); } DCB dcb; dcb.DCBlength = sizeof(DCB); if(!GetCommState(m_impl-&gt;m_hCommPort, &amp;dcb)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); dcb.BaudRate = baudRate; dcb.ByteSize = databits; dcb.Parity = m_impl-&gt;ParityValue(parity); dcb.StopBits = m_impl-&gt;StopBitsValue(stopBit); m_impl-&gt;FlowControlValue(flowControl, dcb); if (!SetCommState(m_impl-&gt;m_hCommPort, &amp;dcb)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); return; } Lite::SerialPort::~SerialPort() { CloseHandle(m_impl-&gt;m_hCommPort); return; } size_t Lite::SerialPort::ReadBytes(uint8_t* data, const size_t bytesToRead) { auto tempBytesToRead = bytesToRead; if (tempBytesToRead &gt; MAXDWORD) tempBytesToRead = MAXDWORD; DWORD bytesRead; if (!ReadFile(m_impl-&gt;m_hCommPort, &amp;data, tempBytesToRead, &amp;bytesRead, NULL)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); return bytesRead; } size_t Lite::SerialPort::SendBytes(const uint8_t* data, const size_t bytesToSend) { auto tempBytesToSend = bytesToSend; if (tempBytesToSend &gt; MAXDWORD) tempBytesToSend = MAXDWORD; DWORD sentSize; if(!WriteFile(m_impl-&gt;m_hCommPort, &amp;data, tempBytesToSend, &amp;sentSize, NULL)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); return sentSize; } void Lite::SerialPort::SetRxTimeouts(const std::chrono::milliseconds&amp; timeOut, const std::chrono::milliseconds&amp; readIntervalTimeout) { COMMTIMEOUTS to; if (!GetCommTimeouts(m_impl-&gt;m_hCommPort, &amp;to)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); to.ReadIntervalTimeout = readIntervalTimeout.count(); to.ReadTotalTimeoutMultiplier = 0; to.ReadTotalTimeoutConstant = timeOut.count(); if(!SetCommTimeouts(m_impl-&gt;m_hCommPort, &amp;to)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); return; } void Lite::SerialPort::FlushRx() { if (!PurgeComm(m_impl-&gt;m_hCommPort, PURGE_RXCLEAR)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); return; } void Lite::SerialPort::FlushTx() { if (!PurgeComm(m_impl-&gt;m_hCommPort, PURGE_TXCLEAR)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); return; } size_t Lite::SerialPort::CurrentRxQueueSize() { COMMPROP cp; if (!GetCommProperties(m_impl-&gt;m_hCommPort, &amp;cp)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); return cp.dwCurrentRxQueue; } size_t Lite::SerialPort::CurrentTxQueueSize() { COMMPROP cp; if (!GetCommProperties(m_impl-&gt;m_hCommPort, &amp;cp)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); return cp.dwCurrentTxQueue; } size_t Lite::SerialPort::CurrentRxInQueue() { COMSTAT cs; DWORD error; if (!ClearCommError(m_impl-&gt;m_hCommPort, &amp;error, &amp;cs)) throw SerialPortRuntimeException(m_impl-&gt;GetCommError().c_str()); return cs.cbInQue; } size_t Lite::SerialPort::CurrentTxInQueue() { COMSTAT cs; DWORD error; if (!ClearCommError(m_impl-&gt;m_hCommPort, &amp;error, &amp;cs)) throw std::runtime_error(m_impl-&gt;GetCommError().c_str()); return cs.cbOutQue; } BYTE Lite::SerialPort::Impl::ParityValue(const SerialPort::PARITY parity) { BYTE temp; switch (parity) { case SerialPort::PARITY::NONE: temp = NOPARITY; break; case SerialPort::PARITY::ODD: temp = ODDPARITY; break; case SerialPort::PARITY::EVEN: temp = EVENPARITY; break; case SerialPort::PARITY::MARK: temp = MARKPARITY; break; case SerialPort::PARITY::SPACE: temp = SPACEPARITY; break; default: throw SerialPortRangeError("Parity Enum out of Range"); break; } return temp; } BYTE Lite::SerialPort::Impl::StopBitsValue(const SerialPort::STOPBITS stopBits) { BYTE temp; switch (stopBits) { case SerialPort::STOPBITS::ONE: temp = ONESTOPBIT; break; case SerialPort::STOPBITS::ONEPT5: temp = ONE5STOPBITS; break; case SerialPort::STOPBITS::TWO: temp = TWOSTOPBITS; break; default: throw SerialPortRangeError("Stop Bits Enum out of range"); break; } return temp; } DCB&amp; Lite::SerialPort::Impl::FlowControlValue(const SerialPort::FLOWCONTROL flowcontrol, DCB&amp; dcb) { switch (flowcontrol) { case Lite::SerialPort::FLOWCONTROL::SW: dcb.fOutxCtsFlow = false; dcb.fRtsControl = RTS_CONTROL_DISABLE; dcb.fOutX = true; dcb.fInX = true; break; case Lite::SerialPort::FLOWCONTROL::HW: dcb.fOutxCtsFlow = true; dcb.fRtsControl = RTS_CONTROL_HANDSHAKE; dcb.fOutX = false; dcb.fInX = false; break; case Lite::SerialPort::FLOWCONTROL::NONE: dcb.fOutxCtsFlow = false; dcb.fRtsControl = RTS_CONTROL_DISABLE; dcb.fOutX = false; dcb.fInX = false; break; default: throw SerialPortRangeError("Flow Control Enum out of range"); break; } return dcb; } #endif </code></pre> <p>main.cpp</p> <pre><code>#include &lt;iostream&gt; #include "SerialPort.h" void HandleException() { try { throw; } catch (const Lite::SerialPortRuntimeException &amp;e) { std::cerr &lt;&lt; e.what() &lt;&lt; '\n'; // catches standard error message } catch (const Lite::SerialPortRangeError &amp;e) { std::cerr &lt;&lt; e.what() &lt;&lt; '\n';; // catches standard error message } return; } int main() { try { Lite::SerialPort sp{ "COM5", 4800 }; sp.FlushRx(); sp.FlushTx(); std::cout &lt;&lt; "rx queue size: " &lt;&lt; sp.CurrentRxQueueSize() &lt;&lt; '\n'; std::cout &lt;&lt; "rx in queue size: " &lt;&lt; sp.CurrentRxInQueue() &lt;&lt; '\n'; sp.SetRxTimeouts(std::chrono::milliseconds(1000), std::chrono::milliseconds(1000)); std::vector&lt;uint8_t&gt; writeBuf(100); sp.SendBytes(writeBuf.data(), writeBuf.size()); std::vector&lt;uint8_t&gt; test(sp.CurrentRxQueueSize()); test.resize(sp.ReadBytes(test.data(), 100)); sp.FlushRx(); sp.FlushTx(); } catch (...) { HandleException(); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T05:57:48.310", "Id": "211971", "Score": "1", "Tags": [ "c++", "object-oriented", "windows", "interface", "serial-port" ], "Title": "Simple Serial Port Windows Interface" }
211971
<p>I just deep dived to Python and I came with this <a href="https://www.hackerrank.com/challenges/30-inheritance/problem" rel="nofollow noreferrer">Hackerrank problem</a>:</p> <p>Create two class, <code>Person</code> with <code>firstName</code>, <code>lastName</code>, <code>idNumber</code> as its attributes with method <code>printPerson()</code> simply print last name and first name and id, and the derived class <code>Student</code>.</p> <p>The <code>Student</code> class has additional attributes, its score and an array with two value, and I need to calculate the average of all scores in this array. Then finally I will decide which letter I should assign to this average score and print it.</p> <p>Sample Input:</p> <pre><code>Heraldo Memelli 8135627 2 100 80 </code></pre> <p>Sample Output:</p> <pre><code>Name: Memelli, Heraldo ID: 8135627 Grade: O </code></pre> <p>My code in Python 3:</p> <pre><code>class Person: def __init__(self, firstName, lastName, idNumber): self.firstName = firstName self.lastName = lastName self.idNumber = idNumber def printPerson(self): print("Name:", self.lastName + ",", self.firstName) print("ID:", self.idNumber) def avg(a): return sum(a)/len(a) def m(a): return [int(r) for r in list(a.values())[0].split('-')] class Student(Person): def __init__(self, f, l, i, s): Person.__init__(self, f, l, i) self.s = s def calculate(self): avgScore = avg(self.s) scoreList = [ {'O': '90-100'}, {'E': '80-89'}, {'A': '70-79'}, {'P': '55-69'}, {'D': '40-54'}, {'T': '0-39'}, ] scoreLetter = list([x for x in scoreList if m(x)[0] &lt;= avgScore == avgScore &lt;=m(x)[1]][0].keys())[0] return '{}'.format(scoreLetter) line = input().split() firstName = line[0] lastName = line[1] idNum = line[2] numScores = int(input()) # not needed for Python scores = list( map(int, input().split()) ) s = Student(firstName, lastName, idNum, scores) s.printPerson() print("Grade:", s.calculate()) </code></pre> <p>It passes all test cases. Could you please help me to review it and give me some advice?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T11:25:57.277", "Id": "409906", "Score": "0", "body": "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 to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." } ]
[ { "body": "<ul>\n<li><p>Read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> the Python style guide</p>\n\n<p>Functions and variables should be <code>lower_snake_case</code></p></li>\n<li><p>Naming</p>\n\n<p>Single letter variable names are a bad habit. Code should be self explanatory and function names like <code>m()</code> don't tell what they are supposed to do</p></li>\n<li><p>Instead of the <code>printPerson()</code> function, override the magic function <code>__str__</code></p>\n\n<p>Doing this you can do <code>print(student)</code> to print the class</p></li>\n<li><p>You should make the <code>avg</code> function a part of the <code>Student</code> class</p></li>\n<li><p>Your grade function can be simplified</p>\n\n<blockquote>\n<pre><code> scoreList = [\n {'O': '90-100'},\n {'E': '80-89'},\n {'A': '70-79'},\n {'P': '55-69'},\n {'D': '40-54'},\n {'T': '0-39'},\n]\n</code></pre>\n</blockquote>\n\n<p>When you swap the key and values around, and loop over them in order</p>\n\n<pre><code>self.score_dictionary = {\n 90 : 'O',\n 80 : 'E',\n 70 : 'A',\n 55 : 'P',\n 40 : 'D',\n 0 : 'T'\n}\n</code></pre>\n\n<p>It becomes clear that if the average is higher than the value that should be the grade to give, else go to the next value</p>\n\n<p>This will happen automatically with Python3.7+, or else you can make use of an <a href=\"https://docs.python.org/3/library/collections.html#collections.OrderedDict\" rel=\"nofollow noreferrer\">OrderedDict</a></p>\n\n<pre><code>from collections import OrderedDict\nself.score_dictionary = OrderedDict([\n (90, 'O'),\n (80, 'E'),\n (70, 'A'),\n (55, 'P'),\n (40, 'D'),\n (0, 'T')\n])\n</code></pre>\n\n<p>Thnx <a href=\"https://codereview.stackexchange.com/users/98493/graipher\">@Graipher</a>, for correcting my mistake regarding the OrderedDict</p>\n\n<p>Another way (which might be clearer) is to loop over the dictionary keys in sorted order</p></li>\n<li><p>You can unpack multiple arguments in one go</p>\n\n<blockquote>\n<pre><code>line = input().split()\nfirstName = line[0]\nlastName = line[1]\nidNum = line[2]\n</code></pre>\n</blockquote>\n\n<p>Could be </p>\n\n<pre><code>f, l, i = input().split()\n</code></pre></li>\n<li><p>It is Python idion to use <code>_</code> for variables you don't use</p></li>\n</ul>\n\n<h1>Code</h1>\n\n<pre><code>class Person:\n def __init__(self, first_name, last_name, id):\n self.first_name = first_name\n self.last_name = last_name\n self.id = id\n\n def __str__(self):\n return f\"Name: {self.last_name}, {self.first_name}\\nID: {self.id}\"\n\nclass Student(Person):\n def __init__(self, first_name, last_name, id, scores):\n super().__init__(first_name, last_name, id)\n self.scores = scores\n self.avg = sum(self.scores) / len(scores)\n self.score_dictionary = {\n 90 : 'O',\n 80 : 'E',\n 70 : 'A',\n 55 : 'P',\n 40 : 'D',\n 0 : 'T'\n }\n\n def grade(self):\n for score in sorted(self.score_dictionary.keys(), reverse=True):\n if self.avg &gt;= score:\n return self.score_dictionary[score]\n\nif __name__ == '__main__':\n f, l, i = input().split()\n _ = input()\n scores = list(map(int, input().split()))\n student = Student(f, l, i, scores)\n print(student)\n print(f\"Grade: {student.grade()}\")\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:19:14.057", "Id": "409887", "Score": "0", "body": "And the naming scheme and having to define a `printPerson` method was required in the problem, but recommending the normal best-practice is still good." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T10:32:28.623", "Id": "409901", "Score": "0", "body": "Thank you @Graipher and Ludisposed, I upvoted all of you, I will try to understand, thank you again for helping me!" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T08:54:51.000", "Id": "211981", "ParentId": "211973", "Score": "5" } } ]
{ "AcceptedAnswerId": "211981", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T06:31:46.653", "Id": "211973", "Score": "4", "Tags": [ "python", "python-3.x", "programming-challenge" ], "Title": "Python Inheritance and Class (Hackerank problem)" }
211973
<p>I have implemented PropertyInfo GetValue and Expression Cache GetValue by Logic from <a href="http://www.palmmedia.de/blog/2012/2/4/reflection-vs-compiled-expressions-vs-delegates-performance-comparison" rel="nofollow noreferrer">Reflection vs. compiled expressions vs. delegates - Performance comparison</a>,but I'm sure that there are better ways to do every thing that I did. I would appreciate any feedback on this code, which does work according to spec:</p> <h3>MyLogic</h3> <blockquote> <ul> <li>Asynchronous nonblocking, which does not block thread when adding a Cache</li> <li>Dictionary Key use propertyInfo GetHash()</li> <li>if dictionary cache containskey then use compiler expression function else use Reflection GetValue</li> </ul> </blockquote> <h3>My Class</h3> <pre><code>using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; public class TestService { private static Dictionary&lt;int, object&gt; ExpressionCache = new Dictionary&lt;int, object&gt;(); public IEnumerable&lt;string&gt; Execute&lt;T&gt;(IEnumerable&lt;T&gt; enums) { var expressionCache = (enums); var props = typeof(T).GetProperties(); foreach (var e in enums) { foreach (var p in props) { var func = GetOrAddExpressionCache&lt;T&gt;(p); var value = string.Empty; if (func == null) { Debug.WriteLine("Use Reflection"); value = p.GetValue(e).ToString(); } else { Debug.WriteLine("Use Expression"); value = func(e); } yield return value; } } } private Func&lt;T, string&gt; GetOrAddExpressionCache&lt;T&gt;(PropertyInfo prop) { var key = prop.GetHashCode(); if (ExpressionCache.ContainsKey(key)) { var func = ExpressionCache[key] as Func&lt;T, string&gt;; return func; }else{ Task.Run(()=&gt;AddExpressionCacheAsync&lt;T&gt;(prop)); return null; } } //Asynchronous nonblocking, which does not block a thread when adding a Cache private async Task AddExpressionCacheAsync&lt;T&gt;(PropertyInfo propertyInfo) { var key = propertyInfo.GetHashCode(); if (!ExpressionCache.ContainsKey(key)) { var func = GetValueGetter&lt;T&gt;(propertyInfo); ExpressionCache.Add(key, func); } await Task.Yield(); } private static Func&lt;T, string&gt; GetValueGetter&lt;T&gt;(PropertyInfo propertyInfo) { var instance = Expression.Parameter(propertyInfo.DeclaringType); var property = Expression.Property(instance, propertyInfo); var toString = Expression.Call(property, "ToString", Type.EmptyTypes); return Expression.Lambda&lt;Func&lt;T, string&gt;&gt;(toString, instance).Compile(); } } </code></pre> <h3>Demo</h3> <pre><code>class Program{ public static void Main(string[] args){ var data = new[] { new { Name = "Henry", Age = 25 } }; for (int i = 0; i &lt; 2; i++) { var service = new TestService(); var result = service.Execute(data).ToArray(); } } } /* Console : Use Reflection Use Reflection Use Expression Use Expression */ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T08:01:46.357", "Id": "409877", "Score": "0", "body": "Making a method `async` without `await` doesn't make it automagically asynchronous - your assumptions are wrong so the code is not working as you think it is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T08:07:32.210", "Id": "409879", "Score": "0", "body": "thanks @t3chb0t , i read doc about async without await now." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T08:13:58.090", "Id": "409880", "Score": "0", "body": "I read this page [task parallel library - Using async without await in C#? - Stack Overflow](https://stackoverflow.com/questions/17805887/using-async-without-await-in-c),it looks like `await Task.Run` is better. @t3chb0t" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:54:45.083", "Id": "409895", "Score": "0", "body": "Why should `AddExpressionCacheAsync` be asynchronous anyway? It results in repeated (wasted) lambda-compilation work and unhandled task exceptions..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T11:02:15.023", "Id": "409903", "Score": "0", "body": "@PieterWitvoet I want to avoid expression first compile time then blocked thread" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T14:41:00.183", "Id": "409931", "Score": "1", "body": "But the way you've implemented it causes multiple compilations for the same lambda, and you could run into obscure bugs because `Dictionary` is not thread-safe. Did you do this because you think it's too slow, or because you actually profiled it?" } ]
[ { "body": "<h3>Problems</h3>\n\n<ul>\n<li>Both the reflection and expression-based approach fail to take <code>null</code> values into account (<code>NullReferenceException</code>).</li>\n<li>They also fail to take types with indexers into account (<code>TargetParameterCountException</code>).</li>\n<li>Hash-codes are not unique identifiers. Different properties (and objects in general) can have the same hash code - that just means that they <em>might</em> be equal. Use <code>prop.MetadataToken</code> in combination with the module they're declared in (<code>prop.Module.ModuleVersionId</code>).</li>\n<li>Compiling expressions asynchronously makes this a lot more complex than it needs to be, and that complexity is not properly taken care of:\n\n<ul>\n<li>There's no guarantee that compilation will be finished when the next object is processed. This can result in multiple compilations for the same property. That's a waste of work.</li>\n<li>The results of these compilations are added to a <code>Dictionary</code>, which is not thread-safe. In the best case, adding a key that already exists will throw an exception. In the worst case, the dictionary's internal state will become corrupted.</li>\n<li>Those exceptions are not being caught. Before .NET Framework 4.5, that would've caused a crash, and in 4.5 and higher it may still do so, depending on certain settings.</li>\n</ul></li>\n</ul>\n\n<h3>Other improvements</h3>\n\n<ul>\n<li>Why does <code>Execute</code> take a sequence of items, instead of a single item? Flattening results is easy (<code>data.SelectMany(service.Execute)</code>), 'unflattening' is not - the caller would have to figure out the number of properties, and you'd have to write a method to split up a single sequence into sub-sequences.</li>\n<li>Instead of doing <code>ExpressionCache.ContainsKey(key)</code>, followed by <code>ExpressionCache[key]</code>, use <code>TryGetValue</code>. This lets you check the presence of a key and get its associated value with a single lookup.</li>\n<li>There's no point in making <code>AddExpressionCacheAsync</code> <code>async</code>. It's not doing any asynchronous work (that <code>await Task.Yield()</code> is useless). You're already calling this method from within a <code>Task.Run</code> call, so it'll be executed asynchronously anyway.</li>\n<li>In <code>GetValueGetter</code>, use <code>nameof(object.ToString)</code> instead of <code>\"ToString\"</code>.</li>\n</ul>\n\n<h3>Readability issues</h3>\n\n<ul>\n<li>Some names are not very descriptive: <code>Execute</code> -> <code>GetPropertyValues</code>, <code>enums</code> -> <code>items</code>, <code>func</code> -> <code>compiledExpression</code>, <code>GetValueGetter</code> -> <code>CompileGetValueExpression</code>.</li>\n<li>There are several abbreviations that do not improve readability: <code>e</code> -> <code>item</code>, <code>props</code> -> <code>properties</code>, <code>p</code> -> <code>property</code>.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T11:05:33.630", "Id": "212056", "ParentId": "211976", "Score": "2" } } ]
{ "AcceptedAnswerId": "212056", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T07:57:50.443", "Id": "211976", "Score": "1", "Tags": [ "c#" ], "Title": "PropertyInfo GetValue and Expression Cache GetValue" }
211976
<p>I've seen tutorials of <code>Unit Testing</code> and I've never seen that <code>IEnumerable&lt;T&gt;</code> used as an argument of method. All authors use <code>Repository pattern</code> and <code>Service layers</code> to interact with data, that is, authors of tutorials get data in <code>Service layer</code> by <code>Repository</code> and there is no need to pass collections between the methods of <code>Service layer</code>.</p> <p>However, I've written a simple quiz game which imitates <code>Repository pattern</code> and <strong>when I started writing unit test methods, then I realized that many of my methods has arguments type of <code>IEnumerable&lt;T&gt;</code></strong>.</p> <p>This is a simple quiz game where user can give simple answers to simple questions . For example, quiz asks question, then program will remember the answer of player and in the end program will calculate the overall score of the player answers. e.g. "How many continents are there on the Earth?", then quiz shows 4 possible answers, and then quiz remembers answers.</p> <p>The whole code of my quiz game looks like this:</p> <p><strong>Model classes:</strong></p> <pre><code>public class Answer { public Answer(int idAnswer, int idQuestion, string content) { IdAnswer = idAnswer; IdQuestion = idQuestion; Content = content; } public int IdAnswer { get; } public string Content { get; } public int IdQuestion { get; } } public class Question { public Question(int idQuestion, string content) { IdQuestion = idQuestion; Content = content; } public int IdQuestion { get; } public string Content { get; } } public class QuestionAnswer { public QuestionAnswer(int idQuestion, int idAnswer) { IdQuestion = idQuestion; IdAnswer = idAnswer; } public int IdQuestion { get; set; } public int IdAnswer { get; set; } } </code></pre> <p><strong>Program class:</strong></p> <pre><code>static void Main(string[] args) { IQuestionRepository questionService = Factory.CreateInstance&lt;QuestionRepository&gt;(); var questions = questionService.GetQuestions(); IAnswerRepository answerService = Factory.CreateInstance&lt;AnswerRepository&gt;(); var possibleAnswers = answerService.GetPossibleAnswers(questions); var playerAnswers = GetPlayerAnswers(questions, possibleAnswers); IQuestionAnswerRepository questionAnswerRepository = Factory.CreateInstance&lt;QuestionAnswerRepository&gt;(); var correctAnswers = questionAnswerRepository.GetCorrectAnswers(questions); ICountPlayerScoreBySum playerScores = Factory.CreateInstance&lt;CountPlayerScoreBySumService&gt;(); var playerScore = playerScores.CountPlayerScoreBySum(playerAnswers, correctAnswers); var winScoreString = ConfigurationManager.AppSettings.Get("WinScore"); int winScore = 0; int.TryParse(winScoreString, out winScore); Console.WriteLine( playerScore == winScore ? $"Wow! You are a winner! Your score is {playerScore}" : $"Try again! It is just the lesson to win! Your score is {playerScore}"); } </code></pre> <p>The method <code>GetPlayerAnswers</code> of <code>Program</code> class:</p> <pre><code>private static IEnumerable&lt;Answer&gt; GetPlayerAnswers(IEnumerable&lt;Question&gt; questions, IEnumerable&lt;Answer&gt; possibleAnswers) { List&lt;string&gt; allowedAnswers = new List&lt;string&gt;() { Constants.Constants.Answers.A, Constants.Constants.Answers.B, Constants.Constants.Answers.C, Constants.Constants.Answers.D, }; var playerAnswers = new List&lt;Answer&gt;(); foreach (var question in questions) { var possibleAnswersViewModel = possibleAnswers .Where(a =&gt; a.IdQuestion == question.IdQuestion) .OrderBy(a=&gt;a.IdAnswer) .Select((a, i) =&gt; new PlayerAnswerViewModel { Content = $"{ IntToLetters(i)}. {a.Content}", IdAnswer = a.IdAnswer, IdQuestion = a.IdQuestion, PlayerKey = IntToLetters(i) }); AskQuestion(question, possibleAnswersViewModel); while (true) { var playerKey = Console.ReadKey().KeyChar.ToString().ToUpper(); Console.WriteLine(); if (!allowedAnswers.Contains(playerKey)) { AskQuestion(question, possibleAnswersViewModel, true); } else { var answer = possibleAnswersViewModel .Where(a =&gt; a.PlayerKey == playerKey) .FirstOrDefault(); if(answer != null) playerAnswers.Add(new Answer( answer.IdAnswer, question.IdQuestion, playerKey)); break; } } } return playerAnswers; } </code></pre> <p>The methods <code>AskQuestion</code> and <code>IntToLetters</code> of <code>Program</code> class:</p> <pre><code>private static void AskQuestion(Question question, IEnumerable&lt;PlayerAnswerViewModel&gt; possibleAnswers, bool showPossibleKeys = false) { if (showPossibleKeys) { Console.WriteLine(); Console.WriteLine("Possible keys are A, B, C or D"); } Console.WriteLine(question.Content); possibleAnswers .ToList() .ForEach(a =&gt; Console.WriteLine(a.Content)); } public static string IntToLetters(int value) { string result = string.Empty; result = (char)('A' + value % 26) + result; return result; } </code></pre> <p>Repositories:</p> <pre><code>public interface IAnswerRepository { IEnumerable&lt;Answer&gt; GetPossibleAnswers(IEnumerable&lt;Question&gt; questions); } interface IQuestionAnswerRepository { IEnumerable&lt;QuestionAnswer&gt; GetCorrectAnswers(IEnumerable&lt;Question&gt; questions); } interface IQuestionRepository { IEnumerable&lt;Question&gt; GetQuestions(); } </code></pre> <p>And implementation of repositories. AnswerRepository: </p> <pre><code>class AnswerRepository : IAnswerRepository { public IEnumerable&lt;Answer&gt; GetPossibleAnswers(IEnumerable&lt;Question&gt; questions) { return new List&lt;Answer&gt;() { new Answer(11, 3, "Sequoia"), new Answer(12, 3, "Berch"), new Answer(13, 3, "Lindens"), new Answer(14, 3, "Alder"), new Answer(1, 1, "1"), new Answer(2, 1, "2"), new Answer(3, 1, "5"), new Answer(4, 1, "6"), new Answer(7, 2, "More than 1"), new Answer(8, 2, "More than 2"), new Answer(9, 2, "More than 5"), new Answer(10, 2, "More than 6"), new Answer(15, 4, "yes, I do!"), new Answer(16, 4, "Sure!"), new Answer(17, 4, "Exactly"), new Answer(18, 4, "Yeap!"), new Answer(19, 5, "yes, I do!"), new Answer(20, 5, "Sure!"), new Answer(21, 5, "Exactly"), new Answer(22, 5, "Yeap!"), new Answer(23, 6, "yes, I do!"), new Answer(24, 6, "Sure!"), new Answer(25, 6, "Exactly"), new Answer(26, 6, "Yeap!"), new Answer(27, 7, "yes, I do!"), new Answer(28, 7, "Sure!"), new Answer(29, 7, "Exactly"), new Answer(30, 7, "Yeap!") }.Where(qa =&gt; questions .Select(q =&gt; q.IdQuestion) .Contains(qa.IdQuestion) ); } } </code></pre> <p><strong>QuestionAnswerRepository. Imitation of getting correct answers of questions from Database:</strong></p> <pre><code>public class QuestionAnswerRepository : IQuestionAnswerRepository { public IEnumerable&lt;QuestionAnswer&gt; GetCorrectAnswers(IEnumerable&lt;Question&gt; questions) { return new List&lt;QuestionAnswer&gt;() { new QuestionAnswer(1, 1), new QuestionAnswer(2, 2), new QuestionAnswer(3, 3), new QuestionAnswer(4, 4), new QuestionAnswer(5, 1), new QuestionAnswer(6, 1), new QuestionAnswer(7, 1), new QuestionAnswer(8, 1), new QuestionAnswer(9, 1), new QuestionAnswer(10, 1) } .Where(qa =&gt; questions .Select(q=&gt;q.IdQuestion) .Contains(qa.IdQuestion) ); } } </code></pre> <p>QuestionRepository: </p> <pre><code>public class QuestionRepository : IQuestionRepository { public IEnumerable&lt;Question&gt; GetQuestions() { return new List&lt;Question&gt;() { new Question(1, "How many are there contintents?"), new Question(2, "How many are there colours?"), new Question(3, "What is the tallest tree?"), new Question(4, "Do you like dolphins?"), }; } } </code></pre> <p>and CountPlayerScoreBySumService:</p> <pre><code>public class CountPlayerScoreBySumService : ICountPlayerScoreBySum { public int CountPlayerScoreBySum(IEnumerable&lt;Answer&gt; playerAnswers, IEnumerable&lt;QuestionAnswer&gt; correctAnswers) { var sum = 0; foreach (var userAnswer in playerAnswers) { var correctAnswer = correctAnswers .Where(a =&gt; a.IdQuestion == userAnswer.IdQuestion) .FirstOrDefault(); if (correctAnswer != null) { if (userAnswer.IdAnswer == correctAnswer.IdAnswer) sum += 1; } } return sum; } } </code></pre> <p>and Factory service:</p> <pre><code>public class Factory { public static T CreateInstance&lt;T&gt;() where T : new() { return new T(); } } </code></pre> <p>However, my signatures of methods looks like this. Many methods have arguments type of array:</p> <pre><code>private IEnumerable&lt;Answer&gt; GetPlayerAnswers(IEnumerable&lt;Question&gt; questions, IEnumerable&lt;Answer&gt; possibleAnswers) { ... } </code></pre> <p>Is it okay? Is it a code smell to pass collections as arguments of a method? Or my quiz game is not properly designed? If yes, please be very kind, to advice me how design of an application can be improved.</p> <p>In addition, I've pushed all my code of <a href="https://github.com/NiceStepUp/Quiz" rel="nofollow noreferrer">Quiz game code into GitHub</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:23:35.297", "Id": "409888", "Score": "1", "body": "Could you [edit] your question please and explain what the quiz is about? We need this for context. Otherwise if you're not interested in a general review you should try [Software Engineering](https://softwareengineering.stackexchange.com/)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:29:20.420", "Id": "409890", "Score": "1", "body": "@t3chb0t Thank you for your attention, I've edited my question and explained what the quiz about." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T08:44:05.907", "Id": "410011", "Score": "0", "body": "@Mathematics thanks for your comment. Upvoted. Could you show me please where `Repository` called as `Service`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T10:10:10.427", "Id": "410027", "Score": "0", "body": "@Mathematics thank you very much for ERD. It is better than my tables as I have conjunction table to match a right answer to a question. This design of tables will give me less repositories. You should write your comments as an answer and I will upvote you. These are really helpful comments!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T11:43:00.280", "Id": "410035", "Score": "0", "body": "@StepUp I added answer to your question as suggested, feel free to ask any question" } ]
[ { "body": "<p>There is no general rule for using <code>IEnumerable</code> or not but there is one that says that you should use the most abstract representation of something because it gives you the most felxibility in what you can pass to such method because there would be fewer restrictions. </p>\n\n<p>This means if you are iterating a collection and you do this only once then <code>IEnumerable&lt;T&gt;</code> is perfect because there is virtually nothing more general than this. However, if you plan to use <code>Add</code> or <code>Count</code> or iterate a collection multiple times then something meterialized would be more appropriate like <code>IList&lt;T&gt;</code> or <code>ICollection&lt;T&gt;</code>.</p>\n\n<blockquote>\n<pre><code>public int CountPlayerScoreBySum(IEnumerable&lt;Answer&gt; playerAnswers, \n IEnumerable&lt;QuestionAnswer&gt; correctAnswers)\n{\n var sum = 0;\n foreach (var userAnswer in playerAnswers)\n {\n var correctAnswer = correctAnswers\n .Where(a =&gt; a.IdQuestion == userAnswer.IdQuestion)\n .FirstOrDefault();\n\n if (correctAnswer != null) {\n if (userAnswer.IdAnswer == correctAnswer.IdAnswer)\n sum += 1;\n }\n }\n\n return sum;\n}\n</code></pre>\n</blockquote>\n\n<p>Here, e.g. the first argument is ok, it's iterated only once but <code>correctAnswers</code> is used multiple times inside the loop so it probably should be something like <code>IList&lt;T&gt;</code> to make it more predictible and to inform the caller that you are going to use it more then once because it might otherwise execute some lengthly query.</p>\n\n<p>You could also materialize it inside the method but this is not always a good idea and to make such decisions requires to take a look at the big picture and the entire design. Sometimes it's acceptable, another time it might not be the case.</p>\n\n<p>So the bottom line is, don't <em>stupidly</em> use any type because some book says so but rather look carefully which type is the simplest one you can use and gives you the required felxibility at the same time. You have to decide in on case by case basis. You'll mostly end up with <code>IEnumerable&lt;T&gt;</code> anyway but make it a sensible decision and not <em>I've heard that...</em>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:55:54.667", "Id": "409896", "Score": "0", "body": "Thanks for so great answer! Is it appropriate to ask you here or should I create another question to make a code review of my whole program? Is it possible to get comments of my quiz game?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:57:24.713", "Id": "409897", "Score": "0", "body": "@StepUp your question is only 45min old --- give it some time, I'm sure more answers will appear later ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:58:47.843", "Id": "409898", "Score": "0", "body": "ok. Is it appropriate to ask you here or should I create another question to make a code review of my whole program? Is it possible to get comments of my quiz game?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T13:29:55.853", "Id": "409919", "Score": "0", "body": "Why would you say that you should use the most abstract type for an *output* value? An `ICollection<T>` or an `IList<T>` **is** an `IEnumerable<T>`. So you lose no flexibility by returning a supertype, you **gain** flexibility, because you provide addtional functionality (which you might choose to ignore). An *input* value is a different story though. You want to put a minimum burden on the caller, so it is generally a good idea to ask for the minimum type that works for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T13:32:58.893", "Id": "409920", "Score": "0", "body": "@Sefe AKA Postel's Law." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T14:40:30.217", "Id": "409930", "Score": "0", "body": "@Safe I'm not talking about _out_ parameters. In this case you're right, it would not hurt to return a derived one." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T19:31:24.053", "Id": "409960", "Score": "0", "body": "@t3chb0t why do you think passing an enumerable makes the caller assume it is only enumerated once? If you want something that can only be enumerated once you pass an enumerator. I think it is totally fine to enumerate an enumerable multiple times. That is why enumerators are not enumerable even though they could just return this." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T10:41:33.043", "Id": "410028", "Score": "0", "body": "Is it enough to change `IEnumerable<QuestionAnswer> correctAnswers` to `List<QuestionAnswer> correctAnswers`? Could you please, tell me, how it helps to reduce length of query length?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T10:54:12.173", "Id": "410031", "Score": "0", "body": "@StepUp I didn't say anything about reducing the length of the query... it isn't supposed to. I don't understand your question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T11:07:11.877", "Id": "410033", "Score": "0", "body": "@t3chb0t ` it might otherwise execute some lengthly query.` Is it enough to change IEnumerable<QuestionAnswer> correctAnswers to List<QuestionAnswer> correctAnswers? But I cannot understand the profit of this. Could you please very kind to explain this statement in code?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:50:28.743", "Id": "410058", "Score": "0", "body": "@StepUp oh, now I see what you mean ;-) the _lengthy query_ stands for a linq expression that might take some time to execute. I'm not sure if you know that `IEnumerable<T>` means _deferred_ execution and there is now guarantee that behind it is a list or an array and if you let it do the whole linq stuff each time, you might create a bottleneck in you application. In your case there is a chance that the entire `GetCorrectAnswers` method would be executed `foreach` item in the loop." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:40:30.923", "Id": "211983", "ParentId": "211982", "Score": "6" } }, { "body": "<p>There is nothing inherently wrong with using <code>IEnumerable&lt;T&gt;</code>, just as there would be nothing wrong with using <code>List&lt;T&gt;</code>. Whatever collection type you choose to accept or return is far more a matter of your application's needs than any style guide.</p>\n\n<p>For example, if you were writing a public-facing API, you would likely want to be most permissible in what you accept in order to make it easy for clients to use that API. In that case, using <code>IEnumerable&lt;T&gt;</code> would allow any collection type (including arrays) to be passed to your methods.</p>\n\n<p>On the other hand, if you were writing high-performance code that is internal to your application, you'd probably use <code>List&lt;T&gt;</code> and pass it between your (presumably private) methods (using concrete types is slightly faster than interfaces).</p>\n\n<p>Remember that style guides are just that - <strong>guides</strong>. It's up to you the programmer to apply those guidelines intelligently and logically.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:06:41.000", "Id": "212045", "ParentId": "211982", "Score": "3" } }, { "body": "<p>Changing comments to answer on OP request. I am not answering the direct question asked by OP but few comments about the overall architecture and design of there solution which may indirectly solve the issue OP is worried about, passing collections as parameters.</p>\n\n<pre><code>IQuestionRepository questionService = Factory.CreateInstance&lt;QuestionRepository&gt;(); \n</code></pre>\n\n<p>Light heartly, never ever create an object from repository and name it a service, it makes code confusing for people me like who following onion architecture as show below,</p>\n\n<p><a href=\"https://i.stack.imgur.com/otnyn.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/otnyn.png\" alt=\"enter image description here\"></a></p>\n\n<p>Also in C# usually objects are initialled together WHEN you are only initiating them for calling a single function or maybe 2 and there is no risk of memory leak, it also makes code more readable. Did you thought about using DI ? </p>\n\n<pre><code> IQuestionRepository questionService = Factory.CreateInstance&lt;QuestionRepository&gt;();\n IAnswerRepository answerService = Factory.CreateInstance&lt;AnswerRepository&gt;();\n IQuestionAnswerRepository questionAnswerRepository = Factory.CreateInstance&lt;QuestionAnswerRepository&gt;();\n ICountPlayerScoreBySum playerScores = Factory.CreateInstance&lt;CountPlayerScoreBySumService&gt;();\n\n var possibleAnswers = answerService.GetPossibleAnswers(questions);\n var questions = questionService.GetQuestions();\n var playerAnswers = GetPlayerAnswers(questions, possibleAnswers);\n var correctAnswers = questionAnswerRepository.GetCorrectAnswers(questions);\n var playerScore = playerScores.CountPlayerScoreBySum(playerAnswers, correctAnswers);\n\n var winScoreString = ConfigurationManager.AppSettings.Get(\"WinScore\");\n int winScore = 0;\n int.TryParse(winScoreString, out winScore);\n</code></pre>\n\n<p>Also sometimes abstraction is not a good thing, especially if there is no scope of scalling program in future. Do you have any ERD for your this app ? Your quiz app doesn't seems relational when it could be a good candidate - here's an example ERD I picked up from internet,</p>\n\n<p><a href=\"https://i.stack.imgur.com/qcSP6.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qcSP6.jpg\" alt=\"enter image description here\"></a> </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T16:13:24.107", "Id": "410062", "Score": "1", "body": "Thanks for so great answer! It is really useful! Have a nice day!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T11:42:21.780", "Id": "212060", "ParentId": "211982", "Score": "1" } } ]
{ "AcceptedAnswerId": "211983", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:11:08.450", "Id": "211982", "Score": "4", "Tags": [ "c#", "design-patterns", "collections", "repository" ], "Title": "Pass IEnumerable<T> as an argument of method and repository pattern" }
211982
<p>I have created a cumulative profiler, meaning it runs a function several times in a row and prints the cumulative profiler results.</p> <p>it's python >= 3.6 specific, but you can remove <code>nonlocal</code> and the type hints for it work on older versions.</p> <pre><code>import cProfile, pstats from typing import Union, List, Callable, Optional, Tuple, Any DEFAULT_AMOUNT = 5 class ProfileFunc: def __init__(self, func: Callable, sort_stats_by: str): self.func: Callable = func self.profile_runs: List[cProfile.Profile] = [] self.sort_stats_by: str = sort_stats_by def __call__(self, *args, **kwargs) -&gt; Tuple[Any, pstats.Stats]: pr = cProfile.Profile() pr.enable() # this is the profiling section retval = self.func(*args, **kwargs) pr.disable() self.profile_runs.append(pr) ps = pstats.Stats(*self.profile_runs).sort_stats(self.sort_stats_by) return retval, ps def cumulative_profiler(amount_of_times: Optional[Union[Callable, int]] = DEFAULT_AMOUNT, sort_stats_by: str='time') -&gt; Callable: def real_decorator(func: Callable): def wrapper(*args, **kwargs): nonlocal func, amount_of_times, sort_stats_by profiled_func = ProfileFunc(func, sort_stats_by) assert amount_of_times &gt; 0, 'Cant profile for less then 1 run' for i in range(amount_of_times): retval, ps = profiled_func(*args, **kwargs) ps.print_stats() return retval # returns the results of the function return wrapper # in case you don't want to specify the amount of times if callable(amount_of_times): the_func = amount_of_times # amount_of_times is the function in here global DEFAULT_AMOUNT amount_of_times = DEFAULT_AMOUNT return real_decorator(the_func) return real_decorator </code></pre> <p><strong>Example</strong></p> <p>profiling the function <code>baz</code> </p> <pre><code>import time @cumulative_profiler def baz(): time.sleep(1) time.sleep(2) return 1 baz() </code></pre> <p><code>baz</code> ran 5 times and printed this:</p> <pre><code> 20 function calls in 15.003 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 10 15.003 1.500 15.003 1.500 {built-in method time.sleep} 5 0.000 0.000 15.003 3.001 &lt;ipython-input-9-c89afe010372&gt;:3(baz) 5 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} </code></pre> <p>specifying the amount of times</p> <pre><code>@cumulative_profiler(3) def baz(): ... </code></pre> <hr> <p>One small problem is that <code>pstats.Stats</code> is called each time instead of only one time in the end. however I don't think it's an expensive operation and it doesn't affect the results.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T09:51:02.523", "Id": "211984", "Score": "3", "Tags": [ "python", "meta-programming", "benchmarking" ], "Title": "Cumulative profiler for a function" }
211984
<p>I have a CSV holding a "flat" table of a tree's edges (NOT binary, but a node cannot have two parents), ~1M edges:</p> <pre><code>node_id parent_id 1 0 2 1 3 1 4 2 ... </code></pre> <p>The nodes are sorted in a way that a <code>parent_id</code> must always come before any of its children, so a <code>parent_id</code> will always be lower than <code>node_id</code>.</p> <p>I wish, for each node_id, to get the set of all ancestor nodes (including itself, propagated until root which is node 0 here), and a set of all descendant nodes (including itself, propagated until leaves), and speed is crucial.</p> <p>Currently what I do at high level:</p> <ol> <li>Read the CSV in pandas, call it <code>nodes_df</code></li> <li>Iterate once through <code>nodes_df</code> to get <code>node_ancestors</code>, a <code>{node_id: set(ancestors)}</code> dict adding for each node's ancestors itself and its parent's ancestors (which I know I have seen all by then)</li> <li>Iterate through <code>nodes_df</code> again <em>in reverse order</em> to get <code>node_descendants</code>, a <code>{node_id: set(ancestors)}</code> dict adding for each node's descendants itself and its child's descendants (which I know I have seen all by then)</li> </ol> <p></p> <pre><code>import pandas as pd from collections import defaultdict # phase 1 nodes_df = pd.read_csv('input.csv') # phase 2 node_ancestors = defaultdict(set) node_ancestors[0] = set([0]) for id, ndata in nodes_df1.iterrows(): node_ancestors[ndata['node_id']].add(ndata['node_id']) node_ancestors[ndata['node_id']].update(node_ancestors[ndata['parent_id']]) # phase 3 node_descendants = defaultdict(set) node_descendants[0] = set([0]) for id, ndata in nodes_df1[::-1].iterrows(): node_descendants[ndata['node_id']].add(ndata['node_id']) node_descendants[ndata['parent_id']].\ update(node_descendants[ndata['node_id']]) </code></pre> <p>So, this takes dozens of seconds on my laptop, which is ages for my application. How do I improve?</p> <p>Plausible directions:</p> <ol> <li>Can I use pandas better? Can I get <code>node_ancestors</code> and/or <code>node_descendants</code> by some clever join which is out of my league?</li> <li>Can I use a python graph library like <code>Networkx</code> or <code>igraph</code> (which in my experience is faster on large graphs)? E.g. in both libraries I have a <code>get_all_shortest_paths</code> methods, which returns something like a <code>{node_id: dist}</code> dictionary, from which I could select the keys, but... I need this for every node, so again a long long loop</li> <li>Parallelizing - no idea how to do this</li> </ol>
[]
[ { "body": "<h1><code>id</code></h1>\n\n<p>you shadow the builtin <code>id</code> with this name as variable</p>\n\n<h1>itertuples</h1>\n\n<p>a way to improve performance is using <code>itertuples</code> to iterate over the <code>DataFrame</code>: <code>for _, node, parent in df.itertuples():</code></p>\n\n<h1>iterations</h1>\n\n<p>You can do this in 1 iteration over the input with a nested loop over the ancestors:</p>\n\n<pre><code>node_ancestors = defaultdict(set)\nnode_ancestors[0] = set([0])\nnode_descendants = defaultdict(set)\nnode_descendants[0] = set([0])\nfor _, node, parent in df.itertuples():\n node_ancestors[node].add(node)\n node_ancestors[node].update(node_ancestors[parent])\n\n for ancestor in node_ancestors[node]:\n node_descendants[ancestor].add(node)\n</code></pre>\n\n<p>Depending on how nested the tree is, this will be faster or slower than iterating over the whole input twice. You'll need to test it on your dataset.</p>\n\n<h1>global vs local</h1>\n\n<p>another speedup might be achieved by doing this in a function instead of the global namespace (<a href=\"https://stackoverflow.com/q/12590058/1562285\">explanation</a>)</p>\n\n<pre><code>def parse_tree(df):\n node_ancestors = defaultdict(set)\n node_ancestors[0] = set([0])\n node_descendants = defaultdict(set)\n node_descendants[0] = set([0])\n for _, node, parent in df.itertuples():\n node_ancestors[node].add(node)\n node_ancestors[node].update(node_ancestors[parent])\n\n for ancestor in node_ancestors[node]:\n node_descendants[ancestor].add(node)\n\n return node_ancestors, node_descendants \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T06:47:14.753", "Id": "409998", "Score": "0", "body": "Not `parents[node] = parent` isn't necessary." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T16:15:25.997", "Id": "212004", "ParentId": "211989", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T10:30:47.977", "Id": "211989", "Score": "0", "Tags": [ "python", "performance", "tree", "graph", "pandas" ], "Title": "Get all node descendants in a tree" }
211989
<p>In the code shown below, I have created 3 classes. The first of these are an 'Payment' class and a 'Annuity' class, which allow the user to create objects representing individual or recurring payments respectively.</p> <p>The third of these classes is a 'Cashflow' class, which takes a combination of Payment and Annuity object to construct a cashflow, and returns allows the user to calculate various related properties. One example of such a property is the discounted payback period, which is the earliest point in time that the net present value of the cashflows given is equal to zero.</p> <pre><code>import math class Annuity(): #Initialise function def __init__(self, annuity_type, effective_interest_rate, term, payment_rate = 1, payment_frequency = 1): self.annuity_type = annuity_type self.effective_interest_rate = effective_interest_rate self.term = term self.payment_rate = payment_rate self.payment_frequency = payment_frequency #Properties @property def present_value(self): if self.annuity_type == 'continuous': return self.payment_rate * (1 - (1 + self.effective_interest_rate) ** -self.term) / math.log(1 + self.effective_interest_rate) elif self.annuity_type == 'due': return self.payment_rate * (1 - (1 + self.effective_interest_rate) ** -self.term) / (self.effective_interest_rate / (1 + self.effective_interest_rate)) elif self.annuity_type == 'immediate': return self.payment_rate * (1 - (1 + self.effective_interest_rate) ** -self.term) / self.effective_interest_rate @property def time_payable(self): return self.term #Functions def present_value_to_time(self, time): if time &gt;= self.term: return self.present_value elif self.annuity_type == 'continuous': return self.payment_rate * (1 - (1 + self.effective_interest_rate) ** -time) / math.log(1 + self.effective_interest_rate) elif self.annuity_type == 'due': return self.payment_rate * (1 - (1 + self.effective_interest_rate) ** -time) / (self.effective_interest_rate / (1 + self.effective_interest_rate)) elif self.annuity_type == 'immediate': return self.payment_rate * (1 - (1 + self.effective_interest_rate) ** -time) / self.effective_interest_rate class Payment(): #Initialise function def __init__(self, effective_interest_rate, time_payable, ammount): self.effective_interest_rate = effective_interest_rate self.time_payable = time_payable self.ammount = ammount #Properties @property def present_value(self): return self.ammount * (1 + self.effective_interest_rate) ** -self.time_payable #Functions def present_value_to_time(self, time): if time &lt; self.time_payable: return 0 else: return self.present_value class Cashflow(object): #Initialise function def __init__(self, cashflow = []): self.cashflow = cashflow #Properties @property def net_present_value(self): npv = 0 for cf in self.cashflow: npv += cf.present_value return npv @property def cashflow_timings(self): cashflow_timings = [] for cf in self.cashflow: cashflow_timings.append(cf.time_payable) cashflow_timings.sort() return cashflow_timings @property def discounted_payback_period(self): n1 = min(self.cashflow_timings) n2 = max(self.cashflow_timings) + 1 discounted_payback_period = 0 for t in range(0, 6): for n in range(n1, n2): n /= 10 ** t n += discounted_payback_period if self.net_present_value_to_time(n) &gt;= 0: discounted_payback_period = n - (1 / 10 ** t) n1 = 0 n2 = 11 break return round(discounted_payback_period, 5) #Functions def add_to_cashflow(self, cashflow_item): self.cashflow.append(cashflow_item) def net_present_value_to_time(self, time): net_present_value_to_time = 0 for cf in self.cashflow: net_present_value_to_time += cf.present_value_to_time(time) return net_present_value_to_time </code></pre> <p>An example of how one might use the above classes is as follows:</p> <pre><code>my_cashflow = Cashflow() a1 = Annuity('continuous', 0.1, 5, 10000) a2 = Annuity('continuous', 0.1, 5, -2000) p1 = Payment(0.1, 0, -25000) p2 = Payment(0.1, 6, -5000) my_cashflow.add_to_cashflow(a1) my_cashflow.add_to_cashflow(a2) my_cashflow.add_to_cashflow(p1) my_cashflow.add_to_cashflow(p2) print(my_cashflow.discounted_payback_period) </code></pre> <p>Does anyone have any suggestions as to how the above code might be improved? In particular, I was hoping that there might be a more 'elegant' solution than the use of <code>if</code> / <code>elif</code> statements used in the Annuity class. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T13:50:55.663", "Id": "409922", "Score": "1", "body": "Using the strategy pattern from the GOF would be a solution, but I don't speak python... See https://sourcemaking.com/design_patterns/strategy/python/1 as an example" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T23:20:21.937", "Id": "409982", "Score": "0", "body": "Hi, cheers for your response. Unfortunately, the strategy described there goes somewhat over my head, on account of my current lack of knowledge of python. I'll try deciphering it with the help of Google though!" } ]
[ { "body": "<p>Using the strategy pattern from the GOF would be a solution, but I don't speak python... </p>\n\n<ol>\n<li>create an abstract class <code>ValueCalculator</code> with the functions <code>calculate_value_to_time(self, time)</code>and <code>calculate_value(self)</code></li>\n<li>create three different classes that implement the interface: <code>ValueCalculatorWithContinuous</code>, <code>ValueCalculatorWithDue</code> and <code>ValueCalculatorWithImmediate</code></li>\n<li>each class offers the special implementation of the formula</li>\n<li>create a <code>self.valueCalculator</code>-property for the Annuity-class</li>\n<li>instantiate the correct ValueCalculator, decided from the annuity_type, and set the <code>self.valueCalculator</code> in the <code>__init__</code>-part to this</li>\n<li>then you can shorten the functions to</li>\n</ol>\n\n<pre><code>#Functions\ndef present_value_to_time(self, time):\n if time &gt;= self.term:\n return self.present_value\n else:\n return self.valueCalculator.calculate_value_to_time(self, time)\n</code></pre>\n\n<p>Hope that helps. Watch out, this is not REAL Python code!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T09:27:04.647", "Id": "212054", "ParentId": "211991", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T11:55:34.247", "Id": "211991", "Score": "1", "Tags": [ "python", "object-oriented", "finance" ], "Title": "Python 'Cashflow' object" }
211991
<p>Here is my code for making an Hour Glass pattern with odd or even input using Python. I think I could make it simpler.</p> <p>Here's the output example:</p> <p><img src="https://i.stack.imgur.com/y3S8s.jpg" alt="Expected Output"></p> <p>And then, here is my code:</p> <pre><code>def evenGlassHour(target): jsp=1 jtop=target jbot=2 jbotspace=int(target/2) eventarget=int(target/2) temp="" for i in range(eventarget): for j in range(i): temp+=" " for jsp in range(jtop): temp+="@" jtop-=2 temp+="\n" for i in range(eventarget-1): for j in range(jbotspace-2): temp+=" " for j in range(jbot+2): temp+="@" jbot+=2 jbotspace-=1 temp+="\n" print(temp) def oddGlassHour(target): jsp=1 jtop=target jbot=1 jbotspace=int(target/2) oddtarget=int(target/2) temp="" for i in range(oddtarget): for j in range(i): temp+=" " for jsp in range(jtop): temp+="@" jtop-=2 temp+="\n" for i in range(oddtarget+1): for j in range(jbotspace): temp+=" " for j in range(jbot): temp+="@" jbot+=2 jbotspace-=1 temp+="\n" print(temp) target=int(input("Input : ")) if(target%2==0): evenGlassHour(target) else: oddGlassHour(target) </code></pre> <p>And this is the result from my code:</p> <pre><code> Input : 6 @@@@@@ @@@@ @@ @@@@ @@@@@@ Input : 7 @@@@@@@ @@@@@ @@@ @ @@@ @@@@@ @@@@@@@ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T12:41:28.073", "Id": "409914", "Score": "2", "body": "Welcome to Code Review! I changed the title so that it describes what the code does per [site goals](/questions/how-to-ask): \"*State what your code does in your title, not your main concerns about it.*\". Please check that I haven't misrepresented your code, and correct it if I have." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T12:42:37.317", "Id": "409915", "Score": "3", "body": "I've also edited to remove your request for Java code, as that's off-topic here; we simply *review* your code. We might make concrete suggestions, but we don't write code to order!" } ]
[ { "body": "<p>Read <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">PEP8</a>, it will give you directions on how to write Python code that look like Python code to other.</p>\n\n<p>Other than that, the behaviour you're seeking is already implemented in <code>range</code>:</p>\n\n<pre><code>&gt;&gt;&gt; a = range(7, 0, -2)\n&gt;&gt;&gt; list(a)\n[7, 5, 3, 1]\n</code></pre>\n\n<p>You just need to reverse it to form the full hourglass:</p>\n\n<pre><code>&gt;&gt;&gt; a = range(7, 0, -2)\n&gt;&gt;&gt; list(a) + list(reversed(a))\n[7, 5, 3, 1, 1, 3, 5, 7]\n</code></pre>\n\n<p>And remove the repeated center:</p>\n\n<pre><code>&gt;&gt;&gt; decreasing = range(7, 0, -2)\n&gt;&gt;&gt; increasing = reversed(decreasing)\n&gt;&gt;&gt; next(increasing) # Remove duplicated center\n&gt;&gt;&gt; list(decreasing) + list(increasing)\n[7, 5, 3, 1, 3, 5, 7]\n</code></pre>\n\n<p>Now you can make use of <a href=\"https://docs.python.org/3/library/itertools.html#itertools.chain\" rel=\"noreferrer\"><code>itertools.chain</code></a> instead of list concatenation and turn your function into a generator to separate computation from printing.</p>\n\n<pre><code>import itertools\n\n\ndef hourglass(size):\n decreasing = range(size, 0, -2)\n increasing = reversed(decreasing)\n next(increasing, None) # Remove duplicated center\n for length in itertools.chain(decreasing, increasing):\n yield '{:^{}}'.format('@' * length, size)\n\n\nif __name__ == '__main__':\n for i in range(20): # Test our function\n print('\\n'.join(hourglass(i)), end='\\n---\\n')\n</code></pre>\n\n<p>Note that if you are using Python 3.6+ you can format the line using</p>\n\n<pre><code>yield f'{\"@\" * length:^{size}}'\n</code></pre>\n\n<p>instead which may be slightly more readable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T14:05:31.750", "Id": "211997", "ParentId": "211992", "Score": "16" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T12:11:58.807", "Id": "211992", "Score": "9", "Tags": [ "python", "ascii-art" ], "Title": "Generate an Hour Glass pattern" }
211992
<p>I took a task from Codility to find longest sequence of zeros in binary representation of an integer. </p> <blockquote> <p>For example, number 9 has binary representation 1001 and contains a binary gap of length 2. The number 529 has binary representation 1000010001 and contains two binary gaps: one of length 4 and one of length 3. The number 20 has binary representation 10100 and contains one binary gap of length 1. The number 15 has binary representation 1111 and has no binary gaps. The number 32 has binary representation 100000 and has no binary gaps.</p> </blockquote> <p>I am a Java developer, but decided to implement it in C++. What could be improved? Is my approach correct? (The compiler version provided by Codility is C++14).</p> <pre><code>int solution(int N) { int longest_binary_gap = -1; unsigned int mask = 1 &lt;&lt; 31; // Find the first occurence of 1 for (; !(mask &amp; N) &amp;&amp; mask != 0; mask &gt;&gt;= 1); while (mask != 0) { // Move to the next binary digit mask &gt;&gt;= 1; int current_gap = 0; // Count zeroes for (; !(mask &amp; N) &amp;&amp; mask != 0; mask &gt;&gt;= 1, current_gap += 1); // Check if the interval ends with 1 and if it is the longes found so far if (mask != 0 &amp;&amp; current_gap &gt; longest_binary_gap) { longest_binary_gap = current_gap; } } return (longest_binary_gap &lt; 0) ? 0 : longest_binary_gap; } </code></pre>
[]
[ { "body": "<ol>\n<li>I would use <strong><code>unsigned int</code></strong>.</li>\n<li>Gap count must be <strong>initialized to zero</strong>. What's the meaning of -1?</li>\n<li><p>Why do you need a mask to move to the first 1? This looks <strong>cleaner</strong>:</p>\n\n<pre><code>while( n &amp;&amp; !( n &amp; 1u ) )\n n &gt;&gt;= 1;\n</code></pre></li>\n<li><p>Testing for end is just testing for <strong>zero</strong>, again you do not need the mask:</p>\n\n<pre><code>while ( n )\n{ // ...\n</code></pre>\n\n<p>or</p>\n\n<pre><code>for ( ; n; n &gt;&gt;= 1 )\n{ //...\n</code></pre></li>\n<li>The algorithm seems <strong>unnecessarily complicated</strong>.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T17:24:11.290", "Id": "409955", "Score": "1", "body": "Not only is testing the MSB cleaner, it also eliminates that assumption that `unsigned int` has 32 or more bits (and works when the input is larger than that)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T17:32:46.517", "Id": "409956", "Score": "0", "body": "@TobySpeight Correct." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T17:18:40.947", "Id": "212008", "ParentId": "211995", "Score": "3" } }, { "body": "<p>Your question states that you want to solve this problem in <code>C++</code>/<code>C++14</code>. In your solution you are mainly using old <code>C</code> style code.</p>\n<p>In order to make your code more <strong>readable / maintable / bug-free</strong> (you choose!), try to make use of <code>STL</code> as much as possible.</p>\n<h2>std::vector&lt; bool &gt;</h2>\n<p>Using <a href=\"https://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector&lt;bool&gt;</code></a> as the binary representation we can make use of the <code>algorithm</code> library of STL.</p>\n<h2>STL iterators</h2>\n<p>When dealing with containers in STL, <a href=\"https://en.cppreference.com/w/cpp/iterator\" rel=\"nofollow noreferrer\"><code>iterator</code></a>s are used to specify a range for a container. These <code>begin</code> and <code>end</code> iterators (specifying a range) are needed for the algorithms.</p>\n<h2>STL algorithm</h2>\n<p>The STL <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\"><code>algorithm</code></a> module has most of algorithms you need for manipulating containers.\nTry to use STL algorithms as much as possible whenever you need to operate on a range of elements.</p>\n<p>Here is another approach using <code>std::vector&lt;bool&gt;</code>, <code>iterator</code>s and <code>algorithm</code> from STL.</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;numeric&gt;\n#include &lt;vector&gt;\n\nstd::vector&lt;bool&gt; to_binary(int num)\n{\n std::vector&lt;bool&gt; binary;\n while(num != 0)\n {\n binary.push_back(num % 2 != 0);\n num /= 2;\n }\n return binary;\n}\n\nint findlargestGap(int num)\n{\n int largest_gap = 0;\n auto binary = to_binary(num);\n auto it = binary.begin();\n const auto it_end = binary.end();\n while(it != it_end)\n {\n auto current_true = std::find(it, it_end, true);\n if(current_true == it_end)\n break;\n\n auto next_true = std::find(current_true+1, it_end, true);\n if(next_true == it_end)\n break;\n\n const auto d = std::distance(current_true, next_true) - 1;\n largest_gap = std::max(largest_gap, static_cast&lt;int&gt;(d));\n\n it++;\n }\n\n return largest_gap;\n}\n\nint main(int argc, char** argv)\n{\n std::cout &lt;&lt; &quot;largest gap for 9: &quot; &lt;&lt; findlargestGap(9) &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;largest gap for 529: &quot; &lt;&lt; findlargestGap(529) &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;largest gap for 20: &quot; &lt;&lt; findlargestGap(20) &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;largest gap for 15: &quot; &lt;&lt; findlargestGap(15) &lt;&lt; '\\n';\n std::cout &lt;&lt; &quot;largest gap for 32: &quot; &lt;&lt; findlargestGap(32) &lt;&lt; '\\n';\n}\n</code></pre>\n<h1>EDIT</h1>\n<p>Change the last line in <code>findLargestGap()</code> from <code>it++</code> to <code>it = next_true</code> to start the next iteration where the last one was found to save cycles in some cases.</p>\n<h1><a href=\"https://ideone.com/ywhVfB\" rel=\"nofollow noreferrer\">LIVE DEMO</a></h1>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T23:52:23.093", "Id": "409983", "Score": "0", "body": "@MartinR Edited my answer to include some reasoning to my solution." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T06:33:48.090", "Id": "409997", "Score": "2", "body": "Note that your approach repeatedly finds the same gaps. For the number 529 it finds a gap of length 3, and then the same gap (of length 4) four times. Yes, I know about “premature optimization,” but it should be possible to start the search for next gap where the last gap ended (so that the bits are only traversed once, as in the original code)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:12:22.047", "Id": "410097", "Score": "0", "body": "@MartinR Thanks, I edited my solution to include the fix." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T21:56:16.283", "Id": "212027", "ParentId": "211995", "Score": "4" } }, { "body": "<ol>\n<li><p>Using a signed type for an integer you want to do bit-manipulations on, or which cannot (must not) be negative is an obvious case of Java damage.</p></li>\n<li><p>While in Java, an <code>int</code> is always a 32 bits 2's complement integer, C++ caters to a far wider range of targets. Admittedly, not all the options are still used (even rarely), but you should not assume the bit-width.</p></li>\n<li><p>Java may not allow implicit conversion of integers to boolean, but C++ does. You seem to get that difference though. Sometimes. Maybe half the time.</p></li>\n<li><p>Yes, you <em>can</em> start from the most significant bit. The most telling disadvantages are</p>\n\n<ul>\n<li>that you will always traverse <em>all</em> bits,</li>\n<li>that you have to use a mask, and</li>\n<li>that you need the bit-width (look in <a href=\"https://en.cppreference.com/w/cpp/types/integer\" rel=\"noreferrer\"><code>&lt;cstdint&gt;</code>/<code>stdint.h&gt;</code></a> for a macro, or better use <a href=\"https://en.cppreference.com/w/cpp/types/numeric_limits\" rel=\"noreferrer\"><code>std::numeric_limits</code> from <code>&lt;limits&gt;</code></a>) for the mask.</li>\n</ul>\n\n<p>Better start on the other end.</p></li>\n<li><p>I really wonder why you initialize <code>longest_binary_gap</code> to <code>-1</code> and then use a conditional-operator to ensure you return at least <code>0</code>. That's a lot of work for nothing,</p></li>\n<li><p>You were exceedingly generous with long and descriptive names <em>in</em> your function, don't you think it's much more important for the function itself?</p></li>\n<li><p>The function cannot throw by design, so make it <code>noexcept</code>.</p></li>\n<li><p>There also doesn't seem to be a reason not to allow use in a ctce, so mark it <code>constexpr</code>.</p></li>\n</ol>\n\n<p>Re-coded:</p>\n\n<pre><code>constexpr int biggest_binary_gap(unsigned n) noexcept {\n while (n &amp;&amp; !(n &amp; 1))\n n &gt;&gt;= 1;\n int r = 0;\n for (;;) {\n while (n &amp; 1)\n n &gt;&gt;= 1;\n if (!n)\n return r;\n int m = 0;\n while (!(n &amp; 1)) {\n ++m;\n n &gt;&gt;= 1;\n }\n if (r &lt; m)\n r = m;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:33:40.820", "Id": "410000", "Score": "0", "body": "Thank you very much for such a detailed explanation!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T22:36:11.093", "Id": "212032", "ParentId": "211995", "Score": "5" } }, { "body": "<p>Your solution seems rather complicated. I suggest this: shift the argument right until it is zero, counting runs of zeros, noting the longest. I hope this is valid C++, I mostly write in C#.</p>\n\n<pre><code>int binary_gap ( unsigned n )\n{\n int best_gap = 0;\n for ( int gap = 0; n != 0; n &gt;&gt;= 1 )\n {\n if ( ( n &amp; 1 ) == 0 ) gap += 1;\n else \n {\n if ( gap &gt; best_gap ) best_gap = gap;\n gap = 0;\n }\n }\n return best_gap;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T01:28:18.320", "Id": "212034", "ParentId": "211995", "Score": "3" } }, { "body": "<p>I'm a bit late to the party, but I'll add my two cents nonetheless!</p>\n\n<p>Your code is quite good, even if, as other reviewers pointed, you can still improve it marginally. But I also agree with other reviewers that you could have chosen a more modern, less C-like approach. I would defend one based on ranges, that needs a bit of scaffolding but could be used to solve many other binary-oriented code challenges.</p>\n\n<p>If you don't know what ranges are, you could start <a href=\"https://arne-mertz.de/2017/01/ranges-stl-next-level/\" rel=\"noreferrer\">here</a> or google \"Eric Niebler ranges\". With ranges you can (among other things) combine <em>views</em> on a sequence of values; <em>views</em> modify the way you look at the sequence.</p>\n\n<p>Making a number into a binary view of the said number is relatively straight-forward thanks to the <code>view_facade</code> class:</p>\n\n<pre><code>class binary_view\n : public ranges::view_facade&lt;binary_view&gt; // magic here ...\n{\n friend ranges::range_access; // ... and here\n int value = 0;\n\n // how you read the current element of the view\n int read() const { return value &amp; 1; } \n\n // how you know you're at the end of the view\n bool equal(ranges::default_sentinel) const { return value == 0; } \n\n // how you compare two positions in the view\n bool equal(const binary_view&amp; that) const { return value == that.value; } \n\n // how you get to the next position in the view\n void next() { value &gt;&gt;= 1; } \n\npublic:\n binary_view() = default;\n explicit binary_view(int value) : value(value) {}\n};\n</code></pre>\n\n<p>Once you have this view that allows you to look at a number as a sequence of zeros and ones, you can use the operator <code>|</code> to combine it with other views . For instance, we can view the sequence of zeros and ones as a sequence of sequences of consecutive zeros or consecutives ones:</p>\n\n<pre><code>auto zeros_and_ones = binary_view(my_number);\nauto split_zeros_and_ones = zeros_and_ones | group_by(std::equal_to&lt;&gt;());\n</code></pre>\n\n<p>We can then view those groups of consecutive ones or zeros as the number of zeros they contain:</p>\n\n<pre><code>auto numbers_of_zeros = split_zeros_and_ones | transform([](auto&amp;&amp; group) { \n return count(group, 0); \n});\n</code></pre>\n\n<p>Then we can simply request the maximum value out of that view with <code>max_element</code>:</p>\n\n<pre><code>auto consecutive_zeros =\n binary_view(0b1001000) \n | group_by(std::equal_to&lt;&gt;())\n | transform([](auto&amp;&amp; group) { return count(group, 0); });\n\nauto largest_gap = *max_element(consecutive_zeros);\n</code></pre>\n\n<p>Here's a link to the full code (with a slightly buffed-up <code>binary_view</code> allowing bidirectional traversal): <a href=\"https://wandbox.org/permlink/OVlg6aJP9DC1wkPR\" rel=\"noreferrer\">https://wandbox.org/permlink/OVlg6aJP9DC1wkPR</a></p>\n\n<p>If you're skeptical about the benefit you can get from all this (after all, my solution is quite complicated compared to the original code), I suggest you visit <a href=\"https://ericniebler.github.io/range-v3/index.html#range-views\" rel=\"noreferrer\">this page</a> where you'll find all pre-defined <code>view</code>s and think about all the problems you could solve with a combination of them!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T08:15:23.380", "Id": "212047", "ParentId": "211995", "Score": "5" } } ]
{ "AcceptedAnswerId": "212032", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T13:49:27.613", "Id": "211995", "Score": "4", "Tags": [ "c++", "programming-challenge", "c++14", "bitwise" ], "Title": "Largest binary gap" }
211995
<p>I have a thread-safe API for an observable <code>Sensor</code>. The concrete type of the <code>Sensor</code> is chosen in the <code>configure</code> method (strategy pattern). To avoid deadlock when calling the <code>stop</code>method, I had to use two mutexes. The first one is to protect the observers list <code>obs_</code> and the other one is to protect the strategy pointer <code>sensor_</code>.</p> <p>I am not a fan of using multiple mutexes to make a thread-safe API. My hunch is that there may be a better way to do that.</p> <pre><code>#include &lt;memory&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;list&gt; #include &lt;iostream&gt; class SensorImpl { public: virtual void start() = 0; virtual void stop() = 0; }; class SensorA : public SensorImpl { public: typedef std::function&lt;void(int)&gt; DataCallback; SensorA(DataCallback cb) : dataCallback_(cb) { } virtual ~SensorA() { } void start() override { running_ = true; workerThread_.reset(new std::thread(&amp;SensorA::dataProducer, this)); } void stop() override { if(workerThread_) { running_ = false; workerThread_-&gt;join(); workerThread_.reset(); } } private: void dataProducer() { while(running_) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); int data = 6; dataCallback_(data); } } DataCallback dataCallback_; std::unique_ptr&lt;std::thread&gt; workerThread_; bool running_{false}; }; class SensorObserver { virtual void configured() = 0; virtual void started() = 0; virtual void dataReceived(int data) = 0; virtual void stopped() = 0; virtual void cleanup() = 0; }; // Sensor API must be thread-safe class Sensor { public: Sensor() { } ~Sensor() { } void configure() { std::lock_guard&lt;std::mutex&gt; lock(implMtx_); auto dataCallback = [this](int data) { std::lock_guard&lt;std::mutex&gt; lock(obsMtx_); std::cout &lt;&lt; "dataReceived" &lt;&lt; std::endl; // notify SensorObserver::dataReceived }; sensor_.reset(new SensorA(dataCallback)); { std::lock_guard&lt;std::mutex&gt; lock(obsMtx_); std::cout &lt;&lt; "configured" &lt;&lt; std::endl; // notify SensorObserver::configured() } } void start() { std::lock_guard&lt;std::mutex&gt; lock(implMtx_); if(sensor_) { sensor_-&gt;start(); { std::lock_guard&lt;std::mutex&gt; lock(obsMtx_); std::cout &lt;&lt; "started" &lt;&lt; std::endl; // notify SensorObserver::started() } } } void stop() { std::lock_guard&lt;std::mutex&gt; lock(implMtx_); if(sensor_) { sensor_-&gt;stop(); { std::lock_guard&lt;std::mutex&gt; lock(obsMtx_); std::cout &lt;&lt; "stopped" &lt;&lt; std::endl; // notify SensorObserver::stopped() } } } void cleanup() { std::lock_guard&lt;std::mutex&gt; lock(implMtx_); sensor_.reset(); { std::lock_guard&lt;std::mutex&gt; lock(obsMtx_); std::cout &lt;&lt; "cleanup" &lt;&lt; std::endl; // notify SensorObserver::cleanup() } } // Observer attach/detach/notify code omitted private: std::mutex obsMtx_, implMtx_; std::unique_ptr&lt;SensorImpl&gt; sensor_; std::list&lt;SensorObserver*&gt; obs_; }; int main() { Sensor sensor; sensor.configure(); sensor.start(); std::this_thread::sleep_for(std::chrono::milliseconds(500)); sensor.stop(); sensor.cleanup(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T15:07:41.813", "Id": "409938", "Score": "1", "body": "You appear to have tested this code, but it looks like it doesn't work as intended. Please clarify after taking a look at the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T15:25:48.150", "Id": "409940", "Score": "0", "body": "@TobySpeight `@Mast` Thank you for educating me as a new contributor. I edited the question with the working code." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T14:55:19.210", "Id": "211998", "Score": "2", "Tags": [ "c++", "object-oriented", "c++11", "multithreading", "thread-safety" ], "Title": "Thread-safe sensor interface with observer and strategy patterns" }
211998
<p>I’m using Redux and thunk, I have a list component </p> <pre><code>class List extends Component { render() { //code } return( &lt;Aux&gt; &lt;Button type="button" click={() =&gt; this.props.addNew(data)} btnType="add" &gt; Add &lt;/Button&gt; &lt;Button type="button" click={() =&gt; this.props.deleteB(id, type)} btnType="Delete" &gt; Delete &lt;/Button&gt; &lt;Button type="button" click={() =&gt; this.props.editStart(id)} btnType="edit" &gt; Edit &lt;/Button&gt; &lt;Button type="button" click={() =&gt; this.props.editSave(data, type)} btnType="save" &gt; save &lt;/Button&gt; &lt;/Aux&gt; ) } const mapStateToProps = state =&gt; { return { editing: state.list.editing }; }; const mapDispatchtoProps = dispatch =&gt; { return { deleteB: (id, type) =&gt; {dispatch(actions.deleteB(id, type))}, editStart: (id) =&gt; {dispatch(actions.editStart(id))}, editSave: (data, type) =&gt; {dispatch(actions.editSave(data, type))}, addNew: (data) =&gt; dispatch(actions.addNew(data)) }; }; export default connect(mapStateToProps, mapDispatchtoProps)(List); </code></pre> <p>A reducer</p> <pre><code>const addNew = ( state, action ) =&gt; { //immutable state //add new //return updated state }; const deleteB = ( state, action ) =&gt; { //immutable state //delete //return updated state }; const editStart = ( state, action ) =&gt; { //immutable state //update editing to true //return updated state }; const editSave = ( state, action ) =&gt; { //immutable state if(action.type === state.editing.type) { //update object with user data } else { //delete old data same code of deleteB //add data user like addNew //update editing to false } //return updated state }; const reducer = ( state = initialState, action ) =&gt; { //switch case }; export default reducer; </code></pre> <p>When the user clicks on the “save” button if the type of the data changed the reducer uses the same functions that the buttons “add” and “delete” uses. I’ve created an utility function for deleting and adding data, but It still looks ugly.</p> <p>I was wondering if when the user clicks “Save” it is better to call a function in the List component that calls “addNew” and “deleteB” and finally “editSave” to only update the state for the “editing” state property.</p> <p>I think that a reducer needs to know only the state he needs to update, so editSave should only update the editing slice of state, and I need to reuse the others reducers. But I don’t know if there is a better way, or if I wrote a bad pattern for the reducers.</p>
[]
[ { "body": "<blockquote>\n <p>I was wondering if when the user clicks “Save” it is better to call a function in the List component that calls “addNew” and “deleteB” and finally “editSave” to only update the state for the “editing” state property.</p>\n</blockquote>\n\n<p>I would avoid this. Ideally, all your logic should live either the reducer or the thunk, NOT in components. This way, your logic is in one place, are easily and uniformly testable, and are not affected by things such as re-implementation of the UI (i.e. changing of components, replacing the UI library, etc).</p>\n\n<p>Reducers are just pure functions - they take in old state and an action, and they return new state. As long as you follow that basic principle, you're good. When you call a reducer from another reducer, you're effectively just <a href=\"https://redux.js.org/recipes/structuring-reducers/splitting-reducer-logic\" rel=\"nofollow noreferrer\">composing reducers</a> - which isn't a strange concept in Redux. So it's not weird to have something like this:</p>\n\n<pre><code>export const add = (state, action) =&gt; { ... }\n\nexport const edit = (state, action) =&gt; { ... }\n\nexport const delete = (state, action) =&gt; { ... }\n\nexport const someWeirdCaseOfAddEditDelete = (state, action) =&gt; {\n if(action.type === state.editing.type) {\n return edit(state, action)\n } else {\n const intermediateState = add(delete(state, action), action)\n const finalState = doMoreStuffWith(intermediateState, action)\n return finalState\n }\n}\n</code></pre>\n\n<p>As an added bonus, when the time comes when <code>someWeirdCaseOfAddEditDelete</code> starts to deviate from your regular <code>add</code>, <code>edit</code> and <code>delete</code>, you can simply replace its implementation and its tests without having to meddle with the other three reducers.</p>\n\n<hr>\n\n<p>To address your concerns in the comments:</p>\n\n<blockquote>\n <p>I thought that was an anti-pattern because it's like dispatching an action inside a reducer that got executed from an action.</p>\n</blockquote>\n\n<p>Calling <code>dispatch</code> in a reducer is the antipattern. But composing functions (i.e. breaking up your reducer into subfunctions that deal with specific parts of the state) is totally fine.</p>\n\n<p>It may be easier to wrap your head around the idea by dropping the assumption that the common operation is a reducer. Think of it as just a common utility function:</p>\n\n<pre><code>const thatCommonFunction = (somePartOfTheState) =&gt; ({\n thatOnePropertyYouNeedToChange: { ... }\n})\n\nconst reducer1 = (state, action) =&gt; ({\n ...state,\n ...thatCommonFunction(state.some.part)\n})\n\nconst reducer2 = (state, action) =&gt; ({\n ...state,\n ...thatCommonFunction(state.some.part)\n})\n</code></pre>\n\n<blockquote>\n <p>Every time I call \"deleteB\" or \"add\" from \"someWeirdCaseOfAddEditDelete\" the state will update, before returning the intended \"finalState\".</p>\n</blockquote>\n\n<p>If the state updates before all of your reducers return the new state to Redux, then there's something wrong with your code.</p>\n\n<p>Redux receives the updated state only after it runs through all the reducers. The state should never update while execution is still in the reducer.</p>\n\n<p>Under the hood, at the very basic, Redux does something like this:</p>\n\n<pre><code>const createStore = (rootReducer, initialState = {}) =&gt; {\n let currentState = initialState;\n const subscriptions = [];\n\n return {\n dispatch(action) {\n // This part is where control is handed over to your reducers.\n currentState = rootReducer(currentState, action);\n\n // Only after the line above should your state be updated.\n\n // After that one line, the UI is informed of the update.\n subscriptions.forEach(s =&gt; s(currentState))\n },\n subscribe(fn) {\n subscriptions.push(fn)\n }\n })\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:03:16.107", "Id": "410507", "Score": "0", "body": "I was first going for this solution, but I thought that was an anti-pattern because it's like dispatching an action inside a reducer that got executed from an action. How the state will behave in this situation? Every time I call \"deleteB\" or \"add\" from \"someWeirdCaseOfAddEditDelete\" the state will update, before returning the intended \"finalState\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:09:17.650", "Id": "410761", "Score": "0", "body": "@AskaNor_29 *\"Every time I call \"deleteB\" or \"add\" from \"someWeirdCaseOfAddEditDelete\" the state will update, before returning the intended \"finalState\".\"* - there's the confusion. I'll update the answer to address this since it's too long for the comment box." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T18:04:34.580", "Id": "410836", "Score": "0", "body": "Thank you for the clarification. Yes, I was confused, I was not sure if the \"common operator\" could be called inside another common operator. I will test this solution." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T03:41:29.540", "Id": "212188", "ParentId": "212001", "Score": "2" } } ]
{ "AcceptedAnswerId": "212188", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T15:35:24.730", "Id": "212001", "Score": "1", "Tags": [ "javascript", "react.js", "redux" ], "Title": "Redux: button click potentially fires 3 action for different reducers" }
212001
<p>The start of a simple Scrabble solver.</p> <p>What I have so far: </p> <ul> <li>Add a word to the trie</li> <li>Return a sorted list with the all possible combinations, based on the letters input</li> <li>Some basic tests</li> </ul> <p><em>Edit</em></p> <p>Since it hasn't received any answer yet...</p> <ul> <li>Added a joker letter, for getting the best possible words</li> </ul> <p><em>Please critique any and all</em></p> <pre><code>from queue import Queue import unittest class Node(): def __init__(self, char): self.char = char self.children = set() self.finished = False class Trie(): def __init__(self): self.root = Node('') self.char_score = { 'a' : 1, 'b' : 3, 'c' : 5, 'd' : 2, 'e' : 1, 'f' : 4, 'g' : 3, 'h' : 4, 'i' : 1, 'j' : 4, 'k' : 3, 'l' : 3, 'm' : 3, 'n' : 1, 'o' : 1, 'p' : 3, 'q' : 10, 'r' : 2, 's' : 2, 't' : 2, 'u' : 4, 'v' : 4, 'w' : 5, 'x' : 8, 'y' : 8, 'z' : 4 } def add(self, word): """Adds a word to the trie""" node = self.root for char in word: for child in node.children: if child.char == char: node = child break else: new_node = Node(char) node.children.add(new_node) node = new_node node.finished = True def _get_possible_words(self, letters): """ Generates all possible words that can be made in the trie letters: (list) A list of letters * stands for a joker """ que = Queue() que.put((self.root, self.root.char, letters)) while que.qsize() &gt; 0: node, word, letters_left = que.get() for child in node.children: if letters_left and (child.char in letters_left or "*" in letters_left): new_word = word + child.char new_bag = letters_left[:] new_bag.remove(child.char if child.char in letters_left else "*") que.put((child, new_word, new_bag)) if child.finished: yield new_word def get_best_words(self, letters): """Returns a sorted list based on the (score, length of the word)""" return sorted( (w for w in self._get_possible_words(letters)), key=lambda w: ( -sum(self.char_score[c] for c in w), len(w) ) ) # Tests class TrieTest(unittest.TestCase): def setUp(self): self.trie = Trie() self.words = ('tekst', 'test', 'tekens', 'tek', 'tekst', 'teksten') for word in self.words: self.trie.add(word) def test_get_best(self): self.assertEqual( ['tekst', 'test', 'tek'], self.trie.get_best_words(['t', 'k', 'e', 's', 't', 'n']) ) def test_get_best_joker(self): self.assertEqual( ['teksten', 'tekst', 'tekens', 'test', 'tek'], self.trie.get_best_words(['t', 'k', 'e', 's', 't', '*', 'n']) ) if __name__ == '__main__': unittest.main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T08:23:08.507", "Id": "410201", "Score": "0", "body": "@BaileyParker Your comment confuses me. If you have seen the code, you would have seen the unittests, and if you had run the code, you would have noticed that they all pass. ;) Could you tell me why you think this is not working, so I can edit the question and remove the ambiguity.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:25:12.553", "Id": "410217", "Score": "0", "body": "I saw both the code and unittests. Your comment reaffirms what I said before. CodeReview is for fully working code. StackOverflow is for “why this is not working” and “does my Trie seem correct”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:30:20.507", "Id": "410218", "Score": "0", "body": "@BaileyParker There has been some discussion about this recently in chat. I know it is working, I am wondering if this is the best way to do it... Why else would I ask for a review? Me stating if this is correct does not mean I don't know if it is correct or not, but rather if there is a better way to write it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:37:25.360", "Id": "410221", "Score": "0", "body": "@BaileyParker chat reference: https://chat.stackexchange.com/transcript/message/48534932#48534932" } ]
[ { "body": "<ol>\n<li><p>You have a couple of style issues:</p>\n\n<ul>\n<li>you don't need the empty brackets after class definitions.</li>\n<li>You should have two new lines before and after class definitions.</li>\n</ul></li>\n<li><p>You're conflating a base class and an implementation of it. I find keeping them separate to increase readability as you should know roughly what the base dose without reading the code. And you can more easily view the additional functionality.</p></li>\n<li><code>Node</code> and <code>Trie</code> should be the same class.</li>\n<li><p>To be a pedant, I don't think your implementation is a Trie:</p>\n\n<ul>\n<li><p>It's not ordered, and you don't apply the key to the edges.</p>\n\n<pre><code>self.children = set()\n</code></pre></li>\n<li><p>Nodes in the tree store the keys.</p>\n\n<pre><code>self.char = char\n</code></pre></li>\n</ul></li>\n<li><p>I'd change <code>add</code> to <code>__setitem__</code>, and you could change it to be a for loop constantly using <code>dict.setdefault</code>.</p></li>\n</ol>\n\n<p>And so I'd start with the following base class:</p>\n\n<pre><code>class Trie:\n __slots__ = ('value', 'children')\n\n def __init__(self, value=None):\n self.value = value\n self.children = {}\n\n def __getitem__(self, keys):\n node = self\n for key in keys:\n node = node.children[key]\n if node.value is None:\n raise KeyError('No value for the provided key')\n return node.value\n\n def __setitem__(self, keys, value):\n cls = type(self)\n node = self\n for key in keys:\n node = node.children.setdefault(key, cls())\n node.value = value\n</code></pre>\n\n<p>The largest difference between the above <code>Trie</code> and yours is the addition of a <code>value</code>. This should be the score of the word, which the Trie shouldn't be tasked with finding.</p>\n\n<ol>\n<li>As stated above, you should find the score of the word outside the <code>Trie</code> and so would make a function <code>word_score</code>.</li>\n<li>I personally would make <code>get_best_words</code> a function outside of the class, so that we don't depend on the class. However if you want it for ease of use, then I'd make it call the external function.</li>\n<li><p>This leaves <code>_get_possible_words</code>.</p>\n\n<ul>\n<li>It has a <span class=\"math-container\">\\$O(n^3)\\$</span> space complexity because you keep duplicating <code>letters</code>.</li>\n<li>Your code is hard to read as you've manually implemented recursion. This is as you didn't define the function on <code>Node</code>.</li>\n</ul>\n\n<p>You can make a public function that changes <code>letters</code> to a <code>collections.Counter</code>, and then define the recursion on a private function that adds and removes a value from letters. It also allowed me to write the code in what I think is a far simpler manner.</p></li>\n</ol>\n\n<p>Giving me the code:</p>\n\n<pre><code>import collections\nimport functools\n\n\ndef score(word, scores):\n return sum(scores[l] for l in word)\n\n\nword_score = functools.partial(\n score,\n scores={\n 'a' : 1, 'b' : 3, 'c' : 5, 'd' : 2, 'e' : 1, 'f' : 4,\n 'g' : 3, 'h' : 4, 'i' : 1, 'j' : 4, 'k' : 3, 'l' : 3,\n 'm' : 3, 'n' : 1, 'o' : 1, 'p' : 3, 'q' : 10, 'r' : 2,\n 's' : 2, 't' : 2, 'u' : 4, 'v' : 4, 'w' : 5, 'x' : 8,\n 'y' : 8, 'z' : 4\n }\n)\n\n\ndef best_words(s_trie, letters):\n return sorted(\n s_trie.get_possible_words(letters)\n key=lambda (k, v): (-v, len(k))\n )\n\n\nclass Trie:\n __slots__ = ('value', 'children')\n\n def __init__(self, value=None):\n self.value = value\n self.children = {}\n\n def __getitem__(self, keys):\n node = self\n for key in keys:\n node = node.children[key]\n if node.value is None:\n raise KeyError('No value for the provided key')\n return node.value\n\n def __setitem__(self, keys, value):\n cls = type(self)\n node = self\n for key in keys:\n node = node.children.setdefault(key, cls())\n node.value = value\n\n\nclass ScrabbleTrie(Trie):\n def _get_possible_words(self, letters, prefix):\n if self.value is not None:\n yield prefix, node.value\n\n for key, node in self.children.items():\n if not letters.get(key, 0):\n continue\n letters[key] -= 1\n yield from node._get_possible_words(letters, prefix + key)\n letters[key] += 1\n\n if letters.get('#', 0):\n letters['#'] -= 1\n for key, node in self.children.items():\n yield from node._get_possible_words(letters, prefix + key)\n letters['#'] += 1\n\n def get_possible_words(self, letters):\n return self._get_possible_words(collections.Counter(letters), '')\n\n def get_best_words(self, letters):\n return best_words(self, letters)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T18:56:26.040", "Id": "410283", "Score": "0", "body": "I like your additions, the Counter is a smart *counter* to the problem I had with the copying of lists. I did go iterative (queue), because i thought Python and recursion don't really work well together. The generator does not have these issues I take?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:00:14.843", "Id": "410285", "Score": "0", "body": "@Ludisposed recursion is good, unless you're going to nestively recurse around 1000 times or more (IIRC). I highly doubt you'll have a word that long as the board is like 15 squares big." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:02:01.227", "Id": "410286", "Score": "0", "body": "But there can be more then 1000 possible words" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:03:36.647", "Id": "410287", "Score": "1", "body": "@Ludisposed That doesn't matter, as the limits come from nested recursion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T10:10:55.443", "Id": "410946", "Score": "0", "body": "I have decided to expand on this code, but there were a few issues I needed to fix before being able to use it. 1. That lambda expression is Python2.x iirc can't unpack in lambda anymore. 2. A typo with `node.value` -> `self.value` 3. Having to `set` the possible words to avoid duplicates when adding a joker. But overall it works fine, and the value addition does come in handy in the future. Thnx :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T13:10:14.730", "Id": "410968", "Score": "0", "body": "Ah oops about 2, I left 3 as technically they are different words, or atleast use different tiles. But since you don't need that the set should work fine" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T17:43:42.497", "Id": "212149", "ParentId": "212003", "Score": "2" } }, { "body": "<p>You are too enamored of the <code>Trie</code> class. Ask yourself, &quot;what am I doing?&quot; I believe the answer looks something like this:</p>\n<blockquote>\n<p>In order to &quot;solve&quot; word-generation board games, I am trying to write code that can:</p>\n<ol>\n<li><p>Given a 'context' string and two numeric 'limits' indicating the maximum number of before/after cells, plus a list of 'tile' characters possibly including match-any-letter wildcard values, generate the sequence of all possible words that can be built starting with, ending with, or surrounding the context string.</p>\n</li>\n<li><p>Compute a score for each generated word, using a provided &quot;base&quot; scoring mechanism and possibly a position-based mechanism for additional &quot;word&quot; or &quot;letter&quot; scores. (E.g., &quot;Double Letter Score&quot; or &quot;Triple Word Score&quot;)</p>\n</li>\n</ol>\n</blockquote>\n<p>Notice that the word &quot;trie&quot; never appears in those requirements. This is because the trie is an implementation detail, rather than a part of the solution. In simple OO terms, your WordList object might &quot;has-a&quot; trie, but it doesn't &quot;is-a&quot; trie.</p>\n<p>What you have, I think, is a <code>Lexicon</code> (which is a way of saying &quot;WordList&quot; without using the word 'list'). And you're going to ask that Lexicon one question to start with: what words can you make with this fixed part and these variable parts?</p>\n<pre><code># Board like _ _ _ _ _ _ _ A N D _ _ with tiles [a,e,f,m,q,r,t]\nlex.generate_words(fixed='and', max_before=7, max_after=2, tiles='aefmqrt')\n</code></pre>\n<p>(Obviously you would also call with fixed='a', fixed='n', fixed='d' going crossways.)</p>\n<p>Once you have a sequence of words coming from the <code>Lexicon</code>, you will want to score the words. You will need to somehow map the words to positions on the board, and then to scoring. For example, if your <code>fixed='an'</code> you might generate &quot;banana&quot; two ways (b[an]ana vs. ban[an]a), and the <code>Lexicon</code> should report that, and your scoring algorithm should account for it so you can try to match the &quot;Double Word Score&quot; in whatever position.</p>\n<p>So I think you will need a scoring mechanism that is sensitive to the board location, and also to the rules of the game. (Official Scrabble(tm) has different scoring rules than Words-with-Friends, for example.)</p>\n<p>When you get particularly advanced, you might also want to ask the <code>Lexicon</code> for matches involving multiple fixed parts: _ _ _ A N D _ _ R A M _ _. I'll leave that as an exercise for the coder.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T13:18:02.763", "Id": "410497", "Score": "0", "body": "I haven't implemented all that yet, but would you say a Trie is the correct dataclass for generating words from a lexicon or should I drop it entirely?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:42:29.100", "Id": "410511", "Score": "0", "body": "It seems like you have the trie working, so keep it by all means. But remember what you're building. If the trie starts to give you problems, switch to something else." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T00:09:05.293", "Id": "212244", "ParentId": "212003", "Score": "2" } } ]
{ "AcceptedAnswerId": "212149", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T15:49:18.227", "Id": "212003", "Score": "5", "Tags": [ "python", "python-3.x", "trie" ], "Title": "Scrabble Solver" }
212003
<p>I made a simple password vault in Java and I was wondering if anyone had any input on it. The code works fine, I just wanted to know if there are any improvements that could be made. </p> <pre><code>import javax.swing.*; import javax.swing.table.*; import java.awt.event.*; public class PasswordVault implements ActionListener { static String masterPassword, enteredPassword; JFrame masterPasswordFrame, passwordVault; JPasswordField masterPasswordField; JTable passwordTable; Object[] columnNames = {"Name of Application", "Application Password", "Description"}; Object[] rowData = new Object[3]; JTextField appName, appPass, appDesc; JButton add, delete, update; JLabel nameOfApp, passOfApp, descOfApp; public static void main(String[] args) { String name = JOptionPane.showInputDialog("What is your name?"); masterPassword = JOptionPane.showInputDialog("Hello, " + name + ". " + "What would you like your master password to be?"); new PasswordVault(); } public PasswordVault() { masterPasswordFrame = new JFrame("Master Password"); masterPasswordFrame.setSize(400,100); masterPasswordFrame.setLocationRelativeTo(null); masterPasswordFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JPanel masterPasswordPanel = new JPanel(); masterPasswordField = new JPasswordField(10); masterPasswordField.setEchoChar('*'); JLabel passwordLabel = new JLabel("Enter Password: "); JButton okayButton = new JButton("Check"); okayButton.addActionListener(this); masterPasswordPanel.add(passwordLabel); masterPasswordPanel.add(masterPasswordField); masterPasswordPanel.add(okayButton); masterPasswordFrame.add(masterPasswordPanel); masterPasswordFrame.setVisible(true); masterPasswordFrame.pack(); enteredPassword = new String(masterPasswordField.getPassword()); passwordVault = new JFrame("Password Vault"); passwordTable = new JTable(); DefaultTableModel tableModel = new DefaultTableModel(); tableModel.setColumnIdentifiers(columnNames); passwordTable.setModel(tableModel); appName = new JTextField(); appPass = new JTextField(); appDesc = new JTextField(); add = new JButton("Add"); delete = new JButton("Delete"); update = new JButton("Update"); nameOfApp = new JLabel("App Name: "); passOfApp = new JLabel("App password: "); descOfApp = new JLabel("Description: "); appName.setBounds(400, 220, 100, 25); appPass.setBounds(400, 250, 100, 25); appDesc.setBounds(400, 280, 100, 25); add.setBounds(530, 220, 100, 25); update.setBounds(530, 250, 100, 25); delete.setBounds(530, 280, 100, 25); JScrollPane scrollPane = new JScrollPane(passwordTable); scrollPane.setBounds(0, 0, 1000, 200); passwordVault.setLayout(null); passwordVault.add(scrollPane); passwordVault.add(nameOfApp); passwordVault.add(passOfApp); passwordVault.add(descOfApp); passwordVault.add(appName); passwordVault.add(appPass); passwordVault.add(appDesc); passwordVault.add(add); passwordVault.add(update); passwordVault.add(delete); add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { rowData[0] = appName.getText(); rowData[1] = appPass.getText(); rowData[2] = appDesc.getText(); tableModel.addRow(rowData); appName.setText(""); appPass.setText(""); appDesc.setText(""); } }); update.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = passwordTable.getSelectedRow(); if(i &gt;= 0) { tableModel.setValueAt(appName.getText(), i, 0); tableModel.setValueAt(appPass.getText(), i, 1); tableModel.setValueAt(appDesc.getText(), i, 2); appName.setText(""); appPass.setText(""); appDesc.setText(""); } else { JOptionPane.showMessageDialog(null, "Update Error"); } } }); delete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { int i = passwordTable.getSelectedRow(); if(i &gt;= 0) { tableModel.removeRow(i); appName.setText(""); appPass.setText(""); appDesc.setText(""); } else { JOptionPane.showMessageDialog(null, "Delete Error"); } } }); passwordTable.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { int i = passwordTable.getSelectedRow(); appName.setText(tableModel.getValueAt(i, 0).toString()); appPass.setText(tableModel.getValueAt(i, 1).toString()); appDesc.setText(tableModel.getValueAt(i, 2).toString()); } }); passwordVault.setSize(1000,500); passwordVault.setLocationRelativeTo(null); passwordVault.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void actionPerformed(ActionEvent event) { if(new String(masterPasswordField.getPassword()).equals(masterPassword)) { masterPasswordFrame.setVisible(false); passwordVault.setVisible(true); } else { JOptionPane.showMessageDialog(null, "Password Incorrect. Please Try Again."); } } } </code></pre>
[]
[ { "body": "<p>Some things that caught my eye:</p>\n\n<p>you don't seem to have any persistent storage just in memory. I believe you would get more versatility by implementing external persistent storage. The storage can be in several different formats, physical file on disk, a database, cloud storage.</p>\n\n<p>In line with that, it is usually not a very good idea to store passwords as literal strings. This leaves you prone to hacking. I would suggest looking at the Cryptography api.</p>\n\n<p>Separate the vault from the GUI. What happens if you decide to run the vault from a server in a webpage or as a console application? You basically have to start over again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T22:55:09.010", "Id": "409977", "Score": "0", "body": "What do you mean by seperate the vault from the GUI? Should I make a seperate class and have the vault in there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T22:56:34.737", "Id": "409978", "Score": "0", "body": "Also how would I implement external persistent storage?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T23:07:09.607", "Id": "409980", "Score": "0", "body": "@Blake - Yes the vault should be a separate class. The storage can be in several different formats, physical file on disk, a database, cloud storage. You would have to decide which will suit your purposes the best." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T20:27:11.483", "Id": "212022", "ParentId": "212005", "Score": "1" } } ]
{ "AcceptedAnswerId": "212022", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T16:19:32.030", "Id": "212005", "Score": "4", "Tags": [ "java" ], "Title": "Simple Password Vault" }
212005
<p>One of the app is inserting date in UTC format (column <code>CreateDate</code>). When reporting from this table, I used a difference in hours between the inbuilt <code>GetUTCDate()</code> and <code>GetDate()</code> and added the same to the <code>CreateDate</code> column. I was hoping to not worry about the daylight time. Is this approach OK?</p> <pre><code>SELECT GetUTCDate() SELECT GetDate() DECLARE @DifferenceInHoursBetween INT SELECT @DifferenceInHoursBetween = DATEDIFF(HH,GetUTCDate(), GETDATE()) SELECT USER_ID, CreateDate AS [DateTime IN UTC], DATEADD(HOUR,@DifferenceInHoursBetween,CreateDate) AS [LocalDateTime] FROM EVENTLOG(nolock) </code></pre> <p>/<em>Tests</em>/</p> <pre><code>SELECT GetUTCDate() AS [UTCDateTime] SELECT GetDate() AS [LocalDateTime] DECLARE @DifferenceInHoursBetween INT SELECT @DifferenceInHoursBetween = DATEDIFF(HH,GetUTCDate(), GETDATE()) SELECT @DifferenceInHoursBetween AS [Difference in Hours] </code></pre> <p>-- UTCDateTime</p> <p>2019-01-22 16:34:46.943</p> <p>--LocalDateTime</p> <p>2019-01-22 08:34:46.943</p> <p>-- Difference in hours -8</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T13:32:56.970", "Id": "410042", "Score": "1", "body": "good approach is to save the date in UTC" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T18:20:38.537", "Id": "436722", "Score": "0", "body": "To be fair, if DST was your initial concern, your SQL is not working as intended." } ]
[ { "body": "<h2>Review</h2>\n\n<p>You don't need to calculate the difference from two temporary values <code>GetUTCDate</code> and <code>GETDATE</code>.</p>\n\n<blockquote>\n<pre><code>SELECT @DifferenceInHoursBetween = DATEDIFF(HH,GetUTCDate(), GETDATE())\n</code></pre>\n</blockquote>\n\n<h2>Proposed Solution</h2>\n\n<p>Instead, you could apply the local time zone offset to the specified datetime.</p>\n\n<pre><code>SELECT \n USER_ID, \n CreateDate AS [DateTime IN UTC], \n CONVERT(datetime, \n SWITCHOFFSET(CONVERT(datetimeoffset, CreateDate), \n DATENAME(TzOffset, SYSDATETIMEOFFSET()))) AS [LocalDateTime] \nFROM EVENTLOG(nolock);\n</code></pre>\n\n<hr>\n\n<p><a href=\"https://dbfiddle.uk/?rdbms=sqlserver_2017&amp;fiddle=27b7cc4016dcabffeb7e4a32d0c25d3b\" rel=\"nofollow noreferrer\">Fiddle: SQL Server 2017</a></p>\n\n<p><a href=\"https://i.stack.imgur.com/s3oVu.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/s3oVu.jpg\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<h3>Daylight Savings Time</h3>\n\n<p>Both methods, OP and solution don't take into account DST. And unfortunately, SQL Server does not come with a built-in conversion from DST. You'd have to make a function yourself. <a href=\"https://dba.stackexchange.com/questions/28187/how-can-i-get-the-correct-offset-between-utc-and-local-times-for-a-date-that-is\">More about DST in SQL Server</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-07-27T17:41:47.760", "Id": "225049", "ParentId": "212006", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T16:37:37.647", "Id": "212006", "Score": "4", "Tags": [ "sql", "datetime", "sql-server", "converting", "t-sql" ], "Title": "Get local datetime from UTC time" }
212006
<p>To check out the cssv module i wrote a small programm which takes all xlsx files in a folder and converts them into csv files.</p> <p>Let me know what you would improve on this program.</p> <p><strong>xlsx_tp_csv</strong></p> <pre><code>""" All xlsx files in the folder of the script get converted into csv files (One for each sheet). The names are created as excel filename + sheet name. """ import csv import os from pathlib import Path import openpyxl def make_csv_filename(filename_excel: str, sheet_name: str) -&gt; str: """ Make a filename out of the filename of the excel file and the corresponding sheet """ return Path(filename_excel).resolve().stem + '_' + sheet_name + '.csv' def xlsx_to_csv(): """Main loop""" target_folder: str = 'csv' os.makedirs(target_folder, exist_ok=True) for filename in os.listdir('.'): if not filename.endswith('.xlsx'): continue workbook = openpyxl.load_workbook(filename) for sheet_name in workbook.sheetnames: sheet = workbook[sheet_name] csv_filename = make_csv_filename(filename, sheet_name) csv_path: Path = Path(target_folder, csv_filename) with open(csv_path, 'w', newline='') as csv_file: csv_writer = csv.writer(csv_file) for row_number in range(1, sheet.max_row + 1): row_data = [] for column_number in range(1, sheet.max_column + 1): cell_data = sheet.cell( column=column_number, row=row_number).value row_data.append(cell_data) csv_writer.writerow(row_data) if __name__ == "__main__": xlsx_to_csv() </code></pre>
[]
[ { "body": "<p>Good job with the type annotations! Here are a few things you could simplify/improve:</p>\n\n<ul>\n<li><p>instead of <code>listdir</code> and an extra file extension check, you could use <a href=\"https://docs.python.org/3/library/glob.html#glob.iglob\" rel=\"nofollow noreferrer\"><code>glob.iglob()</code></a>:</p>\n\n<pre><code>for filename in glob.iglob('./**/*.xlsx'):\n</code></pre></li>\n<li><p>to improve excel file read performance and memory consumption, you could use <a href=\"https://openpyxl.readthedocs.io/en/stable/optimized.html#read-only-mode\" rel=\"nofollow noreferrer\"><code>read_only=True</code> mode</a></p></li>\n<li><p>instead of iterating over <code>sheetnames</code> and getting a sheet by name, you could <a href=\"https://openpyxl.readthedocs.io/en/stable/api/openpyxl.workbook.workbook.html#openpyxl.workbook.workbook.Workbook.worksheets\" rel=\"nofollow noreferrer\">iterate over available worksheets directly</a>:</p>\n\n<pre><code>for sheet in workbook.worksheets:\n</code></pre></li>\n<li><p><a href=\"https://stackoverflow.com/a/31237077/771848\"><code>iter_rows()</code></a> should improve the way you read the sheet cells</p></li>\n</ul>\n\n<hr>\n\n<p>As a side note and as an idea for an alternative solution: what if you transition the data through a <code>pandas.DataFrame</code>, <code>pandas</code> has <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html\" rel=\"nofollow noreferrer\"><code>.read_excel()</code></a> and <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_csv.html\" rel=\"nofollow noreferrer\"><code>.to_csv()</code></a> methods.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T20:00:50.843", "Id": "409962", "Score": "1", "body": "Instead of `glob.iglob`, there is also [`pathlib.Path.glob`](https://docs.python.org/3/library/pathlib.html#pathlib.Path.glob), since OP is already using `Path`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T17:54:58.120", "Id": "212011", "ParentId": "212007", "Score": "4" } } ]
{ "AcceptedAnswerId": "212011", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T17:05:00.710", "Id": "212007", "Score": "3", "Tags": [ "python", "beginner", "excel", "csv" ], "Title": "Excel to CSV converter" }
212007
<p>I've been assigned to use Dijkstra's algorithm in order to find the shortest path on real data, more specifically on Luxembourg's map. </p> <p>The map is an .xml file with the following structure.</p> <pre><code>&lt;nodes&gt; &lt;node id="0" longitude="4963454" latitude="621476"/&gt; &lt;node id="1" longitude="4959493" latitude="614350"/&gt; &lt;node id="2" longitude="4959247" latitude="612096"/&gt; ... &lt;/nodes&gt; &lt;arcs&gt; &lt;arc from="0" to="40115" length="57"/&gt; &lt;arc from="0" to="40114" length="13"/&gt; &lt;arc from="1" to="16852" length="49"/&gt; ... &lt;/arcs&gt; </code></pre> <p>I've got this .xml file alongside all the source files on this <a href="https://gitlab.com/ISilviu/luxembourg" rel="nofollow noreferrer">repository</a>.</p> <p>The purpose of the assignment is: given the drawn map, you have to click on 2 different screen locations and get the shortest path between the closest Nodes to those clicks.</p> <p>Because the assignment wasn't that hard, I focused on elegance, performance, and reusability.</p> <p>Here's a snippet of the final program. <a href="https://i.stack.imgur.com/CL3U2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CL3U2.png" alt=""></a> </p> <p>Now let's dive in the code. I've come up with 4 interface-like classes which would let you make a truly custom Node class. </p> <p><strong>Earth.hpp</strong></p> <pre><code>#pragma once #include &lt;cstdint&gt; #include "Point2D.hpp" namespace Localizable { template &lt;typename LatLongType = int32_t&gt; class Earth { public: constexpr Earth(LatLongType latitude, LatLongType longitude) noexcept; constexpr LatLongType latitude() const noexcept; constexpr LatLongType longitutde() const noexcept; protected: Point2D&lt;LatLongType&gt; _location; }; template &lt;typename LatLongType&gt; inline constexpr Earth&lt;LatLongType&gt;::Earth(LatLongType latitude, LatLongType longitude) noexcept : _location(latitude, longitude) {} template &lt;typename LatLongType&gt; inline constexpr LatLongType Earth&lt;LatLongType&gt;::latitude() const noexcept { return _location.x; } template &lt;typename LatLongType&gt; inline constexpr LatLongType Earth&lt;LatLongType&gt;::longitutde() const noexcept { return _location.y; } } </code></pre> <p><strong>Screen.hpp</strong></p> <pre><code>#pragma once #include &lt;cstdint&gt; #include "Point2D.hpp" namespace Localizable { class Screen { public: constexpr Screen(uint16_t x, uint16_t y) noexcept; constexpr uint16_t x() const noexcept; constexpr uint16_t y() const noexcept; protected: Point2D&lt;uint16_t&gt; _location; }; inline constexpr Screen::Screen(uint16_t x, uint16_t y) noexcept : _location(x, y) {} inline constexpr uint16_t Screen::x() const noexcept { return _location.x; } inline constexpr uint16_t Screen::y() const noexcept { return _location.y; } } </code></pre> <p><strong>Associable.hpp</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include &lt;memory&gt; template &lt;typename KeyType&gt; class Node; template &lt;typename KeyType&gt; class Associable { protected: std::vector&lt;std::weak_ptr&lt;Node&lt;KeyType&gt;&gt;&gt; _neighbours; using NeighboursIterator = decltype(std::cbegin(_neighbours)); public: void add(std::weak_ptr&lt;Node&lt;KeyType&gt;&gt; neighbour); void remove(std::weak_ptr&lt;Node&lt;KeyType&gt;&gt; neighbour); constexpr std::pair&lt;NeighboursIterator, NeighboursIterator&gt; getNeighbours() const noexcept { return std::make_pair(std::cbegin(_neighbours), std::cend(_neighbours)); } }; template&lt;typename KeyType&gt; inline void Associable&lt;KeyType&gt;::add(std::weak_ptr&lt;Node&lt;KeyType&gt;&gt; neighbour) { _neighbours.push_back(neighbour); } template&lt;typename KeyType&gt; inline void Associable&lt;KeyType&gt;::remove(std::weak_ptr&lt;Node&lt;KeyType&gt;&gt; neighbour) { auto it = std::find(std::begin(_neighbours), std::end(_neighbours), neighbour); if (it != std::end(_neighbours)) _neighbours.erase(it); } </code></pre> <p><strong>Identifiable.hpp</strong></p> <pre><code>#pragma once #include &lt;cstdint&gt; template &lt;typename IdentifierType = uint16_t&gt; class Identifiable { public: constexpr explicit Identifiable(IdentifierType identifier) noexcept; constexpr IdentifierType key() const noexcept; protected: IdentifierType _key; }; template&lt;typename IdentifierType&gt; inline constexpr Identifiable&lt;IdentifierType&gt;::Identifiable(IdentifierType identifier) noexcept : _key(identifier) { } template&lt;typename IdentifierType&gt; inline constexpr IdentifierType Identifiable&lt;IdentifierType&gt;::key() const noexcept { return _key; } </code></pre> <p>Having all of these defined, making the custom Node class for the assignment was easy:</p> <p><strong>Node.hpp</strong></p> <pre><code>#pragma once #include "Earth.hpp" #include "Identifiable.hpp" #include "Associable.hpp" #include "Screen.hpp" #include "Utilities.hpp" template &lt;typename KeyType = uint16_t&gt; class Node : public Localizable::Earth&lt;int32_t&gt;, public Identifiable&lt;KeyType&gt;, public Associable&lt;KeyType&gt;, public Localizable::Screen { public: constexpr Node(KeyType key, int32_t latitude, int32_t longitutde) noexcept; }; template&lt;typename KeyType&gt; inline constexpr Node&lt;KeyType&gt;::Node(KeyType key, int32_t latitude, int32_t longitutde) noexcept : Identifiable&lt;KeyType&gt;(key), Localizable::Earth&lt;int32_t&gt;(latitude, longitutde), Localizable::Screen(Utilities::getScreenCoordinates(1280, 1020, latitude, longitutde)), Associable&lt;KeyType&gt;() { } namespace std { template&lt;typename KeyType&gt; struct hash&lt;Node&lt;KeyType&gt;&gt; { std::size_t operator()(const Node&lt;KeyType&gt;&amp; node) const noexcept { return std::hash&lt;KeyType&gt;{}(node.key()); } }; template &lt;typename KeyType&gt; struct equal_to&lt;Node&lt;KeyType&gt;&gt; { constexpr bool operator()(const Node&lt;KeyType&gt;&amp; lhs, const Node&lt;KeyType&gt;&amp; rhs) const noexcept { return lhs.key() == rhs.key(); } }; } template &lt;typename KeyType&gt; constexpr bool operator == (const Node&lt;KeyType&gt;&amp; lhs, const Node&lt;KeyType&gt;&amp; rhs) noexcept { return lhs.key() == rhs.key(); } template &lt;typename KeyType&gt; constexpr bool operator != (const Node&lt;KeyType&gt;&amp; lhs, const Node&lt;KeyType&gt;&amp; rhs) noexcept { return lhs.key() != rhs.key(); } </code></pre> <p>Then I've integrated my Node class in the Graph class. </p> <p><strong>Graph.hpp</strong></p> <pre><code>#pragma once #include &lt;unordered_map&gt; #include &lt;vector&gt; #include "Node.hpp" #include "Point2D.hpp" class GraphFactory; namespace std { template &lt;&gt; struct hash&lt;std::pair&lt;uint16_t, uint16_t&gt;&gt; { std::size_t operator ()(const std::pair&lt;uint16_t, uint16_t&gt;&amp; pair) const noexcept { return std::hash&lt;uint16_t&gt;{}(pair.first) + std::hash&lt;uint16_t&gt;{}(pair.second); } }; } namespace ShortestPath { template &lt;typename KeyType&gt; class Dijkstra; } /** * This Graph implements the Node class using an uint16_t KeyType. * Feel free to use any other data type for KeyType on your graph. */ template &lt;typename KeyType = uint16_t&gt; class Graph { private: std::unordered_map&lt;KeyType, std::shared_ptr&lt;Node&lt;KeyType&gt;&gt;&gt; _keyToNode; std::unordered_map&lt;std::pair&lt;KeyType, KeyType&gt;, uint16_t&gt; _weights; std::unordered_map&lt;Point2D&lt;uint16_t&gt;, std::weak_ptr&lt;Node&lt;KeyType&gt;&gt;&gt; _coordinatesToNode; using WeightsIterator = decltype(std::cbegin(_weights)); using NodesIterator = decltype(std::cbegin(_keyToNode)); public: friend class GraphFactory; template &lt;typename KeyType&gt; friend class ShortestPath::Dijkstra; public: constexpr std::pair&lt;NodesIterator, NodesIterator&gt; nodes() const noexcept { return std::make_pair(std::cbegin(_keyToNode), std::cend(_keyToNode)); } constexpr std::pair&lt;WeightsIterator, WeightsIterator&gt; arcs() const noexcept { return std::make_pair(std::cbegin(_weights), std::cend(_weights)); } std::shared_ptr&lt;Node&lt;KeyType&gt;&gt; operator [](KeyType key) const noexcept; std::weak_ptr&lt;Node&lt;KeyType&gt;&gt; operator [](Point2D&lt;uint16_t&gt; coordinates) const noexcept; uint16_t cost(const std::pair&lt;KeyType, KeyType&gt;&amp; keys) const; protected: template &lt;typename InputKeyMappingIterator, typename InputWeightingIterator, typename CoordinatesMapping&gt; Graph(InputKeyMappingIterator keysFirst, InputKeyMappingIterator keysLast, InputWeightingIterator weightsFirst, InputWeightingIterator weightsLast, CoordinatesMapping coordsFirst, CoordinatesMapping coordsLast); }; template&lt;typename KeyType&gt; std::shared_ptr&lt;Node&lt;KeyType&gt;&gt; Graph&lt;KeyType&gt;::operator[](KeyType key) const noexcept { auto it = _keyToNode.find(key); return it != std::end(_keyToNode) ? it-&gt;second : nullptr; } template&lt;typename KeyType&gt; inline std::weak_ptr&lt;Node&lt;KeyType&gt;&gt; Graph&lt;KeyType&gt;::operator[](Point2D&lt;uint16_t&gt; coordinates) const noexcept { auto it = _coordinatesToNode.find(coordinates); return it != std::end(_coordinatesToNode) ? it-&gt;second : std::weak_ptr&lt;Node&lt;KeyType&gt;&gt;(); } template&lt;typename KeyType&gt; inline uint16_t Graph&lt;KeyType&gt;::cost(const std::pair&lt;KeyType, KeyType&gt;&amp; keys) const { const auto&amp;[firstKey, secondKey] = keys; if (auto it = _weights.find(std::make_pair(firstKey, secondKey)); it != std::end(_weights)) return it-&gt;second; if (auto it = _weights.find(std::make_pair(secondKey, firstKey)); it != std::end(_weights)) return it-&gt;second; static constexpr uint16_t kDefaultValue = 0; return kDefaultValue; } template&lt;typename KeyType&gt; template&lt;typename InputKeyMappingIterator, typename InputWeightingIterator, typename CoordinatesMapping&gt; inline Graph&lt;KeyType&gt;::Graph(InputKeyMappingIterator keysFirst, InputKeyMappingIterator keysLast, InputWeightingIterator weightsFirst, InputWeightingIterator weightsLast, CoordinatesMapping coordsFirst, CoordinatesMapping coordsLast) : _keyToNode(keysFirst, keysLast), _weights(weightsFirst, weightsLast), _coordinatesToNode(coordsFirst, coordsLast) { } </code></pre> <p>The reason I'm returning a pair of iterators instead of the whole container is because of encapsulation and abstraction reasons. Why would anyone care that the Graph class is using a HashTable to retain the nodes?</p> <p>The final code snippet I'm exposing is the trivial Dijkstra implementation.</p> <pre><code>#pragma once #include "Graph.hpp" #include &lt;queue&gt; #include &lt;stdexcept&gt; namespace ShortestPath { template &lt;typename KeyType = uint16_t&gt; class Dijkstra { private: std::vector&lt;Node&lt;KeyType&gt;&gt; _path; public: explicit Dijkstra(const Graph&lt;KeyType&gt;&amp; graph, const std::shared_ptr&lt;Node&lt;KeyType&gt;&gt;&amp; source, const std::shared_ptr&lt;Node&lt;KeyType&gt;&gt;&amp; destination); constexpr std::pair&lt;decltype(std::cbegin(_path)), decltype(std::cend(_path))&gt; path() const noexcept { return std::make_pair(std::cbegin(_path), std::cend(_path)); } private: void computeShortestPath(const Graph&lt;KeyType&gt;&amp; graph); void populatePath() noexcept; const std::weak_ptr&lt;Node&lt;KeyType&gt;&gt; _source; const std::weak_ptr&lt;Node&lt;KeyType&gt;&gt; _destination; std::unordered_map&lt;Node&lt;KeyType&gt;, Node&lt;KeyType&gt;&gt; _cameFrom; std::unordered_map&lt;Node&lt;KeyType&gt;, uint16_t&gt; _cost; }; template&lt;typename KeyType&gt; inline Dijkstra&lt;KeyType&gt;::Dijkstra(const Graph&lt;KeyType&gt;&amp; graph, const std::shared_ptr&lt;Node&lt;KeyType&gt;&gt;&amp; source, const std::shared_ptr&lt;Node&lt;KeyType&gt;&gt;&amp; destination) : _source(source), _destination(destination) { computeShortestPath(graph); populatePath(); } template&lt;typename KeyType&gt; inline void Dijkstra&lt;KeyType&gt;::computeShortestPath(const Graph&lt;KeyType&gt; &amp; graph) { using Location = std::pair&lt;Node&lt;KeyType&gt;, uint16_t&gt;; auto compareLocations = [](const Location&amp; lhs, const Location&amp; rhs) { return lhs.second &gt; rhs.second; }; std::priority_queue&lt;Location, std::vector&lt;Location&gt;, decltype(compareLocations)&gt; discoveredNodes(compareLocations); static constexpr uint16_t kDefaultDistanceCost = 0; discoveredNodes.push(std::make_pair(*_source.lock(), kDefaultDistanceCost)); _cameFrom.insert(std::make_pair(*_source.lock(), *_source.lock())); _cost[*_source.lock()] = kDefaultDistanceCost; while (!discoveredNodes.empty()) { Location currentLocation = discoveredNodes.top(); discoveredNodes.pop(); if (auto destination = _destination.lock(); currentLocation.first.key() == destination-&gt;key()) return; auto locationFromGraph = graph[currentLocation.first.key()]; auto[first, last] = locationFromGraph-&gt;getNeighbours(); for (; first != last; ++first) { auto neighbour = *((*first).lock()); uint16_t newCost = _cost[currentLocation.first] + graph.cost(std::make_pair(currentLocation.first.key(), neighbour.key())); if (_cost.find(neighbour) == std::end(_cost) || newCost &lt; _cost[neighbour]) { _cost[neighbour] = newCost; _cameFrom.insert(std::make_pair(neighbour, currentLocation.first)); discoveredNodes.push(std::make_pair(neighbour, newCost)); } } } throw std::domain_error("No path was found.\n"); } template&lt;typename KeyType&gt; inline void Dijkstra&lt;KeyType&gt;::populatePath() noexcept { Node&lt;KeyType&gt; currentNode = *_destination.lock(); const Node&lt;KeyType&gt; sourceNode = *_source.lock(); while (currentNode != sourceNode) { _path.push_back(currentNode); currentNode = _cameFrom.at(currentNode); } _path.push_back(sourceNode); } } </code></pre> <p>All in all, what do you think? </p> <p>Did I use smart pointers properly?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T20:27:44.630", "Id": "409967", "Score": "1", "body": "I removed square brackets because they are usually for post status. I also added memory management tag, as it seems like it is one of the underlying concerns." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T16:51:39.513", "Id": "410066", "Score": "1", "body": "In terms of breaking this down into classes its way of verbose. Both Earth and Screen can simply be `std::pair`. Only Earth and Screen seem to be in a namespace; why only them? Weak pointer is usually used to break circular dependencies, is that why you are using it here? What's the point of `Identifiable`? I think you can simplify this to Graph and Node." } ]
[ { "body": "<p><strong>code:</strong></p>\n\n<ul>\n<li><p>Longitude is misspelled as <code>longitutde</code> a few times.</p></li>\n<li><p>Use <code>std::int32_t</code> etc. instead of <code>int32_t</code>. The C versions are in the global namespace, but the C++ ones are in namespace <code>std</code>.</p></li>\n<li><p>In the <code>Graph</code> class <code>_keyToNode</code> and <code>_coordinatesToNode</code> duplicate data already contained in the <code>Node</code> class (key and screen coordinates respectively). We can either:</p>\n\n<ol>\n<li><p>use an <a href=\"https://en.cppreference.com/w/cpp/container/unordered_set\" rel=\"nofollow noreferrer\"><code>unordered_set</code></a> and supply custom <code>Hash</code> and <code>KeyEquals</code> types as template arguments or</p></li>\n<li><p>move these data out of the <code>Node</code> class.</p></li>\n</ol></li>\n<li><p>A named function (e.g. <code>FindNode</code>) may be preferable to overloading the <code>Graph::operator[]</code> (the user may have preconceptions as to what <code>operator[]</code> should do on failure to find a node).</p></li>\n<li><p>The <code>protected</code> <code>Graph</code> constructor is a bit weird. Is there any special reason to restrict the construction of a <code>Graph</code> to derived objects / friends, and allow the <code>GraphFactory</code> access to all private class members? If not, just leave the constructor public.</p></li>\n<li><p>The <code>std::pair&lt;uint16_t, uint16_t&gt;</code> hash function could probably <a href=\"https://stackoverflow.com/questions/2590677/how-do-i-combine-hash-values-in-c0x\">use a better technique to combine hashes</a>.</p></li>\n</ul>\n\n<hr>\n\n<p><strong>concepts:</strong></p>\n\n<p>C++ has the notion of <em>concepts</em>, where classes of different types may adhere to the same static interface. These currently exist in the form of <em><a href=\"https://en.cppreference.com/w/cpp/named_req\" rel=\"nofollow noreferrer\">named requirements</a></em>, and <a href=\"https://en.cppreference.com/w/cpp/language/constraints\" rel=\"nofollow noreferrer\">will soon be in the language itself</a>.</p>\n\n<p>While a <em>concept</em> itself may be named something like <code>Associable</code>, this label refers to the static interface, and not to a concrete class. A more suitable name for the class itself would be <code>Associates</code> or simply <code>Neighbours</code>, and the class would adhere to the <code>Associable</code> <em>concept</em> by providing the appropriate static interface (functions, members, typedefs, etc.).</p>\n\n<p>Template classes or functions would then expect to receive types that adhere to the relevant <em>concept</em>. In this case, the <code>Graph</code> class might instead be templated on <code>Node</code>, and expect it to be e.g. <code>Associable</code> and <code>Identifiable</code>.</p>\n\n<p>Anywya, since the classes shown above are concrete classes, I'd recommend naming them more like this:</p>\n\n<ul>\n<li><code>Localizable::Earth -&gt; EarthCoords</code></li>\n<li><code>Localizable::Screen -&gt; ScreenCoords</code></li>\n<li><code>Associable -&gt; Neighbours</code></li>\n<li><code>Identifiable -&gt; Id</code></li>\n</ul>\n\n<p>Note that there's no actual relationship between <code>Localizable::Earth</code> and <code>Localizable::Screen</code> so there's no reason for them to share a namespace.</p>\n\n<hr>\n\n<p><strong>pointers:</strong></p>\n\n<p><code>std::shared_ptr</code> implies shared ownership. This is seldom something we actually want or need, as it makes object lifetime much harder to determine.</p>\n\n<p>In this case, there doesn't seem to be any sharing going on. As long as we ensure the lifetime of a <code>Node</code> object is longer than the lifetimes of any <code>Node*</code>s that refer to it, we can use raw pointers safely. In other words, the <code>std::shared_ptr&lt;Node&gt;</code> in the <code>Graph</code> class can be changed to <code>std::unique_ptr&lt;Node&gt;</code>, and all of the <code>std::weak_ptr&lt;Node&gt;</code>s can be <code>Node*</code>s.</p>\n\n<p>Note, however, that we don't actually need to use pointers here at all. We can simply store the node index instead. </p>\n\n<hr>\n\n<p><strong>Graph:</strong></p>\n\n<p>The <code>Graph</code> doesn't need to know about most of what's in the <code>Node</code> class. The minimal data required for a <code>Graph</code> is an adjacency list. Grouping this together with the edge weights into a <code>WeightedGraph</code> is reasonable:</p>\n\n<pre><code>template&lt;class IndexT, class WeightT, class IndexPairHashT = std::hash&lt;std::pair&lt;IndexT, IndexT&gt;&gt;&gt;\nstruct WeightedGraph\n{\n std::unordered_map&lt;IndexT, std::vector&lt;IndexT&gt;&gt; _adjacency;\n std::unordered_map&lt;std::pair&lt;IndexT, IndexT&gt;, WeightT, IndexPairHashT&gt; _edgeWeights;\n};\n</code></pre>\n\n<p>The <code>Graph</code> now depends only on the index type and weight type, and we're free to store nodes however we want (or not at all) outside of it, which is a lot more flexible.</p>\n\n<p>Note that the screen coordinates are unrelated to the <code>Graph</code>. (In fact, we might want a separate data structure to accelerate finding the nearest point to a mouse click, like a <code>PointQuadTree&lt;ScreenCoords, NodeIndex&gt;</code>.)</p>\n\n<hr>\n\n<p><strong>Dijkstra algorithm:</strong></p>\n\n<ul>\n<li>This should be a free function, not a class. It could return the path as a <code>std::vector&lt;Node&gt;</code>, or a struct containing the path and any additional data needed.</li>\n<li>It shouldn't throw on failure to find a path (it's would be quite reasonable to encounter unconnected nodes, and we shouldn't use exceptions for flow control).</li>\n</ul>\n\n<hr>\n\n<p><strong>misc:</strong></p>\n\n<p>Your xml file has latitude and longitude switched around! I think the data may also be horizontally (longitudinally) stretched, but I could be wrong about that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T13:48:33.970", "Id": "212139", "ParentId": "212009", "Score": "3" } } ]
{ "AcceptedAnswerId": "212139", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T17:33:28.370", "Id": "212009", "Score": "6", "Tags": [ "c++", "graph", "memory-management" ], "Title": "Yet Another Dijkstra with real data and drawing" }
212009
<p>Please, review the code:</p> <pre><code>const callback = (...args) =&gt; { console.count('callback throttled with arguments:', args); } const debounce = (callback, delay) =&gt; { let timeoutHandler = null return (...args) =&gt; { if (timeoutHandler) { clearTimeout(timeoutHandler) } timeoutHandler = setTimeout(() =&gt; { callback(...args) timeoutHandler = null }, delay) } } window.addEventListener('oninput', debounce(callback, 100)) </code></pre> <p>P.S. As @Anshul explained: Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T20:23:46.577", "Id": "409966", "Score": "0", "body": "Welcome to Code Review! I'm always somewhat surprised when people don't understand debounce, but it doesn't appear to be a common term outside of electromechanical engineering. For future reference, you can refer to [this page](https://en.wikipedia.org/wiki/Switch#Contact_bounce), with a note that debouncing can also be done for any type of (UI) button." } ]
[ { "body": "<h1>DELAY V DEBOUNCE</h1>\n<p>What you have implemented is a delay not a debounce. You delay the firing of the event until after a set time. Events during this time further delay the final event.</p>\n<h2>Design</h2>\n<p>Debouncing should respond to the first event immediately and then hold any response during the debouncing period after the listener has been called.</p>\n<p>It would be better to clearly identify the event argument passed to the listener.</p>\n<p>You do not provide a way of passing additional arguments to the event. By adding them to the outer function, you get better control. (see example)</p>\n<h2>General points</h2>\n<ul>\n<li>Inconsistent use of semicolon. Either use it (recommended) or not. Don't mix styles.</li>\n<li><code>var</code> is function scoped, <code>let</code> os block scope. It is better to use var when a variable is declared in function scope.</li>\n<li><code>timeoutHandler</code> is a poor name. The timeout function returns and Id (AKA a handle). The name you used implies that the variable is a function. A better name could be <code>timeoutHandle</code>, or in context just <code>id</code> or <code>handle</code> will do.</li>\n<li>The is no need to assign null to the variable <code>timeoutHandler</code>. undefined variable are <code>undefined</code> and making it <code>null</code> is just noise and semantically incorrect</li>\n<li>The handle returned by setTimeout (and setInterval) are unique to the context and the call. It is never reused. <code>clearTimeout</code> ignores invalid handles so there is no need check if the handle is valid, nor change its value inside the timeout function.</li>\n<li>You can reduce the call stack depth by using the trailing arguments of <code>setTimeout</code> to pass the arguments.</li>\n<li><code>window</code> is the default object. Inconsistent use is poor style. You do not use it for <code>clearTimeout</code>, <code>setTimeout</code>, and <code>console</code> so why for <code>addEventListener</code>?</li>\n<li><code>addEventListener('oninput'...</code> is incorrect, there is no event called <code>oninput</code>. Should be <code>addEventListener('input'...</code></li>\n</ul>\n<h2>Examples</h2>\n<p>Covering the general points and comparing debounce, delay, and immediate event responses. The delay is also used to clear the displays 2sec after the last event.</p>\n<p>It also shows when to use window. In the example emoticons can not be used as direct references to elements, thus I use window bracket notation to access the names.</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 DELAY_MS = 250;\nconst CLEAR_DELAY_MS = 2000;\nconst CLEAR_SPEED_MS = 17;\nconst DISPLAYS = [\"\",\"\",\"⚡\"];\n\nconst logger = (event, ...args) =&gt; log(args[0]);\n\nconst delay = (callback, delay, ...args) =&gt; {\n var handle;\n return event =&gt; {\n clearTimeout(handle);\n handle = setTimeout(callback, delay, event, ...args);\n }\n}\n\nconst debounce = (callback, delay, ...args) =&gt; {\n const timerClear = () =&gt; clear = true;\n var clear = true;\n return event =&gt; {\n if (clear) { \n clear = false;\n setTimeout(timerClear, delay);\n callback(event, ...args);\n }\n }\n}\n\naddEventListener('input', debounce(logger, DELAY_MS, DISPLAYS[0]));\naddEventListener('input', delay(logger, DELAY_MS, DISPLAYS[1]));\naddEventListener('input', event =&gt; logger(event, DISPLAYS[2]));\naddEventListener('input', delay(clear, CLEAR_DELAY_MS));\ngun.focus();\n\n\n\n\n/* Helper functions unrelated to question */\nfunction clear() {\n var allClear = \"\";\n DISPLAYS.forEach(name =&gt; {\n var text = window[\"log\" + name].textContent;\n allClear += window[\"log\" + name].textContent = text.substring(1);\n })\n if (allClear !== \"\") {\n setTimeout(clear, CLEAR_SPEED_MS);\n } else {\n gun.value = \"\";\n }\n}\n\nfunction log(which) { window[\"log\" + which].textContent += which }</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>b { font-size : large }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;code&gt;\n&lt;b&gt;Rumble!! Debounce V Delay V Immediate. With a 2 second delayed clear.&lt;/b&gt;&lt;/br&gt;\nDebounced 250ms: &lt;span id=\"log\"&gt;&lt;/span&gt;&lt;/br&gt;\nDelayed.. 250ms: &lt;span id=\"log\"&gt;&lt;/span&gt;&lt;/br&gt;\nImmediate.. 0ms: &lt;span id=\"log⚡\"&gt;&lt;/span&gt;&lt;/br&gt;\n&lt;/code&gt;\n&lt;/br&gt;\n&lt;input type=\"text\" placeholder=\"Rapid fire key strokes\" size=\"50\" id=\"gun\"&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": "2019-01-23T08:23:59.287", "Id": "212048", "ParentId": "212016", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T19:39:12.573", "Id": "212016", "Score": "5", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Debouncing function, ES6 version" }
212016
<p>I'm creating multiple Django apps with vote possibilities, so I made an app <code>vote</code> to handle all this votes. In my templates I'm including an ajax-function named <code>vote</code>. To know on which model I'm liking I add <code>app_name</code> and <code>model_name</code> to the <code>vote</code> function (I made some templatetags to get these values). In my views.py I use <code>model = apps.get_model(app_name, model_name)</code> to get the model class. But now I'm worried a hacker could do something with the <code>app_name</code> and <code>model_name</code> values.</p> <h2>vote/ajax.html (only function):</h2> <pre><code>function vote(bool){ $.ajax({ type: "post", timeout: 8000, url: '{% url 'ajax:vote' %}', dataType: 'json', data: { 'csrfmiddlewaretoken': getCookie('csrftoken'), 'model_name': "{{ model|get_model_name }}", 'app_name': "{{ model|get_app_name }}", 'voted': bool, 'id': "{{ model.id }}", }, success: function(data) { if (!data.error){ if (bool){ $(".half .fa-thumbs-up").removeClass("far").addClass("fas"); $(".half #count").text(parseInt($(".half #count").text()) + 1); } else { $(".half .fa-thumbs-down").removeClass("far").addClass("fas"); $(".half #count").text(parseInt($(".half #count").text()) - 1); } } } }); } </code></pre> <h2>ajax/views.py:</h2> <pre><code>def vote(request): try: app_name = request.POST.get("app_name") model_name = request.POST.get("model_name") id = request.POST.get("id") votedFor = True if request.POST.get("voted") == "true" else False except ValueError: return JsonResponse({"error": True}) model = apps.get_model(app_name, model_name) if model is None or id is None: return JsonResponse({"error": True}) try: usable_model = model.objects.get(id=id) except model.DoesNotExist: return JsonResponse({"error": True}) try: usable_model.vote._meta.get_field("votes") except FieldDoesNotExist: return JsonResponse({"error": True}) usable_model.vote.vote(request, votedFor) return JsonResponse({"error": False}) </code></pre> <h2>vote/functions:</h2> <pre><code>def vote(self, request, votedFor): if request.user.is_authenticated: if not UserVoted.objects.filter(User=request.user, Vote=self).exists(): UserVoted.objects.create(User=request.user, Vote=self, votedFor=votedFor) self._like_or_dislike(votedFor) return True return False ip = get_client_ip(request) if ip: if not UserVoted.objects.filter(ip=ip, Vote=self).exists(): UserVoted.objects.create(ip=ip, Vote=self, votedFor=votedFor) self._like_or_dislike(votedFor) return True return False return False def _like_or_dislike(self, votedFor): if votedFor is not None: Vote.objects.filter(id=self.id).update(votes=F('votes') + 1) if votedFor else Vote.objects.filter(id=self.id).update(votes=F('votes') - 1) return True return False </code></pre> <p>I already manipulated <code>app_name</code> and <code>model_name</code> and the server didn't crash but I don't know what a hacker can do. Can he crash my server when he manipulate these values? (maybe "ajax-injection" or something like this?)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T21:21:27.783", "Id": "409972", "Score": "5", "body": "Your indentation is off. This being Python, indentation is very important. Remove your code, paste it in file-by-file and with every bit you paste in, select it, hit Ctrl + K. The question editor should do the rest." } ]
[ { "body": "<h2>Question</h2>\n\n<blockquote>\n <p>But now I'm worried a hacker could do something with the <code>app_name</code> and <code>model_name</code> values.</p>\n \n <p>Can he crash my server when he manipulate these values? (maybe \"ajax-injection\" or something like this?)</p>\n</blockquote>\n\n<p>I'm not sure what the best approach to this would be. Perhaps it would be wise to define a list of the values that are acceptable for a user to pass there, though maybe that wouldn't be sufficient.</p>\n\n<h2>Other review points</h2>\n\n<blockquote>\n<pre><code>function vote(bool){\n</code></pre>\n</blockquote>\n\n<p>The name <code>bool</code> is not very descriptive. Given that it is used as the value for the <code>voted</code> parameter a name like <code>voted</code> would be more appropriate. And if your code complies with <a href=\"/questions/tagged/ecmascript-6\" class=\"post-tag\" title=\"show questions tagged &#39;ecmascript-6&#39;\" rel=\"tag\">ecmascript-6</a> standards you could simply write\n voted</p>\n\n<p>in the list of parameters as a shorthand for <code>voted: voted</code></p>\n\n<hr>\n\n<p>The success handler looks like this:</p>\n\n<blockquote>\n<pre><code>success: function(data) {\n if (!data.error){\n if (bool){\n $(\".half .fa-thumbs-up\").removeClass(\"far\").addClass(\"fas\");\n $(\".half #count\").text(parseInt($(\".half #count\").text()) + 1);\n } else {\n $(\".half .fa-thumbs-down\").removeClass(\"far\").addClass(\"fas\");\n $(\".half #count\").text(parseInt($(\".half #count\").text()) - 1);\n }\n</code></pre>\n</blockquote>\n\n<p>There is quite a bit of redundancy in both cases. Also <code>parseInt()</code> calls should pass a radix<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Octal_interpretations_with_no_radix\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n\n<pre><code>if (!data.error){\n const thumbClass = '.fa-thumbs-' + bool ? 'up' : 'down';\n $(\".half \" + thumbClass).removeClass(\"far\").addClass(\"fas\");\n const toAdd = bool ? 1 : -1;\n $(\".half #count\").text(parseInt($(\".half #count\").text(), 10) + toAdd);\n</code></pre>\n\n<hr>\n\n<p>In the <code>vote</code> function in ajax/views.py there is this line:</p>\n\n<blockquote>\n<pre><code>votedFor = True if request.GET.get(\"voted\") == \"true\" else False\n</code></pre>\n</blockquote>\n\n<p>This could be simplified to just:</p>\n\n<pre><code>votedFor = request.GET.get(\"voted\") == \"true\"\n</code></pre>\n\n<p><sup>1</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Octal_interpretations_with_no_radix\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Octal_interpretations_with_no_radix</a></sub></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T20:21:07.407", "Id": "471162", "Score": "1", "body": "Wow thank you for your answer for my old question, that isn`t very common! I already found a better way. I register all models in a global dict by saving the model class with a random ID. In the frontend then I use the ID and send it, in the backend I then can easily get the model by the ID." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-09T18:58:51.760", "Id": "240222", "ParentId": "212021", "Score": "1" } } ]
{ "AcceptedAnswerId": "240222", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T20:25:15.303", "Id": "212021", "Score": "4", "Tags": [ "python", "javascript", "jquery", "security", "django" ], "Title": "Python/Django Class based saving" }
212021
<p>I am trying to ensure that (once a cache item is populated) even if it's refresh object takes a long time to retrieve, the original cache item can be requested.</p> <pre><code>using System; using System.Runtime.Caching; namespace LongCacheTest { class Program { static void Main(string[] args) { Cacher.Add("key", "object", Get); Console.ReadLine(); } public static Object Get() { // load big file from disck return "stuff"; } } public class Cacheable { public delegate Object CacheEntryGet(); public Object Obj { get; set; } public CacheEntryGet Getter { get; set; } } public class Cacher { private static MemoryCache _cache = null; private static MemoryCache Cache =&gt; _cache = _cache ?? new MemoryCache("long"); private static CacheItemPolicy Policy =&gt; new CacheItemPolicy { AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(1)), Priority = CacheItemPriority.Default, RemovedCallback = DidRemove }; public static void DidRemove(CacheEntryRemovedArguments args) { Cache.Add(args.CacheItem.Key, args.CacheItem.Value, Policy); var item = args.CacheItem.Value as Cacheable; item.Obj = item.Getter(); Cache.Remove(args.CacheItem.Key); Cache.Add(args.CacheItem.Key, item, Policy); } public static void Add(string key, Object obj, Cacheable.CacheEntryGet getter) { var item = new Cacheable{ Obj = obj, Getter = getter }; Cache.Add(key, item, Policy); } } } </code></pre> <p>The practice here is to provide a method <code>Getter</code> and cache it alongside the cached <code>Object</code>. When the cache item expires, it is reinserted and the <code>Getter</code> method is called to get the refresh object. Once the fresh object is retrieved it replaces the original cache item.</p>
[]
[ { "body": "<h3>How do I use this?</h3>\n\n<p>I don't understand how to use this. It took me some time to understand the reason for the getter, and I can't see how to retrieve anything from this cache.</p>\n\n<h3>Why do I need to <code>Add</code> the value when I have the delegate?</h3>\n\n<p>In the <code>Add</code> method, it doesn't make sense to add provide both a value and a method that calculates the value; it is very likely that someone will pass in inconsistent arguments and get unexpected results. It should suffice to simply pass in the delegate, and let the value calculate itself.</p>\n\n<h3>Why is this static?</h3>\n\n<p>It is very dangerous to have one global cache holding every different type. You should allow for multiple caches for different purposes, and then you can...</p>\n\n<h3>Make this cache generic</h3>\n\n<p>Nobody likes to cast from <code>Object</code>. Your interface should be <code>Cacheable&lt;T&gt;</code>, so that we can check at compile time that the type to be returned is what we expect.</p>\n\n<h3>Your response is not guaranteed</h3>\n\n<p>Your callback is only called after the item has been removed from the cache. Even if you add the previous value back straight away, a poorly-timed interrupt could have another thread searching for a key in that split-millisecond it's not there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T05:35:33.807", "Id": "409993", "Score": "0", "body": "Thanks for your help! If I wanted to post the revised code, should it be as an updated to the original post or a new post?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:33:42.193", "Id": "410102", "Score": "1", "body": "@MattW Refer to [this meta post for the acceptable options](https://codereview.meta.stackexchange.com/a/1765/120114)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T21:32:31.407", "Id": "212026", "ParentId": "212024", "Score": "3" } } ]
{ "AcceptedAnswerId": "212026", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T21:09:26.280", "Id": "212024", "Score": "2", "Tags": [ "c#", "cache" ], "Title": "Long cache refresh with guaranteed response" }
212024
<p>I'm following the project found <a href="https://learn.freecodecamp.org/responsive-web-design/responsive-web-design-projects/build-a-tribute-page" rel="nofollow noreferrer">here</a>. I'm sure I forced some flexboxes where they didn't need to be. Tried to apply some accessibility topics that were discussed in earlier lessons. Overall its a very plain static page, but I'm trying to get the basics down in terms of structuring my html page correct before moving on to more complicated topics. I'm looking mostly for tips on how I'm structuring/nesting the HTML, as well as adding accessibility, and if my CSS structurally makes sense.</p> <p><a href="https://codepen.io/tommyk154/pen/pqBKaW" rel="nofollow noreferrer">Solution</a></p> <p>Note: this was wrote in Codepen so head/body tags are missing.</p> <p>HTML:</p> <pre class="lang-html prettyprint-override"><code>&lt;main id="main"&gt; &lt;h1 id="title"&gt;Philip Drury Dawson&lt;/h1&gt; &lt;div id="img-div"&gt; &lt;img id="image" src="http://media.cleveland.com/shaw_impact/photo/dawson-tiphelmet-2012-ccjpg-ad91451e0875bce2.jpg" alt="Phil Dawson greeting fans in First Energy Stadium"&gt; &lt;p id="img-caption"&gt;&lt;em&gt;Phil greeting his fans&lt;/em&gt;&lt;/p&gt; &lt;/div&gt; &lt;!-- END img id="image" --&gt; &lt;div id="tribute-info"&gt; &lt;p&gt;Phil was the best. &lt;a href="https://www.reddit.com/r/Browns" target="_blank" id="tribute-link"&gt;We love him.&lt;/a&gt; &lt;/p&gt; &lt;article&gt; &lt;h2&gt;Cleveland Browns&lt;/h2&gt; &lt;p&gt;The Cleveland Browns signed him as a free agent in March 1999, and he remained with the team for 14 years until he was signed by the San Francisco 49ers on March 19, 2013. (He was the only player left from the 1999 Browns squad). Dawson holds the Browns record for most consecutive field goals made (29) and most field goals in a game (6). Dawson is currently the 7th most accurate kicker in the NFL. On October 10, 2010, Dawson tied Lou Groza for the Browns' career field-goal record with 234. The two are tied for 35th in NFL history. Dawson scored the first points in the history of the "new" Cleveland Browns in 1999. On October 10 of that year, he scored the only touchdown of his career on a fake field goal against the Bengals in an 18-17 loss. His official career long was a 56-yard field goal on November 17, 2008, which would prove to be the game-winner against the Buffalo Bills on Monday Night Football. However, he did hit a 59-yard field goal in an August 14, 2010 preseason game. Dawson would have become an unrestricted free agent at the end of the 2010 season, but he was given the franchise tag on February 22, keeping him for the 2011 season. &lt;/p&gt; &lt;/article&gt; &lt;article&gt; &lt;h2&gt;The Phil Dawson Rule&lt;/h2&gt; &lt;p&gt;Dawson had a rule named after him after a missed call by referees. On November 18, 2007, Dawson attempted a 51-yard field goal in the closing seconds of the fourth quarter to tie the game against the Baltimore Ravens. The kick carried through the air and hit the left upright and then the rear curved support post (stanchion), which bounced the football over the crossbar and into the end zone, in front of the goalpost. The kick was originally ruled no good. Under NFL rules, the play was not reviewable. &lt;a href=#references&gt;&lt;sup&gt;[1]&lt;/sup&gt;&lt;/a&gt; Officials discussed the play among themselves for several minutes and decided that, since the ball had indeed crossed the crossbar within the goal, whatever happened afterward to the ball did not matter. The kick was considered good, as announced by referee Pete Morelli. However, as the play is not technically reviewable, referee Pete Morelli announced that the play was reversed "after discussion," as opposed to "after further review," as is usually stated. At this point the Ravens, already celebrating in the locker room (they would have won 30-27 if the field goal was no good), were called back out onto the field to proceed to an overtime period. The Browns went on to win the game, 33-30 in overtime, as Dawson came through again with a more visible 33-yard field goal. Dawson finished 4 for 5 in FGs whereas fellow Lake Highlands High School alumnus Matt Stover finished 3 for 3 in FGs for the Ravens.&lt;a href=#references&gt;&lt;sup&gt;[2]&lt;/sup&gt;&lt;/a&gt; Notably, later in the season on December 16, in driving snow and wind gusts up to 40 mph, Dawson kicked another field goal, an improbable 49-yarder, that hit the same center support post. This field goal helped the Browns achieve an 8-0 win over the Buffalo Bills in blizzard conditions. Hitting this same structure twice in the same season has led some members of the Cleveland press to begin referring to the support post as "The Dawson Bar."&lt;a href=#references&gt;&lt;sup&gt;[3]&lt;/sup&gt;&lt;/a&gt; Prior to the 2008 season, the rule was changed to allow field goal and extra point attempts that hit the uprights or crossbar to be reviewed. This new rule is dubbed the "Phil Dawson Rule." &lt;/p&gt; &lt;/article&gt; &lt;/div&gt; &lt;!-- END div id="tribute-info" --&gt; &lt;/main&gt; &lt;footer&gt; &lt;div id="references"&gt; &lt;h2&gt;References&lt;/h2&gt; &lt;ol&gt; &lt;li&gt; &lt;a href="http://www.espn.com/nfl/columns/story?columnist=sando_mike&amp;id=3120230"&gt;http://www.espn.com/nfl/columns/story?columnist=sando_mike&amp;id=3120230&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="http://www.espn.com/nfl/boxscore?gameId=271118033"&gt;http://www.espn.com/nfl/boxscore?gameId=271118033&lt;/a&gt; &lt;/li&gt; &lt;li&gt; &lt;a href="https://halftimeadjustments.wordpress.com/2007/12/20/the-dawson-bar/"&gt;https://halftimeadjustments.wordpress.com/2007/12/20/the-dawson-bar/&lt;/a&gt; &lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;/footer&gt; &lt;script src="https://cdn.freecodecamp.org/testable-projects-fcc/v1/bundle.js"&gt;&lt;/script&gt; </code></pre> <p>CSS:</p> <pre class="lang-css prettyprint-override"><code>html, body { font-family: verdana, arial, helvetica, sans-serif; } body { background-color: #444; } #main { color: #efefef; display: flex; flex-direction: column; align-items: center; margin: 0px 5%; } #img-div { background-color: #ff3c00; display: flex; flex-direction: column; justify-conent: flex-end; align-items: center; padding: 0px 0px 0px; } #image { max-width: 100%; height: auto; } #tribute-info { color: #222; background-color: #efefef; margin: 30px 0px; padding: 10px 5%; text-align: center; } #tribute-info h2 { border-bottom: 1px solid rgb(2, 2, 2, 0.2); padding-bottom: 10px; margin: 10px 0px; font-size: 1.5em; } p { font-size: 0.88em; line-height: 1.5; } sup { vertical-align: top; line-height: 1; font-size: 75%; } footer { color: #efefef; display: flex; flex-direction: column; align-items: center; margin: 0px 5%; } footer h2 { border-bottom: 1px solid rgb(239, 239, 239, 0.2); padding-bottom: 10px; margin: 10px 0px; font-size: 1.5em; text-align: center; } footer ol { columns: 2; column-width: 15em; font-size: 0.84em; list-style-position: inside; } footer a { color: #efefef; font-style: italic; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T23:06:14.210", "Id": "410153", "Score": "0", "body": "really dude you went and edited capitalizations but couldn't give a single piece of feedback on the code at hand?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T09:44:42.267", "Id": "410486", "Score": "1", "body": "The user changed more than just capitalization (e.g., syntax highlighting), and editing and answering are two separate tasks (users might edit questions even if they don’t have expertise, or anything to say, or time to post)." } ]
[ { "body": "<p><strong>HTML semantics</strong></p>\n\n<p>The following snippet:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;img id=\"image\" src=\"http://media.cleveland.com/shaw_impact/photo/dawson-tiphelmet-2012-ccjpg-ad91451e0875bce2.jpg\" alt=\"Phil Dawson greeting fans in First Energy Stadium\"&gt;\n&lt;p id=\"img-caption\"&gt;&lt;em&gt;Phil greeting his fans&lt;/em&gt;&lt;/p&gt;\n</code></pre>\n\n<p>Looks like an ideal candidate for <code>&lt;figure&gt;</code> and <code>&lt;figcaption&gt;</code>. Beyond semantics, It would visually simplify the markup, too.</p>\n\n<blockquote>\n <p>The figure element represents some flow content, optionally with a caption, that is self-contained and is typically referenced as single unit from the main flow of the document.</p>\n</blockquote>\n\n<pre class=\"lang-html prettyprint-override\"><code>&lt;figure&gt;\n &lt;img src=“…”&gt;\n &lt;figcaption&gt;Phil greeting his fans&lt;/figcaption&gt;\n&lt;/figure&gt;\n</code></pre>\n\n<p><strong>target=“_blank”</strong></p>\n\n<p>Every place you use these should be accompanied by the following attribute: <code>rel=\"noopener external”</code></p>\n\n<p>This is a plus for security and performance. More on that <a href=\"https://jakearchibald.com/2016/performance-benefits-of-rel-noopener/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>The footer</strong></p>\n\n<p>This is more of a design opinion, so feel free to ignore it. I think this area of the page looks jumbled and could use some love.</p>\n\n<p><strong>CSS</strong></p>\n\n<ul>\n<li>The unit is not necessary if the value is <code>0</code>. So <code>0px</code> could just as well be <code>0</code></li>\n<li>If you don’t need to support IE, some native <code>CSS</code> variables would help organize repeating styles</li>\n</ul>\n\n<p>For example:</p>\n\n<pre class=\"lang-css prettyprint-override\"><code>:root {\n —gray: #efefef;\n}\n\n#main {\n color: var(—grey);\n}\n\n#tribute-info {\n background-color: var(—grey);\n}\n</code></pre>\n\n<p><strong>General comments</strong></p>\n\n<ul>\n<li>The number of <code>id</code>s seems unnecessary</li>\n<li>Some of the names of the <code>id</code>s are too general (“image”) and could be a problem if the HTML volume scales</li>\n</ul>\n\n<p>I hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-03T07:02:44.417", "Id": "212783", "ParentId": "212025", "Score": "2" } } ]
{ "AcceptedAnswerId": "212783", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T21:30:19.760", "Id": "212025", "Score": "4", "Tags": [ "html", "css" ], "Title": "Basic static HTML page with applied accessibility" }
212025
<p>I just recently finished the following problem on Leetcode <a href="https://leetcode.com/problems/longest-common-prefix/" rel="nofollow noreferrer">problem</a>. I know it's not the cleanest or fastest solution. I would appreciate if I can get some feedback on how to optimize the code. </p> <p>The idea is too add all possible prefixes into an array and return the longest possible prefix. I believe this is probably why the algorithm doesn't run as fast as it should. </p> <p>Also, I would appreciate if someone can assist in determining what the space and time complexity would be for the algorithm below?</p> <pre><code>var longestCommonPrefix = function(strs) { const firstWord = strs[0]; const arrResults = []; let index = 1; let arrWithoutFirstElement = strs.slice(1, strs.length); if(strs.length===0)return ''; if(strs.length===1)return strs[0]; while(index &lt;= firstWord.length) { if(arrWithoutFirstElement.every(element =&gt; element.substring(0,index)===firstWord.substring(0,index))){ arrResults.push(firstWord.substring(0,index)); } index++; } return arrResults.length &gt; 0 ? arrResults[arrResults.length-1] : ''; } console.log(longestCommonPrefix(["flower","flow","flight"])); </code></pre>
[]
[ { "body": "<h1>Fast strings in Javascript</h1>\n<p>It is important to note that something as simple as assigning a string to a variable will cost the length of the string in complexity <code>a = &quot;12345&quot;</code> will cost 5 characters. Assign to another variable and the cost is the same <code>b = a</code> will cost 5.</p>\n<p>Every time you assign a string you need to count the length of that string. If you copy an array of strings then you move all the characters, not just the number of strings in the array.</p>\n<p>You do a lot of string assignments in your code.</p>\n<h2>Avoid string assignment</h2>\n<p>The trick to handling strings is to avoid assigning strings if you can. Arrays and string array character referencing (eg <code>a = &quot;abcdef&quot;; b = a[1]</code>) lets you treat the JS string like a C (<code>char *</code>) string. You dont copy the string, you are just indexing into the string.</p>\n<p>The only time any sequence of characters are copied is on the return. The performance increase is very significant.</p>\n<pre><code>const longestCommonPrefix = words =&gt; {\n var i, pos = 0, len = words.length;\n const char = words[0][pos];\n var min = words[0].length;\n for (i = 1; i &lt; len; i++) { // finds the min word length and check first char\n min = words[i].length &lt; min ? words[i].length : min;\n if (char !== words[i][pos] || pos === min) { return &quot;&quot; }\n } \n pos ++;\n while (pos &lt; min) { // check up to min word length.\n const char = words[0][pos];\n for (i = 1; i &lt;len; i++) {\n if (char !== words[i][pos]) { return words[0].substring(0,pos) }\n }\n pos ++;\n }\n return words[0].substring(0,pos);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:04:24.023", "Id": "212222", "ParentId": "212029", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-22T22:09:43.890", "Id": "212029", "Score": "1", "Tags": [ "javascript", "algorithm" ], "Title": "Leetcode Longest Common Prefix" }
212029